48. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 5/23/2019 1:16:31 PM Eastern Daylight 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.

48.1 Files compared

# Location File Last Modified
1 PATS_R_SourceCode.zip\MVI Search\MVI Search.Plugins MVISearchAction.cs Mon Apr 29 20:20:30 2019 UTC
2 PATS_R_SourceCode.zip\MVI Search\MVI Search.Plugins MVISearchAction.cs Thu May 23 01:58:05 2019 UTC

48.2 Comparison summary

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

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

48.4 Active regular expressions

No regular expressions were active.

48.5 Comparison detail

  1   using Syst em;
  2   using Syst em.Collect ions.Gener ic;
  3   using Syst em.Globali zation;
  4   using Syst em.IO;
  5   using Syst em.Linq;
  6   using Syst em.Net;
  7   using Syst em.Service Model;
  8   using Micr osoft.Xrm. Sdk;
  9   using Micr osoft.Xrm. Sdk.Query;
  10   using VEIS .Plugins.M essages;
  11   using Syst em.Web.Scr ipt.Serial ization;
  12   using Syst em.Runtime .Serializa tion;
  13   using Syst em.Activit ies;
  14   using Syst em.Text;
  15   using VEIS .Plugins.M odels;
  16   using VEIS .Plugins;
  17  
  18   namespace  VEIS.Plugi ns
  19   {
  20       public  partial c lass MVISe archAction  : BaseAct ion
  21       {
  22           pr otected ov erride voi d Execute( CodeActivi tyContext  context)
  23           {
  24                try
  25                {
  26                    Resp onse.Set(c ontext, "" );
  27                    // U se a 'usin g' stateme nt to disp ose of the  service c ontext pro perly
  28                    // T o use a sp ecific ear ly bound e ntity repl ace the 'E ntity' bel ow with th e appropri ate class  type
  29                    usin g (var loc alContext  = new Acti onContext( context))
  30                    {
  31                         MVISearchR equest req uest = Jso nHelper.De serialize< MVISearchR equest>(th is.Request .Get<strin g>(context ));
  32                         if (reques t.Query ==  null)
  33                         {
  34                             throw  new Argume ntNullExce ption("Que ry Not Spe cified in  Request");
  35                         }
  36  
  37                         PersonSear chRequest  searchRequ est = new  PersonSear chRequest( );
  38                         VeisConfig  config =  localConte xt.Retriev eVeisConfi g("patsr_m viserviceu rl", "pats r_mvisubsc riptionkey ");
  39                         switch (re quest.Quer y.type)
  40                         {
  41                             case " SearchEdip i":
  42                             case " SearchById entifier":
  43                                 Se tQueryStri ng(config,  localCont ext, searc hRequest,  request.Qu ery.criter ia);
  44                                 se archReques t.MessageI d = Guid.N ewGuid().T oString();
  45                                 se archReques t.Organiza tionName =  config.Or gName;
  46                                 se archReques t.UserId =  localCont ext.Workfl owExecutio nContext.I nitiatingU serId;
  47                                 se archReques t.Debug =  false;
  48                                 se archReques t.LogSoap  = config.L ogSoap;
  49                                 se archReques t.LogTimin g = config .LogTimer;
  50                                 
  51                                 Ve isRawReque st.Set(loc alContext. ActivityCo ntext, Jso nHelper.Se rialize(se archReques t));
  52                                 st ring messa ge = reque st.Query.t ype == "Se archEdipi"  ? "Search Message" :  "SearchPe rson";
  53                                 st ring searc hResponse  = WebApiUt ility.Send ReceiveVei sRequest<s tring>(loc alContext,  config, m essage, se archReques t);
  54                                 Ve isRawRespo nse.Set(lo calContext .ActivityC ontext, se archRespon se);
  55                                 Ma p(localCon text, requ est.Query. criteria,  JsonHelper .Deseriali ze<PersonS earchRespo nse>(searc hResponse) , config);
  56                                 br eak;
  57                             case " SelectedPe rsonSearch ":
  58                                 va r selected Request =  new Select edPersonRe quest();
  59                                 Se tQueryStri ng(config,  localCont ext, selec tedRequest , request. Query.crit eria);
  60                                 se lectedRequ est.Organi zationName  = config. OrgName;
  61                                 se lectedRequ est.UserId  = localCo ntext.Work flowExecut ionContext .Initiatin gUserId;
  62                                 se lectedRequ est.Messag eId = Guid .NewGuid() .ToString( );
  63                                 se lectedRequ est.LogSoa p = config .LogSoap;
  64                                 se lectedRequ est.LogTim ing = conf ig.LogTime r;
  65                                 se lectedRequ est.Record Source = " MVI";
  66                                 se lectedRequ est.Assign ingAuthori ty = "USVH A";
  67                                 se lectedRequ est.Correl ationId =  Guid.Empty ;
  68                                 En tity user  = TryGetUs erInfo(con fig, local Context);
  69                                 if  (user !=  null)
  70                                 {
  71                                      selected Request.Us erFirstNam e = user[" FirstName" ].ToString ();
  72                                      selected Request.Us erLastName  = user["L astName"]. ToString() ;
  73                                      config.U serName =  selectedRe quest.User FirstName  + " " + se lectedRequ est.UserLa stName;
  74                                 }
  75                                 Ve isRawReque st.Set(loc alContext. ActivityCo ntext, Jso nHelper.Se rialize(se lectedRequ est));
  76                                 st ring selec tedRespons e = WebApi Utility.Se ndReceiveV eisRequest <string>(l ocalContex t, config,  "Selected Person", s electedReq uest);
  77                                 Ve isRawRespo nse.Set(lo calContext .ActivityC ontext, se lectedResp onse);
  78                                 Ma pCorrespon dingIds(co nfig, loca lContext,  JsonHelper .Deseriali ze<Corresp ondingIdsR esponse>(s electedRes ponse), se lectedRequ est);
  79  
  80                                 br eak;
  81  
  82                             case " Determinis ticSearch" :
  83                                 va r determin isticReque st = new D eterminist icSearchRe quest();
  84                                 Se tQueryStri ngDetermin istic(conf ig, localC ontext, de terministi cRequest,  request.Qu ery.criter ia);
  85                                 de terministi cRequest.O rganizatio nName = co nfig.OrgNa me;
  86                                 de terministi cRequest.U serId = lo calContext .WorkflowE xecutionCo ntext.Init iatingUser Id;
  87                                 de terministi cRequest.M essageId =  Guid.NewG uid().ToSt ring();
  88  
  89                                 va r determin isticRespo nse = WebA piUtility. SendReceiv eVeisReque st<PersonS earchRespo nse>(local Context, c onfig, "De terministi cSearch",  determinis ticRequest );
  90                                 Ve isRawRespo nse.Set(lo calContext .ActivityC ontext, Js onHelper.S erialize(d eterminist icRequest) );
  91                                 Ma p(localCon text, requ est.Query. criteria,  (PersonSea rchRespons e)determin isticRespo nse, confi g);
  92  
  93                                 // var people Found = (( determinis ticRespons e.Person ! = null) &&  (determin isticRespo nse.Person .Length >  0)) ? true  : false;
  94                                 // Logger.Wri teDebugMes sage(strin g.Format(" DEBUG::" +  mviSearch Type + ":  Search Res ponse Mess age: Peopl e Found: { 0}", peopl eFound));
  95  
  96                                 br eak;
  97                         }
  98                    }
  99                }
  100                catch (E xception e x)
  101                {
  102                    thro w new Inva lidPluginE xecutionEx ception(We bApiUtilit y.BuildExc eptionMess age(ex));
  103                }
  104           }
  105  
  106           pr ivate void  SetQueryS tringDeter ministic(V eisConfig  config, Ac tionContex t localCon text, Dete rministicS earchReque st request , List<Cri teria> cri teria)
  107           {
  108                try
  109                {
  110                    if ( criteria ! = null &&  criteria.C ount > 0)
  111                    {
  112                         if (localC ontext !=  null && lo calContext .WorkflowE xecutionCo ntext != n ull)
  113                         {
  114                             reques t.Organiza tionName =  localCont ext.Workfl owExecutio nContext.O rganizatio nName;
  115                             reques t.UserId =  localCont ext.Workfl owExecutio nContext.U serId;
  116                             foreac h (Criteri a c in cri teria)
  117                             {
  118                                 if  (c != nul l && c.att ribute !=  null && c. value != n ull && c.v alue != "n ull")
  119                                 {
  120                                      switch ( c.attribut e.ToLower( ))
  121                                      {
  122                                          case  "vetnumbe r":
  123                                               request.Se archType =  Determini sticSearch Type.Socia lSecurity;
  124                                               request.So cialSecuri tyNumber =  c.value;
  125                                               break;
  126                                          case  "edipi":
  127                                               request.Se archType =  Determini sticSearch Type.Edipi ;
  128                                               request.Ed iPi = c.va lue;
  129                                               break;
  130                                      }
  131                                 }
  132                             }
  133                             Entity  user = Tr yGetUserIn fo(config,  localCont ext);
  134                             if (us er != null )
  135                             {
  136                                 re quest.User FirstName  = user["Fi rstName"]. ToString() ;
  137                                 re quest.User LastName =  user["Las tName"].To String();
  138                                 co nfig.UserN ame = requ est.UserFi rstName +  " " + requ est.UserLa stName;
  139                             }
  140                             // add ing Auditi ng
  141                             if (co nfig.Enabl eAuditing)
  142                             {
  143                                 au ditRequest (config, l ocalContex t, request );
  144                             }
  145                             if (re quest.Soci alSecurity Number !=  null && re quest.Soci alSecurity Number.Con tains("XXX "))
  146                             {
  147                                 re quest.Soci alSecurity Number = " ";
  148                             }
  149                         }
  150                    }
  151                }
  152                catch (E xception e x)
  153                {
  154                    //Lo gger.Write ToFile("Un able to se t Query St ring due t o: {0}".Re place("{0} ",ex.Messa ge));
  155                    thro w new Inva lidPluginE xecutionEx ception("U nable to s et Query S tring due  to: {0}".R eplace("{0 }", ex.Mes sage));
  156                }
  157           }
  158  
  159           pr ivate void  SetQueryS tring(Veis Config con fig, Actio nContext l ocalContex t, PersonS earchReque st request , List<Cri teria> cri teria)
  160           {
  161                try
  162                {
  163                    if ( criteria ! = null &&  criteria.C ount > 0)
  164                    {
  165                         if (localC ontext !=  null && lo calContext .WorkflowE xecutionCo ntext != n ull)
  166                         {
  167                             reques t.Organiza tionName =  localCont ext.Workfl owExecutio nContext.O rganizatio nName;
  168                             reques t.FetchMes sageProces sType = "r emote";
  169                             reques t.UserId =  localCont ext.Workfl owExecutio nContext.U serId;
  170                             string  street =  string.Emp ty;
  171                             string  city = st ring.Empty ;
  172                             string  state = s tring.Empt y;
  173                             string  zip = str ing.Empty;
  174                             foreac h (Criteri a c in cri teria)
  175                             {
  176                                 if  (c != nul l && c.att ribute !=  null && c. value != n ull && c.v alue != "n ull")
  177                                 {
  178                                      switch ( c.attribut e.ToLower( ))
  179                                      {
  180                                          case  "isattend ed":
  181                                               request.Is Attended =  Boolean.P arse(c.val ue);
  182                                               break;
  183                                          case  "classcod e":
  184                                               request.Id entifierCl assCode =  c.value;
  185                                               break;
  186                                          case  "firstnam e":
  187                                               request.Fi rstName =  c.value;
  188                                               break;
  189                                          case  "lastname ":
  190                                               request.Fa milyName =  c.value;
  191                                               break;
  192                                          case  "dobstrin g":
  193                                               request.Bi rthDate =  c.value;
  194                                               break;
  195                                          case  "vetnumbe r":
  196                                               request.So cialSecuri tyNumber =  c.value;
  197                                               break;
  198                                          case  "middlena me":
  199                                               request.Mi ddleName =  c.value;
  200                                               break;
  201                                          case  "gender":
  202                                               request.Ge nder = c.v alue;
  203                                               break;
  204                                          case  "maidenna me":
  205                                               request.MM N = c.valu e;
  206                                               break;
  207                                          case  "phone":
  208                                               request.Ph oneNumber  = c.value;
  209                                               break;
  210                                          case  "homestre et":
  211                                               street = c .value;
  212                                               break;
  213                                          case  "homecity ":
  214                                               city = c.v alue;
  215                                               break;
  216                                          case  "homestat e":
  217                                               state = c. value;
  218                                               break;
  219                                          case  "homezip" :
  220                                               zip = c.va lue;
  221                                               break;
  222                                          case  "birthcit y":
  223                                               request.PO BC = c.val ue;
  224                                               break;
  225                                          case  "birthsta te":
  226                                               request.PO BS = c.val ue;
  227                                               break;
  228                                          case  "edipi":
  229                                               request.Ed ipi = c.va lue;
  230                                               break;
  231                                      }
  232                                 }
  233                             }
  234                             if (!s tring.IsNu llOrEmpty( street) &&  !string.I sNullOrEmp ty(city) & & !string. IsNullOrEm pty(state)  && !strin g.IsNullOr Empty(zip) )
  235                             {
  236                                 re quest.Addr ess = $"{s treet} {ci ty}, {stat e} {zip}";
  237                             }
  238                             Entity  user = Tr yGetUserIn fo(config,  localCont ext);
  239                             if (us er != null )
  240                             {
  241                                 re quest.User FirstName  = user["Fi rstName"]. ToString() ;
  242                                 re quest.User LastName =  user["Las tName"].To String();
  243                                 co nfig.UserN ame = requ est.UserFi rstName +  " " + requ est.UserLa stName;
  244                             }
  245                             // add ing Auditi ng
  246                             if (co nfig.Enabl eAuditing)
  247                             {
  248                                 au ditRequest (config, l ocalContex t, request );
  249                             }
  250                             if (re quest.Soci alSecurity Number !=  null && re quest.Soci alSecurity Number.Con tains("XXX "))
  251                             {
  252                                 re quest.Soci alSecurity Number = " ";
  253                             }
  254                             if (re quest.Birt hDate != n ull && req uest.Birth Date.Conta ins("XX/XX "))
  255                             {
  256                                 re quest.Birt hDate = "" ;
  257                             }
  258                         }
  259                    }
  260                }
  261                catch (E xception e x)
  262                {
  263                    //Lo gger.Write ToFile("Un able to se t Query St ring due t o: {0}".Re place("{0} ",ex.Messa ge));
  264                    thro w new Inva lidPluginE xecutionEx ception("U nable to s et Query S tring due  to: {0}".R eplace("{0 }", ex.Mes sage));
  265                }
  266           }
  267  
  268           pr ivate void  SetQueryS tring(Veis Config con fig, Actio nContext l ocalContex t, Selecte dPersonReq uest reque st, List<C riteria> c riteria)
  269           {
  270                try
  271                {
  272                    if ( criteria ! = null &&  criteria.C ount > 0)
  273                    {
  274                         if (localC ontext !=  null && lo calContext .WorkflowE xecutionCo ntext != n ull)
  275                         {
  276                             foreac h (Criteri a c in cri teria)
  277                             {
  278                                 if  (c != nul l && c.att ribute !=  null && c. value != n ull && c.v alue != "n ull")
  279                                 {
  280                                      switch ( c.attribut e.ToLower( ))
  281                                      {
  282                                          case  "patients earchident ifier":
  283                                               request.Pa tientSearc hIdentifie r = c.valu e;
  284                                               break;
  285                                      }
  286                                 }
  287                             }
  288                         }
  289                    }
  290                }
  291                catch (E xception e x)
  292                {
  293                    //Lo gger.Write ToFile("Un able to se t Query St ring due t o: {0}".Re place("{0} ",ex.Messa ge));
  294                    thro w new Inva lidPluginE xecutionEx ception("U nable to s et Query S tring due  to: {0}".R eplace("{0 }", ex.Mes sage));
  295                }
  296           }
  297  
  298           // / <summary >
  299           //
  300           // / </summar y>
  301           // /// <param  name="use rId"></par am>
  302           // / <returns ></returns >
  303           pr ivate Enti ty TryGetU serInfo(Ve isConfig c onfig, Act ionContext  localCont ext)
  304           {
  305                Entity u ser = new  Entity("sy stemuser") ;
  306                ColumnSe t cols = n ull;
  307                // will  vary here  for VBA vs . VHA appl ications
  308                if (conf ig.OrgName .ToUpper() .Contains( "VRE"))
  309                {
  310                    cols  = new Col umnSet("fi rstname",  "lastname" , "patsr_c ss_text",  "new_sensi tivityleve l", "patsr _stationid ");
  311                }
  312                else
  313                {
  314                    cols  = new Col umnSet("fi rstname",  "lastname" );
  315                }
  316  
  317                Entity r esult = lo calContext .Organizat ionService .Retrieve( "systemuse r", localC ontext.Wor kflowExecu tionContex t.UserId,  cols);
  318  
  319                if (resu lt != null )
  320                {
  321                    user ["FirstNam e"] = resu lt.Attribu tes.Contai ns("firstn ame") && r esult.Attr ibutes["fi rstname"]  != null ?  result.Att ributes["f irstname"] .ToString( ) : string .Empty;
  322                    user ["LastName "] = resul t.Attribut es.Contain s("lastnam e") && res ult.Attrib utes["last name"] !=  null ? res ult.Attrib utes["last name"].ToS tring() :  string.Emp ty;
  323                }
  324  
  325                if (conf ig.OrgName .ToUpper() .Contains( "VRE"))
  326                {
  327                    if ( result.Att ributes.Co ntains("pa tsr_statio nid"))
  328                    {
  329                         EntityRefe rence stat ion = (Ent ityReferen ce)result. Attributes ["patsr_st ationid"];
  330                         if (statio n != null)
  331                         {
  332                             int st art = stat ion.Name.I ndexOf("(" ) + 1;
  333                             int le n = statio n.Name.Ind exOf(")")  - start;
  334                             config .StationNu mber = sta tion.Name. Substring( start, len );
  335                         }
  336                    }
  337                    conf ig.CssName  = result. Attributes .Contains( "patsr_css _text") &&  result.At tributes[" patsr_css_ text"] !=  null ? res ult.Attrib utes["pats r_css_text "].ToStrin g() : stri ng.Empty;
  338                    conf ig.UserSen sLevel = r esult.Attr ibutes.Con tains("new _sensitivi tylevel")  && result. Attributes ["new_sens itivitylev el"] != nu ll ? resul t.Attribut es["new_se nsitivityl evel"].ToS tring() :  string.Emp ty;
  339                }
  340  
  341                return u ser;
  342           }
  343  
  344  
  345           #r egion Pers on Search  Mapping
  346           pr ivate void  Map(Actio nContext l ocalContex t, List<Cr iteria> cr iteria, Pe rsonSearch Response r esponse, V eisConfig  config)
  347           {
  348                Response  responseO bj = new R esponse()
  349                {
  350                    Resu lts = new  List<Perso n>()
  351                };
  352                List<Per son> perso nCollectio n = new Li st<Person> ();
  353                // excep tion check
  354                if (resp onse == nu ll || (res ponse.Exce ptionOccur ed && (str ing.IsNull OrEmpty(re sponse.Mes sage) || ( !response. Message.To Lower().Co ntains("co rrelation  does not e xist") &&  !response. Message.To Lower().Co ntains("un known key  identifier ")))))
  355                {
  356                    resp onseObj.Ex ceptionOcc ured = tru e;
  357                    resp onseObj.Ex ceptionMes sage = "An  unexpecte d error oc cured duri ng the MVI  search. P lease try  again or c ontact you r system a dministrat or if the  problem pe rsists.";
  358                    Resp onse.Set(l ocalContex t.Activity Context, J sonHelper. Serialize( responseOb j));
  359                }
  360                else if  (response. Person ==  null || re sponse.Per son.Length  == 0 || r esponse.Pe rson[0] ==  null)
  361                {
  362                    resp onseObj.Ex ceptionMes sage = "Yo ur search  in MVI did  not find  any record s matching  the searc h criteria .";
  363                    if ( !string.Is NullOrEmpt y(response .Message))
  364                    {
  365                         responseOb j.ReturnMe ssage = re sponse.Mes sage;
  366                    }
  367                    if ( !string.Is NullOrEmpt y(response .CORPDbMes sage))
  368                    {
  369                         responseOb j.ReturnMe ssage += r esponse.CO RPDbMessag e;
  370                    }
  371                    //   internal s earch depr ecated 4/3 /2019 - go nna train  up users t o use the  stock Cont act search  instead.
  372                    //Qu eryInterna l(localCon text, crit eria, resp onseObj);
  373                    Resp onse.Set(l ocalContex t.Activity Context, J sonHelper. Serialize( responseOb j));
  374                }
  375                else
  376                {
  377                    // f or each pe rson retur ned create  a Person  in CRM
  378                    if ( response.P erson.Leng th > 0)
  379                    {
  380                         string vba SensitiveL evel = "";
  381                         List<Veter anEmployee Flag> vHAV eteranEmpl oyeeFlags  = new List <VeteranEm ployeeFlag >();
  382                         localConte xt.Trace(" GetSensiti veInfo : { 0}", confi g.GetSensi tiveInfo.T oString()) ;
  383                         if (config .GetSensit iveInfo)
  384                         {
  385                             List<s tring> str s = new Li st<string> ();
  386                             strs.A dd(TryGetI CN(respons e.Person[0 ]));
  387                             string  url = Str ing.Format ("{0}{1}",  config.Ve isConfigur ation.SvcC onfigInfo. SvcBaseUrl , config.E mployeeEnd point);
  388                             string  key = con fig.VeisCo nfiguratio n.SvcConfi gInfo.Apim Subscripti onKey;
  389                             localC ontext.Tra ce("vHAVet eranEmploy eeFlags: { 0} key: {1 }", url, k ey);
  390                             NonVet Response n vResponse  = getVHAVe teranEmplo yeeFlags(u rl, key, s trs);
  391                             foreac h (NVDatum  datum in  nvResponse .Data)
  392                             {
  393                                 lo calContext .Trace("da tum: {0}",  JsonHelpe r.Serializ e(datum));
  394                                 if  (datum.Na tionalId = = null)
  395                                 {
  396                                      vHAVeter anEmployee Flags.Add( new Vetera nEmployeeF lag() { Na tionalId =  "", Value  = "NO" }) ;
  397                                 }
  398                                 el se if (!(d atum.Veter an == null  || datum. Veteran ==  "" ? fals e : !(datu m.Veteran. ToUpper()  == "YES")) )
  399                                 {
  400                                      vHAVeter anEmployee Flags.Add( new Vetera nEmployeeF lag() { Na tionalId =  datum.Nat ionalId, V alue = "NO " });
  401                                 }
  402                                 el se if (!(! (datum.Vet eran.ToUpp er() == "N O") || dat um.NewPers onIndicato r == null  ? true : ! (datum.New PersonIndi cator.ToUp per() == " YES")))
  403                                 {
  404                                      vHAVeter anEmployee Flags.Add( new Vetera nEmployeeF lag() { Na tionalId =  datum.Nat ionalId, V alue = "YE S" });
  405                                 }
  406                                 el se if ((!( datum.Vete ran.ToUppe r() == "NO ") || datu m.PrimaryE ligibility Code == nu ll ? false  : datum.P rimaryElig ibilityCod e.ToUpper( ) == "EMPL OYEE"))
  407                                 {
  408                                      vHAVeter anEmployee Flags.Add( new Vetera nEmployeeF lag() { Na tionalId =  datum.Nat ionalId, V alue = "YE S" });
  409                                 }
  410  
  411                             }
  412                         }
  413                        
  414                         VeisRawRes ponse.Set( localConte xt.Activit yContext,  "{ \"vetEm pFlags\":  " + JsonHe lper.Seria lize(vHAVe teranEmplo yeeFlags.T oArray())  + "}");
  415  
  416                         foreach (v ar person  in respons e.Person)
  417                         {
  418                             localC ontext.Tra ce("Initia l Person M ap");
  419                             try
  420                             {
  421                                 #r egion map  the person  with data
  422                                 Pe rson newPe rson = new  Person();
  423                                 ne wPerson.Id  = Guid.Ne wGuid();
  424                                 ne wPerson.pe rsonId = n ewPerson.I d;
  425                                 ne wPerson.VH AVeteranEm ployeeFlag s = JsonHe lper.Seria lize(vHAVe teranEmplo yeeFlags.T oArray());
  426  
  427                                 //   get MVII ndentifier , ICN, pat ient ident ifier
  428                                 lo calContext .Trace("Tr yGetIdenti fiers");
  429                                 Tr yGetMviQue ryParams(p erson, new Person);
  430                                
  431                                 //  need to h andle VBA  sensitivit y for each  result
  432                                 if  ((!config .OrgName.T oUpper().C ontains("V RE") ? tru e : !confi g.GetSensi tiveInfo))
  433                                 {
  434                                      TryGetCo rpInfo(per son, newPe rson);
  435                                      newPerso n.VeteranS ensitivity Level = pe rson.Veter anSensitiv ityLevel;
  436                                      newPerso n.EDIPI =  person.Edi Pi;
  437                                 }
  438                                 el se
  439                                 {
  440                                      getMVICo rpPidBIRLS FN(config,  localCont ext, newPe rson);
  441                                      vbaSensi tiveLevel  = "";
  442                                      bool fla g2 = true;
  443                                      if (!(ne wPerson.Pa rticipantI D != "" ?  true : !(n ewPerson.F ileNumber  != "")))
  444                                      {
  445                                          vbaS ensitiveLe vel = getS ensitivity LevelVBA(c onfig, new Person.Fil eNumber);
  446                                          flag 2 = false;
  447                                          Veis RawRespons e.Set(loca lContext.A ctivityCon text, "{\" flag2\":"  + flag2.To String() +  ",\"1vbaS ensitiveLe vel\":" +  vbaSensiti veLevel);
  448                                      }
  449                                      else if  (newPerson .Participa ntID != "" )
  450                                      {
  451                                          vbaS ensitiveLe vel = getS ensitivity LevelVBA(c onfig, new Person.Par ticipantID );
  452                                          Veis RawRespons e.Set(loca lContext.A ctivityCon text, "{\" flag2\":"  + flag2.To String() +  ",\"2vbaS ensitiveLe vel\":" +  vbaSensiti veLevel);
  453                                      }
  454                                      if (vbaS ensitiveLe vel == "")
  455                                      {
  456                                          if ( !(!flag2 ?  true : !( newPerson. FileNumber  != "")))
  457                                          {
  458                                               vbaSensiti veLevel =  getSensiti vityLevelV BA(config,  newPerson .FileNumbe r);
  459                                               VeisRawRes ponse.Set( localConte xt.Activit yContext,  "{\"flag2\ ":" + flag 2.ToString () + ",\"3 vbaSensiti veLevel\": " + vbaSen sitiveLeve l);
  460                                          }
  461                                          else  if (newPe rson.Parti cipantID ! = "")
  462                                          {
  463                                               vbaSensiti veLevel =  getSensiti vityLevelV BA(config,  newPerson .Participa ntID);
  464                                               VeisRawRes ponse.Set( localConte xt.Activit yContext,  "{\"flag2\ ":" + flag 2.ToString () + ",\"4 vbaSensiti veLevel\": " + vbaSen sitiveLeve l);
  465                                          }
  466                                      }
  467                                      if (vbaS ensitiveLe vel == "")
  468                                      {
  469                                          vbaS ensitiveLe vel = "0";
  470                                      }
  471                                      newPerso n.VeteranS ensitivity Level = vb aSensitive Level;
  472                                      if (conf ig.UserSen sLevel ==  "")
  473                                      {
  474                                          conf ig.UserSen sLevel = " 0";
  475                                      }
  476                                      int num  = Convert. ToInt32(co nfig.UserS ensLevel);
  477                                      int num1  = Convert .ToInt32(v baSensitiv eLevel);
  478                                      object[]  objArray  = new obje ct[] { "DE BUG::User  Level: ",  num, ": Ca ller Level : ", num1  };
  479                                      if (num  < num1)
  480                                      {
  481                                          //   TODO: mask  ??
  482                                          //go to Label1;
  483                                      }
  484                                 }
  485  
  486                                 lo calContext .Trace("Na meList");
  487                                 if  (person.N ameList !=  null)
  488                                 {
  489                                      var lega lName = pe rson.NameL ist.FirstO rDefault(v  => v.Name Type.Equal s("Legal",  StringCom parison.Or dinalIgnor eCase));
  490                                      var alia s = person .NameList. FirstOrDef ault(v =>  v.NameType .Equals("A lias", Str ingCompari son.Ordina lIgnoreCas e));
  491  
  492                                      if (lega lName != n ull)
  493                                      {
  494                                          newP erson.Firs tName = le galName.Gi venName;
  495                                          newP erson.Last Name = leg alName.Fam ilyName;
  496                                          newP erson.Midd leName = l egalName.M iddleName;
  497                                      }
  498                                      else
  499                                      {
  500                                          lega lName = pe rson.NameL ist.FirstO rDefault() ;
  501  
  502                                          if ( legalName  != null)
  503                                          {
  504                                               newPerson. FirstName  = legalNam e.GivenNam e;
  505                                               newPerson. LastName =  legalName .FamilyNam e;
  506                                               newPerson. MiddleName  = legalNa me.MiddleN ame;
  507                                          }
  508                                      }
  509  
  510                                      newPerso n.Alias =  TryGetAlia s(alias);
  511                                 }
  512  
  513                                 ne wPerson.Fu llName = " ";
  514                                 ne wPerson.Fu llName = F ullNameBui lder(newPe rson.First Name, newP erson.Midd leName, ne wPerson.La stName);
  515                                 if  (person.A ddress !=  null && pe rson.Addre ss.StreetA ddressLine  != "" &&  person.Add ress.State  != "" &&  person.Add ress.City  != "" && p erson.Addr ess.State  != "" && p erson.Addr ess.Postal Code != "" )
  516                                      newPerso n.FullAddr ess = pers on.Address .StreetAdd ressLine +  " " + per son.Addres s.City + "  " + perso n.Address. State + "  " + person .Address.P ostalCode;
  517                                 el se
  518                                      newPerso n.FullAddr ess = pers on.FullAdd ress;
  519                                 if  (person.A ddress !=  null && pe rson.Addre ss.StreetA ddressLine  != "")
  520                                 {
  521                                      newPerso n.StreetAd dressLine  = person.A ddress.Str eetAddress Line;
  522                                 }
  523                                 if  (person.A ddress !=  null && pe rson.Addre ss.City !=  "")
  524                                 {
  525                                      newPerso n.City = p erson.Addr ess.City;
  526                                 }
  527                                 if  (person.A ddress !=  null && pe rson.Addre ss.State ! = "")
  528                                 {
  529                                      newPerso n.State =  person.Add ress.State ;
  530                                 }
  531                                 if  (person.A ddress !=  null && pe rson.Addre ss.PostalC ode != "")
  532                                 {
  533                                      newPerso n.PostalCo de = perso n.Address. PostalCode ;
  534                                 }
  535                                 ne wPerson.Br anchOfServ ice = pers on.BranchO fService;
  536                                 ne wPerson.Pr imaryPhone  = person. PhoneNumbe r;
  537                                 ne wPerson.Re cordSource  = person. RecordSour ce;
  538                                 ne wPerson.Ge nder = per son.Gender Code;
  539                                 ne wPerson.De ceasedDate  = person. DeceasedDa te;
  540                                 ne wPerson.Id entityThef t = person .IdentifyT heft;
  541                                 ne wPerson.ur l = person .Url;
  542                                 // added from  FtP, work s with ass isting in  clicking o n the reco rd for the  2nd (sele ctedperson search) MV I call
  543                                 ne wPerson.ur l = " & se lect=*&$fi lter=patsr _PatientMv iIdentifie r eq '" +  newPerson. PatientMvi Identifier  + "' and  patsr_Sear chType eq  'SelectedP ersonSearc h'";
  544                                 ne wPerson.DO BString =  person.Bir thDate;
  545                                 ne wPerson.Ve tNumber =  person.Soc ialSecurit yNumber;
  546                                 if  (config.E nableAudit ing)
  547                                 {
  548                                      auditPer sonRespons e(config,  localConte xt, newPer son);
  549                                 }
  550  
  551                                 //  will eith er set or  mask the S SN and DOB  values
  552                                 st ring isEmp  = string. Empty;
  553                                 if  ((!config .GetSensit iveInfo ?  false : vH AVeteranEm ployeeFlag s.Count >  0))
  554                                 {
  555                                      isEmp =  this.isEmp loyee(newP erson.ICN,  vHAVetera nEmployeeF lags);
  556                                 }
  557                                 Ha ndleSensit ivityMaski ng(config,  person, n ewPerson,  isEmp);
  558  
  559                                 Li st<Facilit y> facilit ies = new  List<Facil ity>();
  560                                 if  (person.C orrespondi ngIdList ! = null)
  561                                 {
  562                                      foreach  (var corre spondingId  in person .Correspon dingIdList )
  563                                      {
  564                                          // f or Corp/BR LS add the  FileNumbe r
  565                                          if ( correspond ingId.Assi gningFacil ity.Contai ns("CORP")  && corres pondingId. AssigningA uthority = = "USVBA"  && corresp ondingId.I dentifierT ype == "PI ")
  566                                          {
  567                                               newPerson. FileNumber  = corresp ondingId.P atientIden tifier;
  568                                          }
  569                                          // a ttempt to  get the ED IPI, if pr esent
  570                                          else  if (strin g.IsNullOr Empty(newP erson.EDIP I) && corr espondingI d.Identifi erType ==  "NI")
  571                                          {
  572                                               //  take f irst 10 of  ICN?
  573                                               newPerson. EDIPI = (c orrespondi ngId.Patie ntIdentifi er.Length  > 10) ? co rrespondin gId.Patien tIdentifie r.Substrin g(0, 10) :  correspon dingId.Pat ientIdenti fier;
  574                                          }
  575  
  576                                          if ( !string.Is NullOrEmpt y(correspo ndingId.As signingFac ility))
  577                                          {
  578                                               var facili ty = this. RetrieveFa cility(loc alContext,  correspon dingId.Ass igningFaci lity);
  579                                               if (facili ty != null )
  580                                               {
  581                                                   facili ties.Add(n ew Facilit y() { Name  = facilit y.GetAttri buteValue< string>("p atsr_name" ), Id = fa cility.Id  });
  582                                               }
  583                                          }
  584                                      }
  585                                 }
  586  
  587                                 ne wPerson.Fa cilities =  facilitie s.ToArray( );
  588                                 ne wPerson.Re turnMessag e = respon se.Message  + respons e.CORPDbMe ssage;
  589                                 re sponseObj. Results.Ad d(newPerso n);
  590  
  591                             }
  592                             catch  (Exception  e)
  593                             {
  594                                 re sponseObj. ExceptionO ccured = t rue;
  595                                 re sponseObj. ExceptionM essage = " ERROR::Err or while m apping per son from N ameList: "  + e.Messa ge;
  596                             }
  597                             #endre gion
  598                             Respon se.Set(loc alContext. ActivityCo ntext, Jso nHelper.Se rialize(re sponseObj) );
  599                         }
  600                    }
  601                }
  602           }
  603  
  604           pr ivate Pers on MapSele ctedPerson (ActionCon text local Context, C orrespondi ngIdsRespo nse respon se, VeisCo nfig confi g)
  605           {
  606                string v baSensitiv eLevel = " ";
  607  
  608                #region  map the pe rson with  data
  609                Person n ewPerson =  new Perso n();
  610                newPerso n.Id = Gui d.NewGuid( );
  611                newPerso n.personId  = newPers on.Id;
  612  
  613                // need  to handle  VBA sensit ivity for  each resul t
  614                if (!str ing.IsNull OrEmpty(co nfig.OrgNa me) && con fig.OrgNam e.ToUpper( ).Contains ("VRE") &&  config.Ge tSensitive Info)
  615                {
  616                    getM VICorpPidB IRLSFN(con fig, local Context, n ewPerson);
  617  
  618                    bool  usedPid =  true;
  619                    if ( newPerson. Participan tID == ""  && newPers on.FileNum ber != "")
  620                    {
  621                         //vbaSensi tiveLevel  = getSensi tivityLeve lVBA(confi g, newPers on.FileNum ber, false );      //  sending f alse will  search by  FN and not  Pid
  622                         usedPid =  false;
  623                    }
  624                    else  if (newPe rson.Parti cipantID ! = "")
  625                         //vbaSensi tiveLevel  = getSensi tivityLeve lVBA(confi g, newPers on.Partici pantID, tr ue);
  626  
  627                    // c heck if we  got a val ue with on e, if not  try the ot her
  628                    if ( vbaSensiti veLevel ==  "")
  629                    {
  630                         if (usedPi d)
  631                         {
  632                             //vbaS ensitiveLe vel = getS ensitivity LevelVBA(c onfig, new Person.Fil eNumber, f alse);
  633                         }
  634                         //else
  635                             //vbaS ensitiveLe vel = getS ensitivity LevelVBA(c onfig, new Person.Par ticipantID , true);
  636                    }
  637  
  638                    if ( string.IsN ullOrEmpty (vbaSensit iveLevel))
  639                         vbaSensiti veLevel =  "0";
  640  
  641                    //ne wPerson.Ve teranSensi tivityLeve l = vbaSen sitiveLeve l;
  642                    int  userLvl =  Convert.To Int32(conf ig.UserSen sLevel);
  643                    int  callerLvl  = Convert. ToInt32(vb aSensitive Level);
  644  
  645                    //Lo gger.Write DebugMessa ge("LOG::U ser Level:  " + userL vl + ": Ca ller Level : " + call erLvl);
  646  
  647                    if ( userLvl <  callerLvl)
  648                    { //  user does  not have  access      
  649                      //  log attem pted acces s
  650                         auditSensi tivity(loc alContext,  config, r esponse.Fu llName, fa lse);
  651  
  652                         newPerson. FirstName  = "Sensiti ve";
  653                         newPerson. LastName =  "Record";
  654                    }
  655                }
  656                else
  657                {
  658                    newP erson.EDIP I = respon se.Edipi;
  659                }
  660  
  661                newPerso n.FullName  = "";
  662                newPerso n.FullName  = FullNam eBuilder(n ewPerson.F irstName,
  663                    newP erson.Midd leName, ne wPerson.La stName);
  664  
  665                newPerso n.url = re sponse.Url ;
  666                //added  from FtP,  works with  assisting  in clicki ng on the  record for  the 2nd ( selectedpe rsonsearch ) MVI call
  667                newPerso n.url = "  & select=* &$filter=p atsr_Patie ntMviIdent ifier eq ' " + newPer son.Patien tMviIdenti fier + "'  and patsr_ SearchType  eq 'Selec tedPersonS earch'";
  668  
  669                // handl e auditing  of all ca lls
  670                if (conf ig.EnableA uditing)
  671                {
  672                    audi tPersonRes ponse(conf ig, localC ontext, ne wPerson);
  673                }
  674  
  675                List<Fac ility> fac ilities =  new List<F acility>() ;
  676                if (resp onse.Corre spondingId List != nu ll)
  677                {
  678                    fore ach (var c orrespondi ngId in re sponse.Cor responding IdList)
  679                    {
  680                         // for Cor p/BRLS add  the FileN umber
  681                         if (corres pondingId. AssigningF acility.Co ntains("CO RP") && co rrespondin gId.Assign ingAuthori ty == "USV BA" && cor responding Id.Identif ierType ==  "PI")
  682                         {
  683                             newPer son.FileNu mber = cor responding Id.Patient Identifier ;
  684                             newPer son.Identi fierType =  correspon dingId.Ide ntifierTyp e;
  685                             newPer son.Identi fierAssign ingFacilit y = corres pondingId. AssigningF acility;
  686                             newPer son.Identi fierAssign ingAuthori ty = corre spondingId .Assigning Authority;
  687                         }
  688                         // attempt  to get th e EDIPI, i f present
  689                         else if (s tring.IsNu llOrEmpty( newPerson. EDIPI) &&  correspond ingId.Iden tifierType  == "NI")
  690                         {
  691                             newPer son.EDIPI  = correspo ndingId.Pa tientIdent ifier;
  692                             newPer son.Identi fierType =  correspon dingId.Ide ntifierTyp e;
  693                             newPer son.Identi fierAssign ingFacilit y = corres pondingId. AssigningF acility;
  694                             newPer son.Identi fierAssign ingAuthori ty = corre spondingId .Assigning Authority;
  695                         }
  696  
  697                         if (!strin g.IsNullOr Empty(corr espondingI d.Assignin gFacility) )
  698                         {
  699                             var fa cility = t his.Retrie veFacility (localCont ext, corre spondingId .Assigning Facility);
  700                             if (fa cility !=  null)
  701                             {
  702                                 fa cilities.A dd(new Fac ility() {  Name = fac ility.GetA ttributeVa lue<string >("patsr_n ame"), Id  = facility .Id });
  703                             }
  704                         }
  705                    }
  706                }
  707                newPerso n.Faciliti es = facil ities.ToAr ray();
  708                return n ewPerson;
  709           }
  710           #e ndregion
  711           pr ivate Enti ty Retriev eFacility( ActionCont ext localC ontext, st ring assig ningFacili ty)
  712           {
  713                QueryByA ttribute q uery = new  QueryByAt tribute
  714                {
  715                    //ch ange these  fields as  required  for your i mplementat ion
  716                    Colu mnSet = ne w ColumnSe t("patsr_f acilityid" , "patsr_n ame"),
  717                    Enti tyName = " patsr_faci lity"
  718                };
  719                query.Ad dAttribute Value("pat sr_facilit ycode", as signingFac ility);
  720  
  721                EntityCo llection r esults = l ocalContex t.Organiza tionServic e.Retrieve Multiple(q uery);
  722                if (resu lts.Entiti es.Count >  0)
  723                {
  724                    retu rn results .Entities[ 0];
  725                }
  726                return n ull;
  727           }
  728  
  729           pr ivate void  MapCorres pondingIds (VeisConfi g config,  ActionCont ext localC ontext, Co rrespondin gIdsRespon se respons e, Selecte dPersonReq uest reque st)
  730           {
  731                //  map  to facilit y
  732                if (resp onse != nu ll && !res ponse.Exce ptionOccur ed)
  733                {
  734                    List <Correspon dingID> fa cilities =  new List< Correspond ingID>();
  735                    fore ach(Corres pondingID  facility i n response .Correspon dingIdList )
  736                    {
  737                         //if (faci lity.Assig ningFacili ty.Substri ng(0, 1) ! = "1" && f acility.As signingFac ility.Subs tring(0, 1 ) != "2")
  738                         //{
  739                             Entity  retrieved Facility =  RetrieveF acility(lo calContext , facility .Assigning Facility);
  740                             facili ty.Facilit yId = (ret rievedFaci lity != nu ll ? retri evedFacili ty.Id : Gu id.Empty);
  741                             facili ty.Facilit yName = (r etrievedFa cility !=  null ? ret rievedFaci lity.GetAt tributeVal ue<string> ("patsr_na me") : "") ;
  742                             facili ties.Add(f acility);
  743                         //}
  744                    }
  745                    resp onse.Corre spondingId List = fac ilities.To Array();
  746                }
  747                Response .Set(local Context.Ac tivityCont ext, JsonH elper.Seri alize(resp onse));
  748           }
  749  
  750           
  751  
  752           pr ivate stri ng getKVPS etting(Act ionContext  localCont ext, strin g name)
  753           {
  754                /*
  755                QueryByA ttribute q uery = new  QueryByAt tribute
  756                {
  757                    //ch ange these  fields as  required  for your i mplementat ion
  758                    Colu mnSet = ne w ColumnSe t("patsr_s tringvalue _text"),
  759                    Enti tyName = " patsr_keyv aluepair"
  760                };
  761                query.Ad dAttribute Value("pat sr_name_te xt", name) ;
  762  
  763                EntityCo llection r esults = l ocalContex t.Organiza tionServic e.Retrieve Multiple(q uery);
  764                if (resu lts.Entiti es.Count >  0)
  765                {
  766                    retu rn (result s.Entities [0].Contai ns("patsr_ stringvalu e_text"))  ? results. Entities[0 ]["patsr_s tringvalue _text"].To String() :  string.Em pty;
  767                }
  768                */
  769                return s tring.Empt y;
  770           }
  771  
  772           pr ivate stat ic string  TryGetICN( PatientPer son person )
  773           {
  774                string e mpty;
  775                try
  776                {
  777                    if ( (person.Co rrespondin gIdList ==  null ? fa lse : pers on.Corresp ondingIdLi st.Length> 0))
  778                    {
  779                         Correspond ingID corr espondingI D = person .Correspon dingIdList .FirstOrDe fault<Corr espondingI D>((Corres pondingID  v) => (v.A ssigningAu thority ==  null || ! v.Assignin gAuthority .Equals("U SVHA", Str ingCompari son.Invari antCulture IgnoreCase ) || v.Ass igningFaci lity == nu ll || !(v. AssigningF acility ==  "200M") | | v.Identi fierType = = null ? f alse : v.I dentifierT ype.Equals ("NI", Str ingCompari son.Invari antCulture IgnoreCase ))) ?? ((I Enumerable <Correspon dingID>)pe rson.Corre spondingId List).Firs tOrDefault <Correspon dingID>((C orrespondi ngID v) =>  (v.Assign ingAuthori ty == null  || !v.Ass igningAuth ority.Equa ls("USVHA" , StringCo mparison.I nvariantCu ltureIgnor eCase) ||  v.Identifi erType ==  null ? fal se : v.Ide ntifierTyp e.Equals(" PI", Strin gCompariso n.Invarian tCultureIg noreCase)) );
  780                         empty = (c orrespondi ngID != nu ll ? corre spondingID .PatientId entifier :  string.Em pty);
  781                    }
  782                    else
  783                    {
  784                         empty = st ring.Empty ;
  785                    }
  786                }
  787                catch (A rgumentNul lException  argumentN ullExcepti on1)
  788                {
  789                    Argu mentNullEx ception ar gumentNull Exception  = argument NullExcept ion1;
  790                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}", ar gumentNull Exception. Message));
  791                }
  792                catch (F aultExcept ion<Organi zationServ iceFault>  faultExcep tion1)
  793                {
  794                    Faul tException <Organizat ionService Fault> fau ltExceptio n = faultE xception1;
  795                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}", fa ultExcepti on.Message ));
  796                }
  797                catch (N ullReferen ceExceptio n nullRefe renceExcep tion1)
  798                {
  799                    Null ReferenceE xception n ullReferen ceExceptio n = nullRe ferenceExc eption1;
  800                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}", nu llReferenc eException .Message)) ;
  801                }
  802                catch (E xception e xception1)
  803                {
  804                    Exce ption exce ption = ex ception1;
  805                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}", ex ception.Me ssage));
  806                }
  807                return e mpty;
  808           }
  809  
  810           pr ivate NonV etResponse  getVHAVet eranEmploy eeFlags(st ring url,  string key , List<str ing> list)
  811           // private Li st<KeyValu ePair<stri ng, string >> getVHAV eteranEmpl oyeeFlags( string url , string k ey, List<s tring> lis t)
  812           {
  813                NonVetRe quest requ est = new  NonVetRequ est()
  814                {
  815                    Clie ntName = " VCCM",
  816                    Form at = "JSON ",
  817                    Nati onalIds =  list.ToArr ay()
  818                };
  819                string s tr = JsonH elper.Seri alize(requ est);
  820                HttpWebR equest htt pWebReques t = (HttpW ebRequest) WebRequest .Create(ur l);
  821                httpWebR equest.Hea ders.Add(" Ocp-Apim-S ubscriptio n-Key", ke y);
  822  
  823                httpWebR equest.Con tentType =  "applicat ion/json";
  824                httpWebR equest.Met hod = "POS T";
  825                using (S treamWrite r streamWr iter = new  StreamWri ter(httpWe bRequest.G etRequestS tream()))
  826                {
  827                    stre amWriter.W rite(str);
  828                }
  829  
  830                WebRespo nse webRes ponse = ht tpWebReque st.GetResp onse();
  831                Stream w ebStream =  webRespon se.GetResp onseStream ();
  832                StreamRe ader respo nseReader  = new Stre amReader(w ebStream);
  833                string r esponseStr ing = resp onseReader .ReadToEnd ();
  834                response Reader.Clo se();
  835  
  836                NonVetRe sponse nvR esponse =  JsonHelper .Deseriali ze<NonVetR esponse>(r esponseStr ing);
  837                /*
  838                 * List< KeyValuePa ir<string,  string>>  keyValuePa irs = new  List<KeyVa luePair<st ring, stri ng>>();
  839                try
  840                {
  841                    fore ach (NVDat um datum i n nvRespon se.Data)
  842                    {
  843                         if (datum. NationalId  == null)
  844                         {
  845                             // no  nationalid
  846                             keyVal uePairs.Ad d(new KeyV aluePair<s tring, str ing>("", " NO"));
  847                         }
  848                         else if (! (datum.Vet eran == nu ll || datu m.Veteran  == "" ? fa lse : !(da tum.Vetera n.ToUpper( ) == "YES" )))
  849                         {
  850                             keyVal uePairs.Ad d(new KeyV aluePair<s tring, str ing>(datum .NationalI d, "NO"));
  851                         }
  852                         else if (! (!(datum.V eteran.ToU pper() ==  "NO") || d atum.NewPe rsonIndica tor == nul l ? true :  !(datum.N ewPersonIn dicator.To Upper() ==  "YES")))
  853                        
  854                             keyVal uePairs.Ad d(new KeyV aluePair<s tring, str ing>(datum .NationalI d, "YES")) ;
  855                         }
  856                         else if (( !(datum.Ve teran.ToUp per() == " NO") || da tum.Primar yEligibili tyCode ==  null ? fal se : datum .PrimaryEl igibilityC ode.ToUppe r() == "EM PLOYEE"))
  857                         {
  858                             keyVal uePairs.Ad d(new KeyV aluePair<s tring, str ing>(datum .NationalI d, "YES")) ;
  859                         }
  860                    }
  861                }
  862                catch (E xception e x)
  863                {
  864                    //Ex ception ex ception =  ex;
  865                    //ba se.Logger. WriteDebug Message(st ring.Conca t("ERROR:: Error pull ing NonVet  info from  HDR with  the suppli ed ICNs.",  exception .Message)) ;
  866                }
  867                return k eyValuePai rs;*/
  868                
  869                return n vResponse;
  870           }
  871  
  872           pr ivate stri ng isEmplo yee(string  ICN, List <VeteranEm ployeeFlag > empList)
  873           {
  874                string v alue;
  875                int num  = 0;
  876                while (t rue)
  877                {
  878                    if ( num > empL ist.Count)
  879                    {
  880                         //base.Log ger.WriteD ebugMessag e("DEBUG:: Employee I CN No matc h found fo r employee  logic.");
  881                         value = "" ;
  882                         break;
  883                    }
  884                    else  if (!(emp List[num]. NationalId  == ICN))
  885                    {
  886                         num++;
  887                    }
  888                    else
  889                    {
  890                         //Logger l ogger = ba se.Logger;
  891                         //string[]  key = new  string[]  { "DEBUG:: Employee I CN match f ound : ",  null, null , null, nu ll, null } ;
  892                         //VeteranE mployeeFla g item = e mpList[num ];
  893                         //key[1] =  item.Key;
  894                         //key[2] =  " and ";
  895                         //key[3] =  ICN;
  896                         //key[4] =  " values  match, ret urning: ";
  897                         //item = e mpList[num ];
  898                         //key[5] =  item.Valu e;
  899                         //logger.W riteDebugM essage(str ing.Concat (key));
  900                         value = em pList[num] .Value;
  901                         break;
  902                    }
  903                }
  904                return v alue;
  905           }
  906           // / <summary >
  907           //
  908           // / </summar y>
  909           // / <param n ame="alias Name"></pa ram>
  910           // / <returns ></returns >
  911           pr ivate void  HandleSen sitivityMa sking(Veis Config con fig, Patie ntPerson p erson, Per son newPer son, strin g employee )
  912           {
  913                bool fla g;
  914                if ((!co nfig.GetSe nsitiveInf o || !(new Person.ICN  != "") ||  !(config. SensitiveE ndpoint !=  "") ? tru e : config .OrgName.T oUpper().C ontains("V RE")))
  915                {
  916                    newP erson.DOBS tring = pe rson.Birth Date;
  917                    newP erson.VetN umber = pe rson.Socia lSecurityN umber;
  918                }
  919                else
  920                {
  921                    newP erson.Vete ranSensiti vityLevel  = this.get Sensitivit yLevelVHA( config, ne wPerson, e mployee);
  922                    if ( !config.Or gName.ToUp per().Cont ains("VCL" ))
  923                    {
  924                         flag = tru e;
  925                    }
  926                    else
  927                    {
  928                         flag = (ne wPerson.Ve teranSensi tivityLeve l == "true :false" ||  newPerson .VeteranSe nsitivityL evel == "t rue:true"  ? false :  !(newPerso n.VeteranS ensitivity Level == " false:true "));
  929                    }
  930                    if ( !flag)
  931                    {
  932                         newPerson. DOBString  = "XX/XX/X XXX";
  933                         newPerson. VetNumber  = "XXXXXXX XX";
  934                         newPerson. PrimaryPho ne = "(XXX ) XXX-XXXX ";
  935                         if ((perso n.Address  == null ||  !(person. Address.St reetAddres sLine != " ") || !(pe rson.Addre ss.State ! = "") || ! (person.Ad dress.City  != "") ||  !(person. Address.St ate != "")  ? false :  person.Ad dress.Post alCode !=  ""))
  936                         {
  937                             if (pe rson.Addre ss.StreetA ddressLine  != string .Empty)
  938                             {
  939                                 st ring[] str eetAddress Line = new  string[]  { person.A ddress.Str eetAddress Line, " ",  person.Ad dress.City , " ", per son.Addres s.State, "  ", person .Address.P ostalCode  };
  940                                 if  (!(string .Concat(st reetAddres sLine) !=  "   "))
  941                                 {
  942                                      newPerso n.FullAddr ess = "";
  943                                 }
  944                                 el se
  945                                 {
  946                                      newPerso n.FullAddr ess = "XXX XXXXXX  XX XX, XX  XX XXX";
  947                                      newPerso n.StreetAd dressLine  = "XXXXXXX XX";
  948                                      newPerso n.City = " XXXX";
  949                                      newPerso n.State =  "XX";
  950                                      newPerso n.PostalCo de = "XXXX X";
  951                                 }
  952                             }
  953                         }
  954                    }
  955                    else  if ((newP erson.Vete ranSensiti vityLevel  == "true:t rue" ? tru e : newPer son.Vetera nSensitivi tyLevel ==  "false:tr ue"))
  956                    {
  957                         newPerson. DOBString  = "XX/XX/X XXX";
  958                         newPerson. VetNumber  = "XXXXXXX XX";
  959                    }
  960                }
  961           }
  962  
  963           pr ivate stat ic string  TryGetAlia s(Name ali asName)
  964           {
  965                try
  966                {
  967                    if ( aliasName  == null)
  968                    {
  969                         return str ing.Empty;
  970                    }
  971  
  972                    cons t string n ameFormat  = "{0} {1} ";
  973                    var  alias = st ring.Forma t(nameForm at, aliasN ame.GivenN ame, alias Name.Famil yName);
  974  
  975                    retu rn alias;
  976                }
  977                catch (E xception)
  978                {
  979                    retu rn string. Empty;
  980                }
  981           }
  982  
  983           // / <summary >
  984           //
  985           // / </summar y>
  986           // / <param n ame="perso n"></param >
  987           // / <returns ></returns >
  988           pr ivate stat ic void Tr yGetCorpIn fo(Patient Person per son, Perso n newPerso n)
  989           {
  990                try
  991                {
  992                    if ( person.Cor responding IdList ==  null || !p erson.Corr espondingI dList.Any( ))
  993                    {
  994                         newPerson. Participan tID = stri ng.Empty;
  995                    }
  996                    else
  997                    {
  998  
  999                         var patien tNo = pers on.Corresp ondingIdLi st.FirstOr Default((v  =>
  1000                             v.Assi gningAutho rity != nu ll &&
  1001                             v.Assi gningAutho rity.Equal s("USVBA",  StringCom parison.In variantCul tureIgnore Case) &&
  1002                             v.Assi gningFacil ity != nul l && v.Ass igningFaci lity == "2 00CORP" &&
  1003                             v.Iden tifierType  != null & &
  1004                             v.Iden tifierType .Equals("P I", String Comparison .Invariant CultureIgn oreCase)))  ??
  1005                                          pers on.Corresp ondingIdLi st.FirstOr Default((v  =>
  1006                                               v.Assignin gAuthority  != null & &
  1007                                               v.Assignin gAuthority .Equals("U SVBA", Str ingCompari son.Invari antCulture IgnoreCase ) &&
  1008                                               v.Identifi erType !=  null &&
  1009                                               v.Identifi erType.Equ als("PI",  StringComp arison.Inv ariantCult ureIgnoreC ase)));
  1010  
  1011                         newPerson. Participan tID = pati entNo != n ull ? pati entNo.Pati entIdentif ier : stri ng.Empty;
  1012                         //  newPer son.FileNu mber = pat ientNo !=  null ? pat ientNo.Pat ientIdenti fier : str ing.Empty;                   
  1013                    }
  1014                }
  1015                catch (A rgumentNul lException  ex)
  1016                {
  1017                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}", ex. Message));
  1018                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1019                         ex.Message ));
  1020                }
  1021                catch (F aultExcept ion<Organi zationServ iceFault>  ex)
  1022                {
  1023                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}", ex. Message));
  1024                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1025                         ex.Message ));
  1026                }
  1027                catch (N ullReferen ceExceptio n ex)
  1028                {
  1029                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}", ex. Message));
  1030                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1031                         ex.Message ));
  1032                }
  1033                catch (E xception e x)
  1034                {
  1035                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}", ex. Message));
  1036                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1037                         ex.Message ));
  1038                }
  1039           }
  1040  
  1041           pr ivate stat ic void Tr yGetMviQue ryParams(P atientPers on person,  Person ne wPerson)
  1042           {
  1043                try
  1044                {
  1045                    if ( person.Cor responding IdList ==  null || !p erson.Corr espondingI dList.Any( ))
  1046                    {
  1047                         newPerson. PatientMvi Identifier  = string. Empty;
  1048                         newPerson. ICN = stri ng.Empty;
  1049                    }
  1050                    else
  1051                    {
  1052  
  1053                         var patien tNo = pers on.Corresp ondingIdLi st.FirstOr Default((v  =>
  1054                             v.Assi gningAutho rity != nu ll &&
  1055                             v.Assi gningAutho rity.Equal s("USVHA",  StringCom parison.In variantCul tureIgnore Case) &&
  1056                             v.Assi gningFacil ity != nul l && v.Ass igningFaci lity == "2 00M" &&
  1057                             v.Iden tifierType  != null & &
  1058                             v.Iden tifierType .Equals("N I", String Comparison .Invariant CultureIgn oreCase)))  ??
  1059                                          pers on.Corresp ondingIdLi st.FirstOr Default((v  =>
  1060                                               v.Assignin gAuthority  != null & &
  1061                                               v.Assignin gAuthority .Equals("U SVHA", Str ingCompari son.Invari antCulture IgnoreCase ) &&
  1062                                               v.Identifi erType !=  null &&
  1063                                               v.Identifi erType.Equ als("PI",  StringComp arison.Inv ariantCult ureIgnoreC ase)));
  1064  
  1065                         newPerson. PatientMvi Identifier  = patient No != null  ? patient No.RawValu eFromMvi :  string.Em pty;
  1066                         newPerson. ICN = pati entNo != n ull ? pati entNo.Pati entIdentif ier : stri ng.Empty;
  1067                         newPerson. Participan tID = pati entNo != n ull ? pati entNo.Pati entIdentif ier : stri ng.Empty;
  1068                    }
  1069                }
  1070                catch (A rgumentNul lException  ex)
  1071                {
  1072                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}",
  1073                    //    ex.Messag e));
  1074                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1075                         ex.Message ));
  1076                }
  1077                catch (F aultExcept ion<Organi zationServ iceFault>  ex)
  1078                {
  1079                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}",
  1080                    //    ex.Messag e));
  1081                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1082                         ex.Message ));
  1083                }
  1084                catch (N ullReferen ceExceptio n ex)
  1085                {
  1086                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}", ex. Message));
  1087                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1088                         ex.Message ));
  1089                }
  1090                catch (E xception e x)
  1091                {
  1092                    //Lo gger.Write ToFile("Un able to Ge t MVI Quer y Params d ue to: {0} ".Replace( "{0}", ex. Message));
  1093                    thro w new Inva lidPluginE xecutionEx ception("U nable to G et MVI Que ry Params  due to: {0 }".Replace ("{0}",
  1094                         ex.Message ));
  1095                }
  1096           }
  1097  
  1098           pr ivate stri ng FormatD ate(string  date)
  1099           {
  1100                if (date  != "" &&  !string.Is NullOrWhit eSpace(dat e) && date .Length ==  8)
  1101                {
  1102                    retu rn date.Su bstring(4,  2) + "/"  + date.Sub string(6,  2) + "/" +  date.Subs tring(0, 4 );
  1103                }
  1104  
  1105                return d ate;
  1106           }
  1107  
  1108           // / <summary >
  1109           // / Gets the  sensitivi ty level f rom ESR
  1110           // / </summar y>
  1111           // / <param n ame="url"> </param>
  1112           // / <param n ame="icn"> </param>
  1113           // / <returns ></returns >
  1114           pr ivate stri ng getSens itivityLev elVHA(Veis Config con fig, Perso n person,  string emp loyee)
  1115           {
  1116                string u rl = Strin g.Format(" {0}{1}{2}" , config.V eisConfigu ration.Svc ConfigInfo .SvcBaseUr l, config. SensitiveE ndpoint, p erson.ICN) ;
  1117                //return  url;
  1118                string s tr;
  1119                bool fla g;
  1120  
  1121                HttpWebR equest api Request =  (HttpWebRe quest)WebR equest.Cre ate(url);
  1122                apiReque st.Headers .Add("Ocp- Apim-Subsc ription-Ke y", config .VeisConfi guration.S vcConfigIn fo.ApimSub scriptionK ey);
  1123                apiReque st.Method  = "GET";
  1124  
  1125                WebRespo nse webRes ponse = ap iRequest.G etResponse ();
  1126                Stream w ebStream =  webRespon se.GetResp onseStream ();
  1127                StreamRe ader respo nseReader  = new Stre amReader(w ebStream);
  1128                string s tr1 = resp onseReader .ReadToEnd ();
  1129                response Reader.Clo se();
  1130                //return  str1;
  1131                person.S ensitivity LevelVHA =  str1;
  1132                ESRSensi tiveObject  eSRSensit iveObject  = JsonHelp er.Deseria lize<ESRSe nsitiveObj ect>(str1) ;
  1133                person.P referredFa cility = ( eSRSensiti veObject.D ata.Demogr aphics !=  null ? eSR SensitiveO bject.Data .Demograph ics.Prefer redFacilit y : "");
  1134                if (!(em ployee ==  string.Emp ty))
  1135                {
  1136                    str  = (!(emplo yee == "YE S") ? stri ng.Concat( eSRSensiti veObject.D ata.Sensit ivityInfo. SensityFla g.ToLower( ), ":false ") : "true :true");
  1137                }
  1138                else if  (!config.O rgName.Con tains("VCL "))
  1139                {
  1140                    str  = ((eSRSen sitiveObje ct.Data.En rollmentDe terminatio nInfo == n ull || eSR SensitiveO bject.Data .Enrollmen tDetermina tionInfo.P rimaryElig ibility ==  null || e SRSensitiv eObject.Da ta.Enrollm entDetermi nationInfo .PrimaryEl igibility. Type == nu ll ? true  : !(eSRSen sitiveObje ct.Data.En rollmentDe terminatio nInfo.Prim aryEligibi lity.Type. ToUpper()  == "EMPLOY EE")) ? st ring.Conca t(eSRSensi tiveObject .Data.Sens itivityInf o.SensityF lag.ToLowe r(), ":fal se") : str ing.Concat (eSRSensit iveObject. Data.Sensi tivityInfo .SensityFl ag.ToLower (), ":true "));
  1141                }
  1142                else
  1143                {
  1144                    if ( eSRSensiti veObject.D ata.Enroll mentDeterm inationInf o == null  || eSRSens itiveObjec t.Data.Enr ollmentDet ermination Info.Prima ryEligibil ity == nul l || eSRSe nsitiveObj ect.Data.E nrollmentD eterminati onInfo.Pri maryEligib ility.Type  == null)
  1145                    {
  1146                         flag = tru e;
  1147                    }
  1148                    else
  1149                    {
  1150                         flag = (eS RSensitive Object.Dat a.Enrollme ntDetermin ationInfo. PrimaryEli gibility.T ype.ToUppe r() == "EM PLOYEE" ?  false : !( eSRSensiti veObject.D ata.Enroll mentDeterm inationInf o.Veteran. ToUpper()  == "FALSE" ));
  1151                    }
  1152                    str  = (flag ?  string.Con cat(eSRSen sitiveObje ct.Data.Se nsitivityI nfo.Sensit yFlag.ToLo wer(), ":f alse") : s tring.Conc at(eSRSens itiveObjec t.Data.Sen sitivityIn fo.Sensity Flag.ToLow er(), ":tr ue"));
  1153                }
  1154  
  1155                return s tr;
  1156  
  1157  
  1158           }
  1159           pr ivate stri ng getSens itivityLev elVBA(Veis Config con fig, strin g icn)
  1160           {
  1161                  //https:// DNS . URL /api/ESR/E nrollmentE ligibility Sensitivit y/1.0/json /CRMSensit iveData/10 12991357V9 23306
  1162                /*{"Erro rOccurred" :false,
  1163                 * "Erro rMessage": null,
  1164                 * "Stat us":null,
  1165                 * "Debu gInfo":nul l,
  1166                 * "Data ":{
  1167                 *       "Sensitivi tyInfo":{" SensityFla g":"false" },
  1168                 *       "Enrollmen tDetermina tionInfo": {"PrimaryE ligibility ":{"Type": "NSC"},"Ve teran":"tr ue"},
  1169                 *       "Demograph ics":{"Pre ferredFaci lity":"565  - FAYETTE VILLE VA M EDICAL CEN TER"}
  1170                 *       }
  1171                 *  }
  1172  
  1173                */
  1174                string u rl = Strin g.Format(" {0}{1}{2}" ,config.Ve isConfigur ation.SvcC onfigInfo. SvcBaseUrl ,config.Se nsitiveEnd point, icn );
  1175                string l vl = "";
  1176  
  1177                HttpWebR equest api Request =  (HttpWebRe quest)WebR equest.Cre ate(url);
  1178                apiReque st.Headers .Add("Ocp- Apim-Subsc ription-Ke y", config .VeisConfi guration.S vcConfigIn fo.ApimSub scriptionK ey);
  1179                apiReque st.Method  = "GET";
  1180  
  1181                WebRespo nse webRes ponse = ap iRequest.G etResponse ();
  1182                Stream w ebStream =  webRespon se.GetResp onseStream ();
  1183                StreamRe ader respo nseReader  = new Stre amReader(w ebStream);
  1184                string a piStringRe sponse = r esponseRea der.ReadTo End();
  1185                response Reader.Clo se();
  1186  
  1187                return a piStringRe sponse;
  1188                //using  (var clien t = new We bClient())
  1189                //{
  1190                    //va r response  = client. DownloadSt ring(url);
  1191                    //lv l =  respo nse;
  1192                    //va r serializ er = new J avaScriptS erializer( );
  1193                    //Se nsitiveObj ect ro = s erializer. Deserializ e<Sensitiv eObject>(r esponse);
  1194                    //re turn lvl;
  1195                    //re turn (ro.D ata[0].Ret urn1 == nu ll) ? "" :  ro.Data[0 ].Return1. ScrtyLevel TypeCd;
  1196                //}
  1197                //Logger .WriteToFi le("Sensit ivity Leve l Not Foun d for Pati entId: {0} ".Replace( "{0}", pId ));
  1198                //return  "10";
  1199           }
  1200  
  1201           // / <summary >
  1202           // / This bas ically mak es the 2nd  MVI call  to get the  correlati ons to 
  1203           // / get the  FileNumber  so we can  get the s ensitivity  level and  compare
  1204           // / </summar y>
  1205           // / <param n ame="ICN"> </param>
  1206           // / <returns ></returns >
  1207           pr ivate void  getMVICor pPidBIRLSF N(VeisConf ig config,  ActionCon text local Context, P erson newP erson)
  1208           {
  1209                Selected PersonRequ est select edRequest  = new Sele ctedPerson Request();
  1210                selected Request.Or ganization Name = con fig.OrgNam e;
  1211                selected Request.Us erId = loc alContext. WorkflowEx ecutionCon text.Initi atingUserI d;
  1212                selected Request.Me ssageId =  Guid.NewGu id().ToStr ing();
  1213                //select edRequest. Debug = fa lse;
  1214                selected Request.Lo gSoap = co nfig.LogSo ap;
  1215                selected Request.Lo gTiming =  config.Log Timer;
  1216                selected Request.Re cordSource  = "MVI";
  1217                selected Request.As signingAut hority = " USVHA";
  1218                selected Request.Co rrelationI d = Guid.E mpty;
  1219                Entity u ser = TryG etUserInfo (config, l ocalContex t);
  1220                if (user  != null)
  1221                {
  1222                    sele ctedReques t.UserFirs tName = us er["FirstN ame"].ToSt ring();
  1223                    sele ctedReques t.UserLast Name = use r["LastNam e"].ToStri ng();
  1224                    conf ig.UserNam e = select edRequest. UserFirstN ame + " "  + selected Request.Us erLastName ;
  1225                }
  1226                selected Request.Pa tientSearc hIdentifie r = newPer son.ICN;
  1227  
  1228                string s electedRes ponseStrin g = WebApi Utility.Se ndReceiveV eisRequest <string>(l ocalContex t, config,  "Selected Person", s electedReq uest);
  1229                Correspo ndingIdsRe sponse sel ectedRespo nse = Json Helper.Des erialize<C orrespondi ngIdsRespo nse>(selec tedRespons eString);
  1230  
  1231  
  1232                if (sele ctedRespon se.Excepti onOccured)
  1233                {
  1234                    //Lo gger.Write DebugMessa ge(string. Format("ER ROR::VBASe nsitivityC heck: Sear ch Excepti on Message : {0}", se lectedResp onse.RawMv iException Message));
  1235                }
  1236                //else
  1237                //    Lo gger.Write DebugMessa ge(string. Format("LO G::VBASens itivityChe ck: Succes s: {0}", s electedRes ponse.RawM viExceptio nMessage)) ;
  1238  
  1239                try
  1240                {
  1241                    if ( selectedRe sponse.Cor responding IdList ==  null || !s electedRes ponse.Corr espondingI dList.Any( ))
  1242                    {
  1243                         return;
  1244                    }
  1245                    else
  1246                    {
  1247  
  1248                         var patien tNo = sele ctedRespon se.Corresp ondingIdLi st.FirstOr Default((v  =>
  1249                             v.Assi gningAutho rity != nu ll &&
  1250                             v.Assi gningAutho rity.Equal s("USVBA",  StringCom parison.In variantCul tureIgnore Case) &&
  1251                             v.Assi gningFacil ity != nul l && v.Ass igningFaci lity == "2 00CORP" &&
  1252                             v.Iden tifierType  != null & &
  1253                             v.Iden tifierType .Equals("P I", String Comparison .Invariant CultureIgn oreCase)))  ??
  1254                                          sele ctedRespon se.Corresp ondingIdLi st.FirstOr Default((v  =>
  1255                                               v.Assignin gAuthority  != null & &
  1256                                               v.Assignin gAuthority .Equals("U SVBA", Str ingCompari son.Invari antCulture IgnoreCase ) &&
  1257                                               v.Identifi erType !=  null &&
  1258                                               v.Identifi erType.Equ als("PI",  StringComp arison.Inv ariantCult ureIgnoreC ase)));
  1259                         newPerson. Participan tID = pati entNo != n ull ? pati entNo.Pati entIdentif ier : stri ng.Empty;
  1260  
  1261                         var patien tFN = sele ctedRespon se.Corresp ondingIdLi st.FirstOr Default((v  =>
  1262                           v.Assign ingAuthori ty != null  &&
  1263                           v.Assign ingAuthori ty.Equals( "USVBA", S tringCompa rison.Inva riantCultu reIgnoreCa se) &&
  1264                           v.Assign ingFacilit y != null  && v.Assig ningFacili ty == "200 BRLS" &&
  1265                           v.Identi fierType ! = null &&
  1266                           v.Identi fierType.E quals("PI" , StringCo mparison.I nvariantCu ltureIgnor eCase))) ? ?
  1267                                        select edResponse .Correspon dingIdList .FirstOrDe fault((v = >
  1268                                            v. AssigningA uthority ! = null &&
  1269                                            v. AssigningA uthority.E quals("USV BA", Strin gCompariso n.Invarian tCultureIg noreCase)  &&
  1270                                            v. Identifier Type != nu ll &&
  1271                                            v. Identifier Type.Equal s("PI", St ringCompar ison.Invar iantCultur eIgnoreCas e)));
  1272                         newPerson. FileNumber  = patient FN != null  ? patient FN.Patient Identifier  : string. Empty;
  1273  
  1274                         //99987200 3^NI^200DO D^USDOD}
  1275                         var patien tEDIPI = s electedRes ponse.Corr espondingI dList.Firs tOrDefault ((v =>
  1276                          v.Assigni ngAuthorit y != null  &&
  1277                          v.Assigni ngAuthorit y.Equals(" USDOD", St ringCompar ison.Invar iantCultur eIgnoreCas e) &&
  1278                          v.Assigni ngFacility  != null & & v.Assign ingFacilit y == "200D OD" &&
  1279                          v.Identif ierType !=  null &&
  1280                          v.Identif ierType.Eq uals("NI",  StringCom parison.In variantCul tureIgnore Case))) ??
  1281                                       selecte dResponse. Correspond ingIdList. FirstOrDef ault((v =>
  1282                                           v.A ssigningAu thority !=  null &&
  1283                                           v.A ssigningAu thority.Eq uals("USDO D", String Comparison .Invariant CultureIgn oreCase) & &
  1284                                           v.I dentifierT ype != nul l &&
  1285                                           v.I dentifierT ype.Equals ("NI", Str ingCompari son.Invari antCulture IgnoreCase )));
  1286  
  1287                         newPerson. EDIPI = pa tientEDIPI  != null ?  patientED IPI.Patien tIdentifie r : string .Empty;
  1288  
  1289                         //Logger.W riteDebugM essage(str ing.Format ("LOG::VBA Sensitivit yCheck: Re sponse Suc cess for P Id: {0}, F ileNumber:  {1}, EDIP I: {2} ",  patientNo. PatientIde ntifier, p atientFN.P atientIden tifier, pa tientEDIPI .PatientId entifier)) ;
  1290                    }
  1291                }
  1292                catch (E xception e x)
  1293                {
  1294                    //Lo gger.Write DebugMessa ge("ERROR: :VBASensit ivityCheck : Error in  getMVICor pPidBIRLSF N()");
  1295                }
  1296           }
  1297           // / <summary >
  1298           // / Will ret urn a stri ng of the  response f rom MVI
  1299           // / </summar y>
  1300           // / <param n ame="count "></param>
  1301           // / <param n ame="perso n"></param >
  1302           // / <returns ></returns >
  1303           pr ivate void  auditPers onResponse (VeisConfi g config,  ActionCont ext localC ontext, Pe rson perso n)
  1304           {
  1305                if (stri ng.IsNullO rEmpty(con fig.AuditU rl))
  1306                {
  1307                    conf ig.AuditUr l = getKVP Setting(lo calContext , "MVI_Log ");
  1308                }
  1309  
  1310                string t empICN = p erson.ICN;
  1311                if (temp ICN.Length  > 15)
  1312                    temp ICN = pers on.ICN.Sub string(0,  15);
  1313  
  1314                var MviL og = new M VILog
  1315                {
  1316                    Addr ess = pers on.FullAdd ress,
  1317                    Atte nded = per son.IsAtte nded,
  1318                    Clas sCode = pe rson.Class Code,
  1319                    Crea tedOn = Da teTime.Utc Now,
  1320                    DOB  = person.D OBString,
  1321                    EDIP I = person .EDIPI,
  1322                    Firs t = person .FirstName ,
  1323                    ICN  = tempICN,
  1324                    Last  = person. LastName,
  1325                    Midd le = perso n.MiddleNa me,
  1326                    MMN  = person.M MN,
  1327                    Orga nization_N ame = conf ig.OrgName ,
  1328                    Phon e = person .PrimaryPh one,
  1329                    POBC  = person. POBC,
  1330                    POBS  = person. POBS,
  1331                    Requ estType =  person.Sea rchType,
  1332                    Sess ionId = ne w Guid().T oString(),
  1333                    Sex  = person.G ender,
  1334                    Sour ce = perso n.RecordSo urce,
  1335                    Type  = "Respon se",
  1336                    User Name = con fig.UserNa me,
  1337                    SSN  = person.V etNumber
  1338                };
  1339  
  1340                var json  = new Jav aScriptSer ializer(). Serialize( MviLog);
  1341                handleRe quest(conf ig.AuditUr l, json, " MVILog");
  1342           }
  1343           pr ivate void  auditSens itivity(Ac tionContex t localCon text, Veis Config con fig, strin g crmeFull Name, bool  accessed)
  1344           {
  1345                string s ensitiveUr l = getKVP Setting(lo calContext , "MVI_Sen sitivity_L og");
  1346  
  1347                var Log  = new Sens itiveLog()
  1348                {
  1349                    Acce ssed = acc essed,
  1350                    Acce ss_Time =  DateTime.U tcNow.ToSt ring("G"),
  1351                    HDR_ Response_C ode = "",
  1352                    Orga nization_N ame = conf ig.OrgName .Trim(),
  1353                    Sens itive_Vete ran = true ,
  1354                    Sess ionId = ne w Guid().T oString(),
  1355                    Vete ran = crme FullName,
  1356                    Who_ Accessed =  config.Us erName
  1357                };
  1358  
  1359                var json  = new Jav aScriptSer ializer(). Serialize( Log);
  1360                handleRe quest(sens itiveUrl,  json, "Sen sitivity_L og");
  1361           }
  1362  
  1363           // / <summary >
  1364           // / Will han dle adding  the reque st details  into a st ring to be  kept in a  log recor d
  1365           // / </summar y>
  1366           // / <param n ame="reque st">Person SearchRequ est object </param>
  1367           // / <returns >string of  the reque t</returns >
  1368           pr ivate void  auditRequ est(VeisCo nfig confi g, ActionC ontext loc alContext,  PersonSea rchRequest  request)
  1369           {
  1370                if (stri ng.IsNullO rEmpty(con fig.AuditU rl))
  1371                {
  1372                    conf ig.AuditUr l = getKVP Setting(lo calContext , "MVI_Log ");
  1373                }
  1374                bool att ended = re quest.IsAt tended;
  1375  
  1376                var Log  = new MVIL og
  1377                {
  1378                    Addr ess = requ est.Addres s,
  1379                    Atte nded = att ended,
  1380                    Clas sCode = re quest.Iden tifierClas sCode,
  1381                    Crea tedOn = Da teTime.Utc Now,
  1382                    DOB  = request. BirthDate,
  1383                    EDIP I = reques t.Edipi,
  1384                    Firs t = reques t.FirstNam e,
  1385                    ICN  = request. PatientIde ntifier,
  1386                    Last  = request .FamilyNam e,
  1387                    Midd le = reque st.MiddleN ame,
  1388                    MMN  = request. MMN,
  1389                    Orga nization_N ame = conf ig.OrgName ,
  1390                    Phon e = reques t.PhoneNum ber,
  1391                    POBC  = request .POBC,
  1392                    POBS  = request .POBS,
  1393                    Requ estType =  "PersonSea rchRequest ",
  1394                    Sess ionId = ne w Guid().T oString(),
  1395                    Sex  = request. Gender,
  1396                    Sour ce = "",
  1397                    SSN  = request. SocialSecu rityNumber ,
  1398                    Type  = "Reques t",
  1399                    User Name = con fig.UserNa me
  1400                };
  1401  
  1402                var json  = new Jav aScriptSer ializer(). Serialize( Log);
  1403                //TODO h andleReque st(config. auditUrl,  json, "MVI Log");
  1404           }
  1405           pr ivate void  auditRequ est(VeisCo nfig confi g, ActionC ontext loc alContext,  SelectedP ersonReque st request )
  1406           {
  1407                if (conf ig.AuditUr l == "")
  1408                {
  1409                    conf ig.AuditUr l = getKVP Setting(lo calContext , "MVI_Log ");
  1410                }
  1411                //bool a ttended =  request.Is Attended;
  1412  
  1413                var Log  = new MVIL og
  1414                {
  1415                    //Ad dress = re quest.Addr ess,
  1416                    //At tended = a ttended,
  1417                    //Cl assCode =  request.Id entifierCl assCode,
  1418                    Crea tedOn = Da teTime.Utc Now,
  1419                    //DO B = reques t.BirthDat e,
  1420                    //ED IPI = requ est.Edipi,
  1421                    //Fi rst = requ est.FirstN ame,
  1422                    //IC N = reques t.PatientI dentifier,
  1423                    //La st = reque st.FamilyN ame,
  1424                    //Mi ddle = req uest.Middl eName,
  1425                    //MM N = reques t.MMN,
  1426                    Orga nization_N ame = conf ig.OrgName ,
  1427                    //Ph one = requ est.PhoneN umber,
  1428                    //PO BC = reque st.POBC,
  1429                    //PO BS = reque st.POBS,
  1430                    Requ estType =  "SelectedP ersonReque st",
  1431                    Sess ionId = ne w Guid().T oString(),
  1432                    //Se x = reques t.Gender,
  1433                    Sour ce = "",
  1434                    //SS N = reques t.SocialSe curityNumb er,
  1435                    Type  = "Reques t",
  1436                    User Name = con fig.UserNa me
  1437                };
  1438  
  1439                var json  = new Jav aScriptSer ializer(). Serialize( Log);
  1440                //TODO h andleReque st(config. auditUrl,  json, "MVI Log");
  1441           }
  1442           pr ivate void  auditRequ est(VeisCo nfig confi g, ActionC ontext loc alContext,  Determini sticSearch Request re quest)
  1443           {
  1444                if (stri ng.IsNullO rEmpty(con fig.AuditU rl))
  1445                {
  1446                    conf ig.AuditUr l = getKVP Setting(lo calContext , "MVI_Log ");
  1447                }
  1448  
  1449                var Log  = new MVIL og
  1450                {
  1451                    Crea tedOn = Da teTime.Utc Now,
  1452                    DOB  = request. BirthDate,
  1453                    EDIP I = reques t.EdiPi,
  1454                    Orga nization_N ame = conf ig.OrgName ,
  1455                    Requ estType =  "Determini sticSearch Request",
  1456                    Sess ionId = ne w Guid().T oString(),
  1457                    Sour ce = "",
  1458                    SSN  = request. SocialSecu rityNumber ,
  1459                    Type  = "Reques t",
  1460                    User Name = con fig.UserNa me
  1461                };
  1462  
  1463                var json  = new Jav aScriptSer ializer(). Serialize( Log);
  1464                //TODO h andleReque st(config. auditUrl,  json, "MVI Log");
  1465           }
  1466  
  1467           // / <summary >
  1468           // / Handles  sending th e requests  and respo nses for a udit loggi ng and sen sitivity
  1469           // / </summar y>
  1470           // / <param n ame="url"> The url of  the servi ce</param>
  1471           // / <param n ame="json" >the json  string of  the object </param>
  1472           pr ivate void  handleReq uest(strin g url, str ing json,  string log Table)
  1473           {
  1474                /* TODO
  1475                var http WebRequest  = (HttpWe bRequest)W ebRequest. Create(url );
  1476                httpWebR equest.Con tentType =  "applicat ion/json";
  1477                httpWebR equest.Met hod = "POS T";
  1478  
  1479                using (v ar streamW riter = ne w StreamWr iter(httpW ebRequest. GetRequest Stream()))
  1480                {
  1481                    stre amWriter.W rite(json) ;
  1482                    stre amWriter.F lush();
  1483                    stre amWriter.C lose();
  1484                }
  1485  
  1486                try
  1487                {
  1488                    var  httpRespon se = (Http WebRespons e)httpWebR equest.Get Response() ;
  1489                    usin g (var str eamReader  = new Stre amReader(h ttpRespons e.GetRespo nseStream( )))
  1490                    {
  1491                         streamRead er.ReadToE nd();
  1492                         streamRead er.Close() ;
  1493                    }
  1494                    http Response.C lose();
  1495                }
  1496                catch (E xception e )
  1497                {
  1498                    //Lo gger.Write DebugMessa ge("ERROR: :Error cre ating " +  logTable +  " respons e record:  " + e.Mess age);
  1499                }
  1500                */
  1501           }
  1502  
  1503           pr ivate stri ng FullNam eBuilder(s tring firs t, string  middle, st ring last)
  1504           {
  1505                string f ullName =  "n/a";
  1506  
  1507                var fNam e = (strin g.IsNullOr Empty(firs t)) ? "" :  first;
  1508                var mNam e = (strin g.IsNullOr Empty(midd le)) ? ""  : middle;
  1509                var lNam e = (strin g.IsNullOr Empty(last )) ? "" :  last;
  1510  
  1511                fullName  = string. Format("{0 } {1} {2}" , fName, m Name, lNam e);
  1512  
  1513                return f ullName;
  1514           }
  1515       }
  1516  
  1517       public  class Res ponse
  1518       {
  1519           pu blic bool  ExceptionO ccured = f alse;
  1520           pu blic strin g Exceptio nMessage;
  1521           pu blic strin g ReturnMe ssage;
  1522           pu blic List< Person> Re sults;
  1523       }
  1524  
  1525       public  class Vei sConfig
  1526       {
  1527           pu blic strin g AuditUrl  { get; se t; }
  1528           pu blic strin g OrgOverr ide { get;  set; }
  1529           pu blic strin g OrgName  { get; set ; }
  1530           pu blic bool  GetSensiti veInfo { g et; set; }
  1531           pu blic strin g Employee Endpoint {  get; set;  }
  1532           pu blic strin g Sensitiv eEndpoint  { get; set ; }
  1533           pu blic bool  EnableAudi ting { get ; set; }
  1534           pu blic bool  LogTimer {  get; set;  }
  1535           pu blic bool  LogSoap {  get; set;  }
  1536           pu blic strin g UserSens Level { ge t; set; }
  1537           pu blic strin g UserName  { get; se t; }
  1538           pu blic strin g StationN umber { ge t; set; }
  1539           pu blic strin g CssName  { get; set ; }
  1540           pu blic VeisC onfigurati on VeisCon figuration  { get; se t; }
  1541       }
  1542  
  1543  
  1544       intern al class S ensitiveLo g
  1545       {
  1546           pu blic strin g Organiza tion_Name;
  1547           pu blic strin g Veteran;
  1548           pu blic bool  Sensitive_ Veteran;
  1549           pu blic bool  Accessed;
  1550           pu blic strin g Who_Acce ssed;
  1551           pu blic strin g HDR_Resp onse_Code;
  1552           pu blic strin g Access_T ime;
  1553           pu blic strin g SessionI d;
  1554           pu blic strin g userName ;
  1555       }
  1556  
  1557       intern al class M VILog
  1558       {
  1559           pu blic strin g Organiza tion_Name;
  1560           pu blic strin g First;
  1561           pu blic strin g Last;
  1562           pu blic strin g Middle;
  1563           pu blic strin g DOB;
  1564           pu blic strin g SSN;
  1565           pu blic strin g EDIPI;
  1566           pu blic strin g Phone;
  1567           pu blic bool  Attended;
  1568           pu blic strin g Address;
  1569           pu blic strin g Sex;
  1570           pu blic strin g MMN;
  1571           pu blic strin g POBC;
  1572           pu blic strin g POBS;
  1573           pu blic strin g RequestT ype;
  1574           pu blic strin g ICN; //1 5
  1575           pu blic strin g Source;
  1576           pu blic strin g ClassCod e;
  1577           pu blic strin g Type;
  1578           pu blic DateT ime Create dOn;
  1579           pu blic strin g SessionI d;
  1580           pu blic strin g UserName ;
  1581       }
  1582       intern al class M VILog2
  1583       {
  1584           pu blic strin g Organiza tion_Name;
  1585           pu blic strin g DOB;
  1586           pu blic strin g SSN;
  1587           pu blic strin g EDIPI;
  1588           pu blic strin g Phone;
  1589           pu blic strin g ICN;
  1590           pu blic strin g IDs;
  1591           pu blic DateT ime Create dOn;
  1592           pu blic strin g SessionI d;
  1593           pu blic strin g UserName ;
  1594       }
  1595       public  class Sen sitivityIn fo
  1596       {
  1597           pu blic strin g SensityF lag { get;  set; }
  1598       }
  1599  
  1600       public  class Pri maryEligib ility
  1601       {
  1602           pu blic strin g Type { g et; set; }
  1603       }
  1604  
  1605       public  class Enr ollmentDet ermination Info
  1606       {
  1607           pu blic Prima ryEligibil ity Primar yEligibili ty { get;  set; }
  1608           pu blic strin g Veteran  { get; set ; }
  1609       }
  1610  
  1611       public  class Dem ographics
  1612       {
  1613           pu blic strin g Preferre dFacility  { get; set ; }
  1614       }
  1615  
  1616       public  class ESR SensitiveO bject
  1617       {
  1618           pu blic bool  ErrorOccur red { get;  set; }
  1619           pu blic strin g ErrorMes sage { get ; set; }
  1620           pu blic strin g Status {  get; set;  }
  1621           pu blic strin g DebugInf o { get; s et; }
  1622           pu blic ESRDa ta Data {  get; set;  }
  1623       }
  1624       public  class ESR Data
  1625       {
  1626           pu blic Sensi tivityInfo  Sensitivi tyInfo { g et; set; }
  1627           pu blic Enrol lmentDeter minationIn fo Enrollm entDetermi nationInfo  { get; se t; }
  1628           pu blic Demog raphics De mographics  { get; se t; }
  1629       }
  1630  
  1631                    /*{" ErrorOccur red":false ,
  1632                 * "Erro rMessage": null,
  1633                 * "Stat us":null,
  1634                 * "Debu gInfo":nul l,
  1635                 * "Data ":{
  1636                 *       "Sensitivi tyInfo":{" SensityFla g":"false" },
  1637                 *       "Enrollmen tDetermina tionInfo": {"PrimaryE ligibility ":{"Type": "NSC"},"Ve teran":"tr ue"},
  1638                 *       "Demograph ics":{"Pre ferredFaci lity":"565  - FAYETTE VILLE VA M EDICAL CEN TER"}
  1639                 *       }
  1640                 *  }
  1641                 */
  1642       
  1643  
  1644       public  class Sen sitiveObje ct
  1645       {
  1646           pu blic bool  ErrorOccur red { get;  set; }
  1647           pu blic objec t ErrorMes sage { get ; set; }
  1648           pu blic objec t Status {  get; set;  }
  1649           pu blic objec t DebugInf o { get; s et; }
  1650           pu blic List< Datum> Dat a { get; s et; }
  1651       }
  1652       public  class Dat um
  1653       {
  1654           pu blic objec t Fault {  get; set;  }
  1655           pu blic Sensi tiveInfo R eturn1 { g et; set; }
  1656       }
  1657       public  class Sen sitiveInfo
  1658       {
  1659           pu blic strin g BdnStnNb r { get; s et; }
  1660           pu blic strin g BirlsFol derLctnTxt  { get; se t; }
  1661           pu blic strin g Cd { get ; set; }
  1662           pu blic strin g DgnstcSu prsnInd {  get; set;  }
  1663           pu blic strin g FcltyTyp eCd { get;  set; }
  1664           pu blic DateT ime JrnDt  { get; set ; }
  1665           pu blic strin g JrnLctnI d { get; s et; }
  1666           pu blic strin g JrnObjId  { get; se t; }
  1667           pu blic strin g JrnStatu sTypeCd {  get; set;  }
  1668           pu blic strin g JrnUserI d { get; s et; }
  1669           pu blic strin g PtcpntId  { get; se t; }
  1670           pu blic strin g RmksTxt  { get; set ; }
  1671           pu blic strin g ScrtyLev elTypeCd {  get; set;  }
  1672           pu blic strin g SntvtyLe velId { ge t; set; }
  1673       }
  1674       public  class Vet eranEmploy eeFlag
  1675       {
  1676           pu blic strin g National Id { get;  set; }
  1677           pu blic strin g Value {  get; set;  }
  1678       }
  1679  
  1680   }
  1681   #endregion