56. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 2/8/2019 1:12:19 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.

56.1 Files compared

# Location File Last Modified
1 CIF B10S2.zip\CIF B10S2\VA.PPMS.DataWebServiceV1\VA.PPMS.DataWebServiceV1\PpmsDataService GlobalFunctionsController.cs Thu Jan 3 20:21:00 2019 UTC
2 CIF B10S2.zip\CIF B10S2\VA.PPMS.DataWebServiceV1\VA.PPMS.DataWebServiceV1\PpmsDataService GlobalFunctionsController.cs Fri Feb 8 16:01:26 2019 UTC

56.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 3 1744
Changed 2 6
Inserted 0 0
Removed 0 0

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

56.4 Active regular expressions

No regular expressions were active.

56.5 Comparison detail

  1   using Syst em;
  2   using Syst em.Collect ions.Gener ic;
  3   using Syst em.Configu ration;
  4   using Syst em.Device. Location;
  5   using Syst em.Linq;
  6   using Syst em.Net;
  7   using Syst em.Net.Htt p;
  8   using Syst em.Threadi ng.Tasks;
  9   using Syst em.Web.Htt p;
  10   using Syst em.Web.Htt p.Descript ion;
  11   using Syst em.Web.ODa ta;
  12   using Syst em.Web.ODa ta.Routing ;
  13   using Bing MapsRESTTo olkit;
  14   using Micr osoft.Web. Http;
  15   using Ppms DataServic e.Models;
  16   using Ppms DataServic e.ModelsEn umTypes;
  17   using Ppms DataServic e.V1.Mappe rs;
  18   using Ppms DataServic e.VA.PPMS. Context;
  19   using VA.P PMS.Contex t;
  20   using Newt onsoft.Jso n;
  21   using Syst em.Net.Htt p.Headers;
  22   using Syst em.Runtime .Serializa tion.Json;
  23   using Syst em.Securit y.Cryptogr aphy.X509C ertificate s;
  24   using Syst em.Text;
  25   using Syst em.IO;
  26   using Syst em.Net.Htt p.Formatti ng;
  27   using Micr osoft.Xrm. Sdk;
  28   using Micr osoft.Xrm. Sdk.Query;
  29  
  30   namespace  PpmsDataSe rvice
  31   {
  32       /// <s ummary>
  33       /// Pr ovides unb ound, util ity functi ons.
  34       /// </ summary>
  35       [ApiVe rsionNeutr al]
  36       public  class Glo balFunctio nsControll er : OData Controller
  37       {    
  38           [H ttpGet]
  39           [M apToApiVer sion("1.0" )]
  40           [R esponseTyp e(typeof(P roviderLoc atorResult ))]
  41           [O DataRoute( "ProviderL ocator")]
  42           pu blic async  Task<Http ResponseMe ssage> Pro viderLocat or([FromOD ataUri] st ring addre ss, [FromO DataUri] i nt radius,  [FromODat aUri] int  driveTime,  [FromODat aUri] stri ng special tycode1, [ FromODataU ri] string  specialty code2, [Fr omODataUri ] string s pecialtyco de3, [From ODataUri]  string spe cialtycode 4, [FromOD ataUri] in t network,  [FromODat aUri] int  gender, [F romODataUr i] int pri marycare,  [FromOData Uri] int a cceptingne wpatients,  [FromODat aUri] int  maxResults )
  43           {
  44                //Defaul t Values f or maxResu lts
  45                if (maxR esults > 6 25) { maxR esults = 6 25; }
  46  
  47                var _ser vice = awa it PpmsCon textHelper .GetProxy( );
  48  
  49                using (v ar context  = new Ppm sContext(a wait PpmsC ontextHelp er.GetProx y()))
  50                {
  51                    stri ng key = C onfigurati onManager. AppSetting s["BingMap sKey"];
  52  
  53                    //Ge ocode the  Starting A ddress fir st
  54                    var  request =  new Geocod eRequest()
  55                    {
  56                         Query = ad dress,
  57                         IncludeIso 2 = true,
  58                         IncludeNei ghborhood  = true,
  59                         MaxResults  = 25,
  60                         BingMapsKe y = key
  61                    };
  62  
  63                    //Pr ocess the  request by  using the  ServiceMa nager.
  64                    var  response =  await Ser viceManage r.GetRespo nseAsync(r equest);
  65  
  66                    if ( response ! = null &&
  67                         response.R esourceSet s != null  &&
  68                         response.R esourceSet s.Length >  0 &&
  69                         response.R esourceSet s[0].Resou rces != nu ll &&
  70                         response.R esourceSet s[0].Resou rces.Lengt h > 0)
  71                    {
  72                         var result  = respons e.Resource Sets[0].Re sources[0]  as Locati on;
  73                         if (result  != null)
  74                         {
  75                             double  startLati tude = res ult.Point. Coordinate s[0];
  76                             double  startLong itude = re sult.Point .Coordinat es[1];
  77                             //var  startingCo ord = new  Coordinate (startLati tude, star tLongitude );
  78                             //var  startingWa yPoint = n ew SimpleW aypoint(st artingCoor d);
  79                             //var  origin = n ew List<Si mpleWaypoi nt> { star tingWayPoi nt };
  80  
  81                             //Conv ert to Met ers for fo rmula.
  82                             double  distanceC alc = radi us * 1609. 34;
  83                             /*
  84                             var no rthBoundCo ord = Dist anceCalc.g etBounds(s tartLatitu de, startL ongitude,  0, distanc eCalc);
  85                             decima l northBou ndLat = (d ecimal)nor thBoundCoo rd.Latitud e;
  86                             var ea stBoundCoo rd = Dista nceCalc.ge tBounds(st artLatitud e, startLo ngitude, 9 0, distanc eCalc);
  87                             decima l eastBoun dLong = (d ecimal)eas tBoundCoor d.Longitud e;
  88                             var so uthBoundCo ord = Dist anceCalc.g etBounds(s tartLatitu de, startL ongitude,  180, dista nceCalc);
  89                             decima l southBou ndLat = (d ecimal)sou thBoundCoo rd.Latitud e;
  90                             var we stBoundCoo rd = Dista nceCalc.ge tBounds(st artLatitud e, startLo ngitude, 2 70, distan ceCalc);
  91                             decima l westBoun dLong = (d ecimal)wes tBoundCoor d.Longitud e;
  92                             */
  93  
  94                             //Only  need the  Northwest  and Southe ast coordi nates to d etermine B ounds
  95                             var no rthWestBou ndCoord =  DistanceCa lc.getBoun ds(startLa titude, st artLongitu de, 315, d istanceCal c);
  96                             decima l northWes tBoundLong  = (decima l)northWes tBoundCoor d.Longitud e;
  97                             decima l northWes tBoundLat  = (decimal )northWest BoundCoord .Latitude;
  98  
  99                             var so uthEastBou ndCoord =  DistanceCa lc.getBoun ds(startLa titude, st artLongitu de, 135, d istanceCal c);
  100                             decima l southEas tBoundLong  = (decima l)southEas tBoundCoor d.Longitud e;
  101                             decima l southEas tBoundLat  = (decimal )southEast BoundCoord .Latitude;
  102  
  103                             //Buil d the Fetc hXml
  104                             string  fetchXml  = @"  
  105                             <fetch  version=' 1.0' outpu t-format=' xml - plat form' mapp ing='logic al' distin ct='true'>  
  106                             <entit y name='pp ms_provide rservice'>
  107                             <attri bute name= 'ppms_name '/>
  108                             <attri bute name= 'ppms_care siteaddres s' />
  109                             <attri bute name= 'ppms_care sitecity'  />
  110                             <attri bute name= 'ppms_care sitestatep rovince' / >
  111                             <attri bute name= 'ppms_care sitezipcod e' />
  112                             <attri bute name= 'ppms_lati tude' />
  113                             <attri bute name= 'ppms_long itude' />
  114                             <attri bute name= 'ppms_spec ialtynamet ext' />
  115                             <attri bute name= 'ppms_prov idername'  />
  116                             <attri bute name= 'ppms_qual ityranking totalscore ' />
  117                             <attri bute name= 'ppms_work hours' />
  118                             <attri bute name= 'ppms_prov iderid' />
  119                             <attri bute name= 'ppms_netw ork' />
  120                             <attri bute name= 'ppms_prov ideragreem ent' />
  121                             <attri bute name= 'ppms_spec ialtycode'  />
  122                             <attri bute name= 'ppms_prov ideridenti fer' />
  123                             <attri bute name= 'ppms_care site' />
  124                             <attri bute name= 'ppms_prov iderservic eid' />
  125                             <order  attribute ='ppms_nam e' descend ing='false ' />
  126                             <filte r type='an d'>
  127                             <condi tion attri bute='stat ecode' ope rator='eq'  value='0'  />
  128                             <condi tion attri bute='stat uscode' op erator='eq ' value='1 ' />
  129                             <condi tion attri bute='ppms _geocoded'  operator= 'eq' value ='1' />
  130                             <condi tion attri bute='ppms _addressva lidated' o perator =  'eq' value  = '1' />
  131                             <condi tion attri bute='ppms _latitude'  operator= 'not-null'  />
  132                             <condi tion attri bute='ppms _longitude ' operator ='not-null ' />";
  133                             fetchX ml += "<co ndition at tribute='p pms_latitu de' operat or='lt' va lue='" + n orthWestBo undLat + " '/>";
  134                             fetchX ml += "<co ndition at tribute='p pms_latitu de' operat or='gt' va lue='" + s outhEastBo undLat + " '/>";
  135                             fetchX ml += "<co ndition at tribute='p pms_longit ude' opera tor='gt' v alue='" +  northWestB oundLong +  "'/>";
  136                             fetchX ml += "<co ndition at tribute='p pms_longit ude' opera tor='lt' v alue='" +  southEastB oundLong +  "'/>";
  137  
  138                             //Prov ider Netwo rk
  139                             if (ne twork != 0 )
  140                             {
  141                                 // To DO: Cha nge this f rom a Linq  Lookup
  142                                 va r provider Network =  context.pp ms_vaprovi dernetwork Set.FirstO rDefault(i  => i.ppms _networknu mber == ne twork);
  143                                 if  (provider Network !=  null) {
  144                                      fetchXml  += "<cond ition attr ibute='ppm s_network'  operator= 'eq' uinam e='' uityp e='ppms_va providerne twork' val ue='{" + p roviderNet work.Id +  "}' />";
  145                                 }
  146                             }
  147  
  148                             //Spec ialties
  149                             //If w e have any  specialit es we'll a dd the OR  Filter to  Fetch
  150                             if (sp ecialtycod e1 != null  || specia ltycode2 ! = null ||  specialtyc ode3 != nu ll || spec ialtycode4  != null)
  151                             {
  152                                 fe tchXml +=  "<filter t ype='or'>" ;
  153                                 if  (specialt ycode1 !=  null) { fe tchXml +=  "<conditio n attribut e='ppms_sp ecialtycod e' operato r='eq' val ue='" + sp ecialtycod e1 + "'/>" ; }
  154                                 if  (specialt ycode2 !=  null) { fe tchXml +=  "<conditio n attribut e='ppms_sp ecialtycod e' operato r='eq' val ue='" + sp ecialtycod e2 + "'/>" ; }
  155                                 if  (specialt ycode3 !=  null) { fe tchXml +=  "<conditio n attribut e='ppms_sp ecialtycod e' operato r='eq' val ue='" + sp ecialtycod e3 + "'/>" ; }
  156                                 if  (specialt ycode4 !=  null) { fe tchXml +=  "<conditio n attribut e='ppms_sp ecialtycod e' operato r='eq' val ue='" + sp ecialtycod e4 + "'/>" ; }
  157                                 fe tchXml +=  "</filter> ";
  158                             }
  159  
  160                             //Gend er
  161                             switch  (gender)
  162                             {
  163                                 ca se 0:
  164                                      //Any ge nder
  165                                      break;
  166                                 ca se 1:
  167                                      //Male
  168                                      fetchXml  += "<cond ition attr ibute='ppm s_gender'  operator=' eq' value= '767940002 ' />";
  169                                      break;
  170                                 ca se 2:
  171                                      //Female
  172                                      fetchXml  += "<cond ition attr ibute='ppm s_gender'  operator=' eq' value= '767940001 ' />";
  173                                      break;
  174                                 de fault:
  175                                      break;
  176                             }
  177  
  178                             switch  (primaryc are)
  179                             {
  180                                 ca se 0:
  181                                      //No Pre ference
  182                                      break;
  183                                 ca se 1:
  184                                      fetchXml  += "<cond ition attr ibute='ppm s_primaryc arephysici an' operat or='eq' va lue='1' /> ";
  185                                      break;
  186                                 ca se 2:
  187                                      fetchXml  += "<cond ition attr ibute='ppm s_primaryc arephysici an' operat or='eq' va lue='0' /> ";
  188                                      break;
  189                                 de fault:
  190                                      break;
  191                             }
  192  
  193                             switch  (acceptin gnewpatien ts)
  194                             {
  195                                 ca se 0:
  196                                      //No Pre ference
  197                                      break;
  198                                 ca se 1:
  199                                      fetchXml  = "<condi tion attri bute='ppms _individua lisaccepti ngnewpatie nts' opera tor='eq' v alue='1' / >";
  200                                      fetchXml  = "<condi tion attri bute='ppms _primaryca reprovider acceptingv a' operato r='eq' val ue='1' />" ;
  201                                      break;
  202                                 ca se 2:
  203  
  204                                      break;
  205                                 de fault:
  206                                      break;
  207                             }
  208                             fetchX ml += "</f ilter>";
  209  
  210                             //Chec k status o f the rela ted Provid er, must b e in Activ e State/St atus Reaso n.
  211                             fetchX ml += "<li nk-entity  name='acco unt' alias ='am' to=' ppms_provi derid' fro m='account id' ><filt er type='a nd'>";
  212                             fetchX ml += "<co ndition at tribute='s tatecode'  operator=' eq' value= '0' />";
  213                             fetchX ml += "<co ndition at tribute='s tatuscode'  operator= 'eq' value ='1' />";
  214                             fetchX ml += "</f ilter></li nk-entity> ";
  215  
  216                             //Chec k status o f the Rela ted Provid er Agreeme nt, must b e in Activ e State/St atus Reaso n
  217                             fetchX ml += "<li nk-entity  name='ppms _providera greement'  from='ppms _providera greementid ' to='ppms _providera greement'  visible='f alse' link -type='out er' alias= 'a_6472839 3f394e8118 1201458d04 dc6b8'>";
  218                             fetchX ml += "<at tribute na me='statec ode'/>";
  219                             fetchX ml += "<at tribute na me='status code'/>";
  220                             fetchX ml += "</l ink-entity >";
  221  
  222                             fetchX ml += "</e ntity></fe tch> ";
  223  
  224                             //Retr ieve Resut ls using F etchXml ab ove. 
  225                             Entity Collection  results =  _service. RetrieveMu ltiple(new  FetchExpr ession(fet chXml));
  226                             //Init ial List w ith Filter s defined  above. 
  227  
  228                             //Add  Services t o List wit h one addi tional fit ler to che ck if ther e is eithe r no Provi der Agreem ent or the  Provider  Agreement  is in Acti ve Status.
  229                             var pp msProvider ServicesLi st = resul ts.Entitie s.Where(x  => x.Attri butes.Cont ainsKey("a _64728393f 394e811812 01458d04dc 6b8.status code") ==  false || ( (OptionSet Value)x.Ge tAttribute Value<Alia sedValue>( "a_6472839 3f394e8118 1201458d04 dc6b8.stat uscode").V alue).Valu e == 1).Se lect(e =>  e.ToEntity <ppms_prov iderservic e>()).ToLi st();
  230  
  231                             /*
  232                             //Old  Approach u sing LINQ
  233                              
  234                             var pr ovServices  = from ps  in contex t.ppms_pro viderservi ceSet
  235                                                  where p s.StateCod e.Value ==  (int)ppms _providers erviceStat e.Active
  236                                                  where p s.StatusCo de.Value = = (int)ppm s_provider service_St atusCode.A ctive
  237                                                  where p s.ppms_net work != nu ll
  238                                                  where p s.ppms_Pro viderId !=  null
  239                                                  where p s.ppms_spe cialty !=  null
  240                                                  where p s.ppms_lat itude != n ull
  241                                                  where p s.ppms_lon gitude !=  null
  242                                                  where p s.ppms_lat itude <= n orthBoundL at
  243                                                  where p s.ppms_lat itude >= s outhBoundL at
  244                                                  where p s.ppms_lon gitude >=  westBoundL ong
  245                                                  where p s.ppms_lon gitude <=  eastBoundL ong
  246                                                  select  ps;
  247  
  248                             //Add  Optional F ilters
  249  
  250                             //If a ny Special ty Codes a re given,  check for  Provider S ervices wi th match S pecialty C odes
  251                             if (sp ecialtycod e1 != null  || specia ltycode2 ! = null ||  specialtyc ode3 != nu ll || spec ialtycode4  != null)
  252                                 pr ovServices  = provSer vices.Wher e(ps => ps .ppms_spec ialtycode. Equals(spe cialtycode 1) || ps.p pms_specia ltycode.Eq uals(speci altycode2)  || ps.ppm s_specialt ycode.Equa ls(special tycode3) | | ps.ppms_ specialtyc ode.Equals (specialty code4));
  253  
  254                             //Netw ork Lookup
  255                             if (ne twork != 0 )
  256                             {
  257                                 va r provider Network =  context.pp ms_vaprovi dernetwork Set.FirstO rDefault(i  => i.ppms _networknu mber == ne twork);
  258                                 if  (provider Network !=  null)
  259                                 {
  260                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ network.Id  == provid erNetwork. Id);
  261                                 }
  262                             }
  263                                          
  264                             switch  (gender)
  265                             {
  266                                 ca se 0:
  267                                      //Any ge nder
  268                                      break;
  269                                 ca se 1:
  270                                      //Male
  271                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ providerge nder.Equal s(ppms_Gen der.Male)) ;
  272                                      break;
  273                                 ca se 2:
  274                                      //Female
  275                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ providerge nder.Equal s(ppms_Gen der.Female ));
  276                                      break;
  277                                 de fault:
  278                                      break;
  279                             }
  280                             
  281  
  282                             switch  (primaryc are)
  283                             {
  284                                 ca se 0:
  285                                      //No Pre ference
  286                                      break;
  287                                 ca se 1:
  288                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ provideris primarycar e.Equals(t rue));
  289                                      break;
  290                                 ca se 2:
  291                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ provideris primarycar e.Equals(f alse));
  292                                      break;
  293                                 de fault:
  294                                      break;
  295                             }
  296  
  297                             switch  (acceptin gnewpatien ts)
  298                             {
  299                                 ca se 0:
  300                                      //No Pre ference
  301                                      break;
  302                                 ca se 1:
  303                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ providerac ceptingnew patients.E quals(true ) && ps.pp ms_provide raccepting va.Equals( true));
  304                                      break;
  305                                 ca se 2:
  306                                      provServ ices = pro vServices. Where(ps = > ps.ppms_ providerac ceptingnew patients.E quals(fals e) && ps.p pms_provid eracceptin gva.Equals (false));
  307                                      break;
  308                                 de fault:
  309                                      break;
  310                             }
  311  
  312                             //Init ial List w ith Filter s defined  above. 
  313                             //var  ppmsProvid erServices List = pro vServices. ToList();
  314                              */
  315  
  316                             //If t here are m ore than 6 25 results  inside th e bounds s ort down t o the clos est 625 in side Radiu s zone.
  317                             if (pp msProvider ServicesLi st.Count >  625)
  318                             {
  319                                 va r provServ icesDistan ces = ppms ProviderSe rvicesList
  320                                      .Select( psr => new  ProviderI nRadius
  321                                      {
  322                                          Prov iderServic e = psr,
  323                                          Dist ance = Dis tanceCalc. GetDistanc e(startLat itude, sta rtLongitud e
  324                                       , Conve rt.ToDoubl e(psr.ppms _latitude) , Convert. ToDouble(p sr.ppms_lo ngitude))
  325                                      }).AsEnu merable();
  326  
  327                                 // Add Provid ers to new  list whic h meet the  Radius cr iteria and  Order by  Distance. 
  328                                 pp msProvider ServicesLi st = provS ervicesDis tances.Whe re(psr =>  psr.Distan ce <= radi us).OrderB y(psr => p sr.Distanc e).Take(ma xResults). Select(x = > x.Provid erService) .ToList();
  329                             }
  330  
  331                             if (pp msProvider ServicesLi st.Count >  0)
  332                             {
  333                                 va r provLoca torList =  new List<P roviderLoc atorResult >();
  334                                 
  335                                 // Split up i nto separa te lists o f max 625  for the Di stance Mat rix Reques t.
  336                                 // If adding  a Start ti me the max  # in a re quest is 1 00
  337                                 // var ppmsPr oviderServ icesParsed  = ppmsPro viderServi ces.Select ((x, i) =>  new { Ind ex = i, Va lue = x }) .GroupBy(x  => x.Inde x / 100).S elect(x =>  x.Select( v => v.Val ue).ToList ()).ToList ();
  338                                 us ing (var c lient = ne w HttpClie nt())
  339                                 {
  340                                      var orig ins = new  List<Model s.Distance MatrixRequ est.Origin >();
  341                                      var orig in = new M odels.Dist anceMatrix Request.Or igin() { l atitude =  startLatit ude, longi tude = sta rtLongitud e };
  342                                      origins. Add(origin );
  343                                      var dest inations =  new List< Models.Dis tanceMatri xRequest.D estination >();
  344                                      foreach  (ppms_prov iderservic e ppmsProv iderServic e in ppmsP roviderSer vicesList)
  345                                      {
  346                                          doub le latitud e = Conver t.ToDouble (ppmsProvi derService .ppms_lati tude);
  347                                          doub le longitu de = Conve rt.ToDoubl e(ppmsProv iderServic e.ppms_lon gitude);
  348                                          var  destinatio n = new Mo dels.Dista nceMatrixR equest.Des tination()  { latitud e = latitu de, longit ude = long itude };
  349                                          dest inations.A dd(destina tion);
  350                                      }
  351  
  352                                      //Create  Request C ontent Obj ecet
  353                                      var dist anceMatrix RequestCon tent = new  Models.Di stanceMatr ixRequest. RootObject ()
  354                                      {
  355                                          orig ins = orig ins,
  356                                          dest inations =  destinati ons,
  357                                          time Units = "m inutes",
  358                                          trav elMode = " driving",
  359                                          dist anceUnits  = "mile"                                     
  360                                      };
  361                                      //Can on ly optimiz e with tra ffic if to tal result s is 10 or  less. 
  362                                      if(ppmsP roviderSer vicesList. Count <= 1 0) { dista nceMatrixR equestCont ent.StartT ime = Date Time.Now.T oString();  }
  363  
  364                                      //Serial ize Conten t to Json
  365                                      //var co ntent = Js onConvert. SerializeO bject(dist anceMatrix RequestCon tent);
  366                                      MediaTyp eFormatter  jsonForma tter = new  JsonMedia TypeFormat ter();
  367                                      HttpCont ent httpCo ntent = ne w ObjectCo ntent<Mode ls.Distanc eMatrixReq uest.RootO bject>(dis tanceMatri xRequestCo ntent, jso nFormatter );
  368                                      var dist anceMatrix PostUrl =  String.For mat("https ://dev.vir tualearth. net/REST/v 1/Routes/D istanceMat rix?key={0 }",key);
  369                                      httpCont ent.Header s.ContentT ype.MediaT ype = ("ap plication/ json");
  370                                      var matr ixRequest  = new Http RequestMes sage()
  371                                      {
  372                                          Requ estUri = n ew Uri(dis tanceMatri xPostUrl),
  373                                          Meth od = HttpM ethod.Post ,
  374                                          Cont ent = http Content
  375                                      };
  376                                      //matrix Request.He aders.Add( "Content-T ype", "app lication/j son");
  377                                      HttpResp onseMessag e response Content =  client.Sen dAsync(mat rixRequest ).Result;
  378  
  379                                      var json  = respons eContent.C ontent.Rea dAsStringA sync().Res ult;
  380  
  381                                      var matr ixResponse  = JsonCon vert.Deser ializeObje ct<Models. DistanceMa trixRespon se.RootObj ect>(json) ;
  382                                      if (matr ixResponse  != null & &
  383                                      matrixRe sponse.res ourceSets  != null &&
  384                                      matrixRe sponse.res ourceSets. Count > 0  &&
  385                                      matrixRe sponse.res ourceSets[ 0].resourc es != null  &&
  386                                      matrixRe sponse.res ourceSets[ 0].resourc es.Count >  0)
  387                                      {
  388                                          var  travelTime sDistances  = matrixR esponse.re sourceSets [0].resour ces[0].res ults;
  389  
  390                                          for  (var i = 0 ; i < trav elTimesDis tances.Cou nt; i++)
  391                                          {
  392                                              
  393                                               //Only do  mapping if  the Provi der Servic e falls wi thin Radiu s & DriveT ime
  394                                               if (travel TimesDista nces[i].tr avelDistan ce <= radi us && trav elTimesDis tances[i]. travelDura tion <= dr iveTime)
  395                                               {
  396                                                   var pr ovLocatorR esult = ne w Provider LocatorRes ult();
  397                                                   provLo catorResul t.Miles =  travelTime sDistances [i].travel Distance;
  398                                                   provLo catorResul t.Minutes  = travelTi mesDistanc es[i].trav elDuration ;
  399                                                   provLo catorResul t.Provider Name = ppm sProviderS ervicesLis t[i].ppms_ providerna me;
  400                                                   provLo catorResul t.Provider Specialty  = ppmsProv iderServic esList[i]. ppms_speci altynamete xt;
  401                                                   provLo catorResul t.Specialt yCode = pp msProvider ServicesLi st[i].ppms _specialty code;
  402                                                   provLo catorResul t.Provider Identifier  = ppmsPro viderServi cesList[i] .ppms_prov ideridenti fer;
  403                                                   provLo catorResul t.WorkHour s = ppmsPr oviderServ icesList[i ].ppms_wor khours;
  404  
  405                                                   if (pp msProvider ServicesLi st[i].ppms _qualityra nkingtotal score != n ull)
  406                                                   {
  407                                                       pr ovLocatorR esult.Qual ityRanking  = (int)pp msProvider ServicesLi st[i].ppms _qualityra nkingtotal score;
  408                                                   }
  409                                                   provLo catorResul t.Latitude  = Convert .ToDouble( ppmsProvid erServices List[i].pp ms_latitud e);
  410                                                   provLo catorResul t.Longitud e = Conver t.ToDouble (ppmsProvi derService sList[i].p pms_longit ude);
  411                                                   if (pp msProvider ServicesLi st[i].ppms _caresite  != null)
  412                                                   {
  413                                                       pr ovLocatorR esult.Care Site =
  414                                                            ppmsProv iderServic esList[i]. ppms_cares ite.Name;
  415                                                       va r careSite  = context .ppms_care siteSet.Fi rst(
  416                                                            c => c.I d == ppmsP roviderSer vicesList[ i].ppms_ca resite.Id) ;
  417                                                       pr ovLocatorR esult.Care SitePhoneN umber = ca reSite.ppm s_mainsite phone;
  418                                                   }
  419  
  420                                                   provLo catorResul t.CareSite Address =  ppmsProvid erServices List[i].pp ms_caresit eaddress +  ' ' + ppm sProviderS ervicesLis t[i].ppms_ caresiteci ty + ',' +  ' ' +
  421                                                       pp msProvider ServicesLi st[i].ppms _caresites tateprovin ce + ' ' +  ppmsProvi derService sList[i].p pms_caresi tezipcode;
  422                                                   //Gend er
  423                                                   if (pp msProvider ServicesLi st[i].ppms _providerg ender != n ull)
  424                                                       sw itch (ppms ProviderSe rvicesList [i].ppms_p rovidergen der.Value)
  425                                                       {
  426                                                            case (in t)ppms_Gen der.Male:
  427                                                                prov LocatorRes ult.Provid erGender =  ProviderG ender.Male ;
  428                                                                brea k;
  429                                                            case (in t)ppms_Gen der.Female :
  430                                                                prov LocatorRes ult.Provid erGender =  ProviderG ender.Fema le;
  431                                                                brea k;
  432                                                            case (in t)ppms_Gen der.NotSpe cified:
  433                                                                prov LocatorRes ult.Provid erGender =  ProviderG ender.NotS pecified;
  434                                                                brea k;
  435                                                            case (in t)ppms_Gen der.Other:
  436                                                                prov LocatorRes ult.Provid erGender =  ProviderG ender.Othe r;
  437                                                                brea k;
  438                                                       }
  439  
  440                                                   if (pp msProvider ServicesLi st[i].ppms _qualityra nkingtotal score != n ull)
  441                                                       pr ovLocatorR esult.Qual ityRanking  = (int)pp msProvider ServicesLi st[i].ppms _qualityra nkingtotal score;
  442                                                   if (pp msProvider ServicesLi st[i].ppms _network ! = null)
  443                                                   {
  444                                                       pr ovLocatorR esult.Prov iderNetwor k = ppmsPr oviderServ icesList[i ].ppms_net work.Name;
  445                                                       va r provNetw ork = Netw orkIds.Get Network(pp msProvider ServicesLi st[i].ppms _network.I d);
  446                                                       pr ovLocatorR esult.Netw orkId = pr ovNetwork. Number;
  447                                                   }
  448                                                   if (pp msProvider ServicesLi st[i].ppms _provideri sprimaryca re != null )
  449                                                       pr ovLocatorR esult.Prov iderPrimar yCare = pp msProvider ServicesLi st[i].ppms _provideri sprimaryca re.Value;
  450                                                   if (pp msProvider ServicesLi st[i].ppms _providera cceptingne wpatients  != null)
  451                                                       pr ovLocatorR esult.Prov iderAccept ingNewPati ents = ppm sProviderS ervicesLis t[i].ppms_ providerac ceptingnew patients.V alue;
  452                                                   provLo catorList. Add(provLo catorResul t);
  453                                               }
  454                                          }
  455                                      }
  456                                 }
  457  
  458                                 // Sort the R esults on  Distance a scending.
  459                                 pr ovLocatorL ist.Sort(( x, y) => x .Miles.Com pareTo(y.M iles));
  460                                 // Return the  Results
  461                                 re turn Reque st.CreateR esponse(pr ovLocatorL ist);
  462  
  463                             }
  464                             var me ssage = st ring.Forma t("No Prov iders foun d based on  Address,  Radius and  Filter Cr iteria giv en");
  465                             HttpEr ror err =  new HttpEr ror(messag e);
  466                             return  Request.C reateError Response(H ttpStatusC ode.NotFou nd, err);
  467                         }
  468                    }
  469                    var  geoCodeErr orMessage  = string.F ormat("Una ble to Geo code the g iven addre ss");
  470                    Http Error geoE rr = new H ttpError(g eoCodeErro rMessage);
  471                    retu rn Request .CreateErr orResponse (HttpStatu sCode.NotF ound, geoE rr);
  472                }
  473           }
  474  
  475           
  476  
  477  
  478  
  479  
  480  
  481  
  482  
  483  
  484           pu blic stati c class Di stanceCalc
  485           {
  486                public s tatic bool  IsInRadiu s(double l at1, doubl e lon1, do uble lat2,  double lo n2, double  radius)
  487                {
  488                    var  R = 6372.8 ; // In ki lometers
  489                    var  dLat = toR adians(lat 2 - lat1);
  490                    var  dLon = toR adians(lon 2 - lon1);
  491                    lat1  = toRadia ns(lat1);
  492                    lat2  = toRadia ns(lat2);
  493  
  494                    var  a = Math.S in(dLat /  2) * Math. Sin(dLat /  2) + Math .Sin(dLon  / 2) * Mat h.Sin(dLon  / 2) * Ma th.Cos(lat 1) * Math. Cos(lat2);
  495                    var  c = 2 * Ma th.Asin(Ma th.Sqrt(a) );
  496                    var  distance =  R * 2 * M ath.Asin(M ath.Sqrt(a ));
  497                    if ( distance < = radius)
  498                    {
  499                         return tru e;
  500                    }
  501                    retu rn false;
  502                }
  503  
  504                public s tatic doub le GetDist ance(doubl e lat1, do uble lon1,  double la t2, double  lon2)
  505                {
  506                    var  R = 6372.8 ; // In ki lometers
  507                    var  dLat = toR adians(lat 2 - lat1);
  508                    var  dLon = toR adians(lon 2 - lon1);
  509                    lat1  = toRadia ns(lat1);
  510                    lat2  = toRadia ns(lat2);
  511                    var  a = Math.S in(dLat /  2) * Math. Sin(dLat /  2) + Math .Sin(dLon  / 2) * Mat h.Sin(dLon  / 2) * Ma th.Cos(lat 1) * Math. Cos(lat2);
  512                    var  c = 2 * Ma th.Asin(Ma th.Sqrt(a) );
  513                    var  distance =  R * 2 * M ath.Asin(M ath.Sqrt(a ));
  514                    retu rn distanc e;
  515                }
  516  
  517                public s tatic ppms _providers ervice Ret urnInRadiu s(ppms_pro viderservi ce provSer vice, doub le lat1, d ouble lon1 , int radi us)
  518                {
  519                    doub le lat2 =  Convert.To Double(pro vService.p pms_latitu de);
  520                    doub le lon2 =  Convert.To Double(pro vService.p pms_longit ude);
  521                    var  R = 6372.8 ; // In ki lometers
  522                    var  dLat = toR adians(lat 2 - lat1);
  523                    var  dLon = toR adians(lon 2 - lon1);
  524                    lat1  = toRadia ns(lat1);
  525                    lat2  = toRadia ns(lat2);
  526  
  527                    var  a = Math.S in(dLat /  2) * Math. Sin(dLat /  2) + Math .Sin(dLon  / 2) * Mat h.Sin(dLon  / 2) * Ma th.Cos(lat 1) * Math. Cos(lat2);
  528                    var  c = 2 * Ma th.Asin(Ma th.Sqrt(a) );
  529                    var  distance =  R * 2 * M ath.Asin(M ath.Sqrt(a ));
  530                    prov Service.pp ms_distanc e = distan ce;
  531                    if ( distance < = radius)
  532                    {
  533                         return pro vService;
  534                    }
  535                    retu rn null;
  536                }
  537  
  538                public s tatic doub le toRadia ns(double  angle)
  539                {
  540                    retu rn Math.PI  * angle /  180.0;
  541                }
  542  
  543  
  544                public s tatic Coor dinate get Bounds(dou ble lat1,  double lon 1, double  brng, doub le dist)
  545                {
  546                    var  a = 637813 7;
  547                    var  b = 635675 2.3142;
  548                    var  f = 1 / 29 8.25722356 3; // WGS- 84 ellipsi od
  549                    var  s = dist;
  550                    var  alpha1 = t oRad(brng) ;
  551                    var  sinAlpha1  = Math.Sin (alpha1);
  552                    var  cosAlpha1  = Math.Cos (alpha1);
  553                    var  tanU1 = (1  - f) * Ma th.Tan(toR ad(lat1));
  554                    var  cosU1 = 1  / Math.Sqr t((1 + tan U1 * tanU1 ));
  555                    var  sinU1 = ta nU1 * cosU 1;
  556                    var  sigma1 = M ath.Atan2( tanU1, cos Alpha1);
  557                    var  sinAlpha =  cosU1 * s inAlpha1;
  558                    var  cosSqAlpha  = 1 - sin Alpha * si nAlpha;
  559                    var  uSq = cosS qAlpha * ( a * a - b  * b) / (b  * b);
  560                    var  A = 1 + uS q / 16384  * (4096 +  uSq * (-76 8 + uSq *  (320 - 175  * uSq)));
  561                    var  B = uSq /  1024 * (25 6 + uSq *  (-128 + uS q * (74 -  47 * uSq)) );
  562                    var  sigma = s  / (b * A);
  563                    var  sigmaP = 2  * Math.PI ;
  564                    doub le sinSigm a = 0;
  565                    doub le cosSigm a = 0;
  566                    doub le cos2Sig maM = 0;
  567                    whil e (Math.Ab s(sigma -  sigmaP) >  1e-12)
  568                    {
  569                         cos2SigmaM  = Math.Co s(2 * sigm a1 + sigma );
  570                         sinSigma =  Math.Sin( sigma);
  571                         cosSigma =  Math.Cos( sigma);
  572                         var deltaS igma = B *  sinSigma  * (cos2Sig maM + B /  4 * (cosSi gma * (-1  + 2 * cos2 SigmaM * c os2SigmaM)  - B / 6 *  cos2Sigma M * (-3 +  4 * sinSig ma * sinSi gma) * (-3  + 4 * cos 2SigmaM *  cos2SigmaM )));
  573                         sigmaP = s igma;
  574                         sigma = s  / (b * A)  + deltaSig ma;
  575                    };
  576                    var  tmp = sinU 1 * sinSig ma - cosU1  * cosSigm a * cosAlp ha1;
  577                    var  lat2 = Mat h.Atan2(si nU1 * cosS igma + cos U1 * sinSi gma * cosA lpha1, (1  - f) * Mat h.Sqrt(sin Alpha * si nAlpha + t mp * tmp)) ;
  578                    var  lambda = M ath.Atan2( sinSigma *  sinAlpha1 , cosU1 *  cosSigma -  sinU1 * s inSigma *  cosAlpha1) ;
  579                    var  C = f / 16  * cosSqAl pha * (4 +  f * (4 -  3 * cosSqA lpha));
  580                    var  L = lambda  - (1 - C)  * f * sin Alpha * (s igma + C *  sinSigma  * (cos2Sig maM + C *  cosSigma *  (-1 + 2 *  cos2Sigma M * cos2Si gmaM)));
  581                    var  revAz = Ma th.Atan2(s inAlpha, - tmp); // f inal beari ng
  582  
  583                    var  latitude =  toDeg(lat 2);
  584                    var  longitude  = lon1 + t oDeg(L);
  585                    retu rn new Coo rdinate(la titude, lo ngitude);
  586                }
  587                public s tatic doub le toRad(d ouble n)
  588                {
  589                    retu rn n * Mat h.PI / 180 ;
  590                }
  591                public s tatic doub le toDeg(d ouble n)
  592                {
  593                    retu rn n * 180  / Math.PI ;
  594                }
  595           }
  596  
  597           pu blic class  ProviderI nRadius
  598           {
  599                public p pms_provid erservice  ProviderSe rvice { ge t; set; }
  600                public d ouble Dist ance { get ; set; }
  601           }
  602  
  603  
  604           /*
  605           [H ttpGet]
  606           [M apToApiVer sion("1.0" )]
  607           [R esponseTyp e(typeof(C oordinates ))]
  608           [O DataRoute( "Geocode") ]
  609           pu blic async  Task<Http ResponseMe ssage> Geo code([From ODataUri]  string add ress)
  610           {
  611                using (v ar context  = new Ppm sContext(a wait PpmsC ontextHelp er.GetProx y()))
  612                {
  613                    stri ng key = C onfigurati onManager. AppSetting s["BingMap sKey"];
  614                    var  request =  new Geocod eRequest()
  615                    {
  616                         Query = ad dress,
  617                         IncludeIso 2 = true,
  618                         IncludeNei ghborhood  = true,
  619                         MaxResults  = 25,
  620                         BingMapsKe y = key
  621                    };
  622  
  623                    //Pr ocess the  request by  using the  ServiceMa nager.
  624                    var  response =  await Ser viceManage r.GetRespo nseAsync(r equest);
  625  
  626                    if ( response ! = null &&
  627                         response.R esourceSet s != null  &&
  628                         response.R esourceSet s.Length >  0 &&
  629                         response.R esourceSet s[0].Resou rces != nu ll &&
  630                         response.R esourceSet s[0].Resou rces.Lengt h > 0)
  631                    {
  632                         var result  = respons e.Resource Sets[0].Re sources[0]  as Locati on;
  633                         if (result  != null)
  634                         {
  635                             double  latitude  = result.P oint.Coord inates[0];
  636                             double  longitude  = result. Point.Coor dinates[1] ;
  637                             var co ordinate =  new GeoCo ordinate(l atitude, l ongitude);
  638  
  639  
  640                             //Map  the Lat, L ong, and c oordinate  to Coordin ates Class
  641                             var co ordinates  = new Coor dinates();
  642                             coordi nates.Lati tude = lat itude;
  643                             coordi nates.Long itude = lo ngitude;
  644                             coordi nates.Coor dinate = c oordinate;
  645  
  646                             //Retr un the Coo rdinates
  647                             return  Request.C reateRespo nse(coordi nates);
  648                         }
  649                    }
  650  
  651                    var  message =  string.For mat("Unabl e to Geoco de the giv en address .");
  652                    Http Error err  = new Http Error(mess age);
  653                    retu rn Request .CreateErr orResponse (HttpStatu sCode.NotF ound, err) ;
  654                }
  655           }
  656  
  657           [H ttpGet]
  658           [M apToApiVer sion("1.0" )]
  659           [R esponseTyp e(typeof(A ddressData ))]
  660           [O DataRoute( "ValidateA ddress")]       
  661           pu blic async  Task<Http ResponseMe ssage> Val idateAddre ss([FromOD ataUri] st ring stree tAddress,  [FromOData Uri] strin g city, [F romODataUr i] string  state, [Fr omODataUri ] string z ip)
  662           {
  663                ServiceP ointManage r.ServerCe rtificateV alidationC allback +=  (sender,  certificat e, chain,  sslPolicyE rrors) =>  true;
  664                ServiceP ointManage r.Security Protocol =  SecurityP rotocolTyp e.Tls12;
  665                try
  666                {
  667                    //Th is Control ler Action  called th e Address  Validation  API from  Vets360
  668                    usin g (var cli ent = GetH ttpClient( ))
  669                    {
  670                          client.Bas eAddress =  new Uri(" https:// DNS . URL ");
  671                          //client.B aseAddress  = new Uri ("https:// DNS . URL ");
  672  
  673                         var payloa d = new Ro otObjectRe quest
  674                         {
  675                             reques tAddress =  new Model s.Address
  676                             {
  677                                 ad dressLine1  = streetA ddress,
  678                                 ci ty = city,
  679                                 st ateProvinc e = new St ateProvinc e
  680                                 {
  681                                      name = s tate
  682                                 },
  683                                 zi pCode5 = z ip
  684                             }
  685                         };
  686  
  687                         var json =  Serialize e(payload) ;
  688  
  689                         var conten t = new St ringConten t(json, En coding.UTF 8, "applic ation/json ");
  690                         content.He aders.Cont entType =  new MediaT ypeHeaderV alue("appl ication/js on");
  691  
  692                         var respon se = clien t.PostAsyn c("/addres s-validati on/address /v1/valida te", conte nt).GetAwa iter().Get Result();
  693  
  694                         if (respon se.IsSucce ssStatusCo de)
  695                         {
  696                             var re sult = res ponse.Cont ent.ReadAs StringAsyn c().GetAwa iter().Get Result();
  697                             if (st ring.IsNul lOrEmpty(r esult))
  698                             {
  699                                 //
  700                             }
  701                             else
  702                             {
  703                                 va r addressV alidationR esult = De serialize< RootObject Response>( result);
  704                                 va r addressD ata = awai t AddressD ataMap.Map AddressDat a(addressV alidationR esult);
  705                                 re turn Reque st.CreateR esponse(ad dressData) ;
  706                             }
  707                         }
  708                         var addres sValidatio nError = s tring.Form at("Addres s Validati on Unsucce ssful: " +  response. StatusCode .ToString( ));
  709                         HttpError  addErr = n ew HttpErr or(address Validation Error);
  710                         return Req uest.Creat eErrorResp onse(HttpS tatusCode. NotFound,  addErr);
  711  
  712                    }
  713                }
  714                catch (W ebExceptio n we)
  715                {
  716                    var  addressVal idationErr or = we.To String();                
  717                    Http Error addE rr = new H ttpError(a ddressVali dationErro r);
  718                    retu rn Request .CreateErr orResponse (HttpStatu sCode.NotF ound, addE rr);
  719                 
  720                }
  721                catch (H ttpRequest Exception  he)
  722                {
  723                    var  addressVal idationErr or = he.To String();
  724                    Http Error addE rr = new H ttpError(a ddressVali dationErro r);
  725                    retu rn Request .CreateErr orResponse (HttpStatu sCode.NotF ound, addE rr);
  726                }
  727                catch (E xception e )
  728                {
  729                    var  addressVal idationErr or = e.ToS tring();                 
  730                    Http Error addE rr = new H ttpError(a ddressVali dationErro r);
  731                    retu rn Request .CreateErr orResponse (HttpStatu sCode.NotF ound, addE rr);
  732                }
  733                
  734  
  735           }
  736           */
  737  
  738  
  739           /*
  740           pu blic stati c string S erializee< T>(T data)
  741           {
  742                var ms =  new Memor yStream();
  743                var ser  = new Data ContractJs onSerializ er(typeof( T));
  744                ser.Writ eObject(ms , data);
  745                var json  = ms.ToAr ray();
  746                ms.Close ();
  747  
  748                return E ncoding.UT F8.GetStri ng(json, 0 , json.Len gth);
  749           }
  750  
  751           pu blic stati c T Deseri alize<T>(s tring json )
  752           {
  753                var ms =  new Memor yStream(En coding.UTF 8.GetBytes (json));
  754                var ser  = new Data ContractJs onSerializ er(typeof( T));
  755                var resu lt = (T)se r.ReadObje ct(ms);
  756                ms.Close ();
  757  
  758                return r esult;
  759           }
  760  
  761           pr ivate stat ic HttpCli ent GetHtt pClient()
  762           {
  763                var clie ntHandler  = new WebR equestHand ler();
  764                clientHa ndler.Clie ntCertific ates.Add(G etCertKeyV ault());
  765                //client Handler.Cl ientCertif icates.Add (GetLocalC ert());
  766                return n ew HttpCli ent(client Handler);
  767           }
  768  
  769           pu blic stati c X509Cert ificate2 G etLocalCer t()
  770           {
  771                var stor e = new X5 09Store(St oreName.My , StoreLoc ation.Loca lMachine);
  772                store.Op en(OpenFla gs.OpenExi stingOnly  | OpenFlag s.ReadOnly );
  773                  string cer tificateSu bjectName  = "CN=dws. DNS . URL , OU=PPMS,  O=VA, L=W ashington,  S=DC, C=U S";
  774                var cert  = store.C ertificate s.Find(X50 9FindType. FindBySubj ectDisting uishedName , certific ateSubject Name, true );
  775                if (cert .Count < 1 )
  776                {
  777                    thro w new Exce ption(stri ng.Format( "Could not  find a va lid client  certifica te with su bject {0}" , certific ateSubject Name));
  778                }
  779                return c ert[0];
  780           }
  781  
  782           pr ivate stat ic X509Cer tificate2  GetCertKey Vault()
  783           {
  784                const st ring appId  = "b39bbc 92-24f7-4c 26-961f-fa e26b9290bb ";
  785                const st ring secre t = "wgnf5 EwiMkDQG37 9L031MLpGm xli+1WHtSd qGuGXGMs=" ;
  786                const st ring tenan tId = "f7c 49e36-971b -42c7-b244 -a88eed6c0 bf6";
  787                //const  string cer tUri = "ht tps://vanp eastppmskv 1.vault.us govcloudap i.net/cert ificates/n p-dws-ppms -va-gov-ss lcert/716e 28540d3e45 2d9ed47cf4 053bb790";
  788                const st ring certU ri = "http s://vanpea stppmskv1. vault.usgo vcloudapi. net/certif icates/np- dws-ppms-n prod/ca92b a8988c64a6 091d23c6ad bdf1f1a";
  789  
  790                var toke n = GetTok en(appId,  secret, te nantId);
  791                var cert  = GetCert ificateFro mKeyVault( token.acce ss_token,  certUri);
  792                var priv ateKey = G etPrivateK eyKeyVault (token.acc ess_token,  cert.sid) ;
  793  
  794                //return  new X509C ertificate 2(privateK ey, (strin g)null);
  795                return n ew X509Cer tificate2( privateKey , (string) null, X509 KeyStorage Flags.Mach ineKeySet  | X509KeyS torageFlag s.PersistK eySet | X5 09KeyStora geFlags.Ex portable);
  796           }
  797  
  798  
  799           pr ivate stat ic TokenRe sponse Get Token(stri ng clientI d, string  clientSecr et, string  tenantId)
  800           {
  801                using (v ar httpCli ent = new  HttpClient ())
  802                {
  803                    var  formConten t = new Fo rmUrlEncod edContent( new[]
  804                    {
  805                         new KeyVal uePair<str ing, strin g>("resour ce", "http s://vault. usgovcloud api.net"),
  806                         new KeyVal uePair<str ing, strin g>("client _id", clie ntId),
  807                         new KeyVal uePair<str ing, strin g>("client _secret",  clientSecr et),
  808                         new KeyVal uePair<str ing, strin g>("grant_ type", "cl ient_crede ntials")
  809                    });
  810  
  811                    var  response =  httpClien t.PostAsyn c("https:/ /login.win dows.net/"  + tenantI d + "/oaut h2/token",  formConte nt).GetAwa iter().Get Result();
  812  
  813                    retu rn Deseria lize<Token Response>( response.C ontent.Rea dAsStringA sync().Res ult);
  814                }
  815           }
  816  
  817           pu blic stati c Certific ateRespons e GetCerti ficateFrom KeyVault(s tring toke n, string  certificat eUrl)
  818           {
  819                using (v ar httpCli ent = new  HttpClient ())
  820                {
  821                    var  request =  new HttpRe questMessa ge(HttpMet hod.Get, n ew Uri(cer tificateUr l + "?api- version=20 16-10-01") );
  822                    requ est.Header s.Authoriz ation = ne w Authenti cationHead erValue("B earer", to ken);
  823  
  824                    var  response =  httpClien t.SendAsyn c(request) .GetAwaite r().GetRes ult();
  825  
  826                    retu rn Deseria lize<Certi ficateResp onse>(resp onse.Conte nt.ReadAsS tringAsync ().GetAwai ter().GetR esult());
  827                }
  828           }
  829  
  830           pu blic stati c byte[] G etPrivateK eyKeyVault (string to ken, strin g certific ateUrl)
  831           {
  832                using (v ar httpCli ent = new  HttpClient ())
  833                {
  834                    var  request =  new HttpRe questMessa ge(HttpMet hod.Get, n ew Uri(cer tificateUr l + "?api- version=20 16-10-01") );
  835                    requ est.Header s.Authoriz ation = ne w Authenti cationHead erValue("B earer", to ken);
  836                    var  response =  httpClien t.SendAsyn c(request) .GetAwaite r().GetRes ult();
  837                    var  privateKey  = Deseria lize<Priva teKeyRespo nse>(respo nse.Conten t.ReadAsSt ringAsync( ).GetAwait er().GetRe sult());
  838                    retu rn Convert .FromBase6 4String(pr ivateKey.v alue);
  839                }
  840           }
  841  
  842  
  843       }
  844  
  845       public  class Tok enResponse
  846       {
  847           pu blic strin g token_ty pe { get;  set; }
  848           pu blic strin g expires_ in { get;  set; }
  849           pu blic strin g ext_expi res_in { g et; set; }
  850           pu blic strin g expires_ on { get;  set; }
  851           pu blic strin g not_befo re { get;  set; }
  852           pu blic strin g resource  { get; se t; }
  853           pu blic strin g access_t oken { get ; set; }
  854       }
  855  
  856       public  class Cer tificateRe sponse
  857       {
  858           pu blic strin g id { get ; set; }
  859           pu blic strin g kid { ge t; set; }
  860           pu blic strin g sid { ge t; set; }
  861           pu blic strin g x5t { ge t; set; }
  862           pu blic strin g cer { ge t; set; }
  863       }
  864  
  865       public  class Pri vateKeyRes ponse
  866       {
  867           pu blic strin g value {  get; set;  }
  868       }
  869       */
  870  
  871  
  872  
  873  
  874       }
  875   }