1. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 4/14/2017 7:19:37 AM Central 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.

1.1 Files compared

# Location File Last Modified
1 TMP.CRM.zip\TMP.CRM\Plugins\VA.TMP.CRM.Plugins\Email EMailCreatePostStageRunner.cs Thu Apr 13 20:17:42 2017 UTC
2 TMP.CRM.zip\TMP.CRM\Plugins\VA.TMP.CRM.Plugins\Email EMailCreatePostStageRunner.cs Thu Apr 13 20:32:16 2017 UTC

1.2 Comparison summary

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

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

1.4 Active regular expressions

No regular expressions were active.

1.5 Comparison detail

  1   using MCSS hared;
  2   using Micr osoft.Crm. Sdk.Messag es;
  3   using Micr osoft.Xrm. Sdk;
  4   using Micr osoft.Xrm. Sdk.Query;
  5   using Syst em;
  6   using Syst em.Collect ions.Gener ic;
  7   using Syst em.Globali zation;
  8   using Syst em.Linq;
  9   using Syst em.Text;
  10   using VA.T MP.DataMod el;
  11   using VA.T MP.OptionS ets;
  12  
  13   namespace  VA.TMP.CRM
  14   {
  15       public  class EMa ilCreatePo stStageRun ner : Plug inRunner
  16       {         
  17           pu blic EMail CreatePost StageRunne r(IService Provider s erviceProv ider) : ba se(service Provider)  { }
  18           // Declare gl obal varia bles
  19           st ring custo mMessage;
  20           // Emergency  Contact In fo
  21           st ring SiteM ainPhone,  ProTCTName , ProTCTPh one, ProTC TEmail, Pa tTCTName,  PatTCTPhon e, PatTCTE mail, ProR oom, PatRo om, SiteLo cal911Phon e, TSAProv Emergency,  TSAPatEme rgency;
  22           
  23           st ring Patie ntVirtualM eetingSpac e = string .Empty, Pr oviderVirt ualMeeting Space = st ring.Empty ;
  24           Bo olean isCV TTablet =  false;
  25           cv t_componen t VirtualM eetingSpac e = new cv t_componen t();
  26           st ring steth IP = "";
  27  
  28           #r egion Impl ementation
  29           // / <summary >
  30           // / Called b y PluginRu nner - Dec ide which  email to s end out (a ka which b ranch of t he plugin  to run)
  31           // / </summar y>
  32           pu blic overr ide void E xecute()
  33           {
  34  
  35                Email em ail = (Ema il)Organiz ationServi ce.Retriev e(Email.En tityLogica lName.ToSt ring(), Pr imaryEntit y.Id, new  ColumnSet( true));
  36                if (emai l.Subject. StartsWith ("FW:") ||  email.Sub ject.Start sWith("RE: "))
  37                    retu rn;
  38                if (emai l.mcs_Rela tedService Activity ! = null)
  39                {
  40                    Serv iceAppoint ment relat edAppt = ( ServiceApp ointment)O rganizatio nService.R etrieve(
  41                         ServiceApp ointment.E ntityLogic alName.ToS tring(), e mail.mcs_R elatedServ iceActivit y.Id, new  ColumnSet( true));
  42                    
  43                    if ( (relatedAp pt.StatusC ode.Value  == 9 || re latedAppt. StatusCode .Value ==  4 || relat edAppt.Sta tusCode.Va lue == 917 290000) &&  email.Reg ardingObje ctId == nu ll)
  44                    {
  45                         if (email. Subject.St artsWith(" TSS Schedu ler Action :"))
  46                         {
  47                             Logger .WriteDebu gMessage(" Beginning  Vista Remi nder Email ");
  48                             SendVi staReminde r(email);
  49                             Logger .WriteDebu gMessage(" Completed  Vista Remi nder Email ");
  50                         }
  51                         else if (e mail.Subje ct.Contain s("Telehea lth Appoin tment Noti fication f or"))
  52                         {
  53                             Logger .WriteDebu gMessage(" Beginning  Service Ac tivity Not ification  Email");
  54                             Notify Participan tsOfAppoin tment(emai l, related Appt);
  55                             Logger .WriteDebu gMessage(" Completed  Service Ac tivity Not ification  Email");
  56                         }
  57                    }
  58                    //Se nd Patient  Email (th is email i s created  at the end  of the No tifyPartic ipantsOfAp pointment,  so this c ode will t rigger a 2 nd round o f the plug in executi on to get  to this br anch)
  59                    else  if (email .Regarding ObjectId ! = null &&  email.Rega rdingObjec tId.Logica lName == C ontact.Ent ityLogical Name)
  60                    {
  61                         Logger.Wri teDebugMes sage("Begi nning Pati ent Email" );
  62                         CreateCale ndarAppoin tmentAttac hment(emai l, related Appt, rela tedAppt.St atusCode.V alue, "");
  63                         CvtHelper. UpdateSend Email(emai l, Organiz ationServi ce);
  64                         Logger.Wri teDebugMes sage("Comp leted Pati ent Email" );
  65                    }
  66                    else
  67                         return;
  68                }
  69  
  70                if (emai l.Regardin gObjectId  != null)
  71                {
  72                    Logg er.WriteDe bugMessage ("Beginnin g Send Ema il");
  73                    swit ch (email. RegardingO bjectId.Lo gicalName)
  74                    {
  75                         //Regardin g Object:  TSA
  76                         case mcs_s ervices.En tityLogica lName:
  77                             SendTS AEmail(ema il, email. RegardingO bjectId.Id );
  78                             Logger .WriteDebu gMessage(" Completed  Send TSA E mail");
  79                             break;
  80                         //Regardin g Object:  TSS Privil eging
  81                         case cvt_t ssprivileg ing.Entity LogicalNam e:
  82                             SendPr ivilegingE mail(email , email.Re gardingObj ectId.Id,  email.Rega rdingObjec tId.Logica lName);
  83                             Logger .WriteDebu gMessage(" Completed  Send Privi leging Ema il");
  84                             break;
  85                         //Regardin g Object:  Quality Ch eck
  86                         case cvt_q ualitychec k.EntityLo gicalName:
  87                             SendTr iggerEmail (email, em ail.Regard ingObjectI d.Id, emai l.Regardin gObjectId. LogicalNam e);
  88                             Logger .WriteDebu gMessage(" Completed  FPPE/OPPE  Email");
  89                             break;
  90                         //Regardin g Object:  PPE Review
  91                         case cvt_p pereview.E ntityLogic alName:
  92                             SendPP EReviewEma il(email,  email.Rega rdingObjec tId.Id, em ail.Regard ingObjectI d.LogicalN ame);
  93                             Logger .WriteDebu gMessage(" Completed  PPE Review  Email");
  94                             break;
  95                         //Regardin g Object:  Team
  96                         //case Tea m.EntityLo gicalName:
  97                         //    Send PPESummary Email(emai l, email.R egardingOb jectId.Id,  email.Reg ardingObje ctId.Logic alName);
  98                         //    Logg er.WriteDe bugMessage ("Complete d Team Ema il");
  99                         //    brea k;
  100                         //Regardin g Object:  PPE Review
  101                         case cvt_p pefeedback .EntityLog icalName:
  102                             SendPP EFeedbackE mail(email , email.Re gardingObj ectId.Id,  email.Rega rdingObjec tId.Logica lName);
  103                             Logger .WriteDebu gMessage(" Completed  PPE Feedba ck Email") ;
  104                             break;
  105                    }
  106                }
  107           }
  108  
  109   #endregion
  110  
  111           #r egion Comm only Used  Functions
  112  
  113           // / <summary >
  114           // / Overload  for basic  generateE mailBody -  displays  the url as  the messa ge for "Cl ick Here"
  115           // / </summar y>
  116           // / <param n ame="recor d">ID of t he email</ param>
  117           // / <param n ame="entit yStringNam e">string  name of th e entity -  to retrie ve object  type code< /param>
  118           // / <param n ame="custo mMessage"> The messag e</param>
  119           // / <returns ></returns >
  120           in ternal str ing genera teEmailBod y(Guid rec ord, strin g entitySt ringName,  string cus tomMessage ){
  121                return g enerateEma ilBody(rec ord, entit yStringNam e, customM essage, nu ll);
  122           }
  123  
  124           // / <summary >
  125           // / Standard  "boilerpl ate" E-Mai l body
  126           // / </summar y>
  127           // / <param n ame="recor d">ID of t he email r ecord</par am>
  128           // / <param n ame="entit yStringNam e">The str ing name o f the obje ct type co de</param>
  129           // / <param n ame="custo mMessage"> The custom  string th at goes in to the ema il body</p aram>
  130           // / <param n ame="click HereMessag e">The mes sage that  is used as  the displ ay for the  hyperlink </param>
  131           // / <returns >the body  of the ema il</return s>
  132           in ternal str ing genera teEmailBod y(Guid rec ord, strin g entitySt ringName,  string cus tomMessage , string c lickHereMe ssage)
  133           {
  134                string b ody;
  135                var etc  = CvtHelpe r.GetEntit yTypeCode( Organizati onService,  entityStr ingName);
  136                string s ervernameA ndOrgname  = CvtHelpe r.getServe rURL(Organ izationSer vice);
  137                string u rl = serve rnameAndOr gname + "/ userDefine d/edit.asp x?etc=" +  etc + "&id =" + recor d;
  138                clickHer eMessage =  (clickHer eMessage = = null ||  clickHereM essage ==  string.Emp ty) ? url  : clickHer eMessage;
  139                //Custom  email tex t
  140                body = " <br/><a hr ef=\"" + u rl + "\">"  + clickHe reMessage  + "</a>";
  141                body +=  "<br/><br/ >" + custo mMessage;
  142  
  143                //Standa rd email t ext
  144                body +=  "<br/><br/ >This is a n automate d notifica tion from  the Telehe alth Sched uling Syst em.";
  145  
  146                return b ody;
  147           }
  148  
  149           #e ndregion
  150  
  151           // TO-DO: fix  patient n otificatio n email wh en tsa is  created (t o send to  team inste ad of indi vidual use r)
  152           #r egion Send TSAEmails
  153  
  154           // / <summary >
  155           // / Returns  a string v alue repre senting th e body of  the email  for TSA ap proval not ification
  156           // / </summar y>
  157           // / <param n ame="email ">the obje ct represe nting the  email whic h is being  sent</par am>
  158           // / <param n ame="recor d">the Gui d of the T SA which i s causing  this notif ication to  be sent</ param>
  159           // / <param n ame="entit yStringNam e">the ent ity logica l name of  the tsa (i .e. "mcs_s ervices")< /param>
  160           // / <returns ></returns >
  161           in ternal str ing Approv alEmailBod y(Email em ail)
  162           {
  163  
  164                var appr over = Str ing.Empty;
  165                var next Team = Str ing.Empty;
  166                var FTC  = String.E mpty;
  167                var patF acility =  String.Emp ty;
  168                //Get th e Previous  approvers  by queryi ng most re cent note
  169                using (v ar srv = n ew Xrm(Org anizationS ervice))
  170                {
  171                    var  TSANote =  srv.Annota tionSet.Wh ere(n => n .ObjectId. Id == emai l.Regardin gObjectId. Id).OrderB yDescendin g(n => n.C reatedOn). First(n =>  n.NoteTex t.Contains ("Approved  by"));
  172                    //mo st recent  approver
  173                    appr over = TSA Note.Creat edBy.Name;
  174                    var  tsa = srv. mcs_servic esSet.Firs tOrDefault (t => t.Id  == email. RegardingO bjectId.Id );
  175                    patF acility =  tsa.cvt_Pa tientFacil ity == nul l ? String .Empty : "  To " + ts a.cvt_Pati entFacilit y.Name;
  176                    if ( tsa.cvt_Se rviceScope .Value ==  917290001)
  177                         patFacilit y = " (Int rafacility )";
  178                    //Ge t the next  approver  up and get  the FTC w ho created  the TSA ( assumed to  be provid er side) a nd the FTC  who first  approved  the TSA (a ssumed to  be patient  side)
  179                    swit ch (tsa.st atuscode.V alue)
  180                    {
  181                         case (int) mcs_servic es_statusc ode.Approv edbyPatFTC
  182                             nextTe am = "Prov ider FTC T eam";
  183                             goto c ase 0;
  184                         case (int) mcs_servic es_statusc ode.Approv edbyProvFT C:
  185                             nextTe am = "Prov ider Servi ce Chief T eam";
  186                             goto c ase 0;
  187                         case (int) mcs_servic es_statusc ode.Approv edbyProvSe rviceChief :
  188                             nextTe am = "Prov ider Chief  of Staff  Team";
  189                             goto c ase 0;
  190                         case (int) mcs_servic es_statusc ode.Approv edbyProvCh iefofStaff
  191                             nextTe am = "Pati ent Servic e Chief Te am";
  192                             goto c ase -1;
  193                         case (int) mcs_servic es_statusc ode.Approv edbyPatSer viceChief:  
  194                             nextTe am = "Pati ent Chief  of Staff T eam";
  195                             goto c ase -1;
  196                         case 0: // if Provide r side - g et the use r who crea ted the TS A - assume d to be th e Provider  FTC
  197                             FTC =  srv.System UserSet.Fi rstOrDefau lt(u => u. Id == tsa. CreatedBy. Id).FullNa me;
  198                             break;
  199                         case -1: / /If patien t side - g et user wh o first ap proved the  TSA - ass umed to be  the Patie nt FTC
  200                             var fi rstApprove r = srv.An notationSe t.Where(n  => n.Objec tId.Id ==  email.Rega rdingObjec tId.Id).Or derBy(n =>  n.Created On).First( n => n.Not eText.Cont ains("Appr oved by")) ;
  201                             FTC =  firstAppro ver.Create dBy.Name;
  202                             break;
  203                    }
  204                }
  205  
  206                //TODO:  Add patien t facility , change s pacing
  207                //get th e FTC for  whichever  side the T SA is awai ting appro val
  208                string h yperlink =  GetTSALin k(email);
  209                  string Ops Manual = " http://vaw w.infoshar e. DNS     /sites/tel ehealth/cv tntc/docs/ user_tsa_a ppr.docx";
  210                  string Rol lOut = "ht tp://vaww. telehealth . DNS     /resources /tmp/index .asp";
  211                string e mailBody =  String.Fo rmat("A Te lehealth S ervice Agr eement (TS A), {0} is  awaiting  your appro val. <br/> <ul><li>Pr evious App rover: {1} </li>" +
  212                    "<li >{2} is th e next in  line for t he TSA App roval Proc ess. </ul> The hyperl ink below  will take  you to the  Telehealt h Service  Agreement.   If you w ish to mak e changes  to the TSA  prior to  approval,  please con tact {3}.   If you ch oose to ap prove the  TSA, pleas e select t he Green B utton on t he top lef t corner.   If you ch oose to de cline appr oval, plea se select  the Red Bu tton on th e top left  corner.<b r/><br/><b >Click her e to take  action on  the TSA</b >: {4} <br /><br/>",  email.Rega rdingObjec tId.Name +  patFacili ty, approv er, nextTe am, FTC, h yperlink);
  213                string l oginNotes  = String.F ormat("Not e: A passw ord is not  required  to access  TMP.  Your  credentia ls are pas sed from W indows aut henticatio n used to  log on to  your compu ter.  Simp ly click t he link ab ove.  For  first time  access, o r access a fter a lon g period o f time, yo u may be p rompted to  choose \" VA Account s\" on a p op-up form .  After t hat, click ing the li nk will ta ke you dir ectly to t he TSA.  < br/><br/>T o see a br ief tutori al for app rovers, cl ick this l ink: {0} < br/><br/>T o access a ll resourc es (traini ng materia ls, operat ions manua l, etc.) f or TMP use rs, click  this link:  {1}", "<a  href=\""  + OpsManua l + "\">"  + OpsManua l + "</a>" , "<a href =\"" + Rol lOut + "\" >" + RollO ut + "</a> ");
  214           
  215                return e mailBody +  loginNote s;
  216           }
  217  
  218           // Send appro priate ema il based o n subject  line (deni al, under  revision,  reminder t o take act ion, waiti ng for app roval)
  219           in ternal voi d SendTSAE mail(Email  email, Gu id tsaID)
  220           {
  221                switch ( email.Subj ect)
  222                {
  223                    case  "A Telehe alth Servi ce Agreeme nt has bee n denied":  //Denial
  224                         email.Desc ription =  generateEm ailBody(ts aID, "mcs_ services",  "The foll owing Tele health Ser vice Agree ment has b een Denied .  Please  review the  notes to  see the De nial Reaso n and corr ect any mi stakes if  applicable .", "Click  Here to v iew this T SA");
  225                         break;
  226                    case  "TSA unde r revision ": //Revis ion
  227                         customMess age = "The  following  Telehealt h Service  Agreement  is Under R evision.";
  228                         break;
  229                    case  "Please T ake Action  on the fo llowing TS A": //Remi nder
  230                         customMess age = "Thi s is a rem inder that  the follo wing Teleh ealth Serv ice Agreem ent is wai ting for y ou to take  action.";
  231                         break;
  232                    case  "FYI: A T elehealth  Service Ag reement ha s been com pleted": / /Productio n Notifica tion
  233                         email.Desc ription =  TSANotific ationText( email);
  234                         break;
  235                    case  "A TSA to  your Faci lity has b een create d": //Noti fy patient  site that  TSA was c reated
  236                         email.Desc ription =  generateEm ailBody(ts aID, "mcs_ services",  "Please c oordinate  with the P rovider Si te FTC to  set up the  following  TSA.  Onc e all the  details ar e finalize d, it is t he respons ibility of  the Patie nt Site FT C to begin  the Signa ture colle ction proc ess.", "Cl ick Here t o view thi s TSA");
  237                         break;
  238                    defa ult:
  239                         if (email. Subject.Co ntains("Te lehealth S ervice Agr eement is  awaiting y our approv al")) //Ap proval
  240                             email. Descriptio n = Approv alEmailBod y(email);
  241                         else
  242                         {
  243                             Logger .WriteToFi le("Unable  to match  email subj ect to val id TSA ema il type, e xiting plu gin");
  244                             return ;
  245                         }
  246                         break;
  247                }
  248                //Get Te am Members  will quer y the Team  Members t able and r eturn an A ctivity Pa rty List o f the peop le listed  on the tea m specifie d
  249                //If can t find tea m members,  log the e rror and c ontinue at tempting t o populate  the messa ge descrip tion
  250                try
  251                {
  252                    emai l.To = Get TeamMember s(email, t saID);
  253                    Logg er.WriteDe bugMessage ("Populate d Email Re cipients") ;
  254                }
  255                catch (E xception e x)
  256                {
  257                    Logg er.WriteTo File(ex.Me ssage);
  258                }
  259                if (emai l.Descript ion == nul l)
  260                    emai l.Descript ion = gene rateEmailB ody(tsaID,  "mcs_serv ices", cus tomMessage , "Click H ere to app rove/deny  this TSA") ;
  261                //Get th e owner of  the workf low for th e From fie ld
  262                if (emai l.From.Cou nt() == 0)
  263                    emai l.From = C vtHelper.G etWorkflow Owner("TSA  Approval  Step 1 - A waiting Pr ov FTC", O rganizatio nService);
  264                Logger.W riteDebugM essage("Se nding TSA  Email");
  265                CvtHelpe r.UpdateSe ndEmail(em ail, Organ izationSer vice);
  266                Logger.W riteDebugM essage("TS A Email Se nt");
  267           }
  268  
  269           in ternal str ing GetTSA Link(Email  email)
  270           {
  271                var etc  = CvtHelpe r.GetEntit yTypeCode( Organizati onService,  mcs_servi ces.Entity LogicalNam e);
  272                string s ervernameA ndOrgname  = CvtHelpe r.getServe rURL(Organ izationSer vice);
  273                string u rl = serve rnameAndOr gname + "/ userDefine d/edit.asp x?etc=" +  etc + "&id =" + email .Regarding ObjectId.I d;
  274                return S tring.Form at("<a hre f=\"{0}\"> {1}</a>",  url, url);
  275           }
  276  
  277           in ternal str ing TSANot ificationT ext(Email  email)
  278           {
  279                  return Str ing.Format ("For your  informati on, a Tele health Ser vice Agree ment (TSA) , {0} has  been appro ved.    <br/>The h yperlink b elow will  take you t o the Tele health Ser vice Agree ment. \n\n Click here  to view t he TSA: {1 } <br /><b r />Note:  A password  is not re quired to  access TSS . Your cre dentials a re passed  from Windo ws authent ication us ed to log  on to your  computer.  Simply cl ick the li nk above.  For first  time acces s, or acce ss after a  long peri od of time , you may  be prompte d to choos e \"VA Acc ounts\" on  a pop-up  form.    After that , clicking  the link  will take  you direct ly to the  TSA.    <br /><br  />To acces s all reso urces (tra ining mate rials, ope rations ma nual, etc. ) for TMP  users, cli ck this li nk: {2}",  email.Rega rdingObjec tId.Name,  GetTSALink (email), S tring.Form at("<a hre f=\"{0}\"> {0}</a>"," http://vaw w.infoshar e. DNS     /sites/tel ehelpdesk/ TSS%20Roll -Out/defau lt.aspx")) ;
  280           }
  281  
  282           // / <summary >
  283           // / Query th e team mem bership ta ble to get  the team  appropriat e for the  status of  the TSA.   return the  list of a ctivity pa rties corr esponding  to the sys tem users  that are m embers of  the team.   
  284           // / </summar y>
  285           // / <param n ame="email ">This is  the email  record tha t is being  built and  eventuall y gets sen t out</par am>
  286           // / <param n ame="tsaID ">This is  the ID of  the TSA th at generat ed this em ail.  Base d on the s tatus of t he TSA, a  specific t eam will b e selected </param>
  287           // / <returns >Activity  Party List  correspon ding to Sy stem users  that are  members of  the team< /returns>
  288           in ternal Lis t<Activity Party> Get TeamMember s(Email em ail, Guid  tsaID)
  289           {
  290                //Status  Listing:  917290002= =Approved  by Pat FTC , 91729000 0==Prov FT C, 9172900 01==Prov S C, 9172900 04==Prov C oS, 917290 005==Pat S C, 9172900 06==Pendin g Privileg ing, 25192 0000==PROD , 91729000 3==DENIED,  917290007 ==UNDER RE VISION; 91 7290008==A pproved by  Prov C&P
  291                var memb ers = new  List<Activ ityParty>( );
  292                var team Members =  new List<T eamMembers hip>();
  293                using (v ar srv = n ew Xrm(Org anizationS ervice))
  294                {
  295                    //Ge t both the  Patient a nd Provide r Facility  to check  for the te ams on bot h sides
  296                    var  tsa = srv. mcs_servic esSet.Firs t(t => t.I d == tsaID );
  297                    var  proFacilit yId = tsa. cvt_Provid erFacility .Id;
  298                    var  patFacilit yId = tsa. cvt_Patien tFacility  != null ?  tsa.cvt_Pa tientFacil ity.Id : G uid.Empty;
  299                    var  team = new  Team();
  300                    swit ch (tsa.st atuscode.V alue)
  301                    {
  302                         case (int) mcs_servic es_statusc ode.Draft:  //For Dra ft TSAs, s end notifi cation tha t TSA has  been creat ed for the ir site. 
  303                             team =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == patFac ilityId &&  t.cvt_Typ e != null  && t.cvt_T ype.Value  == (int)Te amcvt_Type .FTC);
  304                             break;
  305                         case (int) mcs_servic es_statusc ode.Approv edbyPatFTC ://Approve d by Patie nt Site FT C (get Pro vider Site  FTC Team)  - Workflo w Step 1
  306                             team =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == proFac ilityId &&  t.cvt_Typ e != null  && t.cvt_T ype.Value  == (int)Te amcvt_Type .FTC);
  307                             break;
  308                         case (int) mcs_servic es_statusc ode.Approv edbyProvFT C://Approv ed by Prov ider Site  FTC (get P rovider Se rvice Chie f Team) -  Workflow S tep 2
  309                             team =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == proFac ilityId &&
  310                                 t. cvt_Type ! = null &&  t.cvt_Type .Value ==  (int)Teamc vt_Type.Se rviceChief  && t.cvt_ ServiceTyp e.Id == ts a.cvt_serv icetype.Id );
  311                             break;
  312                         case (int) mcs_servic es_statusc ode.Approv edbyProvSe rviceChief ://Approve d by Provi der Servic e Chief (g et Prov Ch ief of Sta ff Team) -  Workflow  Step 3
  313                             team =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == proFac ilityId &&  t.cvt_Typ e != null  && t.cvt_T ype.Value  == (int)Te amcvt_Type .ChiefofSt aff);
  314                             break;
  315                         case (int) mcs_servic es_statusc ode.Approv edbyProvCh iefofStaff ://Approve d by Provi der Site C hief of St aff (Get P atient Sit e Service  Chief) - W orkflow St ep 5
  316                             if (pa tFacilityI d != Guid. Empty)
  317                                 te am = srv.T eamSet.Fir stOrDefaul t(t => t.c vt_Facilit y.Id == pa tFacilityI d &&
  318                                      t.cvt_Ty pe != null  && t.cvt_ Type.Value  == (int)T eamcvt_Typ e.ServiceC hief && t. cvt_Servic eType.Id = = tsa.cvt_ servicetyp e.Id);
  319                             break;
  320                         case (int) mcs_servic es_statusc ode.Approv edbyPatSer viceChief: //Approved  by Patien t Site Ser vice Chief  (Get Pati ent Site C hief of St aff) - Wor kflow Step  6
  321                             if (pa tFacilityI d != Guid. Empty)
  322                                 te am = srv.T eamSet.Fir stOrDefaul t(t => t.c vt_Facilit y.Id == pa tFacilityI d && t.cvt _Type != n ull && t.c vt_Type.Va lue == (in t)Teamcvt_ Type.Chief ofStaff);
  323                             break;
  324                         case (int) mcs_servic es_statusc ode.UnderR evision:// Get both s ide FTCs w hether it  is in Deni ed status  or in Unde r Revision
  325                         case (int) mcs_servic es_statusc ode.Denied :
  326                             team =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == proFac ilityId &&  t.cvt_Typ e != null  && t.cvt_T ype.Value  == (int)Te amcvt_Type .FTC);
  327                             if (te am != null )
  328                                 te amMembers  = (List<Te amMembersh ip>)(srv.T eamMembers hipSet.Whe re(t => t. TeamId ==  team.Id).T oList());
  329  
  330                             //repu rpose team  variable  to get pat ient facil ity (prov  facility t eam member s have alr eady been  added abov e) and add  team memb ers from p at facilit y
  331                             if (pa tFacilityI d != Guid. Empty)
  332                             {
  333                                 te am = srv.T eamSet.Fir stOrDefaul t(t => t.c vt_Facilit y.Id == pa tFacilityI d && t.cvt _Type != n ull && t.c vt_Type.Va lue == (in t)Teamcvt_ Type.FTC);
  334                                 if  (team !=  null)
  335                                 {
  336                                      if (team Members.Co unt == 0)
  337                                          team Members =  (List<Team Membership >)(srv.Tea mMembershi pSet.Where (t => t.Te amId == te am.Id).ToL ist());
  338                                      else
  339                                          team Members.Ad dRange((Li st<TeamMem bership>)( srv.TeamMe mbershipSe t.Where(t  => t.TeamI d == team. Id).ToList ()));
  340                                 }
  341                             }
  342                             break;
  343                         case (int) mcs_servic es_statusc ode.Produc tion: //PR OD - Get B oth sides  notificati on team fo r TSA Noti fication e mail
  344                             team =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == proFac ilityId &&  t.cvt_Typ e != null  && t.cvt_T ype.Value  == (int)Te amcvt_Type .TSANotifi cation);
  345                             if (te am != null )
  346                                 te amMembers  = (List<Te amMembersh ip>)(srv.T eamMembers hipSet.Whe re(t => t. TeamId ==  team.Id).T oList());
  347  
  348                             //repu rpose team  variable  to get pat ient facil ity (prov  facility t eam member s have alr eady been  added abov e) and add  team memb ers from p at facilit y (if not  intrafacil ity)
  349                             if (pa tFacilityI d != Guid. Empty && p atFacility Id != proF acilityId)
  350                             {
  351                                 te am = srv.T eamSet.Fir stOrDefaul t(t => t.c vt_Facilit y.Id == pa tFacilityI d && t.cvt _Type != n ull && t.c vt_Type.Va lue == (in t)Teamcvt_ Type.TSANo tification );
  352                                 if  (team !=  null)
  353                                 {
  354                                      if (team Members.Co unt == 0)
  355                                          team Members =  (List<Team Membership >)(srv.Tea mMembershi pSet.Where (t => t.Te amId == te am.Id).ToL ist());
  356                                      else
  357                                          team Members.Ad dRange((Li st<TeamMem bership>)( srv.TeamMe mbershipSe t.Where(t  => t.TeamI d == team. Id).ToList ()));
  358                                 }
  359                             }
  360                             break;  
  361                    }
  362                    if ( team == nu ll)
  363                         throw new  InvalidPlu ginExecuti onExceptio n("No Team  was found  to receiv e this ema il, please  verify th e team is  set up");
  364                    if ( teamMember s.Count ==  0) //if y ou havent  already ad ded the te am members  (everthin g other th an prod no tification , under re vision and  denial) t hen add no w
  365                         teamMember s = (List< TeamMember ship>)(srv .TeamMembe rshipSet.W here(t =>  t.TeamId = = team.Id) .ToList()) ;
  366                    fore ach (var m ember in t eamMembers )
  367                    {
  368                         var party  = new Acti vityParty( ){
  369                             Activi tyId = new  EntityRef erence(ema il.Logical Name, emai l.Id),
  370                             PartyI d = new En tityRefere nce(System User.Entit yLogicalNa me, member .SystemUse rId.Value)
  371                         };
  372                         members.Ad d(party);
  373                    }
  374                }
  375                if (memb ers.Count  == 0)
  376                    memb ers.AddRan ge(email.T o);
  377                return m embers;
  378           }
  379  
  380           #e ndregion
  381  
  382           #r egion Send serviceapp ointmentNo tification s
  383  
  384           // / <summary >
  385           // / Primary  function w hich gener ates the S ervice Act ivity noti fication ( including  ical)
  386           // / </summar y>
  387           // / <param n ame="email ">The emai l object c orrespondi ng to the  email reco rd created  which tri ggered thi s plugin</ param>
  388           // / <param n ame="relat edAppt">Th e service  activity w hich gener ated the e mail and i s the subj ect of the  notificat ion</param >
  389           in ternal voi d NotifyPa rticipants OfAppointm ent(Email  email, Ser viceAppoin tment rela tedAppt)
  390           {
  391                List<Sys temUser> p roTCTuser  = new List <SystemUse r>();
  392                List<Sys temUser> p atTCTuser  = new List <SystemUse r>();
  393  
  394                //Get th e TSA so y ou can fig ure out wh ether the  resource i s provider  or patien t side
  395                mcs_serv ices tsa =  (mcs_serv ices)Organ izationSer vice.Retri eve(mcs_se rvices.Ent ityLogical Name, rela tedAppt.mc s_relatedt sa.Id, new  ColumnSet (true));
  396  
  397                //Get th e Pro/Pat  Emergency  Info from  TSA
  398                TSAProvE mergency =  tsa.cvt_P roviderSta ffEmergenc yResponsib ilities;
  399                TSAPatEm ergency =  tsa.cvt_Pa tientStaff EmergencyR esponsibil ities;
  400  
  401                if (tsa. cvt_Patien tSiteClini calPOC !=  null)
  402                {
  403                    Guid  TCTonTSA  = tsa.cvt_ PatientSit eClinicalP OC.Id;
  404                    //Ge t the TCTs  Mobile or  Office ph one 
  405                    Syst emUser tct  = (System User)Organ izationSer vice.Retri eve(System User.Entit yLogicalNa me, TCTonT SA, new Co lumnSet("m obilephone ", "cvt_of ficephone" , "firstna me", "last name", "in ternalemai laddress") );
  406                    PatT CTPhone =  tct.Mobile Phone;  // Use the TC T number
  407                    PatT CTName = t ct.FirstNa me + " " +  tct.LastN ame;
  408                    PatT CTEmail =  tct.Intern alEMailAdd ress;
  409                    patT CTuser.Add (tct);
  410                    if ( PatTCTPhon e == null)
  411                         PatTCTPhon e = tct.cv t_officeph one;  //Us e the TCT  number
  412                }
  413  
  414                //Get th e Pro TCT
  415                if (tsa. cvt_Provid erSiteClin icalPOC !=  null)
  416                {
  417                    Guid  TCTonTSA  = tsa.cvt_ ProviderSi teClinical POC.Id;
  418                    //Ge t the TCTs  Mobile or  Office ph one 
  419                    Syst emUser tct  = (System User)Organ izationSer vice.Retri eve(System User.Entit yLogicalNa me, TCTonT SA, new Co lumnSet("m obilephone ", "cvt_of ficephone" , "firstna me", "last name", "in ternalemai laddress") );
  420                    ProT CTPhone =  tct.Mobile Phone;  // Use the TC T number
  421                    ProT CTName = t ct.FirstNa me + " " +  tct.LastN ame;
  422                    ProT CTEmail =  tct.Intern alEMailAdd ress;
  423                    proT CTuser.Add (tct);
  424                    if ( ProTCTPhon e == null)
  425                         ProTCTPhon e = tct.cv t_officeph one;  //Us e the TCT  number
  426                }
  427                //Pro Le ad TCT
  428                if (ProT CTPhone ==  null) //N o Phone fr om TCT fro m TSA, loo k at Site  specified  one.
  429                {
  430                    if ( tsa.cvt_re latedprovi dersiteid. Id != null ) //Check  for TSA Pr ovider Sit e
  431                    {
  432                         //Get Prov ider Site
  433                         //get the  TSA's rela ted patien t site
  434                         mcs_site r elatedpros ite = (mcs _site)Orga nizationSe rvice.Retr ieve(mcs_s ite.Entity LogicalNam e, tsa.cvt _relatedpr ovidersite id.Id, new  ColumnSet (true));
  435  
  436                         if (relate dprosite.c vt_LeadTCT  != null)
  437                         {
  438                             //Get  the Lead T CTs Mobile  or Office  phone 
  439                             System User tct =  (SystemUs er)Organiz ationServi ce.Retriev e(SystemUs er.EntityL ogicalName , relatedp rosite.cvt _LeadTCT.I d, new Col umnSet("mo bilephone" , "cvt_off icephone",  "firstnam e", "lastn ame", "int ernalemail address")) ;
  440                             ProTCT Phone = tc t.MobilePh one;  //Us e the TCT  number
  441                             ProTCT Name = tct .FirstName  + " " + t ct.LastNam e;
  442                             ProTCT Email = tc t.Internal EMailAddre ss;
  443                             proTCT user.Clear ();
  444                             proTCT user.Add(t ct);
  445                             if (Pr oTCTPhone  == null)
  446                                 Pr oTCTPhone  = tct.cvt_ officephon e;  //Use  the TCT nu mber
  447                         }
  448                    }
  449                }
  450                //If CVT  to Home,  there is n o patient  site
  451                if ((tsa .cvt_Type  != true) & & (tsa.cvt _groupappo intment !=  true))
  452                {
  453                    //ge t the TSA' s related  patient si te
  454                    mcs_ site relat edpatsite  = (mcs_sit e)Organiza tionServic e.Retrieve (mcs_site. EntityLogi calName, t sa.cvt_rel atedpatien tsiteid.Id , new Colu mnSet(true ));
  455                    //Ge t the Site 's Emergen cy Contact  Info
  456                    if ( relatedpat site.cvt_L ocal911 !=  null)
  457                         SiteLocal9 11Phone =  relatedpat site.cvt_L ocal911; / /Use the L ocal 911
  458                    if ( relatedpat site.cvt_p hone != nu ll)
  459                         SiteMainPh one = rela tedpatsite .cvt_phone ; //Use th e Site Pho ne
  460  
  461                    //Pa t Lead TCT
  462                    if ( PatTCTPhon e == null)  //No Phon e from TCT  from TSA,  look at P at Site sp ecified on e.
  463                    {
  464                         if (relate dpatsite.c vt_LeadTCT  != null)
  465                         {
  466                             //Get  the Lead T CTs Mobile  or Office  phone 
  467                             System User tct =  (SystemUs er)Organiz ationServi ce.Retriev e(SystemUs er.EntityL ogicalName , relatedp atsite.cvt _LeadTCT.I d, new Col umnSet("mo bilephone" , "cvt_off icephone",  "firstnam e", "lastn ame", "int ernalemail address")) ;
  468                             PatTCT Phone = tc t.MobilePh one;  //Us e the TCT  number
  469                             PatTCT Name = tct .FirstName  + " " + t ct.LastNam e;
  470                             PatTCT Email = tc t.Internal EMailAddre ss;
  471                             patTCT user.Clear ();
  472                             patTCT user.Add(t ct);
  473                             if (Pa tTCTPhone  == null)
  474                                 Pa tTCTPhone  = tct.cvt_ officephon e;  //Use  the TCT nu mber
  475                         }
  476                    }
  477                }
  478  
  479                //Get th e Pat TCT
  480                //Get th e resource s listed o n the serv ice activi ty
  481                var reso urces = re latedAppt. GetAttribu teValue<En tityCollec tion>("res ources");
  482                EntityCo llection u sers = new  EntityCol lection();
  483                EntityCo llection e quipmentRe sources =  new Entity Collection ();
  484                resource s.Entities .AddRange( GetApptRes ources(rel atedAppt,  string.Emp ty));
  485  
  486                //Get th e users fr om the res ource list  (filter o ut equipme nt)
  487                foreach  (var res i n resource s.Entities )
  488                {
  489                    var  party = re s.ToEntity <ActivityP arty>();
  490                    if ( party.Part yId.Logica lName == S ystemUser. EntityLogi calName)
  491                    {
  492                         ActivityPa rty p = ne w Activity Party()
  493                         {
  494                             PartyI d = new En tityRefere nce(System User.Entit yLogicalNa me, party. PartyId.Id )
  495                         };
  496                         users.Enti ties.Add(p );
  497                    }
  498                    else
  499                    {
  500                         Equipment  e = (Equip ment)Organ izationSer vice.Retri eve(Equipm ent.Entity LogicalNam e, party.P artyId.Id,  new Colum nSet("equi pmentid",  "mcs_relat edresource "));
  501                         mcs_resour ce equip =  (mcs_reso urce)Organ izationSer vice.Retri eve(mcs_re source.Ent ityLogical Name, e.mc s_relatedr esource.Id , new Colu mnSet(true ));
  502                         equipmentR esources.E ntities.Ad d(equip);
  503                    }
  504                }
  505  
  506                //Get th e rooms an d techs an d segment  them by pa tient/prov ider site
  507                var tsaP roResource s = getPRG s(tsa.Id,  "provider" );
  508                var tsaP atResource s = getPRG s(tsa.Id,  "patient") ;
  509                var prov iderTechs  = Classify Resources( equipmentR esources,  tsaProReso urces, (in t)mcs_reso urcetype.T echnology) ;
  510                var pati entTechs =  ClassifyR esources(e quipmentRe sources, t saPatResou rces, (int )mcs_resou rcetype.Te chnology);
  511                var prov iderRooms  = Classify Resources( equipmentR esources,  tsaProReso urces, (in t)mcs_reso urcetype.R oom);
  512                var pati entRooms =  ClassifyR esources(e quipmentRe sources, t saPatResou rces, (int )mcs_resou rcetype.Ro om);
  513  
  514                //select  which use rs to send  the email  to (provi ders/patie nts): null  means pro vider side , 1 means  patient si de (and 0  means both )
  515                var prov iderResour ces = GetR ecipients( users, tsa ProResourc es);
  516                var pati entResourc es = GetRe cipients(u sers, tsaP atResource s);
  517  
  518                //Get pr oviders so  we can pa ss in stri ng for lis t of clini cians to p atient ema il
  519                var clin icians = p roviderRes ources;
  520  
  521                //format  body of t he email ( telepresen ters can b e duplicat ed)
  522                var date  = string. Empty;
  523                var patS ite = tsa. cvt_relate dpatientsi teid;
  524                var patS iteString  = patSite  != null ?  patSite.Na me : strin g.Empty;
  525                if (patS iteString  == string. Empty)
  526                    patS iteString  = tsa.cvt_ groupappoi ntment.Val ue == true  ? tsa.cvt _PatientFa cility.Nam e : "Home/ Mobile";
  527                email.De scription  = formatNo tification EmailBody( providerTe chs, patie ntTechs, p roviderRoo ms, patien tRooms, pa tientResou rces, rela tedAppt, t sa, provid erResource s, out dat e);
  528                email.Su bject = em ail.Subjec t.Trim() +  " " + pat SiteString  + " " + d ate;
  529                //Combin e the list s and then  add them  as the ema il recipie nts
  530                provider Resources. AddRange(p atientReso urces);
  531  
  532                //Add th e Pro and  Pat TCT to  the .To
  533                provider Resources. AddRange(p roTCTuser) ;
  534                provider Resources. AddRange(p atTCTuser) ;
  535  
  536                email.To  = CvtHelp er.SetPart yList(prov iderResour ces);
  537  
  538                //Get th e owner of  the workf low for th e From fie ld    
  539                if (emai l.From.Cou nt() == 0)
  540                    emai l.From = C vtHelper.G etWorkflow Owner("Ser vice Activ ity Notifi cation", O rganizatio nService);
  541                //Organi zationServ ice.Update (email);
  542  
  543                //Send a  Calendar  Appointmen t if the a ppointment  is schedu led (if ca nceled, se nd cancell ation upda te)
  544                CreateCa lendarAppo intmentAtt achment(em ail, relat edAppt, re latedAppt. StatusCode .Value, st ethIP);
  545                CvtHelpe r.UpdateSe ndEmail(em ail, Organ izationSer vice);
  546  
  547                // Only  send patie nt email f or Home/Mo bile TSAs 
  548                // Futur e Phase TO DO: use st atic VMRs  and notify  patient t o hit desk top icon
  549                if (tsa. cvt_Type.V alue == tr ue)
  550                {
  551                    //Cr eate and S end Email  to Patient /Veteran ( copy sende r from Pro vider Emai l)
  552                    var  providerEm ailSender  = new Enti tyCollecti on();
  553                    prov iderEmailS ender.Enti ties.AddRa nge(email. From);
  554                    Send PatientEma il(related Appt, prov iderEmailS ender, cli nicians);
  555                }
  556           }
  557  
  558           in ternal str ing getPat ientVirtua lMeetingSp ace(Servic eAppointme nt sa, out  bool? pat ientSpace)
  559           {
  560                Logger.W riteDebugM essage("Ge tting Virt ual Meetin g Space");
  561                patientS pace = nul l;
  562                if (sa.m cs_Patient Url != nul l && sa.mc s_provider url != nul l)
  563                {
  564                    Pati entVirtual MeetingSpa ce = sa.mc s_PatientU rl;
  565                    Prov iderVirtua lMeetingSp ace = sa.m cs_provide rurl;
  566                    Logg er.WriteDe bugMessage ("Virtual  Meeting Sp ace is fro m Service  Activity R ecord: " +  PatientVi rtualMeeti ngSpace +  ", " + Pro viderVirtu alMeetingS pace);
  567                }
  568                else
  569                {
  570                    var  patientAP  = sa.Custo mers.First OrDefault( );
  571                    if ( patientAP  == null ||  patientAP .PartyId = = null)
  572                         return str ing.Empty;
  573                    Logg er.WriteDe bugMessage (sa.Custom ers.ToList ().Count() .ToString( ) + " pati ents " + p atientAP.P artyId.Nam e.ToString ());
  574                    var  patient =  (Contact)O rganizatio nService.R etrieve(Co ntact.Enti tyLogicalN ame, patie ntAP.Party Id.Id, new  ColumnSet (true));
  575                    Logg er.WriteDe bugMessage ("Contact:  " + patie nt.FullNam e + " VMR:  " + patie nt.cvt_Pat ientVirtua lMeetingSp ace + " an d Tablet:  " + patien t.cvt_BLTa blet);
  576                    if ( patient !=  null && p atient.cvt _PatientVi rtualMeeti ngSpace !=  null)
  577                    {
  578                         patientSpa ce = true;
  579                         PatientVir tualMeetin gSpace = p atient.cvt _PatientVi rtualMeeti ngSpace;
  580                         ProviderVi rtualMeeti ngSpace =  patient.cv t_Provider VirtualMee tingSpace;
  581                    }
  582                    else  if (patie nt != null  && patien t.cvt_BLTa blet != nu ll)
  583                    {
  584                         patientSpa ce = false ;
  585                         PatientVir tualMeetin gSpace = p atient.cvt _BLTablet;
  586                         isCVTTable t = true;
  587                    }
  588                    else  if (Virtu alMeetingS pace.Id !=  new Guid( ))
  589                         PatientVir tualMeetin gSpace = V irtualMeet ingSpace.c vt_webinte rfaceurl;
  590                    else
  591                         PatientVir tualMeetin gSpace = " Please Con tact Your  TCT for We b Meeting  Details";
  592                    Logg er.WriteDe bugMessage (PatientVi rtualMeeti ngSpace +  ": Virtual  Meeting S pace is fr om Patient  record =  " + patien tSpace.ToS tring());
  593                }
  594                return P atientVirt ualMeeting Space;
  595           }
  596  
  597           in ternal voi d SendPati entEmail(S erviceAppo intment sa , EntityCo llection F rom, List< SystemUser > provs)
  598           {
  599                if (Virt ualMeeting Space != n ull && Vir tualMeetin gSpace.Id  != Guid.Em pty || Pat ientVirtua lMeetingSp ace.IndexO f("Please  Contact Yo ur") == -1
  600                    // l ast check  is only re levant if  we do not  want to ge nerate ema il at all  given the  scenario w here no vi rtual meet ing space  is provide d
  601                {
  602                    //Ge t the Pati ent and th eir timezo ne
  603                    var  patientAP  = sa.Custo mers.First OrDefault( );
  604                    if ( patientAP  == null)
  605                         Logger.Wri teToFile(" No Patient  was found  to receiv e the emai l for foll owing Serv ice Activi ty: " + sa .Id);
  606                    else
  607                    {
  608                         var recipi ent = new  ActivityPa rty()
  609                         {
  610                             PartyI d = new En tityRefere nce(Contac t.EntityLo gicalName,  patientAP .PartyId.I d)
  611                         };
  612                         Logger.Wri teDebugMes sage("Send ing Patien t Email to  " + patie ntAP.Party Id.Name);
  613                         var patien t = (Conta ct)Organiz ationServi ce.Retriev e(Contact. EntityLogi calName, r ecipient.P artyId.Id,  new Colum nSet(true) );
  614  
  615                         //Setup va riables to  get timeZ one conver sion prope rly
  616                         DateTime t imeConvers ion = sa.S cheduledSt art.Value;
  617                         string ful lDate = st ring.Empty , timeZone sString =  string.Emp ty;
  618                         bool conve rtSuccess  = false;
  619                         bool isCan celled = ( sa.StatusC ode.Value  == 9 || sa .StatusCod e.Value ==  917290000 ) ? true :  false; // Cancellati on
  620                         int timeZo ne = patie nt.cvt_Tim eZone != n ull ? pati ent.cvt_Ti meZone.Val ue : 35; / /default t ime zone t o East Coa st if its  not listed  on the pa tient reco rd
  621  
  622                         timeConver sion = Con vertTimeZo ne(sa.Sche duledStart .Value, ti meZone, ou t timeZone sString, o ut convert Success);
  623                         Logger.Wri teDebugMes sage("Time  converted  to " + ti meZonesStr ing);
  624                         fullDate =  convertSu ccess ? ti meConversi on.ToStrin g("ddd dd  MMM yyyy H H:mm") + "  " + timeZ onesString  : timeCon version.To String("dd d dd MMM y yyy HH:mm" ) + " GMT" ;
  625  
  626                         //Creating  the Subje ct text
  627                         var subjec t = "Your  VA Video V isit has b een ";
  628                         subject +=  (isCancel led) ? "ca nceled" :  "scheduled ";
  629                         subject +=  " for " +  fullDate. Trim();
  630                         Logger.Wri teDebugMes sage("Loca l Time: "  + fullDate );
  631  
  632                         //Getting  the Subjec t Specialt y, Special ty Sub Typ e
  633                         var tsa =  (mcs_servi ces)Organi zationServ ice.Retrie ve(mcs_ser vices.Enti tyLogicalN ame, sa.mc s_relatedt sa.Id, new  ColumnSet (true));
  634                         var servic eText = (t sa.cvt_ser vicetype ! = null) ?  "<b>Specia lty:</b> "  + tsa.cvt _servicety pe.Name +  "<br />" :  "";
  635                         serviceTex t += (tsa. cvt_servic esubtype ! = null) ?  "<b>Specia lty Sub Ty pe:</b> "  + tsa.cvt_ servicesub type.Name  + "<br />"  : "";
  636  
  637  
  638                         var clinic ians = str ing.Empty;
  639                         foreach (S ystemUser  user in pr ovs)
  640                         {
  641                             clinic ians += us er.FullNam e + "; ";
  642                         }
  643                         if (clinic ians != st ring.Empty )
  644                             clinic ians = "<b >Clinician :</b> " +  clinicians .Remove(cl inicians.L ength - 2)  + "<br /> ";
  645  
  646                         //if you c an't find  "Please Co ntact Your " that mea ns a real  url was en tered, so  use it as  a hyperlin k, otherwi se, displa y the "Ple ase Contac t Your..."  message a s it comes  across
  647                         var meetin gSpace = P atientVirt ualMeeting Space.Inde xOf("Pleas e Contact  Your") ==  -1 ?
  648                             CvtHel per.buildH TMLUrl(Pat ientVirtua lMeetingSp ace, "Clic k Here to  Join the V irtual Mee ting")
  649                             : "<b> Your virtu al meeting  room was  not found,  " + Patie ntVirtualM eetingSpac e + "</b>" ;
  650  
  651                         var dynami cBody = is CVTTablet  ? "Your pr ovider wil l call you r CVT tabl et for the  appointme nt." : "Pl ease click  the follo wing link  to access  the virtua l meeting.   This wil l take you  into the  virtual wa iting room  until you r provider  joins.<br  />";
  652  
  653                         //Set up d ifference  in Schedul ed vs Canc elation te xt
  654                         var descrS tatus = "r eminder of  your";
  655                         var attach mentText =  "<br /><b r />A cale ndar appoi ntment is  attached t o this ema il, you ca n open the  attachmen t and save  it to you r calendar .";
  656                         if (isCanc elled) //C anceled
  657                         {
  658                             descrS tatus = "c ancelation  notice fo r your pre viously sc heduled";
  659                             attach mentText =  "<br /><b r />A cale ndar appoi ntment can celation i s attached  to this e mail, you  can open t he attachm ent and cl ick \"Remo ve from Ca lendar\" t o remove t his event  from your  calendar." ;
  660                             dynami cBody = "" ;
  661                             meetin gSpace = " ";
  662                         }
  663  
  664                         var descri ption = St ring.Forma t(
  665                             "This  is a {0} V ideo Visit  with a VA  clinician  on <b>{1} </b>. {2}{ 3}<br /><b r />{4}{5} <br />If y ou have an y question s or conce rns, pleas e contact  your clini c. <br />{ 6}",
  666                             descrS tatus,
  667                             fullDa te,
  668                             dynami cBody,
  669                             (!isCV TTablet ?  meetingSpa ce : ""),
  670                             servic eText,
  671                             clinic ians,
  672                             attach mentText);
  673                         Email pati entEmail =  new Email ()
  674                         {
  675                             Subjec t = subjec t,
  676                             Descri ption = de scription,
  677                             mcs_Re latedServi ceActivity  = new Ent ityReferen ce(Service Appointmen t.EntityLo gicalName,  sa.Id),
  678                             Regard ingObjectI d = new En tityRefere nce(Contac t.EntityLo gicalName,  patientAP .PartyId.I d),
  679                             From =  CvtHelper .GetWorkfl owOwner("S ervice Act ivity Noti fication",  Organizat ionService )
  680                         };
  681                         patientEma il.To = Cv tHelper.Se tPartyList (recipient );
  682  
  683                         Organizati onService. Create(pat ientEmail) ;
  684                         Logger.Wri teDebugMes sage("Pati ent Email  Created Su ccessfully ");
  685                    }
  686                }
  687                else
  688                    Logg er.WriteTo File("No V MR informa tion could  be found" );
  689           }
  690  
  691           pu blic DateT ime Conver tTimeZone( DateTime d ate, int C RMTimeZone Code, out  string tim eZonesStri ng, out bo ol success )
  692           {
  693                success  = false;
  694                timeZone sString =  string.Emp ty;
  695                try
  696                {
  697                    Logg er.WriteDe bugMessage ("Converti ng Time to  Appropria te Time Zo ne");
  698                    usin g (var srv  = new Xrm (Organizat ionService ))
  699                    {
  700                         var timeZo nerecord =  srv.TimeZ oneDefinit ionSet.Fir stOrDefaul t(t => t.T imeZoneCod e != null  && t.TimeZ oneCode.Va lue == CRM TimeZoneCo de);
  701                         timeZonesS tring = ti meZonereco rd.Standar dName;
  702                    }
  703                    var  timeZoneCo de = TimeZ oneInfo.Fi ndSystemTi meZoneById (timeZones String);
  704                    var  localTime  = TimeZone Info.Conve rtTimeFrom Utc(date,  timeZoneCo de);
  705                    succ ess = true ;
  706                    retu rn localTi me;
  707                }
  708                catch (T imeZoneNot FoundExcep tion ex)
  709                {
  710                    Logg er.WriteTo File("Coul d not find  " + timeZ onesString  + " time  zone with  code " + C RMTimeZone Code.ToStr ing() + ":  " + ex.Me ssage + "  ; using UT C instead" );
  711                }
  712                catch (E xception e x)
  713                {
  714                    Logg er.WriteTo File("Time  Zone conv ersion iss ue" + ex.M essage + "  ; using U TC instead ");
  715                }
  716                return d ate;
  717           }
  718  
  719           // / <summary >
  720           // / This met hod create s the .ics  attachmen t and appe nds it to  the email
  721           // / </summar y>
  722           // / <param n ame="email ">This is  the email  that the a ttachment  is attachi ng to</par am>
  723           // / <param n ame="sa">T he service  appointme nt which < /param>
  724           // / <param n ame="statu sCode">The  status of  the email  - which s ets the st atus of th e attachme nt as well  as the su bject of t he email</ param>
  725           in ternal voi d CreateCa lendarAppo intmentAtt achment(Em ail email,  ServiceAp pointment  sa, int st atusCode,  string ste thIP)
  726           {
  727                bool gro up = false ;
  728                if (sa.m cs_groupap pointment  != null)
  729                {
  730                    grou p = sa.mcs _groupappo intment.Va lue;
  731                }
  732                Logger.W riteTxnTim ingMessage ("Begin Cr eating Cal endar Appo intment");
  733                string s chLocation  = "See De scription" ;
  734                string s chSubject  = group ==  true ? "T elehealth  Visit-Grou p Appointm ent: Do No t Reply" :  
  735                    "Tel ehealth Vi sit-Single  Appointme nt: Do Not  Reply";
  736                string s chDescript ion = emai l.Descript ion;
  737                System.D ateTime sc hBeginDate  = (System .DateTime) sa.Schedul edStart;
  738                System.D ateTime sc hEndDate =  (System.D ateTime)sa .Scheduled End;
  739                string s equence =  "";
  740                string s tatus = "C ONFIRMED";
  741                string m ethod = "" ;
  742                //if the  appointme nt is canc eled, send  a cancell ation noti ce based o n the UID  of the pre vious entr y sent
  743                if (stat usCode ==  9 || statu sCode == 9 17290000)
  744                {
  745                    meth od = "METH OD:CANCEL\ n";
  746                    sequ ence = "SE QUENCE:1\n ";
  747                    stat us = "CANC ELLED";
  748                    schS ubject = " Canceled:  Telehealth  Visit: Do  Not Reply ";
  749                }
  750  
  751                //attach  a ClearSt eth CVL fi le if a st eth is in  the compon ents
  752                string c vlAtttachm ent = stri ng.IsNullO rEmpty(ste thIP) ? ""  :
  753                    "ATT ACH;ENCODI NG=BASE64; VALUE=BINA RY;X-FILEN AME=invita tion.cvl:"  + Convert .ToBase64S tring(new  ASCIIEncod ing().GetB ytes("<?xm l version= \"1.0\" en coding=\"U TF-8\"?><C VL><IP>" +  stethIP +  "</IP ><P ort>9005</ Port><Conf erenceId>1 2345</Conf erenceId>< /CVL>")) +  "\n";
  754    
  755                string a tt =  "BEG IN:VCALEND AR\n"+
  756                                    "PRODID:-/ /VA//Veter ans Affair s//EN\n"+
  757                                    method +
  758                                    "BEGIN:VEV ENT\n"+
  759                                    cvlAtttach ment +
  760                                    "UID:" + s a.Id + "\n " + sequen ce + 
  761                                    "DTSTART:"  + schBegi nDate.ToUn iversalTim e().ToStri ng("yyyyMM dd\\THHmms s\\Z")+"\n "+
  762                                    "DTEND:" +  schEndDat e.ToUniver salTime(). ToString(" yyyyMMdd\\ THHmmss\\Z ")+"\n"+
  763                                    "LOCATION: " + schLoc ation +
  764                                    //Use Desc ription ta g for emai l clients  that cant  handle x-a lt-desc ta g with HTM L
  765                                    "\nDESCRIP TION;ENCOD ING=QUOTED -PRINTABLE :" + schDe scription. Replace("< br/>", "") .Replace(" <b>", ""). Replace("< /b>", ""). Replace("< u>", "").R eplace("</ u>", "") +
  766                                    "\nSUMMARY :" + schSu bject + "\ nPRIORITY: 3\n" +
  767                                    "STATUS:"  + status +  "\n" +
  768                                    //Include  alternate  descriptio n if the c alendar cl ient can h andle html  x-alt-des c tag
  769                                    "X-ALT-DES C;FMTTYPE= text/html: <html>"+ s chDescript ion.Replac e("\n","<b r/>") +"</ html>" + " \n" +
  770                               "END :VEVENT\n"  + "END:VC ALENDAR\n" ;
  771  
  772                Activity MimeAttach ment calen darAttachm ent = new  ActivityMi meAttachme nt()
  773                {
  774                    Obje ctId = new  EntityRef erence(Ema il.EntityL ogicalName , email.Id ),
  775                    Obje ctTypeCode  = Email.E ntityLogic alName,
  776                    Subj ect = stri ng.Format( "Telehealt h Visit"),
  777                    Body  = Convert .ToBase64S tring(
  778                             new AS CIIEncodin g().GetByt es(att)),
  779                    File Name = str ing.Format (CultureIn fo.Current Culture, " Telehealth -Appointme nt.ics")
  780                 };
  781                Organiza tionServic e.Create(c alendarAtt achment);
  782                Logger.W riteTxnTim ingMessage ("Finished  Creating  Calendar A ppointment ");
  783                return;
  784           }
  785  
  786           in ternal str ing format Notificati onEmailBod y(List<mcs _resource>  providerT echs, List <mcs_resou rce> patie ntTechs, L ist<mcs_re source> pr oviderRoom s,
  787                List<mcs _resource>  patientRo oms, List< SystemUser > telepres enters, Se rviceAppoi ntment sa,  mcs_servi ces tsa, L ist<System User> prov iders, out  string co nvertedDat e)
  788           {
  789                Logger.W riteDebugM essage("St arting For matting Em ail Body") ;
  790                converte dDate = st ring.Empty ;
  791                string e mailBody =  "";
  792                string p roviderTec hsString =  "";
  793                string p atientTech sString =  null;
  794                string p roviderRoo msString =  null;
  795                string p atientRoom sString =  null;
  796                string t elepresent ersString  = null;
  797                string p rovidersSt ring = nul l;
  798                string D EALicensed  = "";
  799  
  800                //DEA Li censed
  801                DEALicen sed = (sa. cvt_Type.V alue == tr ue) ? "Thi s is a Hom e/Mobile v isit, cons ider Ryan  Haight reg ulations p rior to pr escribing  any contro lled medic ations." :  "";
  802  
  803                foreach  (mcs_resou rce r in p roviderTec hs)
  804                {
  805                    prov iderTechsS tring += r .mcs_name;
  806                    if ( r.cvt_rela teduser !=  null)
  807                    {
  808                         SystemUser  poc = (Sy stemUser)O rganizatio nService.R etrieve(Sy stemUser.E ntityLogic alName, r. cvt_relate duser.Id,  new Column Set("fulln ame", "mob ilephone",  "cvt_offi cephone",  "cvt_telew orkphone") );
  809                         providerTe chsString  += "; POC  Name: " +  poc.FullNa me + "; ";
  810                         var phone  = poc.Mobi lePhone ==  null ? po c.cvt_offi cephone :  poc.Mobile Phone;
  811  
  812                         //If TSA i s telework  (true), t hen add th at number  here as we ll.
  813                         providerTe chsString  += ((tsa.c vt_Provide rLocationT ype != nul l) && (tsa .cvt_Provi derLocatio nType.Valu e == true)  && (poc.c vt_Telewor kPhone !=  null)) ? " POC Telewo rk Phone # : " + poc. cvt_Telewo rkPhone +  ";" : "";
  814                         providerTe chsString  += (phone  != null) ?  "POC Phon e #: " + p hone : "";                 
  815                    }
  816                    prov iderTechsS tring += " <br/>";
  817                    prov iderTechsS tring += g etComponen ts(r, sa);
  818                }
  819  
  820                foreach  (mcs_resou rce r in p atientTech s)
  821                {
  822                    pati entTechsSt ring += r. mcs_name;
  823                    if ( r.cvt_rela teduser !=  null)
  824                    {
  825                         SystemUser  poc = (Sy stemUser)O rganizatio nService.R etrieve(
  826                             System User.Entit yLogicalNa me, r.cvt_ relateduse r.Id, new  ColumnSet( "fullname" , "mobilep hone", "cv t_officeph one"));
  827                         patientTec hsString + = "; POC N ame: " + p oc.FullNam e + "; ";
  828                         var phone  = poc.Mobi lePhone ==  null ? po c.cvt_offi cephone :  poc.Mobile Phone;
  829                         patientTec hsString + = "POC Pho ne #: " +  phone;
  830                    }
  831                    pati entTechsSt ring += "< br/>";
  832                    pati entTechsSt ring += ge tComponent s(r, sa);
  833                }
  834  
  835                foreach  (mcs_resou rce r in p roviderRoo ms)
  836                {
  837                    prov iderRoomsS tring += " <b><u>Room :</u></b>  " + r.mcs_ name;
  838                    if ( r.cvt_phon e != null)
  839                         ProRoom +=  (ProRoom  == null) ?  r.cvt_pho ne : ", "  + r.cvt_ph one;
  840                             
  841                    prov iderRoomsS tring += " <br/>";
  842                }
  843  
  844                foreach  (mcs_resou rce r in p atientRoom s)
  845                {
  846                    pati entRoomsSt ring += "< b><u>Room: </u></b> "  + r.mcs_n ame;
  847                    if ( r.cvt_phon e != null)
  848                    {
  849                         PatRoom +=  (PatRoom  == null) ?  r.cvt_pho ne : ", "  + r.cvt_ph one;
  850                    }
  851                    if ( DEALicense d == "" &&  r.mcs_Rel atedSiteId  != null)  {                      
  852                         var resour ceSite = ( mcs_site)O rganizatio nService.R etrieve(mc s_site.Ent ityLogical Name, r.mc s_RelatedS iteId.Id,  new Column Set(true)) ;
  853  
  854                         if (resour ceSite.cvt _DEALicens ed != null  && resour ceSite.cvt _DEALicens ed.Value = = true)
  855                             patien tRoomsStri ng += ";   <u><b>Note : The pati ent care s ite is DEA  registere d.</u></b> ";
  856                         else
  857                             patien tRoomsStri ng += ";   <u><b>Note : The pati ent care s ite is NOT  DEA regis tered.</u> </b>";
  858                    }
  859                    pati entRoomsSt ring += "< br/>";
  860                }
  861  
  862                foreach  (SystemUse r t in tel epresenter s)
  863                {
  864                    var  phone = t. cvt_office phone != n ull ? t.cv t_officeph one : t.Mo bilePhone;
  865                    tele presenters String +=  "<b><u>Tel epresenter :</u></b>  " + t.Full Name + ":  " + phone  + "<br/>";
  866                }
  867                foreach  (SystemUse r t in pro viders)
  868                {
  869                    var  phone = t. cvt_office phone != n ull ? t.cv t_officeph one : t.Mo bilePhone;
  870                    prov idersStrin g += "<b>< u>Provider :</u></b>  " + t.Full Name;
  871                    prov idersStrin g += (phon e != null)  ? "; Phon e: " + pho ne : "";
  872                    
  873                    //If  TSA is te lework (tr ue), then  add that n umber here  as well.
  874                    if ( (tsa.cvt_P roviderLoc ationType  != null) & & (tsa.cvt _ProviderL ocationTyp e.Value ==  true))
  875                    {
  876                         //Check us er for tel ework numb er                   
  877                         providersS tring += ( t.cvt_Tele workPhone  != null) ?  "; Telewo rk Phone:  " + t.cvt_ TeleworkPh one + ";"  : "";
  878                        
  879                    }
  880                    prov idersStrin g += "<br/ >";
  881                }
  882  
  883               
  884  
  885                Logger.W riteDebugM essage("Ge tting Time  Zone to c onvert Str ing");
  886                var proS iteId = sa .mcs_relat edprovider site;
  887                int proS iteTimeZon e = 35;
  888                if (proS iteId != n ull)
  889                {
  890                    usin g (var srv  = new Xrm (Organizat ionService ))
  891                    {
  892                         var site =  srv.mcs_s iteSet.Fir stOrDefaul t(s => s.I d == proSi teId.Id);
  893                         if (site ! = null)
  894                             proSit eTimeZone  = site.mcs _TimeZone  != null ?  site.mcs_T imeZone.Va lue : proS iteTimeZon e;
  895                    }
  896                }
  897                var conv ersionSucc ess = fals e;
  898                var time ZoneString  = string. Empty; //t his will b e retrieve d in Conve rtTimeZone
  899                var conv ertedTime  = ConvertT imeZone(sa .Scheduled Start.Valu e, proSite TimeZone,  out timeZo neString,  out conver sionSucces s);
  900                var full Date = con versionSuc cess ? con vertedTime .ToString( "ddd dd MM M yyyy HH: mm") + " "  + timeZon eString :  convertedT ime.ToStri ng("ddd dd  MMM yyyy  HH:mm") +  " GMT";
  901                converte dDate = fu llDate;
  902                Logger.W riteDebugM essage(str ing.Format ("Converte d Time Zon e to {0}",  timeZoneS tring));
  903  
  904                if (sa.S tatusCode. Value == 9  || sa.Sta tusCode.Va lue == 917 290000)
  905                {
  906                    emai lBody += " This is an  automated  Message t o notify y ou that a  Telehealth  Appointme nt previou sly schedu led for "  + fullDate  +
  907                    "has  been <fon t color='r ed'><u>Can celed</u>< /font>.  P lease open  the attac hment and  click \"Re move from  Calendar\"  to remove  this even t from you r calendar .  " +
  908                    "The  details a re listed  below: <br /><br/>";
  909                }
  910                else if  (sa.Status Code.Value  == 4)
  911                {
  912                    emai lBody += " This is an  automated  Message t o notify y ou that a  Telehealth  Appointme nt has bee n <font co lor='green '><u>Sched uled</u></ font> " +
  913                         "for " + f ullDate +  ".  " + 
  914                         "Please op en the att achment an d click \" Save and C lose\" to  add this e vent to yo ur calenda r.  " +
  915                         "The detai ls are lis ted below:  <br/><br/ >";
  916                }
  917  
  918                //Provid er Info
  919                emailBod y += "<br/ ><font siz e='5' colo r='blue'>P rovider Si te Informa tion:</fon t><br/>";
  920                emailBod y += provi derRoomsSt ring;
  921                emailBod y += (tsa. cvt_provsi tevistacli nics != nu ll) ? "<b> <u>Vista C linic:</u> </b> " + t sa.cvt_pro vsitevista clinics.To String() :  ""; //Nee ds to be s pecific Pr ov VC, not  all
  922                emailBod y += (!Str ing.IsNull OrEmpty(pr oviderTech sString))  ? "<br/><b ><u>Techno logies: </ u></b><br/ > " + prov iderTechsS tring + "< br/>" : "" ;
  923                emailBod y += provi dersString ;
  924                emailBod y += (TSAP rovEmergen cy != "")  ? "<u><b>P rovider Si te Emergen cy Respons ibilities: </u></b><b r/> " + TS AProvEmerg ency + "<b r/>" : "";
  925  
  926                if ((Pro Room != nu ll) || (Pr oTCTPhone  != null &&  ProTCTNam e != null) )
  927                {
  928                    emai lBody += " <u><b>Tele phone Cont act Inform ation:</u> </b><br/>  <ul>";
  929                    emai lBody += ( ProRoom !=  null) ? " <li>To dir ect dial t he room: "  + ProRoom  + "</li>"  : "";
  930                    emai lBody += ( ProTCTPhon e != null  && ProTCTN ame != nul l) ? "<li> To contact  the TCT a t the prov ider site,  call " +  ProTCTName  + " at "  + ProTCTPh one + ".</ li><br/><b r/>" : "";
  931                    emai lBody += " </ul>";
  932                }
  933  
  934                //Patien t Info
  935                if (tsa. cvt_Type ! = true)
  936                {
  937                    emai lBody += " <br/><font  size='5'  color='blu e'>Patient  Site Info rmation:</ font><br/> ";
  938                    emai lBody += p atientRoom sString;
  939                    emai lBody += ( tsa.cvt_pa tsitevista clinics !=  null) ? " <b><u>Vist a Clinic:< /u></b> "  + tsa.cvt_ patsitevis taclinics. ToString()  + "<br/>"  : "";
  940                    emai lBody += ( !String.Is NullOrEmpt y(patientT echsString )) ? "<b>< u>Technolo gies: </u> </b><br/>"  + patient TechsStrin g + "<br/> " : "";
  941                    emai lBody += t elepresent ersString;
  942                    emai lBody += ( TSAPatEmer gency != " ") ? "<b>< u>Patient  Site Emerg ency Respo nsibilitie s:</u></b> <br/> " +  TSAPatEmer gency + "< br/>" : "" ;
  943                    
  944                    if ( (PatRoom ! = null) ||  (SiteMain Phone != n ull) || (S iteLocal91 1Phone !=  null) || ( PatTCTPhon e != null  && PatTCTN ame != nul l))
  945                    {
  946                         emailBody  += "<u><b> Telephone  Contact In formation: </u></b><b r/> <ul>";
  947                         emailBody  += (PatRoo m != null)  ? "<li>To  direct di al the roo m: " + Pat Room + "</ li>" : "";
  948                         emailBody  += (SiteMa inPhone !=  null) ? " <li>To rea ch the mai n phone nu mber for t he patient  side clin ic: " + Si teMainPhon e + "</li> " : "";
  949                         emailBody  += (SiteLo cal911Phon e != null)  ? "<li>If  you are o ut of area , this is  the number  to reach  emergency  services:  " + SiteLo cal911Phon e + "</li> " : "";
  950                         emailBody  += (PatTCT Phone != n ull && Pat TCTName !=  null) ? " <li>To con tact the T CT at the  patient si te, call "  + PatTCTN ame + " at  " + PatTC TPhone + " .</li>" :  "";
  951                         emailBody  += "</ul>" ;
  952                    }
  953                }
  954                else  // Condition  for CVT to  Home
  955                {            
  956                    bool ? patient  = null;
  957                    var  meetingSpa ce = getPa tientVirtu alMeetingS pace(sa, o ut patient );
  958  
  959                    emai lBody += " <br/><br/> <font size ='5' color ='blue'>Ho me/Mobile  Informatio n:</font>< br/>";
  960                    emai lBody += ( DEALicense d != "") ?  "<u><b>Si te DEA Lic ensed:</u> </b><br/>  " + DEALic ensed + "< br/>" : "" ;
  961                    emai lBody += ( patient ==  false) ?  "<br/> Pat ient CVT T ablet: <br />" : "<br /> Virtual  Meeting S pace: <br/ >";
  962  
  963                    if ( meetingSpa ce == stri ng.Empty)
  964                         meetingSpa ce = "Plea se Contact  Your Clin ician for  Web Meetin g Details" ;
  965  
  966                    //Ch ange to re ad the Pro viderVirtu alMeetingS pace on th e patient  record.
  967                    // h ttps://pex ipdemo.com /px/vatest /#/?name=P roviderNam e&join=1&m edia=&esca late=1&con ference=va test@pexip demo.com&p in=1234  
  968                    if ( patient ==  true || P roviderVir tualMeetin gSpace !=  string.Emp ty)
  969                    {
  970                         emailBody  += "From y our Web br owser: " +  CvtHelper .buildHTML Url(Provid erVirtualM eetingSpac e, Provide rVirtualMe etingSpace ) + "<br/> ";
  971  
  972                         var conf =  getParamV alue(Provi derVirtual MeetingSpa ce, "confe rence=");
  973                         var cid =  getParamVa lue(Provid erVirtualM eetingSpac e, "pin=") ;
  974  
  975                         if (!strin g.IsNullOr Empty(conf ) && !stri ng.IsNullO rEmpty(cid ) )
  976                             emailB ody += Str ing.Format ("<br/>And  if you wa nted to di al from yo ur VTC dev ice:<br/>< br/>From a ny VTC dev ice: {0}<b r/>Host CI D: {1}", c onf, cid);
  977                    }
  978                    else
  979                         emailBody  += meeting Space + "< br/>";
  980                }
  981                emailBod y += "<br/ ><br/>Plea se Do Not  Reply to t his messag e.  It com es from an  unmonitor ed mailbox .";
  982  
  983                Logger.W riteDebugM essage("Fi nishing Fo rmatting E mail Body" );
  984                return e mailBody;
  985           }
  986  
  987           in ternal str ing getPar amValue(st ring url,  string key )
  988           {
  989                var resu lt = strin g.Empty;
  990                var para meter = ur l.Split('& ').LastOrD efault(s = > s.ToLowe r().Contai ns(key));
  991                var para meterKeyVa lue = para meter != n ull ? para meter.Spli t('=') : n ull;
  992                if (para meterKeyVa lue != nul l && param eterKeyVal ue.Count()  == 2)
  993                    resu lt = param eterKeyVal ue[1];
  994                return r esult;
  995           }
  996  
  997           in ternal str ing getCom ponents(mc s_resource  technolog y, Service Appointmen t SA)
  998           {
  999                //Get al l the comp onents and  include t he CEVN Al ias and IP  Addresses  for each.   Return t he formatt ed string  with a lin e for each  Component
  1000                //virtua lMeetingSp ace = null ;
  1001                string c omponents  = null; 
  1002                using (v ar context  = new Xrm (Organizat ionService ))
  1003                {
  1004                    var  compList =  context.c vt_compone ntSet.Wher e(c => c.c vt_related resourceid .Id == tec hnology.Id );
  1005                    fore ach (cvt_c omponent c  in compLi st)
  1006                    {
  1007                         if (compon ents == nu ll)
  1008                             compon ents += "< ul>";
  1009                         components  += "<li>"  + c.cvt_n ame;
  1010                         switch (c. cvt_name)
  1011                         {
  1012                             case " Codec, Har dware":
  1013                                 if  (c.cvt_ce vnalias !=  null)
  1014                                      componen ts += "; C EVN Alias:  " + c.cvt _cevnalias ;
  1015                                 br eak;
  1016                             case " Telemedici ne Encount er Managem ent":
  1017                             case " Telemed En counter Ma nagement":
  1018                             case " TEMS (Tele medicine E ncounter M anagement  Software)" :
  1019                             case " TEMS (Tele med Encoun ter Manage ment Softw are)":
  1020                                 if  (c.cvt_ip address !=  null)
  1021                                      componen ts += "; I P Address:  " + CvtHe lper.build HTMLUrl(c. cvt_ipaddr ess);
  1022                                 br eak;
  1023                             case " CVT Patien t Tablet":
  1024                                 if  (c.cvt_se rialnumber  != null)
  1025                                      componen ts += "; S erial Numb er: " + c. cvt_serial number;
  1026                                 br eak;
  1027                             case " Virtual Me eting Spac e":
  1028                                 Vi rtualMeeti ngSpace =  c;
  1029                                 br eak;
  1030                             case " Digital St ethoscope  Peripheral ":
  1031                                 st ethIP = c. cvt_ipaddr ess;
  1032                                 br eak;
  1033                         }
  1034                         //Send URL
  1035                         var url =  "";
  1036                         var contac t = getDum myContact( );
  1037                         var second aryEntitie s = new Li st<Entity> ();
  1038                         secondaryE ntities.Ad d(SA);
  1039                         secondaryE ntities.Ad d(contact) ;
  1040                         if (UrlBui lder.TryGe tUrl(Organ izationSer vice, this .GetType() .ToString( ), c, seco ndaryEntit ies, out u rl))
  1041                             compon ents += ";  <a href="  + url + " >" + url +  "</a>";
  1042                         components  += "</li> ";                      
  1043                    }
  1044                    if ( components  != null)
  1045                         components  += "</ul> ";
  1046                }
  1047                return c omponents;         
  1048           }
  1049  
  1050           in ternal Con tact getDu mmyContact ()
  1051           {
  1052                Contact  c = new Co ntact();
  1053                using (v ar srv = n ew Xrm(Org anizationS ervice)){
  1054                    c =  srv.Contac tSet.First OrDefault( );
  1055                }
  1056                return c ;
  1057           }
  1058  
  1059           in ternal Lis t<Entity>  getPRGs(Gu id tsaId,  string loc ation)
  1060           {
  1061                QueryByA ttribute q a = new Qu eryByAttri bute("cvt_ "+location +"resource group");
  1062                qa.Colum nSet = new  ColumnSet ("cvt_tsar esourcetyp e", "cvt_r elateduser id", "cvt_ relatedres ourcegroup id", "cvt_ relatedres ourceid");
  1063                qa.AddAt tributeVal ue("cvt_re latedtsaid ", tsaId);
  1064                var resu lts = Orga nizationSe rvice.Retr ieveMultip le(qa);
  1065                return r esults.Ent ities.ToLi st();
  1066           }
  1067  
  1068           // if patient OrProvider  == 1, the n get prov ider resou rces, othe rwise get  patient re sources
  1069           in ternal Ent ityCollect ion getPRG s(mcs_serv ices tsa,  int? patie ntOrProvid er)
  1070           {
  1071                EntityCo llection P RGCollecti on = new E ntityColle ction();
  1072                using (v ar context  = new Xrm (Organizat ionService )){
  1073                    if ( patientOrP rovider ==  1)
  1074                    {
  1075                         var ProvRG s = contex t.cvt_prov iderresour cegroupSet .Where(prg  => prg.cv t_RelatedT SAid.Id ==  tsa.Id);
  1076                         foreach (v ar res in  ProvRGs)
  1077                             PRGCol lection.En tities.Add (res);
  1078                    }
  1079                    else
  1080                    {
  1081                         var PatRGs  = context .cvt_patie ntresource groupSet.W here(prg = > prg.cvt_ RelatedTSA id.Id == t sa.Id);
  1082                         foreach (v ar res in  PatRGs)
  1083                             PRGCol lection.En tities.Add (res);
  1084                    }
  1085                }
  1086                return P RGCollecti on;
  1087           }
  1088  
  1089           // / <summary >
  1090           // / looks to  find a gr oup resour ce record  for the gr oup and us er listed
  1091           // / </summar y>
  1092           // / <param n ame="user" >user Id o f the grou p resource </param>
  1093           // / <param n ame="group ">group id  of the gr oup resour ce</param>
  1094           // / <returns >true if a  record ex ists for t he group p assed in a nd the use r passed i t</returns >
  1095           in ternal boo l MatchRes ourceToGro up(Guid us erId, Guid  groupId)
  1096           {
  1097                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1098                    retu rn srv.mcs _groupreso urceSet.Fi rstOrDefau lt(gr => g r.mcs_rela tedResourc eGroupId.I d == group Id && gr.m cs_Related UserId.Id  == userId)  != null;
  1099           }
  1100  
  1101           // / <summary >
  1102           // / looks to  find a gr oup resour ce record  for the gr oup and re source lis ted
  1103           // / </summar y>
  1104           // / <param n ame="resou rce">resou rce record  of the gr oup resour ce</param>
  1105           // / <param n ame="group ">resource  record of  the group  resource< /param>
  1106           // / <returns >true if a  record ex ists for t he group p assed in a nd the res ource pass ed it</ret urns>
  1107  
  1108           in ternal boo l MatchRes ourceToGro up(mcs_res ource reso urce, mcs_ resourcegr oup group)
  1109           {
  1110                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1111                    retu rn srv.mcs _groupreso urceSet.Fi rstOrDefau lt(gr => g r.mcs_rela tedResourc eGroupId.I d == group .Id && gr. mcs_Relate dResourceI d.Id == re source.Id)  != null;
  1112           }
  1113  
  1114           // / <summary >
  1115           // / returns  the list o f users ba sed on the  location  (provider  or patient ) and 
  1116           // / </summar y>
  1117           // / <param n ame="users ">list of  user activ ity partie s in the S A.Resource s field</p aram>
  1118           // / <param n ame="locat ion">"pati ent" or "p rovider"</ param>
  1119           // / <param n ame="tsaId ">id of th e tsa asso ciated wit h the serv ice activi ty that ge nerated th is email</ param>
  1120           // / <returns ></returns >
  1121           in ternal Lis t<SystemUs er> GetRec ipients(En tityCollec tion users , List<Ent ity> prgs)
  1122           {
  1123                List<Sys temUser> r ecipients  = new List <SystemUse r>();
  1124                var sing les = prgs .Where(p = > p.Attrib utes.Conta ins("cvt_t saresource type") &&  ((OptionSe tValue)p.A ttributes[ "cvt_tsare sourcetype "]).Value  == (int)cv t_tsaresou rcetype.Si ngleProvid er).ToList ();
  1125                var grou ps = prgs. Where(p =>  p.Attribu tes.Contai ns("cvt_ts aresourcet ype") && ( (OptionSet Value)p.At tributes[" cvt_tsares ourcetype" ]).Value = = (int)cvt _tsaresour cetype.Res ourceGroup ).ToList() ;
  1126  
  1127                foreach  (var singl ePRG in si ngles)
  1128                {
  1129                    if ( singlePRG. Attributes .Contains( "cvt_relat eduserid")  && single PRG.Attrib utes["cvt_ relateduse rid"] != n ull)
  1130                    {
  1131                         SystemUser  singleUse r = (Syste mUser)Orga nizationSe rvice.Retr ieve(Syste mUser.Enti tyLogicalN ame,
  1132                             ((Enti tyReferenc e)singlePR G.Attribut es["cvt_re lateduseri d"]).Id, n ew ColumnS et(true));
  1133                         if (single User != nu ll && sing leUser.Id  != Guid.Em pty)
  1134                         {
  1135                             foreac h (Activit yParty u i n users.En tities)
  1136                             {
  1137                                 if  (singleUs er.Id == u .PartyId.I d)
  1138                                 {
  1139                                      recipien ts.Add(sin gleUser);
  1140                                      break;
  1141                                 }
  1142                             }
  1143                         }
  1144                    }
  1145                }
  1146                foreach  (var group PRG in gro ups)
  1147                {
  1148                    if ( groupPRG.A ttributes. Contains(" cvt_relate dresourceg roupid") & & groupPRG .Attribute s["cvt_rel atedresour cegroupid" ] != null)
  1149                    {
  1150                         mcs_resour cegroup gr oup = (mcs _resourceg roup)Organ izationSer vice.Retri eve(
  1151                                 mc s_resource group.Enti tyLogicalN ame, ((Ent ityReferen ce)groupPR G.Attribut es["cvt_re latedresou rcegroupid "]).Id, ne w ColumnSe t(true));
  1152                         //if group  type valu e is any o f the "use r-type" gr oups (prov ider or al l required  or telepr esenter)
  1153                         if ((group .mcs_Type. Value == ( int)mcs_re sourcetype .Provider)  || (group .mcs_Type. Value == ( int)mcs_re sourcetype .AllRequir ed) || 
  1154                             (group .mcs_Type. Value == ( int)mcs_re sourcetype .Teleprese nterImager ))
  1155                         {
  1156                             //if t he user se lected is  in the res ource grou p, return  true and a dd the use r to the e ntitycolle ction
  1157                             foreac h (Activit yParty u i n users.En tities)
  1158                             {
  1159                                 va r user = ( SystemUser )Organizat ionService .Retrieve( SystemUser .EntityLog icalName,  u.PartyId. Id, new Co lumnSet(tr ue));
  1160                                 if  (MatchRes ourceToGro up(user.Id , group.Id ))
  1161                                      recipien ts.Add(use r);
  1162                             }
  1163                         }
  1164                    }
  1165                }
  1166                return r ecipients;
  1167           }
  1168  
  1169           // separates  user types  based on  value pass ed into pa rameter -  if user ty pe = null,  then only  providers , if 0 the n both, if  1 then pa tient
  1170           in ternal Ent ityCollect ion GetRec ipients(En tityCollec tion users , int? use rType, mcs _services  tsa)
  1171           {
  1172                EntityCo llection p roviders =  new Entit yCollectio n();
  1173  
  1174                foreach  (ActivityP arty u in  users.Enti ties)
  1175                {
  1176                    Syst emUser use r = (Syste mUser)Orga nizationSe rvice.Retr ieve(Syste mUser.Enti tyLogicalN ame, u.Par tyId.Id, n ew ColumnS et(true));
  1177  
  1178                    //se arch provi der resour ce group r ecords for  a resourc e of type  single pro vider who  matches th e user fro m the list  of resour ces select ed
  1179                    //ot herwise lo ok for a r esource gr oup that c ontains th e user
  1180                    //if  userType  is null, r eturn prov iders, if  0 - return  both (pat ients adde d below)
  1181                    if ( userType = = null ||  userType = = 0)
  1182                    {
  1183                         //get prov iderResour ceGroups f or the giv en TSA
  1184                         var queryR esult = ge tPRGs(tsa,  1).Entiti es;
  1185  
  1186                         var single Providers  = queryRes ult.Where( p => ((cvt _providerr esourcegro up)p).cvt_ TSAResourc eType.Valu e == 2);
  1187                         var resour ceGroups =  queryResu lt.Where(p  => ((cvt_ providerre sourcegrou p)p).cvt_T SAResource Type.Value  == 0);
  1188                         if (single Providers. Count() >  0)
  1189                         {
  1190                             foreac h (cvt_pro viderresou rcegroup p  in single Providers)
  1191                             {
  1192                                 Sy stemUser s ingleProvi derUser =  (SystemUse r)Organiza tionServic e.Retrieve (SystemUse r.EntityLo gicalName,  p.cvt_Rel atedUserId .Id, new C olumnSet(t rue));
  1193                                 if  (singlePr oviderUser  != null & & singlePr oviderUser .Id == use r.Id)
  1194                                     providers .Entities. Add(user);
  1195                             }
  1196                         }
  1197                         if (resour ceGroups.C ount() > 0 )
  1198                         {
  1199                             //for  each resou rce group,  check if  the type i s provider .  If so,  then retri eve the re source gro up, retrie ve get all  the resou rces liste d, and com pare 
  1200                             //the  list of re sources in  the group  to the re source on  the Servic e Activity
  1201                             foreac h (cvt_pro viderresou rcegroup r g in resou rceGroups)
  1202                             {
  1203                                 mc s_resource group grou p = (mcs_r esourcegro up)Organiz ationServi ce.Retriev e(
  1204                                      mcs_reso urcegroup. EntityLogi calName, r g.cvt_Rela tedResourc eGroupid.I d, new Col umnSet(tru e));
  1205                                 // if group t ype value  is provide r or all r equired
  1206                                 if  ((group.m cs_Type.Va lue == 999 99999) ||  (group.mcs _Type.Valu e == 91729 0000))
  1207                                 {
  1208                                      //if the  user sele cted is in  the resou rce group,  return tr ue and add  the user  to the ent itycollect ion
  1209                                      if (Matc hResourceT oGroup(use r.Id, grou p.Id))
  1210                                          prov iders.Enti ties.Add(u ser);
  1211                                 }
  1212                             }
  1213                         }                
  1214                    }
  1215                    //if  userType  is 1, retu rn patient s only, if  0 - retur n both (pr oviders ad ded above)
  1216                    if ( userType = = 0 || use rType == 1 )
  1217                    {
  1218                         //get pati entresourc egroup rec ords for t he TSA
  1219                         var queryR esult = ge tPRGs(tsa,  0).Entiti es;
  1220                         var single Patients =  queryResu lt.Where(p sr => ((cv t_patientr esourcegro up)psr).cv t_TSAResou rceType.Va lue == 3);
  1221                         var resour ceGroups =  queryResu lt.Where(p sr => ((cv t_patientr esourcegro up)psr).cv t_TSAResou rceType.Va lue == 0);
  1222                         if (single Patients.C ount() > 0 )
  1223                         {
  1224                             foreac h (cvt_pat ientresour cegroup p  in singleP atients)
  1225                             {
  1226                                 Sy stemUser s inglePatie ntUser = ( SystemUser )Organizat ionService .Retrieve(
  1227                                      SystemUs er.EntityL ogicalName , p.cvt_Re latedUserI d.Id, new  ColumnSet( true));
  1228                                 if  (singlePa tientUser  != null &&  singlePat ientUser.I d == user. Id)
  1229                                 pr oviders.En tities.Add (user);
  1230                             }
  1231                         }
  1232                         if (resour ceGroups.C ount() > 0 )
  1233                         {
  1234                             foreac h (cvt_pat ientresour cegroup rg  in resour ceGroups)
  1235                             {
  1236                                 mc s_resource group grou p = (mcs_r esourcegro up)Organiz ationServi ce.Retriev e(
  1237                                      mcs_reso urcegroup. EntityLogi calName, r g.cvt_Rela tedResourc eGroupid.I d, new Col umnSet(tru e));
  1238                                 if  (group.mc s_Type.Val ue == 1000 00000)
  1239                                 {
  1240                                      if (Matc hResourceT oGroup(use r.Id, grou p.Id))
  1241                                          prov iders.Enti ties.Add(u ser);
  1242                                 }
  1243                             }
  1244                         }
  1245                    }
  1246                }
  1247                return p roviders;
  1248           }
  1249  
  1250           // / <summary >
  1251           // / filters  down the l ist of all  equipment  on SA bas ed on crit eria provi ded
  1252           // / </summar y>
  1253           // / <param n ame="equip ment">coll ection of  mcs_resour ces that c orrespond  to the equ ipment in  the resour ces field  on the sa< /param>
  1254           // / <param n ame="tsa"> tsa for th e Service  Activity</ param>
  1255           // / <param n ame="prgs" >cvt_patie ntresource group or c vt_provide rresourceg roup for a ll resourc es on the  tsa</param >
  1256           // / <param n ame="equip Type">type  of mcs_re source (ro om, tech,  vista clin ic, etc.)< /param>
  1257           // / <returns >the list  of mcs_res ources bas ed on the  filters li sted (pro  or pat loc ation and  equipment  type)</ret urns>
  1258           in ternal Lis t<mcs_reso urce> Clas sifyResour ces(Entity Collection  equipment , List<Ent ity> prgs,  int? equi pType)
  1259           {
  1260                List<mcs _resource>  relevantR esources =  new List< mcs_resour ce>();
  1261  
  1262                var sing les = prgs .Where(prg  => ((Opti onSetValue )(prg.Attr ibutes["cv t_tsaresou rcetype"]) ).Value ==  (int)cvt_ tsaresourc etype.Sing leResource ).ToList() ;
  1263                var grou ps = prgs. Where(prg  => ((Optio nSetValue) (prg.Attri butes["cvt _tsaresour cetype"])) .Value ==  (int)cvt_t saresource type.Resou rceGroup). ToList();
  1264  
  1265                foreach  (Entity si nglePRG in  singles)
  1266                {
  1267                    if ( singlePRG. Attributes .Contains( "cvt_relat edresource id") && si nglePRG.At tributes[" cvt_relate dresourcei d"] != nul l)
  1268                    {
  1269                         foreach (m cs_resourc e r in equ ipment.Ent ities)
  1270                         {
  1271                             if (r. mcs_Type.V alue != eq uipType &&  equipType  != null)
  1272                                 co ntinue;
  1273  
  1274                             mcs_re source res ource = (m cs_resourc e)Organiza tionServic e.Retrieve (mcs_resou rce.Entity LogicalNam e,
  1275                                      ((Entity Reference) singlePRG. Attributes ["cvt_rela tedresourc eid"]).Id,  new Colum nSet(true) );
  1276                             if (re source !=  null && re source.Id  == r.Id)
  1277                                 re levantReso urces.Add( r);
  1278                         }
  1279                    }
  1280                }
  1281                foreach  (Entity gr oupPRG in  groups)
  1282                {
  1283                    if ( groupPRG.A ttributes. Contains(" cvt_relate dresourceg roupid") & & groupPRG .Attribute s["cvt_rel atedresour cegroupid" ] != null)
  1284                    {
  1285                         mcs_resour cegroup gr oup = (mcs _resourceg roup)Organ izationSer vice.Retri eve(mcs_re sourcegrou p.EntityLo gicalName,  
  1286                                      ((Entity Reference) groupPRG.A ttributes[ "cvt_relat edresource groupid"]) .Id, new C olumnSet(t rue));
  1287                         if (group. mcs_Type.V alue == (i nt)mcs_res ourcetype. Room || gr oup.mcs_Ty pe.Value = = (int)mcs _resourcet ype.Techno logy || gr oup.mcs_Ty pe.Value = = (int)mcs _resourcet ype.AllReq uired)
  1288                         {
  1289                             foreac h (mcs_res ource r in  equipment .Entities)
  1290                             {
  1291                                 if  (r.mcs_Ty pe.Value ! = equipTyp e && equip Type != nu ll)
  1292                                      continue ;
  1293  
  1294                                 if  (MatchRes ourceToGro up(r, grou p))
  1295                                 {
  1296                                      relevant Resources. Add(r);
  1297                                      break;
  1298                                 }
  1299                             }
  1300                         }
  1301                    }
  1302                }
  1303                
  1304                return r elevantRes ources;
  1305           }
  1306           #e ndregion
  1307  
  1308           #r egion Vist a Reminder  Email
  1309           in ternal voi d SendVist aReminder( Email emai l)
  1310           {
  1311                Logger.W riteDebugM essage("Be ginning Vi sta Remind er");
  1312                var prov TeamMember s = new Li st<TeamMem bership>() ;
  1313                var patT eamMembers  = new Lis t<TeamMemb ership>();
  1314                ServiceA ppointment  sa = (Ser viceAppoin tment)Orga nizationSe rvice.Retr ieve(Servi ceAppointm ent.Entity LogicalNam e, email.m cs_Related ServiceAct ivity.Id,  new Column Set(true)) ;
  1315                var crea tor = sa.C reatedBy;
  1316                //Either  get the P rov/Pat Fa cility fro m TSA or f rom the SA .
  1317                mcs_serv ices tsa =  (mcs_serv ices)Organ izationSer vice.Retri eve(mcs_se rvices.Ent ityLogical Name, sa.m cs_related tsa.Id, ne w ColumnSe t(true));
  1318  
  1319                Logger.W riteDebugM essage("Re trieved Se rvice Acti vity and T SA associa ted with t his Email" );
  1320  
  1321                //if (ts a.cvt_Type  != null & & tsa.cvt_ Type.Value )
  1322                //{
  1323                //    De leteVistaR eminder(em ail, "Home /Mobile em ail does n ot require  a VistA R eminder, d eleting em ail");
  1324                //    re turn;
  1325                //}
  1326  
  1327                var prov FacilityId  = tsa.cvt _ProviderF acility.Id ;
  1328                var patF acilityId  = tsa.cvt_ PatientFac ility != n ull ? tsa. cvt_Patien tFacility. Id : Guid. Empty;
  1329                var intr aFacility  = (provFac ilityId ==  patFacili tyId) ? tr ue : false ;
  1330  
  1331                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1332                {
  1333                    var  provTeam =  srv.TeamS et.FirstOr Default(t  => t.cvt_F acility.Id  == provFa cilityId & & t.cvt_Ty pe.Value = = 91729000 5);
  1334                    if ( provTeam ! = null)
  1335                    prov TeamMember s = srv.Te amMembersh ipSet.Wher e(TM => TM .TeamId ==  provTeam. Id).ToList ();
  1336                    else
  1337                         Logger.Wri teToFile(" The provid er side Sc heduler Te am was una ble to be  found for  Service Ac tivity: "  + sa.Id);
  1338  
  1339                    var  patTeam =  srv.TeamSe t.FirstOrD efault(t = > t.cvt_Fa cility.Id  == patFaci lityId &&  t.cvt_Type .Value ==  917290005) ;
  1340                    if ( patTeam !=  null)
  1341                    patT eamMembers  = srv.Tea mMembershi pSet.Where (TM => TM. TeamId ==  patTeam.Id ).ToList() ;
  1342                    else
  1343                         Logger.Wri teToFile(" The patien t side Sch eduler Tea m was unab le to be f ound for S ervice Act ivity: " +  sa.Id);
  1344                }
  1345  
  1346                bool pro vCheck = f alse;
  1347                bool pat Check = fa lse;
  1348                EntityCo llection p rovMembers  = new Ent ityCollect ion();
  1349                EntityCo llection p atMembers  = new Enti tyCollecti on();
  1350                if (prov TeamMember s.Count ==  0)
  1351                    Logg er.WriteTo File("Ther e are no m embers of  the Schedu ler team a t " + tsa. cvt_Provid erFacility .Name + ".   Please c ontact the  FTC and e nsure this  is correc ted.");
  1352                else
  1353                {
  1354                foreach  (TeamMembe rship tm i n provTeam Members)
  1355                {
  1356                    Acti vityParty  p = new Ac tivityPart y()
  1357                    {
  1358                         PartyId =  new Entity Reference( SystemUser .EntityLog icalName,  tm.SystemU serId.Valu e)
  1359                    };
  1360                    prov Members.En tities.Add (p);
  1361                    if ( creator.Id  == tm.Sys temUserId. Value)
  1362                         provCheck  = true;
  1363                    }
  1364                }
  1365                if (patT eamMembers .Count ==  0 && !tsa. cvt_Type.V alue)
  1366                    Logg er.WriteTo File(strin g.Format(" There are  no members  of the Sc heduler te am at {0}.   Please c ontact the  FTC and e nsure this  is correc ted.", tsa .cvt_Patie ntFacility  != null ?  tsa.cvt_P atientFaci lity.Name  : "\"No Fa cility Lis ted\""));
  1367                else
  1368                {
  1369                foreach  (TeamMembe rship tm i n patTeamM embers)
  1370                {
  1371                    Acti vityParty  p = new Ac tivityPart y()
  1372                    {
  1373                         PartyId =  new Entity Reference( SystemUser .EntityLog icalName,  tm.SystemU serId.Valu e)
  1374                    };
  1375                    patM embers.Ent ities.Add( p);
  1376                    if ( creator.Id  == tm.Sys temUserId. Value)
  1377                         patCheck =  true;
  1378                    }
  1379                }
  1380                //If TSA  is Store  Forward an d the sche duler is o n the pati ent Schedu ler team s ide OR if  the schedu ler is on  both Sched uler Teams , then don 't send em ail
  1381                if ((tsa .cvt_Avail ableTelehe althModali ties != nu ll && tsa. cvt_Availa bleTelehea lthModalit ies.Value  == 9172900 01 && patC heck)
  1382                    || ( patCheck & & provChec k))
  1383                {
  1384                    Logg er.WriteDe bugMessage ("No need  to send ou t email, D eleting Em ail.  TSA  is SFT and  Scheduler  is on Pat  Team OR S cheduler i s on Both  Pat and Pr ov Team");
  1385                    try
  1386                    {
  1387                         Organizati onService. Delete(ema il.Logical Name, emai l.Id);
  1388                         Logger.Wri teDebugMes sage("Emai l Deleted" );
  1389                    }
  1390                    catc h (Excepti on ex)
  1391                    {
  1392                         Logger.Wri teToFile(" Unable to  Delete Ema il " + ex. Message +  ".  Leavin g email as  is.");
  1393                    }
  1394                    retu rn;
  1395                }
  1396                else
  1397                {
  1398                    Setu pVistaRemi nderEmail( email, pro vMembers,  patMembers , tsa, pro vCheck, pa tCheck, sa );
  1399                }
  1400           }
  1401  
  1402           in ternal voi d DeleteVi staReminde r(Email em ail, strin g debugMes sage)
  1403           {
  1404                Logger.W riteDebugM essage(deb ugMessage) ;
  1405                try
  1406                {
  1407                    Orga nizationSe rvice.Dele te(email.L ogicalName , email.Id );
  1408                    Logg er.WriteDe bugMessage ("Email De leted");
  1409                }
  1410                catch (E xception e x)
  1411                {
  1412                    Logg er.WriteTo File("Unab le to Dele te Email "  + ex.Mess age + ".   Leaving em ail as is. ");
  1413                }
  1414           }
  1415  
  1416           in ternal voi d SetupVis taReminder Email(Emai l email, E ntityColle ction prov Members, E ntityColle ction patM embers, mc s_services  tsa, bool  provCheck , bool pat Check, Ser viceAppoin tment sa)
  1417           {
  1418                Logger.W riteDebugM essage("Be ginning Se tupVistaRe minderEmai l");
  1419                mcs_faci lity patFa cility = n ull;
  1420                if (tsa. cvt_Patien tFacility  != null)
  1421                    patF acility =  (mcs_facil ity)Organi zationServ ice.Retrie ve(mcs_fac ility.Enti tyLogicalN ame, tsa.c vt_Patient Facility.I d, new Col umnSet("mc s_stationn umber"));
  1422                var patS tation = p atFacility  == null ?  string.Em pty : " ("  + patFaci lity.mcs_S tationNumb er + ")";
  1423                mcs_faci lity proFa cility = n ull;
  1424                if (tsa. cvt_Provid erFacility  != null)
  1425                    proF acility =  (mcs_facil ity)Organi zationServ ice.Retrie ve(mcs_fac ility.Enti tyLogicalN ame, tsa.c vt_Provide rFacility. Id, new Co lumnSet("m cs_station number"));
  1426                var proS tation = p roFacility  == null ?  string.Em pty : " ("  + proFaci lity.mcs_S tationNumb er + ")";
  1427                email.Fr om = CvtHe lper.SetPa rtyList(sa .CreatedBy );
  1428                int time Zone = 0;
  1429                List<Act ivityParty > To = new  List<Acti vityParty> ();
  1430                Logger.W riteDebugM essage(str ing.Format ("Retrieve d pat {0}  and pro {1 } faciliti es and set  the email  sender {2 }", patSta tion, proS tation, em ail.From.T oString()) );
  1431                if (prov Check == f alse)
  1432                {
  1433                    //Ad d Prov Sch eduler Tea m Members  to To Line
  1434                    fore ach (Activ ityParty a p in provM embers.Ent ities)
  1435                    {
  1436                         To.Add(ap) ;
  1437                    }
  1438                    //To  = provMem bers.Entit ies.ToList <ActivityP arty>();
  1439                    Enti ty proSite ; //Either  the site  or facilit y of the p rovider
  1440                    if ( tsa.cvt_re latedprovi dersiteid  != null)
  1441                         proSite =  (mcs_site) Organizati onService. Retrieve(m cs_site.En tityLogica lName, tsa .cvt_relat edprovider siteid.Id,  new Colum nSet(true) );
  1442                    else
  1443                         proSite =  (mcs_facil ity)Organi zationServ ice.Retrie ve(mcs_fac ility.Enti tyLogicalN ame, tsa.c vt_Provide rFacility. Id, new Co lumnSet(tr ue));
  1444                    time Zone = (in t)proSite. Attributes ["mcs_time zone"];
  1445                }
  1446                if (patC heck == fa lse)
  1447                {
  1448                    //Ad d Pat Sche duler Team  Members t o To Line
  1449                    fore ach (Activ ityParty a p in patMe mbers.Enti ties)
  1450                    {
  1451                         To.Add(ap) ;
  1452                    }
  1453                    To =  To.GroupB y(A => A.P artyId.Id) .Select(g  => g.First ()).ToList <ActivityP arty>(); / /Method to  select di stinct rec ipients ba sed on rec ipient ID  (since ent ire Activi ty Party m ay not be  duplicate)
  1454                    Enti ty patSite ;
  1455                    if ( tsa.cvt_re latedprovi dersiteid  != null)
  1456                         patSite =  (mcs_site) Organizati onService. Retrieve(m cs_site.En tityLogica lName, tsa .cvt_relat edprovider siteid.Id,  new Colum nSet(true) );
  1457                    else
  1458                         patSite =  (mcs_facil ity)Organi zationServ ice.Retrie ve(mcs_fac ility.Enti tyLogicalN ame, tsa.c vt_Provide rFacility. Id, new Co lumnSet(tr ue));
  1459                    time Zone = (in t)patSite. Attributes ["mcs_time zone"];
  1460                }
  1461                email.To  = To;
  1462                string t imeZonesSt ring = str ing.Empty;
  1463                bool con vertSucces s = false;
  1464                var time Conversion  = Convert TimeZone(s a.Schedule dStart.Val ue, timeZo ne, out ti meZonesStr ing, out c onvertSucc ess);
  1465                Logger.W riteDebugM essage("Vi sta Remind er (for sc heduler ac tion) Time  converted  to " + ti meZonesStr ing);
  1466                var equi ps = sa.Re sources.Wh ere(ap =>  ap.PartyId .LogicalNa me == Equi pment.Enti tyLogicalN ame).ToLis t();
  1467  
  1468                //Added  to ensure  that resou rces from  child appo intments ( for Group  SAs) are a lso retrie ved and in cluded in  the list o f resource s
  1469                var chil dEquips =  GetApptRes ources(sa,  Equipment .EntityLog icalName);  
  1470                equips.A ddRange(ch ildEquips) ;
  1471                var vist aClinics =  "Vista Cl inic(s): " ;
  1472                foreach  (var equip ment in eq uips)
  1473                {
  1474                    var  e = (Equip ment)Organ izationSer vice.Retri eve(Equipm ent.Entity LogicalNam e, equipme nt.PartyId .Id, new C olumnSet(" mcs_relate dresource" ));
  1475                    var  resource =  (mcs_reso urce)Organ izationSer vice.Retri eve(mcs_re source.Ent ityLogical Name, e.mc s_relatedr esource.Id , new Colu mnSet("mcs _name","mc s_type"));
  1476                    if ( resource.m cs_Type.Va lue == 251 920000)
  1477                         vistaClini cs += reso urce.mcs_n ame + "; " ;
  1478                }
  1479                Logger.W riteDebugM essage("Ad ded vista  clinics to  Scheduler  Action em ail: " + v istaClinic s);
  1480                var disp layTime =  "Appointme nt Start T ime: " + t imeConvers ion + " "  + timeZone sString +  "; <br/>";
  1481                var body  = generat eEmailBody (sa.Id, Se rviceAppoi ntment.Ent ityLogical Name, disp layTime +  vistaClini cs, "Click  Here to o pen the Se rvice Acti vity in TS S");
  1482                var serv iceType =  tsa.cvt_se rvicetype. Name;
  1483                if (tsa. cvt_servic esubtype ! = null)
  1484                    serv iceType +=  " : " + t sa.cvt_ser vicesubtyp e.Name;
  1485                var stat us = sa.St atusCode.V alue == 4  ? "schedul ed" : "can celed";
  1486                var proF acName = t sa.cvt_Pro viderFacil ity == nul l ? string .Empty : t sa.cvt_Pro viderFacil ity.Name +  proStatio n;
  1487                var patF acName = t sa.cvt_Pat ientFacili ty == null   ? string .Empty : t sa.cvt_Pat ientFacili ty.Name +  patStation ;
  1488  
  1489                if (tsa. cvt_Type ! = null &&  tsa.cvt_Ty pe.Value)
  1490                    patF acName = " Home/Mobil e";
  1491  
  1492                email.De scription  = string.F ormat("A { 0} telehea lth appoin tment has  been {1} a t a remote  facility,  please {2 } this pat ient in Vi stA. The p rovider fa cility is:  {3}. The  patient fa cility is:  {4}. {5}" ,
  1493                    serv iceType,
  1494                    stat us,
  1495                    stat us == "sch eduled" ?  "schedule"  : "cancel ",
  1496                    proF acName, 
  1497                    patF acName, 
  1498                    body );
  1499  
  1500                if (tsa. cvt_relate dpatientsi teid == nu ll)
  1501                    emai l.Subject  += patFacN ame;
  1502  
  1503                CvtHelpe r.UpdateSe ndEmail(em ail, Organ izationSer vice);
  1504           }
  1505  
  1506           in ternal Lis t<Activity Party> Get ApptResour ces(Servic eAppointme nt sa, str ing filter  = "")
  1507           {
  1508                var chil dResources  = new Lis t<Activity Party>();
  1509                var chil dAppts = n ew List<Ap pointment> ();
  1510                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1511                {
  1512                    chil dAppts = s rv.Appoint mentSet.Wh ere(a => a .cvt_servi ceactivity id.Id == s a.Id && a. ScheduledS tart.Value  == sa.Sch eduledStar t.Value).T oList();
  1513                }
  1514                foreach  (var appt  in childAp pts)
  1515                {
  1516                    //If  there is  no entityT ype filter  listed, t hen just a dd all mem bers of ap pointment  requiredAt tendees
  1517                    if ( string.IsN ullOrEmpty (filter))
  1518                         childResou rces.AddRa nge(appt.R equiredAtt endees);
  1519                    else
  1520                    {
  1521                         foreach (v ar resourc e in appt. RequiredAt tendees)
  1522                         {
  1523                             //Part yID should  never be  null, but  added null  check jus t in case.   
  1524                             if (re source.Par tyId != nu ll && reso urce.Party Id.Logical Name == fi lter) 
  1525                                 ch ildResourc es.Add(res ource);
  1526                         }
  1527                    }
  1528                }
  1529                Logger.W riteDebugM essage("Ap pointment  Resources  retrieved  for Servic e Activity : " + sa.I d);
  1530                return c hildResour ces;
  1531           }
  1532           #e ndregion
  1533  
  1534           #r egion TSS  Privilege  e-mails
  1535           in ternal Lis t<Activity Party> Ret rieveFacil ityTeamMem bers(Email  email, Gu id TeamId,  IEnumerab le<Activit yParty> or iginalPart y)
  1536           {
  1537                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1538                {
  1539                    var  teamMember s = (List< TeamMember ship>)(srv .TeamMembe rshipSet.W here(t =>  t.TeamId = = TeamId). ToList());
  1540                    var  recipientL ist = new  List<Activ ityParty>( );
  1541  
  1542                    if ( originalPa rty != nul l)
  1543                         recipientL ist.AddRan ge(origina lParty);
  1544                    fore ach (var m ember in t eamMembers )
  1545                    {
  1546                         var party  = new Acti vityParty( )
  1547                         {
  1548                             Activi tyId = new  EntityRef erence(ema il.Logical Name, emai l.Id),
  1549                             PartyI d = new En tityRefere nce(System User.Entit yLogicalNa me, member .SystemUse rId.Value)
  1550                         };
  1551                         recipientL ist.Add(pa rty);
  1552                    }
  1553                    retu rn recipie ntList;
  1554                }   
  1555           }
  1556  
  1557           in ternal voi d SendPriv ilegingEma il(Email e mail, Guid  tssprivil egeId, str ing record Type)
  1558           {
  1559                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1560                {
  1561                    //Ge t the rela ted TSS Pr ivileging  record
  1562                    cvt_ tssprivile ging tsspr ivileging  = (cvt_tss privilegin g)Organiza tionServic e.Retrieve (cvt_tsspr ivileging. EntityLogi calName, t ssprivileg eId, new C olumnSet(t rue));
  1563                    if ( tssprivile ging.cvt_P rivilegedA tId != nul l) //Alway s filled
  1564                    {
  1565  
  1566                         //Notifica tion of Pr ivileging  Status Cha nge
  1567                         List<Team>  TOTeam =  new List<T eam>();
  1568                         if (email. Subject.In dexOf("Not ification  of Privile ging Statu s Change")  != -1)
  1569                         {
  1570                             //Chec k if recor d is inact ive or act ive
  1571                             if (ts sprivilegi ng.stateco de.Value = = cvt_tssp rivileging State.Acti ve)
  1572                             {
  1573                                 cu stomMessag e = String .Format("T his is to  notify all  affected  Facilities  that this  provider  is now pri vileged at  {0}.  If  this provi der posses sed proxy  privileges  for telem edicine pu rposes at  your facil ity, those  privilege s may be r einstated. <br/><br/> This provi der may no w be inclu ded in Tel ehealth Se rvice Agre ements and  schedulin g for this  provider  may commen ce.", tssp rivileging .cvt_Privi legedAtId. Name);
  1574                                 // TO FTC, Se rvice Chie f and C&P  Teams (Pro xy Privile ging Facil ities)
  1575                                 // Loop throu gh each Pr oxy Privil ege
  1576                                 va r proxys =  srv.cvt_t ssprivileg ingSet.Whe re(p => p. cvt_Refere ncedPrivil egeId.Id = = tssprivi leging.Id) ;
  1577  
  1578                                 fo reach (cvt _tssprivil eging prox y in proxy s)
  1579                                 {
  1580                                      List<Tea m> FTCTeam  = new Lis t<Team>();
  1581                                      List<Tea m> SCTeam  = new List <Team>();
  1582                                      List<Tea m> CPTeam  = new List <Team>();
  1583                                      FTCTeam  = srv.Team Set.Where( p => p.cvt _Facility. Id == prox y.cvt_Priv ilegedAtId .Id && p.c vt_Type.Va lue == (in t)Teamcvt_ Type.FTC). Distinct() .ToList();
  1584                                      SCTeam =  srv.TeamS et.Where(p  => p.cvt_ Facility.I d == proxy .cvt_Privi legedAtId. Id && p.cv t_Type.Val ue == (int )Teamcvt_T ype.Servic eChief &&  p.cvt_Serv iceType.Id  == proxy. cvt_Servic eTypeId.Id ).Distinct ().ToList( );
  1585                                      CPTeam =  srv.TeamS et.Where(p  => p.cvt_ Facility.I d == proxy .cvt_Privi legedAtId. Id && p.cv t_Type.Val ue == (int )Teamcvt_T ype.Creden tialingand Privilegin g).Distinc t().ToList ();
  1586  
  1587                                      //Loop t he results  into the  TO field
  1588                                      foreach  (var resul t in FTCTe am)
  1589                                      {
  1590                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , result.I d, email.T o);
  1591                                      }
  1592                                      foreach  (var resul t in SCTea m)
  1593                                      {
  1594                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , result.I d, email.T o);
  1595                                      }
  1596                                      foreach  (var resul t in CPTea m)
  1597                                      {
  1598                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , result.I d, email.T o);
  1599                                      }
  1600                                 }
  1601  
  1602  
  1603                                 // Enable Use r Record.
  1604                                 Se tStateRequ est reques tEnable =  new SetSta teRequest( )
  1605                                 {
  1606                                      EntityMo niker = ne w EntityRe ference(Sy stemUser.E ntityLogic alName, ts sprivilegi ng.cvt_Pro viderId.Id ),
  1607                                      State =  new Option SetValue(0 ),//1=disa bled, 0=en abled
  1608                                      Status =  new Optio nSetValue( -1)
  1609                                 };
  1610  
  1611                                 Or ganization Service.Ex ecute(requ estEnable) ;
  1612                                 // Discuss: A utomatical ly reactiv ate TSS Pr ivileging  for Proxy?
  1613  
  1614                             }
  1615                             else / /Deactivat e
  1616                             {
  1617                                 cu stomMessag e = String .Format("T his is to  notify all  affected  Facilities  that this  provider  is no long er privile ged at {0} .If this p rovider po ssessed pr oxy privil eges for t elemedicin e purposes  at your f acility, t hey are no  longer in  effect.<b r/><br/>Th is provide r will nee d to be re placed on  any existi ng Service  Agreement s or new S ervice Agr eements wi ll need to  be compos ed for a n ew provide r.<br/><br />Any Serv ice Activi ties that  have been  scheduled  for this p rovider wi ll need to  be resche duled with  another." , tssprivi leging.cvt _Privilege dAtId.Name );
  1618  
  1619                                 // TO FTC, Se rvice Chie f and C&P  Teams
  1620                                 Li st<Team> F TCTeam = n ew List<Te am>();
  1621                                 Li st<Team> S CTeam = ne w List<Tea m>();
  1622                                 Li st<Team> C PTeam = ne w List<Tea m>();
  1623                                 FT CTeam = sr v.TeamSet. Where(p =>  p.cvt_Fac ility.Id = = tssprivi leging.cvt _Privilege dAtId.Id & & p.cvt_Ty pe.Value = = (int)Tea mcvt_Type. FTC).Disti nct().ToLi st();
  1624                                 SC Team = srv .TeamSet.W here(p =>  p.cvt_Faci lity.Id ==  tssprivil eging.cvt_ Privileged AtId.Id &&  p.cvt_Typ e.Value ==  (int)Team cvt_Type.S erviceChie f && p.cvt _ServiceTy pe.Id == t ssprivileg ing.cvt_Se rviceTypeI d.Id).Dist inct().ToL ist();
  1625                                 CP Team = srv .TeamSet.W here(p =>  p.cvt_Faci lity.Id ==  tssprivil eging.cvt_ Privileged AtId.Id &&  p.cvt_Typ e.Value ==  (int)Team cvt_Type.C redentiali ngandPrivi leging).Di stinct().T oList();
  1626  
  1627                                 // Loop the r esults int o the TO f ield
  1628                                 fo reach (var  result in  FTCTeam)
  1629                                 {
  1630                                      email.To  = Retriev eFacilityT eamMembers (email, re sult.Id, e mail.To);
  1631                                 }
  1632                                 fo reach (var  result in  SCTeam)
  1633                                 {
  1634                                      email.To  = Retriev eFacilityT eamMembers (email, re sult.Id, e mail.To);
  1635                                 }
  1636                                 fo reach (var  result in  CPTeam)
  1637                                 {
  1638                                      email.To  = Retriev eFacilityT eamMembers (email, re sult.Id, e mail.To);
  1639                                 }
  1640  
  1641                                 // Disable Us er Record.
  1642                                 // Remvoves t he value f rom the fi eld
  1643                                 Sy stemUser p rovUpdate  = new Syst emUser()
  1644                                 {
  1645                                      Id = tss privilegin g.cvt_Prov iderId.Id,
  1646                                      cvt_disa ble = null
  1647                                 };
  1648  
  1649                                 // Disable th e provider 's user re cord here
  1650                                 Se tStateRequ est reques tDisable =  new SetSt ateRequest ()
  1651                                 {
  1652                                      EntityMo niker = ne w EntityRe ference(Sy stemUser.E ntityLogic alName, ts sprivilegi ng.cvt_Pro viderId.Id ),
  1653                                      State =  new Option SetValue(1 ),
  1654                                      Status =  new Optio nSetValue( -1)
  1655                                 };
  1656  
  1657                                 Or ganization Service.Up date(provU pdate);
  1658                                 Or ganization Service.Ex ecute(requ estDisable );
  1659                                 // Automatica lly disabl e Proxy TS S Privileg ing record s
  1660                                 va r proxys =  srv.cvt_t ssprivileg ingSet.Whe re(p => p. cvt_Refere ncedPrivil egeId.Id = = tssprivi leging.Id) ;
  1661  
  1662                                 fo reach (cvt _tssprivil eging prox y in proxy s)
  1663                                 {
  1664                                      SetState Request di sableProxy  = new Set StateReque st()
  1665                                      {
  1666                                          Enti tyMoniker  = new Enti tyReferenc e(cvt_tssp rivileging .EntityLog icalName,  proxy.Id),
  1667                                          Stat e = new Op tionSetVal ue(1),
  1668                                          Stat us = new O ptionSetVa lue(-1)
  1669                                      };
  1670                                      Organiza tionServic e.Execute( disablePro xy);
  1671                                 }
  1672                                 Lo gger.Write DebugMessa ge("Disabl ed all Pro xy Privile ges.");
  1673                             }
  1674  
  1675                             //
  1676                             //Esta blish para meters to  clean up q ueries
  1677                             List<A ctivityPar ty> recipi ent = new  List<Activ ityParty>( );
  1678                             Boolea n isRegard ingPrivHom e = true;
  1679                             cvt_ts sprivilegi ng homePri vRecord =  tssprivile ging;
  1680                             List<T eam> homeC PTeam = ne w List<Tea m>();
  1681                             cvt_ts sprivilegi ng proxyPr ivRecord =  new cvt_t ssprivileg ing();
  1682                             List<T eam> proxy CPTeam = n ew List<Te am>();
  1683  
  1684                             //Rega rding is P roxy, over write home ProvRecord  and isReg ardingPriv Home
  1685                             if ((t ssprivileg ing.cvt_Ty peofPrivil eging != n ull) && (t ssprivileg ing.cvt_Ty peofPrivil eging.Valu e == 91729 0001) && ( tssprivile ging.cvt_R eferencedP rivilegeId  != null))
  1686                             {
  1687                                 is RegardingP rivHome =  false;
  1688                                 ho mePrivReco rd = (cvt_ tssprivile ging)Organ izationSer vice.Retri eve(cvt_ts sprivilegi ng.EntityL ogicalName , tssprivi leging.cvt _Reference dPrivilege Id.Id, new  ColumnSet (true));
  1689                                 pr oxyPrivRec ord = tssp rivileging ;
  1690                                 pr oxyCPTeam  = srv.Team Set.Where( p => p.cvt _Facility. Id == prox yPrivRecor d.cvt_Priv ilegedAtId .Id && p.c vt_Type.Va lue == 917 290003).Di stinct().T oList();
  1691                             }
  1692  
  1693                             //Home  CPTeam is  always se t
  1694                             homeCP Team = srv .TeamSet.W here(p =>  p.cvt_Faci lity.Id ==  homePrivR ecord.cvt_ Privileged AtId.Id &&  p.cvt_Typ e.Value ==  917290003 ).Distinct ().ToList( );
  1695  
  1696                             //Get  the owner  of the wor kflow for  the From f ield
  1697                             email. From = Cvt Helper.Get WorkflowOw ner("Privi leging: PP E Submitte d", Organi zationServ ice);
  1698  
  1699                             //Init ial Privil eging
  1700                             if (em ail.Subjec t.IndexOf( "Telehealt h Notifica tion: A Pr ovider is  now privil eged") !=  -1)
  1701                             {
  1702                                 if  (isRegard ingPrivHom e) //Home
  1703                                 {
  1704                                      foreach  (var cp in  homeCPTea m)
  1705                                      {
  1706                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.To);
  1707                                      }
  1708                                      customMe ssage = "A  Home Priv ilege has  been grant ed at Faci lity: " +  homePrivRe cord.cvt_P rivilegedA tId.Name;
  1709                                 }
  1710                                 el se //Proxy
  1711                                 {
  1712                                      foreach  (var cp in  proxyCPTe am)
  1713                                      {
  1714                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.To);
  1715                                      }
  1716                                      foreach  (var cp in  homeCPTea m)
  1717                                      {
  1718                                          emai l.Cc = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.To);
  1719                                      }
  1720                                      customMe ssage = "A  Proxy Pri vilege has  been gran ted at Fac ility: " +  proxyPriv Record.cvt _Privilege dAtId.Name ;
  1721                                      customMe ssage += " <br/>Home  Privilege:  The provi der's HOME  privilegi ng is at F acility: "  + homePri vRecord.cv t_Privileg edAtId.Nam e;
  1722                                      customMe ssage += " <br/>Remin der: Pleas e enter th e provider  into your  local PPE  process." ;
  1723                                 }
  1724                             }
  1725                             //Chec k if E-mai l subject  = "Renewal "
  1726                             else i f (email.S ubject.Ind exOf("Tele health Not ification:  Upcoming  Renewal fo r a Provid er") != -1 )
  1727                             {
  1728                                 if  (isRegard ingPrivHom e == true)
  1729                                 {
  1730                                      //Update  Home/Prim ary TSS Pr ivilege // If Status  Reason = P rivileged;  set to In  Renewal
  1731                                      if (home PrivRecord .statuscod e.Value ==  917290001 )
  1732                                      {
  1733                                          //De clare new  object
  1734                                          cvt_ tssprivile ging homeR ecord = ne w cvt_tssp rivileging ()
  1735                                          {
  1736                                               Id = homeP rivRecord. Id,
  1737                                               statuscode  = new Opt ionSetValu e(91729000 2)
  1738                                          };
  1739                                          Orga nizationSe rvice.Upda te(homeRec ord);
  1740                                      }
  1741                                      foreach  (var cp in  homeCPTea m)
  1742                                      {
  1743                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.To);
  1744                                      }
  1745                                      //Edit t he E-mail  body
  1746                                      customMe ssage = "P rovider's  Home Privi lege is up  for renew al at Faci lity: " +  homePrivRe cord.cvt_P rivilegedA tId.Name;
  1747                                      //custom Message +=  "<br/>Not e: Home an d any Prox y Privileg es have be en set to  'In Renewa l' status. ";
  1748                                      customMe ssage += " <br/>Note:  Home Priv ilege has  been set t o 'In Rene wal' statu s.";
  1749                                 }
  1750                             }
  1751                             //Else  if Suspen ded
  1752                             else i f (email.S ubject.Ind exOf("Tele health Not ification:  A Provide r's Privil eging has  been Suspe nded") !=  -1)
  1753                             {
  1754                                 if  (isRegard ingPrivHom e == true)
  1755                                 {
  1756                                      foreach  (var cp in  homeCPTea m)
  1757                                      {
  1758                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.To);
  1759                                      }
  1760                                      //Update  the provi der's reco rd
  1761                                      SystemUs er provide r = (Syste mUser)Orga nizationSe rvice.Retr ieve(Syste mUser.Enti tyLogicalN ame, tsspr ivileging. cvt_Provid erId.Id, n ew ColumnS et(true));
  1762                                      provider .cvt_disab le = true;
  1763                                      Organiza tionServic e.Update(p rovider);
  1764  
  1765                                      //Edit t he E-mail  body
  1766                                      customMe ssage = "A  provider' s HOME pri vileging h as been su spended at  Facility:  " + homeP rivRecord. cvt_Privil egedAtId.N ame;
  1767                                      customMe ssage += " <br/>Note:  THE PROVI DER'S USER  RECORD HA S BEEN DIS ABLED.  Th is Provide r can no l onger be s cheduled i n the syst em.";
  1768                                      customMe ssage += " <br/>Suspe nsion: The  suspensio n occurred  at Facili ty: " + ho mePrivReco rd.cvt_Pri vilegedAtI d.Name;
  1769                                 }
  1770                                 el se
  1771                                 {
  1772                                      foreach  (var cp in  homeCPTea m)
  1773                                      {
  1774                                          emai l.To = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.To);
  1775                                      }
  1776                                      foreach  (var cp in  proxyCPTe am)
  1777                                      {
  1778                                          emai l.Cc = Ret rieveFacil ityTeamMem bers(email , cp.Id, e mail.Cc);
  1779                                      }
  1780  
  1781                                      //Edit t he E-mail  body
  1782                                      customMe ssage = "A  provider' s PROXY pr ivileging  has been s uspended a t Facility : " + prox yPrivRecor d.cvt_Priv ilegedAtId .Name;
  1783                                      customMe ssage += " <br/>Note:  This Prov ider is st ill schedu lable in t he system. ";
  1784                                      customMe ssage += " <br/>Suspe nsion: The  suspensio n occurred  at Facili ty:" + pro xyPrivReco rd.cvt_Pri vilegedAtI d.Name;
  1785                                      customMe ssage += " <br/>Home  Privilege:  The provi der's HOME  privilegi ng is at F acility: "  + homePri vRecord.cv t_Privileg edAtId.Nam e;
  1786                                 }
  1787                             }
  1788                             //Gene rate body  and then s end
  1789                             custom Message +=  "<br/>Rem inder: Not ify all pe rtinent C& P Officers  and Servi ce Chiefs. ";
  1790                             email. Descriptio n = genera teEmailBod y(tssprivi legeId, "c vt_tsspriv ileging",  customMess age, "Plea se click t his link t o view the  Privilegi ng record. ");
  1791                             if (em ail.To !=  null)
  1792                                 Cv tHelper.Up dateSendEm ail(email,  Organizat ionService );
  1793                         }
  1794                    }
  1795                }
  1796           }
  1797           #e ndregion 
  1798  
  1799           #r egion FPPE /OPPE Chec k e-mail
  1800           // Add SC Tea m to TO/CC  7/24/15
  1801           in ternal voi d SendTrig gerEmail(E mail email , Guid fpp eID, strin g recordTy pe)
  1802           {
  1803                Logger.s etMethod =  "SendTrig gerEmail";
  1804                Logger.W riteDebugM essage("St arting");
  1805                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1806                {
  1807                    //Ch eck system  generated  e-mail
  1808                    if ( email.Subj ect.IndexO f("Telehea lth Notifi cation: PP E Submitte d") != -1)
  1809                    {
  1810                         //Get the  owner of t he workflo w for the  From field
  1811                         email.From  = CvtHelp er.GetWork flowOwner( "Privilegi ng: PPE Su bmitted",  Organizati onService) ;
  1812  
  1813                         Logger.Wri teDebugMes sage("Get  the PPE re lated to t he email") ;
  1814                         cvt_qualit ycheck fpp e = (cvt_q ualitychec k)Organiza tionServic e.Retrieve (cvt_quali tycheck.En tityLogica lName, fpp eID, new C olumnSet(t rue));
  1815  
  1816                         //Find the  Privilege  record as sociated a nd navigat e to that  record
  1817                         if (fppe.c vt_TSSPriv ilegingId  != null)
  1818                         {                
  1819                             cvt_ts sprivilegi ng fppePri v = (cvt_t ssprivileg ing)Organi zationServ ice.Retrie ve(cvt_tss privilegin g.EntityLo gicalName,  fppe.cvt_ TSSPrivile gingId.Id,  new Colum nSet(true) );
  1820                             //Assu ming Home
  1821                             cvt_ts sprivilegi ng homePri v = fppePr iv;
  1822                             Boolea n isRegard ingRelated PrivHome =  true;
  1823                             Guid h omeService Type = fpp ePriv.cvt_ ServiceTyp eId != nul l ? fppePr iv.cvt_Ser viceTypeId .Id : Guid .Empty;
  1824                             List<T eam> homeS CTeams = n ew List<Te am>();
  1825                             List<T eam> proxy SCTeams =  new List<T eam>();
  1826  
  1827                             if (ho mePriv.cvt _TypeofPri vileging.V alue != 91 7290000) / /Overwriti ng since P roxy
  1828                             {
  1829                                 is RegardingR elatedPriv Home = fal se;
  1830                                 ho mePriv = ( cvt_tsspri vileging)O rganizatio nService.R etrieve(cv t_tssprivi leging.Ent ityLogical Name, fppe Priv.cvt_R eferencedP rivilegeId .Id, new C olumnSet(t rue));
  1831                             }
  1832  
  1833                             if (ho meServiceT ype == Gui d.Empty)
  1834                                 ho meServiceT ype = home Priv.cvt_S erviceType Id != null  ? homePri v.cvt_Serv iceTypeId. Id : Guid. Empty;
  1835  
  1836                             //Add  Service Ch ief Team -  should on ly ever be  one
  1837                             homeSC Teams = sr v.TeamSet. Where(t =>  t.cvt_Fac ility.Id = = homePriv .cvt_Privi legedAtId. Id && t.cv t_Type.Val ue == 9172 90001 && t .cvt_Servi ceType.Id  == homeSer viceType). Distinct() .ToList();
  1838  
  1839                             foreac h (var res ult in hom eSCTeams)
  1840                             {
  1841                                 em ail.To = R etrieveFac ilityTeamM embers(ema il, result .Id, email .To);
  1842                             }
  1843                             var fl ag = "Gree n";
  1844                             if (fp pe.cvt_Fla g != null  && fppe.cv t_Flag.Val ue != 9172 90000)
  1845                                 fl ag = "Red" ;
  1846  
  1847                             //Edit  the E-mai l body
  1848                             custom Message =  "A " + fla g + " flag ged FPPE/O PPE has be en submitt ed.";
  1849  
  1850                             //If a ctually fr om Proxy,  set those  team membe rs as Cc
  1851                             if (is RegardingR elatedPriv Home == fa lse)
  1852                             {
  1853                                 if  (fppePriv .cvt_Privi legedAtId  != null)
  1854                                      proxySCT eams = srv .TeamSet.W here(t =>  t.cvt_Faci lity.Id ==  fppePriv. cvt_Privil egedAtId.I d && 
  1855                                          t.cv t_Type.Val ue == 9172 90001 && t .cvt_Servi ceType.Id  == homeSer viceType). Distinct() .ToList();
  1856                                 fo reach (var  proxyTeam  in proxyS CTeams)
  1857                                 {
  1858                                      email.Cc  = Retriev eFacilityT eamMembers (email, pr oxyTeam.Id , email.Cc );
  1859                                 }
  1860                                 cu stomMessag e += "<br/ >This FPPE /OPPE was  submitted  regarding  the Proxy  Privilege. ";
  1861                                 cu stomMessag e += "<br/ >Proxy Pri vilege is  at Facilit y: " + fpp ePriv.cvt_ Privileged AtId.Name;
  1862                                 
  1863                             }
  1864  
  1865                             custom Message +=  "<br/>Hom e Privileg e is at Fa cility: "  + homePriv .cvt_Privi legedAtId. Name;
  1866                             custom Message +=  "<br/>Spe cialty: "  + homePriv .cvt_Servi ceTypeId.N ame;
  1867                             //cust omMessage  += "Date R ange: " +  fppe.cvt_E valuationS tartDate +  " to " +  fppe.cvt_E valuationE ndDate;
  1868                             custom Message +=  "<br/>Rem inder: Not ify all pe rtinent C& P Officers  and Servi ce Chiefs. ";
  1869                             email. Descriptio n = genera teEmailBod y(fppeID,  "cvt_quali tycheck",  customMess age, "Plea se click t his link t o view the  FPPE/OPPE  record.") ;
  1870                             if (em ail.To !=  null)
  1871                                 Cv tHelper.Up dateSendEm ail(email,  Organizat ionService );
  1872                         }
  1873                    }
  1874                }
  1875           }
  1876           #e ndregion
  1877  
  1878           #r egion PPE  Review/Fee dback
  1879           in ternal voi d SendPPER eviewEmail (Email ema il, Guid p peId, stri ng recordT ype)
  1880           {
  1881                Logger.s etMethod =  "SendPPER eviewEmail ";
  1882                Logger.W riteDebugM essage("St arting");
  1883                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1884                {
  1885                    //Ch eck system  generated  e-mail
  1886                    if ( email.Subj ect.IndexO f("PPE fee dback trac king") !=  -1)
  1887                    {
  1888                         //Get the  owner of t he workflo w for the  From field
  1889                         email.From  = CvtHelp er.GetWork flowOwner( "Privilegi ng: PPE Su bmitted",  Organizati onService) ;
  1890  
  1891                         Logger.Wri teDebugMes sage("Get  the PPE re lated to t he email") ;
  1892                         cvt_pperev iew review  = (cvt_pp ereview)Or ganization Service.Re trieve(cvt _ppereview .EntityLog icalName,  ppeId, new  ColumnSet (true));
  1893  
  1894                         //Find the  Privilege  record as sociated a nd navigat e to that  record
  1895                         if (review .cvt_teleh ealthprivi leging !=  null)
  1896                         {
  1897                             cvt_ts sprivilegi ng ppePriv  = (cvt_ts sprivilegi ng)Organiz ationServi ce.Retriev e(cvt_tssp rivileging .EntityLog icalName,  review.cvt _telehealt hprivilegi ng.Id, new  ColumnSet (true));
  1898                            
  1899                             Guid h omeService Type = ppe Priv.cvt_S erviceType Id != null  ? ppePriv .cvt_Servi ceTypeId.I d : Guid.E mpty;
  1900                             List<T eam> homeS CTeams = n ew List<Te am>();
  1901  
  1902                             //Add  Service Ch ief Team -  should on ly ever be  one
  1903                             homeSC Teams = sr v.TeamSet. Where(t =>  t.cvt_Fac ility.Id = = ppePriv. cvt_Privil egedAtId.I d && t.cvt _Type.Valu e == 91729 0001 && t. cvt_Servic eType.Id = = homeServ iceType).D istinct(). ToList();
  1904  
  1905                             foreac h (var res ult in hom eSCTeams)
  1906                             {
  1907                                 em ail.To = R etrieveFac ilityTeamM embers(ema il, result .Id, email .To);
  1908                             }
  1909  
  1910                             //Comp leted Feed back porti on
  1911                             if (em ail.Subjec t.IndexOf( "Completed ") != -1)
  1912                             {
  1913                                 cu stomMessag e = "<br/> Please set  the new P PE Review  Date.";
  1914                             }
  1915                             else
  1916                             {
  1917                                 // Edit the E -mail body  with the  summary gr id
  1918                                 va r etc = Cv tHelper.Ge tEntityTyp eCode(Orga nizationSe rvice, Tea m.EntityLo gicalName) ;
  1919                                 st ring serve rnameAndOr gname = Cv tHelper.ge tServerURL (Organizat ionService );
  1920                                 st ring url =  servernam eAndOrgnam e + "/user Defined/ed it.aspx?et c=" + etc  + "&id=";
  1921  
  1922                                 cu stomMessag e = "<tabl e style =  'width:100 %'><tr>";
  1923                                 // Table Head ings
  1924                                 cu stomMessag e += "<th> Provider N ame</th>";
  1925                                 cu stomMessag e += "<th> # of Recei ved Feedba ck</th>";
  1926                                 cu stomMessag e += "<th> # of Reque sted Feedb ack</th>";
  1927                                 cu stomMessag e += "<th> Initiation  Date</th> ";
  1928                                 cu stomMessag e += "<th> Due Date</ th>";
  1929                                 cu stomMessag e += "<th> Requests E scalated</ th>";
  1930                                 cu stomMessag e += "<th> PPE Review  record</t h>";
  1931                                 cu stomMessag e += "</tr  >";
  1932  
  1933                                 va r openRevi ews = srv. cvt_pperev iewSet.Whe re(r => r. cvt_facili ty.Id == r eview.cvt_ facility.I d && r.cvt _specialty .Id == rev iew.cvt_sp ecialty.Id  && r.cvt_ outstandin gppefeedba cks != 0);
  1934                                 va r count =  0;
  1935                                 fo reach (cvt _ppereview  open in o penReviews )
  1936                                 {
  1937                                      var esca lated = (o pen.cvt_es calated.Va lue == tru e) ? "Yes"  : "No";
  1938                                      customMe ssage += " <tr>";
  1939                                      customMe ssage += " <th>" + op en.cvt_pro vider.Name  + "</th>" ;
  1940                                      customMe ssage += " <th>" + op en.cvt_sub mittedppef eedbacks +  "</th>";
  1941                                      customMe ssage += " <th>" + op en.cvt_req uestedppef eedbacks +  "</th>";
  1942                                      customMe ssage += " <th>" + (( DateTime)o pen.cvt_in itiateddat e).ToStrin g("MM/dd/y yyy") + "< /th>";
  1943                                      customMe ssage += " <th>" + (( DateTime)o pen.cvt_du edate).ToS tring("MM/ dd/yyyy")  + "</th>";
  1944                                      customMe ssage += " <th>" + es calated +  "</th>";
  1945                                      customMe ssage += " <th>" + "< a href=\""  + url + o pen.Id + " \">View Re cord</a>"  + "</th>";  //URL
  1946                                      customMe ssage += " </tr >";
  1947                                      count++;
  1948                                 }
  1949  
  1950                                 cu stomMessag e += "</ta ble >";
  1951                                 cu stomMessag e += "<br/ ><br/>This  is an aut omated not ification  from the T elehealth  Scheduling  System.";
  1952  
  1953                                 em ail.Descri ption = cu stomMessag e;
  1954  
  1955                                 if  (count >  0)
  1956                                 {
  1957                                      //Update  the PPE n ext date o n the team  record to  check aga in tomorro w:
  1958                                      //var ne xtEmailDat e = ((Date Time)revie w.cvt_next email).ToL ocalTime() ;
  1959                                      //var to morrowDate  = new Dat eTime(next EmailDate. Year, next EmailDate. Month, nex tEmailDate .Day + 1,  6, 0, 0);
  1960  
  1961                                      //var qu eryForMore RecentReco rd = (cvt_ ppereview) Organizati onService. Retrieve(c vt_pperevi ew.EntityL ogicalName , review.I d, new Col umnSet(tru e));
  1962                                      //if (qu eryForMore RecentReco rd.cvt_nex temail ==  review.cvt _nextemail )
  1963                                      //{
  1964                                          if ( email.To ! = null)
  1965                                               CvtHelper. UpdateSend Email(emai l, Organiz ationServi ce);
  1966                                      //}
  1967                                      //else
  1968                                      //{
  1969                                      //    // Delete thi s email.
  1970                                      //    Or ganization Service.De lete(Email .EntityLog icalName,  email.Id);
  1971                                      //    Lo gger.Write DebugMessa ge("Delete d Email be cause it w as already  sent");
  1972                                      //}
  1973  
  1974                                 }
  1975  
  1976                             }
  1977  
  1978                             email. Descriptio n = genera teEmailBod y(review.I d, review. LogicalNam e, customM essage, "P lease clic k this lin k to view  the PPE Re view recor d.");
  1979                             if (em ail.To !=  null)
  1980                                 Cv tHelper.Up dateSendEm ail(email,  Organizat ionService );
  1981                         }
  1982                    }
  1983                }
  1984           }
  1985  
  1986           in ternal voi d SendPPES ummaryEmai l(Email em ail, Guid  teamId, st ring recor dType)
  1987           {
  1988                Logger.s etMethod =  "SendPPER eviewEmail ";
  1989                Logger.W riteDebugM essage("St arting");
  1990                using (v ar srv = n ew Xrm(Org anizationS ervice))
  1991                {
  1992                    //Ch eck system  generated  e-mail
  1993                    if ( email.Subj ect.IndexO f("PPE fee dback trac king") !=  -1)
  1994                    {
  1995                         //Get the  owner of t he workflo w for the  From field
  1996                         email.From  = CvtHelp er.GetWork flowOwner( "Privilegi ng: PPE Su bmitted",  Organizati onService) ;
  1997  
  1998                         Logger.Wri teDebugMes sage("Get  the Team r elated to  the email" );
  1999                         Team team  = (Team)Or ganization Service.Re trieve(Tea m.EntityLo gicalName,  teamId, n ew ColumnS et(true));
  2000  
  2001                         if (team.c vt_Type.Va lue == (in t)Teamcvt_ Type.Servi ceChief)
  2002                             email. To = Retri eveFacilit yTeamMembe rs(email,  team.Id, e mail.To);
  2003  
  2004                         //Edit the  E-mail bo dy with th e summary  grid
  2005                         var etc =  CvtHelper. GetEntityT ypeCode(Or ganization Service, T eam.Entity LogicalNam e);
  2006                         string ser vernameAnd Orgname =  CvtHelper. getServerU RL(Organiz ationServi ce);
  2007                         string url  = servern ameAndOrgn ame + "/us erDefined/ edit.aspx? etc=" + et c + "&id=" ;
  2008  
  2009                         customMess age = "<ta ble style  = 'width:1 00%'><tr>" ;
  2010                         //Table He adings
  2011                         customMess age += "<t h>Provider  Name</th> ";
  2012                         customMess age += "<t h># of Rec eived Feed back</th>" ;
  2013                         customMess age += "<t h># of Req uested Fee dback</th> ";
  2014                         customMess age += "<t h>Initiati on Date</t h>";
  2015                         customMess age += "<t h>Due Date </th>";
  2016                         customMess age += "<t h>Requests  Escalated </th>";
  2017                         customMess age += "<t h>PPE Revi ew record/ th>";
  2018                         customMess age += "</ tr >";
  2019  
  2020                         var openRe views = sr v.cvt_pper eviewSet.W here(r =>  r.cvt_faci lity.Id ==  team.cvt_ Facility.I d && r.cvt _specialty .Id == tea m.cvt_Serv iceType.Id  && r.cvt_ outstandin gppefeedba cks != 0);
  2021                         var count  = 0;
  2022                         foreach (c vt_pperevi ew open in  openRevie ws)
  2023                         {
  2024                             var es calated =  (open.cvt_ escalated. Value == t rue) ? "Ye s" : "No";
  2025                             custom Message +=  "<tr>";
  2026                             custom Message +=  "<th>" +  open.cvt_p rovider.Na me + "</th >";
  2027                             custom Message +=  "<th>" +  open.cvt_s ubmittedpp efeedbacks  + "</th>" ;
  2028                             custom Message +=  "<th>" +  open.cvt_r equestedpp efeedbacks  + "</th>" ;
  2029                             custom Message +=  "<th>" +  open.cvt_i nitiatedda te + "</th >";
  2030                             custom Message +=  "<th>" +  open.cvt_d uedate + " </th>";
  2031                             custom Message +=  "<th>" +  escalated  + "</th>";
  2032                             custom Message +=  "<th>" +  "<a href=\ "" + url +  open.Id +  "\">View  Record</a> " + "</th> "; //URL
  2033                             custom Message +=  "</tr >";
  2034                             count+ +;
  2035                         }
  2036  
  2037                         customMess age += "</ table >";
  2038                         customMess age += "<b r/><br/>Th is is an a utomated n otificatio n from the  Telehealt h Scheduli ng System. ";
  2039  
  2040                         email.Desc ription =  customMess age;
  2041  
  2042                         if (count  > 0)
  2043                         {
  2044                             //Upda te the PPE  next date  on the te am record  to check a gain tomor row:
  2045                             var ne xtEmailDat e = ((Date Time)team. cvt_nextpp eemail).To LocalTime( );
  2046                             var to morrowDate  = new Dat eTime(next EmailDate. Year, next EmailDate. Month, nex tEmailDate .Day + 1,  6, 0, 0);
  2047  
  2048                             //var  queryForTe am = Organ izationSer vice.Retri eve(cvt_pp ereview.En tityLogica lName, )
  2049                             Team u pdateTeam  = new Team ()
  2050                             {
  2051                                 Id  = team.Id ,
  2052                                 cv t_nextppee mail = tom orrowDate
  2053                             };
  2054                             Organi zationServ ice.Update (updateTea m);
  2055                             Logger .WriteDebu gMessage(" Updated th e Team wit h the next  PPE date. ");
  2056  
  2057                             if (em ail.To !=  null)
  2058                                 Cv tHelper.Up dateSendEm ail(email,  Organizat ionService );
  2059  
  2060                         }
  2061                    }
  2062                }
  2063           }
  2064           // internal v oid SendPP ESummaryEm ail(Email  email, Gui d teamId,  string rec ordType)
  2065           // {
  2066           //     Logger .setMethod  = "SendPP EReviewEma il";
  2067           //     Logger .WriteDebu gMessage(" Starting") ;
  2068           //     using  (var srv =  new Xrm(O rganizatio nService))
  2069           //     {
  2070           //         // Check syst em generat ed e-mail
  2071           //         if  (email.Su bject.Inde xOf("PPE f eedback tr acking") ! = -1)
  2072           //         {
  2073           //              //Get th e owner of  the workf low for th e From fie ld
  2074           //              email.Fr om = CvtHe lper.GetWo rkflowOwne r("Privile ging: PPE  Submitted" , Organiza tionServic e);
  2075  
  2076           //              Logger.W riteDebugM essage("Ge t the Team  related t o the emai l");
  2077           //              Team tea m = (Team) Organizati onService. Retrieve(T eam.Entity LogicalNam e, teamId,  new Colum nSet(true) );
  2078  
  2079           //              if (team .cvt_Type. Value == ( int)Teamcv t_Type.Ser viceChief)
  2080           //                  emai l.To = Ret rieveFacil ityTeamMem bers(email , team.Id,  email.To) ;
  2081  
  2082           //              //Edit t he E-mail  body with  the summar y grid
  2083           //              var etc  = CvtHelpe r.GetEntit yTypeCode( Organizati onService,  Team.Enti tyLogicalN ame);
  2084           //              string s ervernameA ndOrgname  = CvtHelpe r.getServe rURL(Organ izationSer vice);
  2085           //              string u rl = serve rnameAndOr gname + "/ userDefine d/edit.asp x?etc=" +  etc + "&id =";
  2086  
  2087           //              customMe ssage = "< table styl e = 'width :100%'><tr >";
  2088           //              //Table  Headings
  2089           //              customMe ssage += " <th>Provid er Name</t h>";
  2090           //              customMe ssage += " <th># of R eceived Fe edback</th >";
  2091           //              customMe ssage += " <th># of R equested F eedback</t h>";
  2092           //              customMe ssage += " <th>Initia tion Date< /th>";
  2093           //              customMe ssage += " <th>Due Da te</th>";
  2094           //              customMe ssage += " <th>Reques ts Escalat ed</th>";
  2095           //              customMe ssage += " <th>PPE Re view recor d/th>";
  2096           //              customMe ssage += " </tr >";
  2097  
  2098           //              var open Reviews =  srv.cvt_pp ereviewSet .Where(r = > r.cvt_fa cility.Id  == team.cv t_Facility .Id && r.c vt_special ty.Id == t eam.cvt_Se rviceType. Id && r.cv t_outstand ingppefeed backs != 0 );
  2099           //              var coun t = 0;
  2100           //              foreach  (cvt_ppere view open  in openRev iews)
  2101           //              {
  2102           //                  var  escalated  = (open.cv t_escalate d.Value ==  true) ? " Yes" : "No ";
  2103           //                  cust omMessage  += "<tr>";
  2104           //                  cust omMessage  += "<th>"  + open.cvt _provider. Name + "</ th>";
  2105           //                  cust omMessage  += "<th>"  + open.cvt _submitted ppefeedbac ks + "</th >";
  2106           //                  cust omMessage  += "<th>"  + open.cvt _requested ppefeedbac ks + "</th >";
  2107           //                  cust omMessage  += "<th>"  + open.cvt _initiated date + "</ th>";
  2108           //                  cust omMessage  += "<th>"  + open.cvt _duedate +  "</th>";
  2109           //                  cust omMessage  += "<th>"  + escalate d + "</th> ";
  2110           //                  cust omMessage  += "<th>"  + "<a href =\"" + url  + open.Id  + "\">Vie w Record</ a>" + "</t h>"; //URL
  2111           //                  cust omMessage  += "</tr > ";
  2112           //                  coun t++;
  2113           //              }
  2114  
  2115           //              customMe ssage += " </table >" ;
  2116           //              customMe ssage += " <br/><br/> This is an  automated  notificat ion from t he Telehea lth Schedu ling Syste m.";
  2117  
  2118           //              email.De scription  = customMe ssage;
  2119  
  2120           //              if (coun t > 0)
  2121           //              {
  2122           //                  //Up date the P PE next da te on the  team recor d to check  again tom orrow:
  2123           //                  var  nextEmailD ate = ((Da teTime)tea m.cvt_next ppeemail). ToLocalTim e();
  2124           //                  var  tomorrowDa te = new D ateTime(ne xtEmailDat e.Year, ne xtEmailDat e.Month, n extEmailDa te.Day + 1 , 6, 0, 0) ;
  2125  
  2126           //                  //va r queryFor Team = Org anizationS ervice.Ret rieve(cvt_ ppereview. EntityLogi calName, )
  2127           //                  Team  updateTea m = new Te am()
  2128           //                  {
  2129           //                       Id = team. Id,
  2130           //                       cvt_nextpp eemail = t omorrowDat e
  2131           //                  };
  2132           //                  Orga nizationSe rvice.Upda te(updateT eam);
  2133           //                  Logg er.WriteDe bugMessage ("Updated  the Team w ith the ne xt PPE dat e.");
  2134  
  2135           //                  if ( email.To ! = null)
  2136           //                       CvtHelper. UpdateSend Email(emai l, Organiz ationServi ce);
  2137  
  2138           //              }
  2139           //         }
  2140           //     }
  2141           // }
  2142           in ternal voi d SendPPEF eedbackEma il(Email e mail, Guid  feedbackI d, string  recordType )
  2143           {
  2144                Logger.s etMethod =  "SendPPEF eedbackEma il";
  2145                Logger.W riteDebugM essage("St arting");
  2146                using (v ar srv = n ew Xrm(Org anizationS ervice))
  2147                {
  2148                    //Ch eck system  generated  e-mail
  2149                    if ( email.Subj ect.IndexO f("PPE fee dback requ ired") !=  -1 || emai l.Subject. IndexOf("A ction Requ ired: PPE  review pro cess feedb ack overdu e") != -1)
  2150                    {
  2151                         //Get the  owner of t he workflo w for the  From field
  2152                         email.From  = CvtHelp er.GetWork flowOwner( "Privilegi ng: PPE Su bmitted",  Organizati onService) ;
  2153  
  2154                         Logger.Wri teDebugMes sage("Get  the PPE re lated to t he email") ;
  2155                         cvt_ppefee dback feed back = (cv t_ppefeedb ack)Organi zationServ ice.Retrie ve(cvt_ppe feedback.E ntityLogic alName, fe edbackId,  new Column Set(true)) ;
  2156  
  2157                         //Get the  ppe_review  record fo r the Due  Date
  2158                         cvt_pperev iew ppeRev iew = (cvt _ppereview )Organizat ionService .Retrieve( cvt_pperev iew.Entity LogicalNam e, feedbac k.cvt_pper eview.Id,  new Column Set(true)) ;
  2159                         var dueDat e = (DateT ime)ppeRev iew.cvt_du edate;
  2160                         var initia tedDate =  (DateTime) ppeReview. cvt_initia teddate;
  2161  
  2162                         var daysRe maining =  (dueDate-D ateTime.To day);
  2163                         var daysEl apsed = (D ateTime.To day-initia tedDate);
  2164  
  2165                         Boolean is Escalation  = false;
  2166                         if (email. Subject.In dexOf("Act ion Requir ed: PPE re view proce ss feedbac k overdue" ) != -1)
  2167                             isEsca lation = t rue;
  2168  
  2169                         //Find the  Privilege  record as sociated a nd navigat e to that  record
  2170                         if (feedba ck.cvt_pro xyprivileg ing != nul l)
  2171                         {
  2172                             cvt_ts sprivilegi ng proxyPr iv = (cvt_ tssprivile ging)Organ izationSer vice.Retri eve(cvt_ts sprivilegi ng.EntityL ogicalName , feedback .cvt_proxy privilegin g.Id, new  ColumnSet( true));
  2173  
  2174                             Guid h omeService Type = pro xyPriv.cvt _ServiceTy peId != nu ll ? proxy Priv.cvt_S erviceType Id.Id : Gu id.Empty;
  2175                             List<T eam> proxy SCTeams =  new List<T eam>();
  2176                             List<T eam> proxy CoSTeams =  new List< Team>();
  2177                             var te am = "";
  2178                             if (is Escalation )
  2179                             {                               
  2180                                 pr oxyCoSTeam s = srv.Te amSet.Wher e(t => t.c vt_Facilit y.Id == pr oxyPriv.cv t_Privileg edAtId.Id  && t.cvt_T ype.Value  == (int)Te amcvt_Type .ChiefofSt aff).Disti nct().ToLi st();
  2181                                 va r proxyCOS Team = srv .TeamSet.F irstOrDefa ult(t => t .cvt_Facil ity.Id ==  proxyPriv. cvt_Privil egedAtId.I d && t.cvt _Type.Valu e == (int) Teamcvt_Ty pe.Chiefof Staff);
  2182                                 if  (proxyCOS Team != nu ll && feed back.cvt_r esponseesc alated ==  null)
  2183                                 {
  2184                                      //Set th e response  requested  field
  2185                                      cvt_ppef eedback up dateFeedba ck = new c vt_ppefeed back()
  2186                                      {
  2187                                          Id =  feedback. Id,
  2188                                          cvt_ responsees calated =  new Entity Reference( Team.Entit yLogicalNa me, proxyC OSTeam.Id)
  2189  
  2190                                      };
  2191                                      Organiza tionServic e.Update(u pdateFeedb ack);
  2192                                      Logger.W riteDebugM essage("Up dated the  PPE Feedba ck's Reque st Team wi th " + pro xyCOSTeam. Name);
  2193                                 }
  2194                             }
  2195                             //Serv ice Chief  Team
  2196                             proxyS CTeams = s rv.TeamSet .Where(t = > t.cvt_Fa cility.Id  == proxyPr iv.cvt_Pri vilegedAtI d.Id && t. cvt_Type.V alue == 91 7290001 &&  t.cvt_Ser viceType.I d == homeS erviceType ).Distinct ().ToList( );
  2197                             
  2198                             //Depe nding if i t is feedb ack or esc alation                        
  2199                             foreac h (var res ult in pro xySCTeams)
  2200                             {
  2201                                 em ail.To = R etrieveFac ilityTeamM embers(ema il, result .Id, email .To);
  2202                             }
  2203                             var pr oxySCTeam  = srv.Team Set.FirstO rDefault(t  => t.cvt_ Facility.I d == proxy Priv.cvt_P rivilegedA tId.Id &&  t.cvt_Type .Value ==  917290001  && t.cvt_S erviceType .Id == hom eServiceTy pe);
  2204                             if (pr oxySCTeam  != null &&  feedback. cvt_respon serequeste d == null)
  2205                             {
  2206                                 // Set the re sponse req uested fie ld
  2207                                 cv t_ppefeedb ack update Feedback =  new cvt_p pefeedback ()
  2208                                 {
  2209                                      Id = fee dback.Id,
  2210                                      cvt_resp onsereques ted = new  EntityRefe rence(Team .EntityLog icalName,  proxySCTea m.Id)
  2211                                      
  2212                                 };
  2213                                 Or ganization Service.Up date(updat eFeedback) ;
  2214                                 Lo gger.Write DebugMessa ge("Update d the PPE  Feedback's  Request T eam with "  + proxySC Team.Name) ;
  2215                             }
  2216  
  2217                             if (is Escalation )
  2218                             {
  2219                                 // Set the Cc  to the SC  team
  2220                                 em ail.Cc = e mail.To;
  2221                                 em ail.To = n ull;
  2222  
  2223                                 // Set the To  to the Co S team
  2224                                 fo reach (var  result in  proxyCoST eams)
  2225                                 {
  2226                                      email.To  = Retriev eFacilityT eamMembers (email, re sult.Id, e mail.To);
  2227                                 }
  2228  
  2229                                 te am = "Spec ialty Serv ice Chief  Team at Pa tient Faci lity team  members";
  2230                             }
  2231  
  2232                             //Edit  the E-mai l body
  2233                             if (!i sEscalatio n)
  2234                                 cu stomMessag e = String .Format("P lease clic k the abov e link and  the provi der identi fied on th e page is  undergoing  a PPE rev iew.  All  facilities  are requi red to pro vide feedb ack into t his proces s where th is provide r is pract icing.  Yo u have {0}  days to t ake action .<br><br>I f you have  anything  to report,  positive  or negativ e, related  to this p rovider’s  performanc e, please  record a “ Yes” and c lick “Save  and Close .”<br><br> If you hav e nothing  to report,  please re cord a “No ” and clic k “Save an d Close.”< br><br>Onc e recorded , you cann ot change  your feedb ack so ple ase be sur e to resea rch your r esponse pr ior to rep orting.<br ><br>Your  feedback w ill be sen t automati cally to t he provide r’s Servic e Chief at  his / her  Home Priv ileging Fa cility.<br ><br>  If  you record ed a “Yes”  you will  be contact ed by secu re e - mai l for your  report.<b r><br>Than k you.", d aysRemaini ng.ToStrin g("%d"));
  2235                             else
  2236                                 cu stomMessag e = String .Format("{ 0} days ag o, a reque st was sen t to these  people: { 1} for fee dback to t he Service  Chief at  the Provid er’s Home  Facility f or PPE pur poses.<br> <br>This f eedback is  overdue.   Please ta ke action  to have th e staff at  our facil ity provid er the req uired info rmation as  soon as p ossible.<  br >< br > Thank you. ", daysEla psed.ToStr ing("%d"),  team);
  2237  
  2238                             email. Descriptio n = genera teEmailBod y(feedback .Id, feedb ack.Logica lName, cus tomMessage , "Please  click this  link to v iew the PP E record." );
  2239                             if (em ail.To !=  null)
  2240                                 Cv tHelper.Up dateSendEm ail(email,  Organizat ionService );
  2241                         }
  2242                    }
  2243                }
  2244           }
  2245           #e ndregion
  2246  
  2247           #r egion Impl ementing a dditional  interface  methods
  2248           pu blic overr ide string  McsSettin gsDebugFie ld
  2249           {
  2250                get { re turn "cvt_ serviceact ivityplugi n"; }
  2251           }
  2252           #e ndregion
  2253       }
  2254   }