61. EPMO Open Source Coordination Office Redaction File Detail Report

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

61.1 Files compared

# Location File Last Modified
1 CIF B10S2.zip\CIF B10S2\VA.PPMS.IWS\VA.PPMS.IWS\VA.PPMS.IWS.CreateResponseService CreateResponseService.cs Thu Jan 3 20:21:46 2019 UTC
2 CIF B10S2.zip\CIF B10S2\VA.PPMS.IWS\VA.PPMS.IWS\VA.PPMS.IWS.CreateResponseService CreateResponseService.cs Fri Feb 8 15:00:24 2019 UTC

61.2 Comparison summary

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

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

61.4 Active regular expressions

No regular expressions were active.

61.5 Comparison detail

  1   using Hl7. Fhir.Model ;
  2   using Hl7. Fhir.Seria lization;
  3   using log4 net;
  4   using Micr osoft.Azur e.KeyVault ;
  5   using Micr osoft.Iden tityModel. Clients.Ac tiveDirect ory;
  6   using Micr osoft.Xrm. Sdk;
  7   using Syst em;
  8   using Syst em.Collect ions.Gener ic;
  9   using Syst em.IO;
  10   using Syst em.Linq;
  11   using Syst em.Net;
  12   using Syst em.Net.Htt p;
  13   using Syst em.Net.Htt p.Headers;
  14   using Syst em.Securit y.Cryptogr aphy.X509C ertificate s;
  15   using Syst em.Service Model;
  16   using Syst em.Text;
  17   using Syst em.Threadi ng.Tasks;
  18   using VA.P PMS.Contex t;
  19   using VA.P PMS.Contex t.Interfac e;
  20   using VA.P PMS.IWS.Co mmon;
  21   using VA.P PMS.IWS.Cr eateRespon seService. Interface;
  22   using VA.P PMS.IWS.Fu nctions.Co nfiguratio n.Interfac e;
  23   using VA.P PMS.IWS.Qu eueService .Interface ;
  24   using VA.P PMS.Provid erData;
  25  
  26   namespace  VA.PPMS.IW S.CreateRe sponseServ ice
  27   {
  28       public  class Cre ateRespons eService :  ICreateRe sponseServ ice
  29       {
  30           pr ivate read only ILog  _logger;
  31           pr ivate read only IIwsC onfigurati on _config uration;
  32           pr ivate read only IQueu eService _ queueServi ce;
  33           pr ivate read only IPpms Helper _pp msHelper;
  34           pr ivate read only IPpms ContextHel per _conte xtHelper;
  35  
  36           pu blic Creat eResponseS ervice(ILo g logger,  IIwsConfig uration co nfiguratio n, IQueueS ervice que ueService,  IPpmsHelp er ppmsHel per, IPpms ContextHel per contex tHelper)
  37           {
  38                _logger  = logger;
  39                _configu ration = c onfigurati on;
  40                _queueSe rvice = qu eueService ;
  41                _ppmsHel per = ppms Helper;
  42                _context Helper = c ontextHelp er;
  43           }
  44  
  45           pu blic async  Task<stri ng> Create Response(D asMessage  message)
  46           {
  47                _logger. Info($"@@@ @ INFO - S tart Creat eResponseS ervice.Cre ateRespons e @@@@");
  48  
  49                try
  50                {
  51                    var  batchId =  Utilities. ValidateGu id(message .Content);
  52                    if ( string.IsN ullOrEmpty (batchId))
  53                    {
  54                         _logger.In fo($"@@@@  INFO - Bat ch ID not  provided f or BatchId : {batchId } @@@@");
  55                         throw new  PpmsServic eException ($"CreateR esponseSer vice.Creat eResponse  - Batch ID  not provi ded for Ba tch {messa ge.Transac tionId}.") ;
  56                    }
  57  
  58                    // C reate XML  response f ile
  59                    var  response =  await Cre ateRespons eDocument( message);
  60  
  61                    _log ger.Info($ "@@@@ INFO  - End Mai n Create R esponse Se rvice for  BatchId: { batchId} @ @@@");
  62  
  63                    retu rn respons e;
  64                }
  65                catch (E xception e x)
  66                {
  67                    _log ger.Error( $"@@@@ ERR OR - There  was a pro blem with  the Create ResponseSe rvice. @@@ @", ex);
  68                    thro w new Ppms ServiceExc eption($"T here was a  problem w ith the Cr eateRespon seService. ", ex);
  69                }
  70           }
  71  
  72           pu blic async  Task<stri ng> Create ProviderPa yload(DasM essage mes sage)
  73           {
  74                _logger. Info($"@@@ @ INFO - S tart Creat eResponseS ervice.Cre ateProvide rPayload @ @@@");
  75  
  76                try
  77                {
  78                    // C reate XML  response f ile
  79                    var  response =  await Cre ateProvide rXmlDoc(me ssage);
  80  
  81                    _log ger.Info($ "@@@@ INFO  - End Mai n Create R esponse Se rvice for  BatchId: { Utilities. ValidateGu id(message .Content)}  @@@@");
  82  
  83                    retu rn respons e;
  84                }
  85                catch (E xception e x)
  86                {
  87                    _log ger.Error( $"@@@@ ERR OR - There  was a pro blem with  the Create ResponseSe rvice @@@@ ", ex);
  88                    thro w new Ppms ServiceExc eption($"T here was a  problem w ith the Cr eateRespon seService. ", ex);
  89                }
  90           }
  91  
  92           pu blic async  Task Noti fyOfRespon se(DasMess age messag e)
  93           {
  94                try
  95                {
  96                    // P arse base6 4 string t o extract  guid
  97                    var  shortGuid  = ShortGui d.Parse(me ssage.Cont ent);
  98                    var  batchId =  shortGuid. ToGuid().T oString();
  99  
  100                    var  batch = aw ait GetBat chById(bat chId);
  101                    if ( batch == n ull) throw  new PpmsS erviceExce ption("Una ble to fin d batch re cord.");
  102  
  103                    // R etrieve Re ceiverId f rom associ ated netwo rk
  104                    if ( batch.ppms _vaprovide rnetwork_b atch_netwo rk == null ) throw ne w PpmsServ iceExcepti on("Unable  to determ ine associ ated netwo rk.");
  105  
  106                    // S et header  values
  107                    mess age.Conver sationId =  batch.ppm s_conversa tionid;
  108                    mess age.Receiv erId = bat ch.ppms_va providerne twork_batc h_network. ppms_short hand;
  109  
  110                    // G et URL pat hs from co nfiguratio n
  111                    var  baseUrl =  await _con figuration .GetPpmsRe sponseNoti ficationUr iAsync(mes sage.IsVaR eceiver);
  112                    var  requestUri  = await _ configurat ion.GetPpm sResponseP ostUriAsyn c(message. IsVaReceiv er);
  113  
  114                    _log ger.Info($ "Receiver:  {message. ReceiverId }");
  115                    stri ng result  = "Success ";
  116                    if ( message.Is VaReceiver )
  117                    {
  118                         var payloa d = await  CreateResp onseDocume nt(message );
  119                         //result =  await Pos tXmlToDas( message, p ayload, ba seUrl, req uestUri);
  120                    }
  121                    else
  122                    {
  123                         var docume ntRef = aw ait Create DocumentRe ference(ba tch.ppms_c onversatio nid);
  124                         //result =  await Pos tToDas(mes sage, docu mentRef, b aseUrl, re questUri);
  125                    }
  126  
  127                    var  logId = Ut ilities.Va lidateGuid (message.C ontent);
  128                    _log ger.Info($ "Updating  batch: {lo gId}");
  129  
  130                    if ( !string.Is NullOrEmpt y(result))
  131                    {
  132                         await _ppm sHelper.Up dateBatch( message, $ "Response  notificati on sent: { logId}", ( int)ppms_b atch_Statu sCode.Rece iverNotifi ed);
  133                    }
  134                }
  135                catch (E xception e x)
  136                {
  137                    _log ger.Error( "CreateRes ponseServi ce.NotifyO fResponse:  Unable to  process r esponse.") ;
  138                    thro w new Ppms ServiceExc eption("Cr eateRespon seService. NotifyOfRe sponse: Un able to pr ocess resp onse.", ex );
  139                }
  140           }
  141  
  142           pr ivate asyn c Task<str ing> PostX mlToDas(Da sMessage m essage, st ring xmlCo ntent, str ing baseUr i, string  requestUri )
  143           {
  144                var clie nt = (Http WebRequest )WebReques t.Create($ "{baseUri} {requestUr i}");
  145                client.C ontentType  = "applic ation/xml" ;
  146                client.M ethod = "P OST";
  147                client.A ccept = "a pplication /xml";
  148                // Set D AS headers
  149                client.H eaders.Add ("X-Conver sationID",  message.C onversatio nId);
  150                client.H eaders.Add ("X-Routin gSenderID" , message. SenderId);
  151                client.H eaders.Add ("X-Routin gReceiverI Ds", messa ge.Receive rId);
  152                client.H eaders.Add ("X-Transa ctionID",  message.Tr ansactionI d);
  153  
  154                using (v ar streamW riter = ne w StreamWr iter(clien t.GetReque stStream() ))
  155                {
  156                    stre amWriter.W rite(xmlCo ntent);
  157                    stre amWriter.F lush();
  158                    stre amWriter.C lose();
  159                }
  160  
  161                var http Response =  (HttpWebR esponse)(a wait clien t.GetRespo nseAsync() );
  162                return " Success";
  163  
  164                throw ne w PpmsServ iceExcepti on($"Error  Posting R esponse No tification .");
  165           }
  166  
  167           pr ivate asyn c Task<str ing> PostT oDas(DasMe ssage mess age, Docum entReferen ce content , string b aseUri, st ring reque stUri)
  168           {
  169                using (v ar client  = await Ge tHttpClien t())
  170                {
  171                    clie nt.BaseAdd ress = new  Uri(baseU ri);
  172                    // S et DAS hea ders
  173                    clie nt.Default RequestHea ders.Accep t.Clear();
  174                    clie nt.Default RequestHea ders.Accep t.Add(new  MediaTypeW ithQuality HeaderValu e("applica tion/json+ fhir"));
  175                    clie nt.Default RequestHea ders.Add(" X-Conversa tionID", m essage.Con versationI d);
  176                    clie nt.Default RequestHea ders.Add(" X-RoutingS enderID",  message.Se nderId);
  177                    clie nt.Default RequestHea ders.Add(" X-RoutingR eceiverIDs ", message .ReceiverI d);
  178                    clie nt.Default RequestHea ders.Add(" X-Transact ionID", me ssage.Tran sactionId) ;
  179  
  180                    var  sout = new  FhirJsonS erializer( );
  181                    var  strDocRef  = sout.Ser ializeToSt ring(conte nt);
  182                    var  docRef = n ew StringC ontent(str DocRef, En coding.Def ault, "app lication/j son+fhir") ;
  183  
  184                    docR ef.Headers .ContentTy pe.CharSet  = string. Empty;
  185  
  186                    //va r response  = await c lient.Post Async(requ estUri, ne w ObjectCo ntent(type of(Documen tReference ), content , new NoCh arSetJsonM ediaTypeFo rmatter(),  "applicat ion/json+f hir"));
  187                    var  response =  await cli ent.PostAs ync(reques tUri, docR ef);
  188  
  189                    if ( response.I sSuccessSt atusCode)  return "Su ccess";
  190  
  191                    thro w new Ppms ServiceExc eption($"E rror Posti ng Respons e Notifica tion to DA S. The err or is {res ponse.Stat usCode.ToS tring()}") ;
  192                }
  193           }
  194  
  195           pr ivate asyn c Task<Doc umentRefer ence> Crea teDocument Reference( string con versationI d)
  196           {
  197                // Const ruct call  back URL
  198                //var re ferencePat h = await  _configura tion.GetRe sponseDocu mentRefere nceUrlAsyn c();
  199                var docu mentPath =  await Get DocumentPa th(convers ationId);
  200                var cont ent = new  List<Docum entReferen ce.Content Component>
  201                {
  202                    new  DocumentRe ference.Co ntentCompo nent { Att achment =  new Attach ment { Con tentType =  "applicat ion/xml",  Url = $"{d ocumentPat h}" } }
  203                };
  204  
  205                // Set D ocumentRef erence pro perties
  206                var docR ef = new D ocumentRef erence
  207                {
  208                    Cust odian = ne w Resource Reference( "PPMS"),
  209                    Crea ted = Date Time.Now.T oString("s ", System. Globalizat ion.Cultur eInfo.Inva riantCultu re),
  210                    Inde xed = new  DateTimeOf fset(DateT ime.Now),
  211                    Stat us = Docum entReferen ceStatus.C urrent,
  212                    Cont ent = cont ent
  213                };
  214  
  215                return d ocRef;
  216           }
  217  
  218           pr ivate asyn c Task<str ing> GetDo cumentPath (string co nversation Id)
  219           {
  220                if (stri ng.IsNullO rEmpty(con versationI d))
  221                {
  222                    _log ger.Info($ "@@@@ INFO  - Paramet er invalid  for Conve rsationId  = {convers ationId} @ @@@");
  223                    thro w new Ppms ServiceExc eption("Un able to cr eate docum ent path,  parameter  invalid");
  224                }
  225  
  226                //{ rela tive - pat h}/ Binary  /[documen tURN] ? tr ansactionI D ={ uniqu e ID}
  227                var rela tivePathPa ttern = aw ait _confi guration.G etResponse DocumentPa thPatternA sync();
  228                return s tring.Form at(relativ ePathPatte rn, conver sationId);
  229           }
  230  
  231           pr ivate asyn c Task<ppm s_batch> G etBatchByI d(string b atchId)
  232           {
  233                var cont ext = awai t _context Helper.Get ContextAsy nc();
  234                var batc h = contex t.ppms_bat chSet.Firs tOrDefault (b => b.pp ms_batchId  == new Gu id(batchId ));
  235  
  236                LoadBatc hPropertie s(context,  batch);
  237  
  238                return b atch;
  239           }
  240  
  241           pu blic async  Task<ppms _batch> Ge tBatchByCo nversation Id(string  conversati onId, bool  loadPrope rties = tr ue)
  242           {
  243                var cont ext = awai t _context Helper.Get ContextAsy nc();
  244                var batc h = contex t.ppms_bat chSet.Firs tOrDefault (b => b.pp ms_convers ationid ==  conversat ionId);
  245  
  246                LoadBatc hPropertie s(context,  batch);
  247  
  248                return b atch;
  249           }
  250  
  251           pr ivate void  LoadBatch Properties (PpmsConte xt context , ppms_bat ch batch)
  252           {
  253                if (batc h == null)  throw new  PpmsServi ceExceptio n("Batch r ecord does  not exist ");
  254  
  255                context. LoadProper ty(batch,  new Relati onship("pp ms_batch_b atchdetail _batch"));
  256                context. LoadProper ty(batch,  new Relati onship("pp ms_vaprovi dernetwork _batch_net work"));
  257  
  258                if (batc h.ppms_bat ch_batchde tail_batch  != null)
  259                {
  260                    fore ach (var i tem in bat ch.ppms_ba tch_batchd etail_batc h)
  261                    {
  262                         context.Lo adProperty (item, new  Relations hip("ppms_ batchdetai l_batchdet ailresult" ));
  263                    }
  264                }
  265           }
  266  
  267           pu blic async  Task<stri ng> Create ResponseDo cument(Das Message qu eueMessage )
  268           {
  269                try
  270                {
  271                    if ( string.IsN ullOrEmpty (queueMess age.Conver sationId))
  272                    {
  273                         _logger.In fo($"@@@@  INFO - Par ameter inv alid for i tem @@@@") ;
  274                         return str ing.Empty;
  275                    }
  276  
  277                    var  conversati onId = que ueMessage. Conversati onId;
  278                    var  batch = aw ait GetBat chByConver sationId(c onversatio nId);
  279  
  280                    var  details =  batch.ppms _batch_bat chdetail_b atch;
  281                    IEnu merable<pp ms_batchde tail> ppms Batchdetai ls = detai ls as ppms _batchdeta il[] ?? de tails.ToAr ray();
  282                    if ( !ppmsBatch details.An y())
  283                    {
  284                         _logger.In fo($"@@@@  INFO - Det ails not f ound @@@@" );
  285                         return str ing.Empty;
  286                    }
  287  
  288                    _log ger.Info($ "@@@@ INFO  - Details  found @@@ @");
  289  
  290                    // C reate XML  doc
  291                    var  doc = new  ProviderRe sponses
  292                    {
  293                         ProviderRe sponse = n ew List<Pr oviderResp onse>()
  294                    };
  295  
  296                    // C apture bat ch details
  297                    fore ach (var d etail in p pmsBatchde tails)
  298                    {
  299                         // Provide r node
  300                         var provid er = new P roviderRes ponse
  301                         {
  302                             Provid erId = det ail.ppms_p roviderid,
  303                             Succes s = detail .GetAttrib uteValue<b ool>("ppms _isvalid")
  304                         };
  305  
  306                         // Set cor relation i d, if appr opriate
  307                         if (detail .ppms_prov ider != nu ll)
  308                         {
  309                             provid er.Correla tionId = d etail.ppms _provider. Id.ToStrin g();
  310                         }
  311  
  312                         // Retriev e batch de tail resul ts
  313                         var batchD etailResul ts = detai l.ppms_bat chdetail_b atchdetail result;
  314  
  315                         if (batchD etailResul ts != null )
  316                         {
  317                             // Cap ture batch  detail re sults
  318                             IEnume rable<ppms _batchdeta ilresult>  ppmsBatchd etailresul ts = batch DetailResu lts as ppm s_batchdet ailresult[ ] ?? batch DetailResu lts.ToArra y();
  319                             if (pp msBatchdet ailresults  != null & & ppmsBatc hdetailres ults.Any() )
  320                             {
  321                                 //  Initializ e results  list
  322                                 pr ovider.Res ults = new  Results {  Item = ne w List<Res ult>() };
  323  
  324                                 fo reach (var  detailRes ult in ppm sBatchdeta ilresults)
  325                                 {
  326                                      var resu lt = new R esult
  327                                      {
  328                                          Type  = detailR esult.ppms _entitytyp e,
  329                                          Id =  detailRes ult.ppms_n ame,
  330                                          Succ ess = deta ilResult.p pms_isvali d.HasValue  && detail Result.ppm s_isvalid. Value
  331                                      };
  332  
  333                                      if (resu lt.Type ==  "Provider Service")
  334                                      {
  335                                          resu lt.Correla tionId = d etailResul t.Id.ToStr ing();
  336                                      }
  337  
  338                                      if (!res ult.Succes s)
  339                                      {
  340                                          resu lt.Header  = detailRe sult.ppms_ result;
  341                                          resu lt.Message  = detailR esult.ppms _message;
  342                                      }
  343  
  344                                      provider .Results.I tem.Add(re sult);
  345                                 }
  346                             }
  347                         }
  348  
  349                         // Add to  list of pr oviders
  350                         doc.Provid erResponse .Add(provi der);
  351                    }
  352  
  353                    // C reate resp onse packe t
  354                    var  responseTo Send = awa it Convert ResponseTo Xml(doc);
  355  
  356                    // C lose batch
  357                    awai t _ppmsHel per.Update Batch(queu eMessage,  "CCN Respo nse sent." , (int)ppm s_batch_St atusCode.C omplete);
  358  
  359                    _log ger.Info($ "@@@@ INFO  - Save co mplete @@@ @");
  360  
  361                    retu rn respons eToSend;
  362                }
  363                catch (F aultExcept ion<Organi zationServ iceFault>  ex)
  364                {
  365                    _log ger.Error( $"@@@@ Cre ateRespons eService E RROR - Fau lt: {ex} @ @@@", ex);
  366                    thro w;
  367                }
  368                catch (E xception e x)
  369                {
  370                    _log ger.Error( $"@@@@ Cre ateRespons eService E RROR - Exc eption: {e x} @@@@",  ex);
  371                    thro w;
  372                }
  373           }
  374  
  375           pu blic async  Task<stri ng> Create ProviderXm lDoc(DasMe ssage queu eMessage)
  376           {
  377                try
  378                {
  379                    if ( string.IsN ullOrEmpty (queueMess age.Conten t))
  380                    {
  381                         _logger.In fo($"@@@@  INFO - Bat ch ID not  provided.  @@@@");
  382                         return str ing.Empty;
  383                    }
  384  
  385                    var  batchId =  queueMessa ge.Content ;
  386                    var  batch = aw ait GetBat chById(bat chId);
  387  
  388                    retu rn await E xportBatch ToXml(batc h);
  389                }
  390                catch (E xception e x)
  391                {
  392                    _log ger.Info($ "!!!! ERRO R - Error  occured cr eated prov ider XML d ocument. ! !!!", ex);
  393                }
  394  
  395                return s tring.Empt y;
  396           }
  397  
  398           pr ivate asyn c Task<str ing> Conve rtResponse ToXml(Prov iderRespon ses respon se)
  399           {
  400                var pack et = await  _configur ation.GetS chemaProfi leAsync(Sc hemaOption s.SchemaPr ofiles.Res ponse);
  401  
  402                var pref ix = packe t.Prefix;
  403                var name Space = pa cket.Names pace;
  404  
  405                return U tilities.S erializeIn stance(res ponse, pre fix, nameS pace);
  406           }
  407  
  408           pr ivate asyn c Task<str ing> Expor tBatchToXm l(ppms_bat ch batch)
  409           {
  410                Context. Account ac count = nu ll;
  411  
  412                if (batc h.ppms_bat ch_batchde tail_batch  == null)  return str ing.Empty;
  413  
  414                var prov iders = ne w List<Pro vider>();
  415  
  416                foreach  (var item  in batch.p pms_batch_ batchdetai l_batch)
  417                {
  418                    acco unt = awai t GetProvi der(item.p pms_provid er.Id);
  419                    if ( account !=  null)
  420                    {
  421                         // convert  provider  to XML
  422                         providers. Add(ToProv ider(accou nt));
  423                    }
  424                }
  425  
  426                  var xml =  Utilities. SerializeI nstance(pr oviders, " p", "https :// DNS . URL /exchange/ ccn/1.0");
  427                xml = xm l.Replace( "ArrayOfPr ovider", " Providers" );
  428  
  429                return x ml;
  430           }
  431  
  432           pr ivate asyn c Task<Con text.Accou nt> GetPro vider(Guid  providerI d)
  433           {
  434                var cont ext = awai t _context Helper.Get ContextAsy nc();
  435                var enti ty = conte xt.Account Set.FirstO rDefault(b  => b.Id = = provider Id);
  436                if (enti ty == null ) throw ne w PpmsServ iceExcepti on("Batch  record doe s not exis t");
  437  
  438                LoadProv iderProper ties(entit y, context );
  439  
  440                return e ntity;
  441           }
  442  
  443           pr otected vo id LoadPro viderPrope rties(Enti ty entity,  PpmsConte xt context )
  444           {
  445                if (enti ty == null  || contex t == null)  return;
  446  
  447                context. LoadProper ty(entity,  "ppms_acc ount_ppms_ providerid entifier_P rovider");
  448                context. LoadProper ty(entity,  "ppms_acc ount_ppms_ providerse rvice");
  449                context. LoadProper ty(entity,  "ppms_acc ount_ppms_ boardcerti fication") ;
  450                context. LoadProper ty(entity,  "ppms_acc ount_organ izationaut horizedoff icial");
  451                context. LoadProper ty(entity,  "ppms_acc ount_ppms_ otherprovi deridentif ier");
  452                context. LoadProper ty(entity,  "contact_ customer_a ccounts");
  453                context. LoadProper ty(entity,  "ppms_acc ount_provi derlicensu re");
  454                context. LoadProper ty(entity,  "ppms_acc ount_ppms_ othername" );
  455                context. LoadProper ty(entity,  "ppms_acc ount_ppms_ providerta xonomy");
  456                context. LoadProper ty(entity,  "ppms_acc ount_deasc hedulepriv ilege");
  457                context. LoadProper ty(entity,  "ppms_acc ount_provi dernetwork id");
  458           }
  459  
  460           pr ivate Prov ider ToPro vider(Cont ext.Accoun t account)
  461           {
  462                if (acco unt == nul l) return  null;
  463  
  464                var prov ider = new  Provider( );
  465  
  466                // Map p roperties
  467                provider .Email = a ccount.EMa ilAddress1 ;
  468                provider .Phone = a ccount.Tel ephone1;
  469                provider .Fax = acc ount.Fax;
  470  
  471                // Addre ss
  472                var addr ess = new  ProviderDa ta.Address ();
  473                address. Address1 =  account.A ddress1_Li ne1;
  474                address. Address2 =  account.A ddress1_Li ne2;
  475                address. Address3 =  account.A ddress1_Li ne3;
  476                address. City = acc ount.Addre ss1_City;
  477                address. State = ac count.Addr ess1_State OrProvince ;
  478                address. PostalCode  = account .Address1_ PostalCode ;
  479                address. County = a ccount.Add ress1_Coun ty;
  480  
  481                provider .Address =  address;
  482  
  483                // NPIs
  484                var npis  = new Lis t<Npi>();
  485                var npi  = new Npi( );
  486                npi.Numb er = accou nt.ppms_Pr oviderIden tifier;
  487                provider .Npis = ne w Npis() {  Item = np is };
  488  
  489                // Speci alties
  490                if (acco unt.ppms_a ccount_ppm s_provider taxonomy ! = null)
  491                {
  492                    var  specialtie s = new Li st<Taxonom y>();
  493                    fore ach (var i tem in acc ount.ppms_ account_pp ms_provide rtaxonomy)
  494                    {
  495                         specialtie s.Add(new  Taxonomy()  { CodedSp ecialty =  item.ppms_ codedspeci alty });
  496                    }
  497                    prov ider.Speci alties = n ew Special ties() { I tem = spec ialties };
  498                }
  499  
  500                // Name
  501                var indi vidual = n ew Individ ual();
  502                var name s = accoun t.Name.Spl it(',');
  503                individu al.FirstNa me = names [0].Trim() ;
  504                individu al.LastNam e = names[ 1].Trim();
  505                individu al.MiddleN ame = "";
  506  
  507                // DEA N umbers
  508                if (acco unt.ppms_a ccount_dea schedulepr ivilege !=  null)
  509                {
  510                    var  deaNumbers  = new Lis t<DeaSched ulePrivile ge>();
  511                    fore ach (var i tem in acc ount.ppms_ account_de aschedulep rivilege)
  512                    {
  513                         deaNumbers .Add(new D eaSchedule Privilege( ) { DeaNum ber = item .ppms_dean umber });
  514                    }
  515                    indi vidual.Dea Numbers =  new DeaSch edulePrivi leges() {  Item = dea Numbers };
  516                }
  517  
  518                // Set p rovider ty pe
  519                var prov iderType =  new Provi derType();
  520                provider Type.Item  = individu al;
  521  
  522                provider .Type = pr oviderType ;
  523  
  524                return p rovider;
  525           }
  526  
  527           #r egion Cert s
  528  
  529           pu blic async  Task<Http Client> Ge tHttpClien t()
  530           {
  531                await Ta sk.Run(()  => { });
  532                var clie ntHandler  = new Http ClientHand ler();
  533                clientHa ndler.Clie ntCertific ates.Add(a wait GetCe rtKeyVault ());
  534  
  535                return n ew HttpCli ent(client Handler);
  536           }
  537  
  538           pr ivate asyn c Task<X50 9Certifica te2> GetCe rtKeyVault ()
  539           {
  540                var keyV aultClient  = new Key VaultClien t(GetToken );
  541                var resu lt = await  keyVaultC lient.GetS ecretAsync (await _co nfiguratio n.GetDasCe rtUrl());
  542  
  543                if (resu lt == null ) throw ne w InvalidO perationEx ception("F ailed to o btain the  certificat e from Key  Vault");
  544  
  545                var secr et = Conve rt.FromBas e64String( result.Val ue);
  546                return n ew X509Cer tificate2( secret, (s tring)null );
  547           }
  548  
  549           pr ivate asyn c Task<str ing> GetTo ken(string  authority , string r esource, s tring scop e)
  550           {
  551                var auth Context =  new Authen ticationCo ntext(auth ority);
  552                var clie ntCred = n ew ClientC redential( await _con figuration .GetDasApp Id(), awai t _configu ration.Get DasSecret( ));
  553                var resu lt = await  authConte xt.Acquire TokenAsync (resource,  clientCre d);
  554  
  555                if (resu lt == null ) throw ne w InvalidO perationEx ception("F ailed to o btain the  token to r etrieve ce rtificate" );
  556  
  557                return r esult.Acce ssToken;
  558           }
  559  
  560           #e ndregion
  561       }
  562   }