<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by João Castelo on Medium]]></title>
        <description><![CDATA[Stories by João Castelo on Medium]]></description>
        <link>https://medium.com/@jhmcastelo?source=rss-3c314038f737------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c6bJgNz0GSfYr4GdXAHxIA.jpeg</url>
            <title>Stories by João Castelo on Medium</title>
            <link>https://medium.com/@jhmcastelo?source=rss-3c314038f737------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:31:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jhmcastelo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[4 years using ESAPI, how to improve your apps]]></title>
            <link>https://jhmcastelo.medium.com/4-years-using-esapi-how-to-improve-your-apps-52b16cd0fc94?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b16cd0fc94</guid>
            <category><![CDATA[radiation-oncology]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 14:01:12 GMT</pubDate>
            <atom:updated>2023-07-06T17:04:08.736Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys! I’ve been hiding for a year because I was finishing my <strong>master thesis</strong> but I’m all good now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*17lJbKytK0PDNwZ3" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since I’ve started my career in <strong>radiation oncology</strong> back in <strong>2019</strong>, I’ve been a massive <strong>ESAPI </strong>user and supporter. After developing several apps I took some notes on my dev <strong>routine</strong>. Hope it helps others and probably myself in the future.</p><p><strong>Python developers</strong> (give up) you have to master C# unfortunately</p><h4>1 -&gt; Do not make your application overwhelming.</h4><p>Every plugin or executable should have an easy user interface, else people won’t use it.</p><p>When designing your <strong>User interface</strong>, the landing page and the default options should yield a good result in one or two clicks. If the user has to think to use your app, they’ll probably use it the wrong way use it wrong.</p><p>As physicists we like to be able to change stuff, but having so much control over the app is bad for the new user. Think of Android and iOS, they may be able to perform the same tasks, but iOS experience seems better, just because its default options are better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*2jNuAfNusm9nyUW7qLYD4w.png" /><figcaption>Simple User interface</figcaption></figure><p>In our auxiliary structure generator script, the default template can’t mess up plans. But the other templates can. SBRT and SRS templates are dangerous if not used correctly. Default template: As simple aux structures as they can be to deliver a good VMAT plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*5TjWwGiWWphmiKHe1Pp0sw.png" /><figcaption>The SBRT model would crop the optimization PTV (brown) inside the all organs at risk (OAR), but for this one might not be the best option. We had to choose in the Select OARs only heart and esophagus. Great vessels and Bronchi are not meant to be spared.</figcaption></figure><h4>1.1 -&gt; Create some kind of documentation</h4><p>For coding, think of your code going online with GitHub, use good git messages for you commits. Create Branchs for each major change in your apps.</p><p>For the app, try to summarize possible errors and create examples for expert users.</p><h4>2 -&gt; Don’t expect user input to be correct.</h4><p>Know that when people use your script they’ll click the run button 4 times in a row, they’ll select the wrong PTV, wrong CTV. Test your application for multiple repetitive actions in a row, if it yields a bad result, block it with pop ups or disabling buttons.</p><p>Create progress bars and warnings!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*ZPUCV2HE03JLCPsBY5yp2Q.png" /></figure><p>Eric and Carlos did an awesome job with this piece of code (almost a plug and play):</p><p><a href="https://github.com/esimiele/SimpleProgressWindow">GitHub - esimiele/SimpleProgressWindow: A linux-style simple progress window for async reporting of operations</a></p><p>Use pop ups, with a message for OK and Cancel. I do not enjoy more complex decision popups (those you make with windows forms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*cVR4ka0UykDf9jWHThiVHw.png" /></figure><p>Our Isodose level converter allows users to add their Isodoses for any PTV they want and the value as they want. The script also reads dose from the PTV depending on the ID matching, and when it does not, it sets the default to 0 cGy. I thought no one was going to use an 0 cGy isodose, but it turns out that I’m seeing a lot of 0 cGy structures! (The power of the default). It can’t do harm, but it is slowing down the loading of structures in the LINAC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*ZtUK1hETT_Bfpb3i7pzUjQ.png" /><figcaption>UI for the isodoselevel converter</figcaption></figure><h4>3 -&gt; Start small but think about expansion and reusability</h4><p>Whenever I get an Idea from colleagues or from myself, the first thinking is: Do I have to create a new app or can I insert the new idea in an existing app?</p><p>There are two paths, if the latter is true. The first is to hardcode the new idea as a Frankenstein or insert it as an extension from the code you wrote before. I always write code to be easy to update and extend in the future.</p><p>When I create a new app, I always start by thinking about the MVP:</p><blockquote>Minimum Viable Product (MVP) Definition</blockquote><blockquote>“The minimum viable product is that version of a new product which allows a team to collect the maximum amount of validated learning about customers with the least effort.” Google’s first page (productboard)</blockquote><p>I mostly reuse an old UI, get it working with the simplest code behind, and present it to other users. If they find it helpful/useful I then begin to build the code as if I had to present it to a Computer Science nerd.</p><p>I always create classes, objects, avoid nesting and avoid methods to hold too much info!</p><p>Think of the methods and classes as your intern, you won’t let him do tasks that he can’t handle or have to think a lot.</p><h3>Examples:</h3><p>Think of a pseudocode to create a VMAT plan:</p><p>Decide whether it’s a plugin or an executable</p><p>Plugin (.esapi.dll)</p><p>First think of the UI (mostly the landing default page), how it should be.</p><p>The user can’t mess up it with wrong typing or multiple actions in a row?</p><p>If you’re a geek you can use Figma to build the UI prototype! (I prefer a malfunctioning WPF prototype)</p><p><a href="https://www.figma.com/">Figma: The collaborative canvas for design, code, and AI</a></p><p><strong>Design the code that runs behind (MVVM):</strong></p><p>I like to do it simple:</p><pre>// UI Code <br>Window(course, structureSet)<br>vm = new ViewModel(course, structureSet)<br>TextBox(&quot;Selected Course&quot;, vm.CourseId)<br>TextBox(&quot;Selected Rx Prescription&quot;)<br>DropDown(vm.AvailablePrescriptions(), changed(e) =&gt; vm.ChangePrescription(e))<br>TextBox(&quot;Selected Target&quot;)<br>DropDown(vm.AvailableTargets(), changed(e) =&gt; vm.ChangeTarget(e))<br>TextBox(&quot;Selected RP Enhanced&quot;)<br>DropDown(vm.AvailablePrescriptions(), changed(e) =&gt; vm.ChangePrescription(e))<br>Button(&quot;CreateAutoPlan&quot;, pressed()=&gt;vm.Automate())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vGWI4eUZ49fZ02TLJah4jQ.png" /></figure><pre>// View Model Creates a information center between UI and Model<br>CourseId<br>Course<br>AvailablePrescriptions()=&gt; SomeMethod()<br>SelectedPrescription<br>AvailableBeamTemplates<br>SelectedBeamTemplate<br>AvailableRPETemplates () =&gt; SomeMethod() // RapidPlan Enhanced<br>SelectedRPETemplate<br>constructor(course, structureSet){<br>  Model = new ModelAll(this) // passing the VM to the model<br>}<br>Automate() =&gt; Model.AutomateAll()</pre><pre>// Model file<br>class ModelAll<br>vm = ViewModel<br>AutomateAll(){<br>  course = GetCourse()<br>  plan = CreatePlan(course)<br>  target = vm.GetTarget()<br>  prescription = GetPrescription(course)<br>  AssignPrescription(plan, prescription)<br>  templateBeams = vm.SelectedBeamTemplate<br>  beams = CreateBeams(plan, templateBeams.BeamArrangement)<br>  AdjustCollimators(beams, target, templateBeams.CollimatorInfo)<br>  AdjustIsocenter(beams, target, templateBeams.IsocenterAdjustment)<br>  <br>}</pre><p>In the future, I might want to add a new Template for Isocenter positioning, so I would have an easy plug and play way to code it. Using the same logic:</p><pre>TextBox(&quot;Selected IsoPosition Template&quot;)<br>DropDown(vm.AvailableIsoTemplates(), changed(e) =&gt; vm.ChangeIsocenterTemplate(e))</pre><p><strong>Create a Visual Studio Project on TBOX:</strong></p><p>I always use the Executable path, and then mimic the plugin behavior by getting a hardcoded patient. You can always use Carlos Anderson’s plugin runner!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*MEe8eBhksFTiqFsO57_sJw.png" /><figcaption>Executable.cs</figcaption></figure><p>Do not let ESAPI code to run in the UI xaml.cs, try to avoid it at your ViewModel, you should keep it under you Model code (backend).</p><p>Although it goes in opposition to what I’ve said, I send the Patient or PlanSetup to a new Window, to start the UI and run the code behind it. Yes it would be better to do a separate class or a Facade, but I’m lazy 😶.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Of8NQzLrYB4RmuV9OJinDA.png" /><figcaption>Script.cs</figcaption></figure><p>Data binding and other stuff are not really in question, but I always do the bindings myself. I’m dumb when trying to figure out the multiple ways to use the AutoFacs and AutoBinders (INotifyPropertyPlease NOOOO).</p><h3>Take home points:</h3><p>Always create an UI, please xaml</p><p>Get a good default option</p><p>Do not expect users to be smart when using your design</p><p>Avoid using too much 3rd party nuGet packages.</p><p>Thanks Jonas for the review!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b16cd0fc94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Varian ESAPI Workshop: Brazilian Medical Physics Conference (CBFM)]]></title>
            <link>https://jhmcastelo.medium.com/varian-esapi-workshop-brazilian-medical-physics-conference-cbfm-8498a3061641?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/8498a3061641</guid>
            <category><![CDATA[radiotherapy]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[course]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Thu, 23 Jun 2022 19:54:14 GMT</pubDate>
            <atom:updated>2022-06-23T23:49:01.181Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! Been gone for some time, but back for business! 😁😁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*jxq5Yeo4z4r0Ux2h4Y294g.png" /></figure><p>In June 8 (2022), <a href="https://github.com/anselmomancini"><strong>Anselmo Mancini</strong></a><strong> </strong>and <strong>I </strong>presented the <strong>Varian Eclipse Scripting</strong> WorkShop at the the<strong> Brazilian Medical Physics Conference (CBFM).</strong></p><p>It was the <strong>first </strong>time since <strong>2019 </strong>we’ve had an “offline” <strong>conference</strong>. It was a <strong>4 hour</strong> long event, and we had <strong>30–40</strong> people attending!</p><p>First part was one hour lecture of <strong>C#</strong> and <strong>ESAPI </strong>basics, we jumped into a very similar example as presented in my <a href="https://jhmcastelo.medium.com/esapi-guide-5-steps-to-start-scripting-including-citrix-users-e72108b2b50c"><strong>5 steps to start ESAPI scripting post</strong></a><strong>.</strong></p><p>We create a class called <strong>Patient, </strong>then we read from a csv file and we create a <strong>patients list</strong> from it<strong>. </strong>Then we filter the urgent patients from the list and print their info.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f30dfc662dcb7604a223913e56f5e24/href">https://medium.com/media/3f30dfc662dcb7604a223913e56f5e24/href</a></iframe><p>The second part was <strong>live coding</strong> two binary plugins with <strong>WPF User Interfaces</strong>:</p><h4>Simple Plan Check tool:</h4><p>Code is here: <a href="https://github.com/joecastelo/JuneWorkShopCBFM22">https://github.com/joecastelo/JuneWorkShopCBFM22</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*-SzA0FkyUY2tM6RRjBVNAQ.png" /><figcaption>User Interface</figcaption></figure><p>In the main Script file, we create a class called <strong>Check</strong>, which has 3 <strong>properties</strong>, <strong>Title</strong>, <strong>Result </strong>and <strong>Comment.</strong></p><p>This <strong>Class </strong>has a constructor with two default arguments, an <strong>empty </strong>comment and an <strong>OK </strong>Result. When you create a check with the Title <strong>“Check whatever”</strong>, you’ll have to code the business logic and change the Result and Comment on the fly.</p><p>A <strong>MainWindow.xaml</strong> is created to hold a <strong>List View</strong> of <strong>CheckScreen.xaml</strong>, that displays the Check’s <strong>Title</strong> and <strong>Result</strong>, changes it’s color based on the test result, and when you click on the check, it pops the <strong>Comment</strong>.</p><h4>Create Optimization Structures:</h4><p>Code is here: <a href="https://github.com/anselmomancini/CreateOptStructures">https://github.com/anselmomancini/CreateOptStructures</a></p><p>In this plugin, the overlapping region between the <strong>OARs </strong>and the <strong>PTVs sum</strong> + <strong>margin </strong>is checked and it crops the OARs with the <strong>margin </strong>chose by the user in a WPF window.</p><p>Since it is a showcase code, it does not handle operations between Structures with High Resolution and Default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*eYdcre7iyzEqz36U-687OA.png" /><figcaption>User interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*iUIEPWRkib0lFP066Ji5cg.png" /><figcaption>Result</figcaption></figure><p>Hope you enjoy!</p><p>Thanks to Anselmo and Varian for this great experience, I hope we can repeat it in the future!</p><p>Thanks to Jonas for reviewing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8498a3061641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics with Python part 2 (AURA)]]></title>
            <link>https://jhmcastelo.medium.com/statistics-with-python-part-2-aura-189ca8c0d7b3?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/189ca8c0d7b3</guid>
            <category><![CDATA[radiation-therapy]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 20:24:00 GMT</pubDate>
            <atom:updated>2022-02-04T16:34:32.442Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! After some time (almost one year man 🙄) <strong>I’m back</strong>!</p><p>Last post I presented a notebook with simple examples in a jupyter notebook to perform some <strong>statistical hypothesis testing</strong>!</p><p><a href="https://jhmcastelo.medium.com/statistics-with-python-part-1-3c708fe9e97d">Statistics with python, Part 1</a></p><p>In Part 3, ESAPI will be used to extract <strong>DVH</strong> information from a <strong>list of patients plans</strong>.</p><p>In this post <strong>(Part 2),</strong> I’m going to show how to use <strong>AURA Reporting</strong> to extract the patient list.</p><p>It can be done using <strong>ESAPI, ARIA database queries or ARIA Web Services</strong>, but I won’t in the moment, I preferred <strong>AURA Reporting.</strong></p><h3>Lets Go!</h3><p>Open the<strong> Reporting Tab</strong> and press <strong>Create new Report</strong>, this command will open the <strong>Microsoft SQL Report Builder</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*FloySVrr_Wbz5tLnerN3-g.png" /><figcaption>Default window for Microsoft SQL Report Builder</figcaption></figure><p>Press the <strong>Blank Report</strong> option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*tXl7prn7ov3Tznlekbm6iw.png" /><figcaption>Brand new Blank Report</figcaption></figure><p>In the end of this post we’ll create a table to <strong>query </strong>the treatments for <strong>Prostate SABR (36.25 Gy in 5 fx)</strong> after 2018.</p><p><strong>First of all </strong>let’s add a <strong>Data Source </strong>(<strong>varian dw</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*x5v4mvuNj12qvjCcdAiRWg.png" /><figcaption>Add Data Source</figcaption></figure><p>Rename the data source to <strong>VarianDW</strong> and click in the <strong>Browse </strong>button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*qIErxiUFMqeSR-BvYuOgaw.png" /><figcaption>Click Browse</figcaption></figure><p>Open the <strong>VarianTemplate </strong>folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*bqI4lxttweDKmUO-N04tWg.png" /><figcaption>Open the VarianTemplate Folder</figcaption></figure><p>Then the <strong>Data Sources</strong> folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*e0FtTNcMQU3trviQzbyPYw.png" /></figure><p>Double Click the<strong> variandw</strong> source:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/88/1*sav7C_AyHn-7plio8LQq0g.png" /><figcaption>Double Click the variandw source:</figcaption></figure><p>Once the <strong>connection </strong>is set, click OK:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*LXytxyWJMU3t6o0Sa-mRwg.png" /><figcaption>Once the connection is set, click OK</figcaption></figure><p>We’ll use the <strong>data source</strong> to create a<strong> custom data set.</strong></p><p>Of course, you can use the <strong>pre-built models from AURA</strong>.</p><p>But I want to show the power of the <strong>Query designer</strong>.</p><p>Press<strong> add DataSet</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*JNlRQwoLDMv_FD7F-jyoJQ.png" /><figcaption>Add Dataset</figcaption></figure><p>In the <strong>dataset properties</strong> tab, Select use dataset <strong>embedded in my report</strong>, choose <strong>Variandw</strong> as data source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*M3LporFvNiTJL1n00IZpeA.png" /></figure><p>Press <strong>Query Designer</strong>, since I’m in <strong>CITRIX</strong>, I’m using my user to sign in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*4BrV1XEVZ3Bz74ruqQqeEQ.png" /><figcaption>Query Designer login</figcaption></figure><p>Then the <strong>query designer</strong> will pop. <strong>Query designer </strong>makes us able to do queries with SQL with limited knowledge (unfortunately I’m not a database nerd 😅).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*2vymhSA948oJmi-RFxRuKg.png" /><figcaption>Query Designer home screen</figcaption></figure><p>See those tabs in the left? The <strong>DWH</strong> contains <strong>tables</strong> we can query, they represent the data in the <strong>AURA</strong> tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*hqXhNXLenjKkWBsS4lFQjA.png" /><figcaption>Treatment Model (From AURA Manual).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*2JkY_-n1OPLy3NgmrYd5pQ.png" /><figcaption>Open the Tables from DWH.</figcaption></figure><p>Let’s check the <strong>fields </strong>we can query from the <strong>FactTreatmentHistory</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*6Y-G1tIrioLQ3CZ7zW30Fw.png" /></figure><p>We’ll select just the following and press the <strong>Run Query</strong> Button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*y_UiBM91OSg9Efsp6_jTHg.png" /></figure><p>This is the result from the <strong>query </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*MLcDrbVzEynz0ERKm_GP9g.png" /></figure><p>I get a series of all treatments. Of course it is the treatment history 😎!</p><p>Now let’s start filtering some information and get the <strong>Plan Id</strong>, <strong>Patient Id</strong>, <strong>Course Id</strong> and <strong>Machine Id</strong> (merging the Treatment History’s table with others).</p><p>First we’ll get only the last fraction of the<strong> Prostate SABR</strong> patients.</p><p>So the filter will be<strong> NoOfFraction = 5</strong> ; <strong>FractionNumber = 5</strong>, and <strong>dose per fraction = 7.25Gy.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*S1_q5gC6RWWol0LsTZ25cg.png" /></figure><p>This is the <strong>result </strong>from the <strong>query</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*X7NGYgrTEExAXGlhZkSp-A.png" /></figure><p>Let’s merge the <strong>Course</strong> and <strong>Plan’s</strong> Table to see their actual ID.</p><p>With the <strong>fact treatment history fields</strong> still selected, select:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*wRZtZ3uOCW7X6EdbMwqpjw.png" /></figure><p>This is the image you’ll see, look how the tables are <strong>automatically merged </strong>by the <strong>query designer</strong>, using the <strong>DimCourseId</strong> field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*A9yAKP9ubtKr6tFn5rIZeg.png" /></figure><p>So when I run the query once more, I’ll get the <strong>Course Id</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*YHuH-AtwU8QbqBdnqXQi-w.png" /></figure><p>Do the same with <strong>Plan Id </strong>with the <strong>DimPlan’</strong>s table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*jQMoP8g3HH8BGnvqur6PQw.png" /></figure><p><strong>Query Designer</strong> already filled the <strong>relationship </strong>for us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*m3DRzjSqPttMNezGiK51rw.png" /></figure><p><strong>There we go!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*BorryXuLohpoJjYG_cVkTA.png" /></figure><blockquote>Do the same with the DimPatient’s table yourself.</blockquote><p>So now I can filter based on another table as well, imagine a <strong>head and neck cohort</strong>, how would you look for the <strong>unilateral </strong>cases?</p><h4>Back to track:</h4><p>I want to get the treatments for a specific <strong>machine</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*vgRPD-RU1jWFsHMgXtaNGA.png" /></figure><p>From the same principle, using the <strong>DimMachine’s</strong> Table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*VAzq5GVbbE6K7fhacIf34g.png" /></figure><p>Adding the <strong>Machine Id</strong> as a filter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*tXYmq3700oo0IN8suxPt8Q.png" /></figure><p><strong>Query </strong>Once More!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*fM6ou9e62Sk2VI-ex66Hng.png" /></figure><p>Now we have a very good <strong>DataSet </strong>to work with!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7--vu29xQercT_a3yd8zlA.png" /></figure><p>Add the <strong>filter fields</strong> as <strong>parameters</strong> so we can change when running the report, and press <strong>OK</strong>.</p><p>There it is: <strong><em>good and old</em></strong> SQL Query written for us by the<strong> query designer</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*7ENy0wrTvK5M1tpiAcs6zg.png" /></figure><p><strong>Finally </strong>we’ll build our table and export it to a <strong>CSV </strong>file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*7k-pe29CWZ1MeUpmzTgFsg.png" /></figure><p><strong>Patient Id, Course Id and PlanSetupId suffice for the next part!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*3oyNjizO-FoyeMOitByzkQ.png" /></figure><p><strong>Run the Report!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*8IzGO8gQvH8NQiYPXxGTIw.png" /></figure><p>Export as <strong>CSV </strong>and you’ll have your <strong>patient list</strong> ready:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*QUanS9D5rojzyZ_zWeFWng.png" /></figure><p>In the next <strong>Part</strong>, we’ll use this <strong>CSV </strong>file to run an <strong>executable </strong>at the <strong>Eclipse DB</strong> to export <strong>DVH </strong>for selected structures!</p><p>See you soon!</p><p>Joao Castelo</p><p>Thanks for reviewing Jonas (Congratz he’s now a certified medical physicist) 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=189ca8c0d7b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics with python, Part 1]]></title>
            <link>https://jhmcastelo.medium.com/statistics-with-python-part-1-3c708fe9e97d?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c708fe9e97d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Fri, 12 Feb 2021 20:22:56 GMT</pubDate>
            <atom:updated>2022-02-01T23:36:16.647Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Sorry for the 2 month break from posts, been busy finishing the residency!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CeIVoKzss813vNPg" /><figcaption>Photo by <a href="https://unsplash.com/@christopher__burns?utm_source=medium&amp;utm_medium=referral">Christopher Burns</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Statistics is the main framework we have to test our hypothesis about data!</p><p>Most of the time we want to test if our new way to do something is really working.</p><p>When applying a new strategy in the clinic, we begin by testing once, twice, three times, and then we agree if it is worthy to test some more or not.</p><p>But how many times we have to test, which test should we perform and how should we display the analyzed data?</p><p>In my opinion, you should be using <strong>python</strong> to figure it out!</p><h4>Easy python, no installing</h4><p>Let’s use <strong>Google Colaboratory </strong>to write python code!</p><p><a href="https://colab.research.google.com/">Google Colab</a></p><p>Log in with a google account and create a new notebook!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*opZyE8dT7tpOLNOMpeEYUw.png" /></figure><p>Change the notebook name to <strong>ESAPIAnalysis.ipynb</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*ZIThTq_MxAlGTOKuEq6mdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*v9F3T7tZ-PO6WKQ7hfu80A.png" /></figure><p>Let’s write a simple hello world:</p><pre><strong>viewer = &quot;😎 Physicist&quot; ## variable assingment<br>print(f&quot;Hello world {viewer}&quot;)</strong></pre><p>Paste this code in the first cell and press <strong>Alt+Enter</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*UMztv_1AcVA-BrRpl19TIA.png" /></figure><p>Let’s reuse the variable <strong>viewer </strong>in another cell!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*lKMcL39m13gANHODtBVi9A.png" /></figure><p>Note that over each cell there are two buttons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aN2Lh3rxJN_5JwZVBHFHcg.png" /></figure><p>If you choose text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*usuc03mszAG2EgpEINEQDA.png" /></figure><p>With the hashtags you can create sections and subsections!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*tBYJ3oOsYkpk6eTh6zOz-A.png" /></figure><p>And then you have <strong>hyperlinks </strong>in the contents tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*8Hnda3iuaL5A4ZSpqlKkPg.png" /></figure><p>In python it is usual to import libraries and use someone else’s code.</p><p>Use the keyword <strong>import</strong>:</p><p><strong>Numpy </strong>is a library with useful methods for dealing with arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*3Q41jx2kAU2tAj8wRgI3yg.png" /></figure><p>We’re using the normal method from the numpy random class.</p><p>The keyword to create 60 pseudo-random numbers based on a normal distribution with mean 30 and standard deviation 5 is:</p><pre><strong>normal_dist = np.random.normal(30,5,60)</strong></pre><p><strong>Matplotlib </strong>is a library with methods for plotting data.</p><p>Plot the distribution:</p><pre>import matplotlib.pyplot as plt<br><strong>figure = plt.hist(normal_dist)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*5MEBVdUImrkU7wiiWkFTXA.png" /></figure><p>Let`s create another normal distribution with another mean and variance:</p><pre><strong>normal_dist2 = np.random.normal(34,3,60)</strong></pre><p>Plot both:</p><pre><strong>fig1 = plt.hist(normal_dist)<br>fig2 = plt.hist(normal_dist2)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*n9cNAKig08Jq6vqyyDOasA.png" /></figure><p>Now let`s use the student`s t test to check the hypothesis that both independent samples come from the same distribution:</p><pre><strong>from scipy.stats import ttest_ind<br>test = ttest_ind(normal_dist,normal_dist2)<br>print(test)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*fIUh_hYop72m6jVkz64A_w.png" /><figcaption>Result, the statistic is -5, and p-value = 1e-8</figcaption></figure><p>We can have paired samples too:</p><pre><strong>from scipy.stats import ttest_rel<br>test = ttest_rel(normal_dist,normal_dist2)<br>print(test)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*KVXbypHCaaHvaIPNiQ-hfA.png" /></figure><p>Remember that t-test assumes normality and equal variance between samples, when those cant be assumed, one can use the wilcoxon paired test (for paired samples):</p><pre><strong>from scipy.stats import wilcoxontest<br>test = wilcoxon(normal_dist,normal_dist2)<br>print(test)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*j7GLO68UUw0KQ5Eo-5uzRg.png" /></figure><p>or the U-Mann-Whitney (for independent samples):</p><pre><strong>from scipy.stats import mannwhitneyu<br>test = mannwhitneyu(normal_dist,normal_dist2)<br>print(test)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*2xuJfryVf6ltjkWGqRh20g.png" /></figure><p>Do you like this kind of post?</p><p>Next we’ll get some <strong>ESAPI</strong> data with a single file plugin, export as CSV and use python to analyze it based on Chaickh et al!</p><p>Chaikh, A., Giraud, JY., Perrin, E. <em>et al.</em> The choice of statistical methods for comparisons of dosimetric data in radiotherapy. <em>Radiat Oncol</em> <strong>9, </strong>205 (2014). <a href="https://doi.org/10.1186/1748-717X-9-205">https://doi.org/10.1186/1748-717X-9-205</a></p><p>Thanks for reading!</p><p>Thanks to Jonas for reviewing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c708fe9e97d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Portal Dosimetry Scripting: Export Images as CSV]]></title>
            <link>https://jhmcastelo.medium.com/portal-dosimetry-scripting-export-images-as-csv-5d63177e7ed9?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d63177e7ed9</guid>
            <category><![CDATA[medical-physics]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[radiotherapy]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Fri, 02 Oct 2020 20:16:21 GMT</pubDate>
            <atom:updated>2020-10-02T20:16:21.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys, hope you’re doing great!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gLPDOx0Ci5XFevVp" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post I want to share with you a simple <strong>UI </strong>that I’ve started to develop a few days ago.</p><blockquote>This script is just for testing, it is not supposed to be used in clinic.</blockquote><p>It is a simple <strong>WPF </strong>app to ease the exporting process of <strong>Portal Dosimetry</strong> images.</p><p>Before all that, I’ll share <strong>4 </strong>main aspects of <strong>Portal Dosimetry Scripting API.</strong></p><h4>Where to find Portal Dosimetry dlls?</h4><p>They are located in the computer in which Eclipse is installed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*AdH_Zrz9AY3LQwoQtyfSMw.png" /><figcaption>C:\Program Files (x86)\Varian\ProductLine\Workspaces\VMS.PortalDosimetry.Workspace</figcaption></figure><p>The <strong>Workspaces </strong>folder also has the Image Registration API libraries. (Which I won’t cover in this post).</p><p>You’ll import in Visual Studio the two dlls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*9xCjaHjzynBzyJ8Cwit-2g.png" /></figure><h4>Where to run the plugins:</h4><p>You have to access the <strong>Portal Dosimetry UI </strong>in <strong>Eclipse</strong>. And then click in <strong>Tools/Scripts:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*kueQ5Vktct5c_TMJN_VwGQ.png" /></figure><p>On this interface you can run <strong>single file</strong> and <strong>binary </strong>plugins. One interesting thing is that in <strong>Portal Dosimetry API</strong> you don’t need to declare your assembly name as <strong>Something</strong>.<strong>esapi</strong>.dll for binary plugins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*GAxtLCxjoraej9w9j9fapw.png" /><figcaption>All helper libraries can be executed, but only the VMS.DV.PD.Scripting.Execute will be targeted.</figcaption></figure><h4>Testing Binary Plugins:</h4><p>All versions of the assembly are kept loaded inside Eclipse after running just like in <strong>ESAPI</strong>, so you need to compile multiple times with different assembly names. <a href="https://github.com/mattcschmidt"><strong>Matt</strong></a><strong> </strong>figured out a similar solution as <a href="https://www.carlosjanderson.com/">Carlos Anderson’s</a> <strong>plugin runner </strong>for <strong>TBOX</strong>.</p><p><a href="https://www.nuget.org/packages/PDPluginRunner/2.0.1">PDPlugInRunner 2.0.1</a></p><h4>Testing Executables:</h4><p><strong>Executables </strong>need to be executed via the computer that Eclipse is installed. So be aware <strong>CITRIX </strong>Users!</p><h4>Please I need a template!</h4><p>You can use the Script Wizard, but I do not like it because the separation between <strong>Project </strong>and <strong>Plugin </strong>makes the <strong>Git </strong>repository <strong>creation </strong>and commit difficult.</p><p>Remember to change the project’s <strong>CPU settings to x64</strong>.</p><p>So here are the templates for <strong>binary and single file plugins</strong> (Class Library Project):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8a3d2c007e89b3cca2a16348be76c92/href">https://medium.com/media/e8a3d2c007e89b3cca2a16348be76c92/href</a></iframe><p>And for <strong>executables</strong> (Console Application):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10053f32379cdcd18d89db708aad9c3a/href">https://medium.com/media/10053f32379cdcd18d89db708aad9c3a/href</a></iframe><h4>Is Portal Dosimetry Scripting writable?</h4><p>You can’t really save anything, but you can do <strong>Portal Dosimetry </strong>analysis using the method <strong>CreateTransientAnalysis.</strong></p><h4>Can I trigger the Portal Dosimetry API from an ESAPI plugin?</h4><p>Yes, you can use the methodology described in this <a href="https://medium.com/@jhmcastelo/how-to-emulate-plugins-with-executables-in-esapi-97f5213f4560"><strong>earlier </strong>post</a> on the blog. Instead of creating the executable using the <strong>VMS.TPS </strong>libraries, you should use the <strong>VMS.CA.Scripting </strong>and <strong>VMS.DV.PD.Scripting</strong>.</p><h4>Portal Dosimetry Script to Export the acquired images:</h4><p>The project is in the following repo in my <strong>GitHub</strong>:</p><p><a href="https://github.com/joecastelo/PortalDosimetryExporter">joecastelo/PortalDosimetryExporter</a></p><p>Clone, download the references needed in the<strong> NuGet Package Manager</strong> and compile it on visual studio.</p><h3>Code Highlights:</h3><h4>Passing the window as argument in the <strong>Execute </strong>method:</h4><pre>public void Execute(ScriptContext scriptContext, Window window)        { .....</pre><pre>   // create an userControl </pre><pre>   window.Content = showImg; // Add the userControl to the Window</pre><p>This allow you to Add User Controls to the <strong>script Window from PD API </strong>and still use the <strong>ScriptContext.</strong></p><blockquote>There is no need to call window.Show() in PD API, but it’s a must in ESAPI.</blockquote><h4>Creating a method to close the window if you Close the UserControl:</h4><pre>showImg.Closed += new EventHandler((sender, e) =&gt; window.Close());</pre><h4>Using the images to get the course (Reversing the query order):</h4><pre>var planPortals = scriptContext.Patient.PDPlanSetups.SelectMany(e =&gt; e.Beams);        <br>var courses = planPortals.Select(e =&gt; e.PDPlanSetup.PlanSetup.Course.Id).Distinct();</pre><p>In those lines I use <strong>SelectMany </strong>to get every beam available, then I use the beams to get their respective courses. When I use this query order I’ll be certain to only select courses with PD Beams.</p><h4>Create a MV Image recipient:</h4><p>I created a class to handle the <strong>MV Image</strong>, all the MV Images come from a PD Frame, that exists inside the beam property of the <strong>PDPlanSetup.</strong></p><p>The <strong>ShowImageModel</strong>’s constructor handles the <strong>MVImage </strong>creation process. For each frame, it creates a list of <strong>MVImage</strong>s. One interesting code <strong>optimization </strong>trick was to use the property Array as a method, this allows to only perform the long operation to get the <strong>calibration unit </strong>matrix when creating the heatmap (Once the image is selected in the dropdown) or when the user needs to export the <strong>MVImages</strong>.</p><pre>public double[,] Array { get =&gt; GetCUMatrix(Frame);  }</pre><p>Notice when I use it more than once I call it a local variable, so only one operation is performed.</p><pre>...<br>var array = Array; // <strong>Calling the GetCUMatrix method once</strong><br>File.WriteAllText(exportpath, &quot;&quot;);<br>for (int y = 0; y &lt;= array.GetUpperBound(1); y++)            { ....</pre><h4>Using a ViewModel as proxy for the content:</h4><p><strong>A WPF </strong>app needs the <strong>xaml </strong>and the<strong> xaml.cs</strong> files. The <strong>xaml </strong>contains the markdown that create the Text, buttons and etc.</p><pre>&lt;Button Background=&quot;DarkSlateGray&quot; Foreground=&quot;WhiteSmoke&quot; Click=&quot;ExportPD_Click&quot; Content=&quot;Export Portal Images&quot; Name=&quot;ExportPD&quot; /&gt;<br></pre><p>And the <strong>xaml.cs</strong> contains the logic to handle dynamic changes in the <strong>xaml.</strong></p><p>Notice that <strong>Background </strong>and <strong>Foreground </strong>are static properties, however the Click action is a <strong>method</strong>, so we defined it in the<strong> xaml.cs </strong>file.</p><pre>private void ExportPD_Click(object sender, RoutedEventArgs e)        {            string dirToSave = &quot;&quot;;</pre><p>The <strong>ExportPD_Click action </strong>depends on the course selected by the user by the following dropdown (<strong>ComboBox</strong>).</p><pre>&lt;ComboBox x:Name=&quot;Courses&quot; ItemsSource=&quot;{Binding Courses}&quot; SelectedItem=&quot;{Binding SelectedCourse}&quot; SelectionChanged=&quot;Courses_SelectionChanged&quot;                  Background=&quot;LightSlateGray&quot;/&gt;</pre><p>It is absolutely possible to do every <strong>operation </strong>related to the <strong>matrices </strong>and <strong>scriptContext </strong>inside, but I preferred to keep only the <strong>xaml </strong>objects behavior in the <strong>xaml.cs</strong> file. All the other tasks regarding the <strong>scriptContext </strong>were kept<strong> </strong>in the <strong>ShowImageViewModel, </strong>which is responsible for the <strong>connection</strong> between the View (<strong>ShowImage</strong>) and the <strong>MVImages </strong>List (<strong>ShowImageModel</strong>).</p><p>Using this logic, I set the <strong>xaml DataContext </strong>to be the <strong>ShowImageViewModel </strong>instance, and now it is possible to use its properties directly in the <strong>xaml</strong>. Notice that <strong>Courses </strong>(List of the courses Ids) does not exists in the <strong>xaml </strong>nor the <strong>xaml.cs</strong> file and yet can be called as the <strong>ComboBox ItemSource</strong>.</p><pre>ItemsSource=&quot;{Binding Courses}&quot;</pre><p>Every time the selection of the course <strong>ComboBox </strong>changes, the <strong>Courses_SelectionChanged action </strong>repopulates the <strong>MVImages List (ShowImageViewModel</strong>.RefreshImages()) and shows in the <strong>OxyPlot Heatmap</strong> the first element of the former.</p><pre>PortalImages.SelectedItem = ShowImageViewModel.SelectedModel;            PortalImages.ItemsSource = ShowImageViewModel.ModelsSource;</pre><h4>OxyPlot:</h4><p>The usage of <strong>Oxyplot </strong>is very straightforward, you create a <strong>PlotModel (ImageModel) </strong>in the <strong>ShowImageViewModel </strong>based on the present <strong>MVImage (SelectedModel) </strong>and bind it to the <strong>oxyView </strong>in the <strong>xaml </strong>file.</p><pre>&lt;oxy:PlotView MinHeight=&quot;600&quot; MinWidth=&quot;600&quot; MaxWidth=&quot;600&quot; MaxHeight=&quot;600&quot;  Background=&quot;Black&quot; x:Name=&quot;OxyView&quot;  Model=&quot;<strong>{Binding ImageModel}</strong>&quot;/&gt;</pre><p>To hide the axes, I get a black <strong>Background</strong>.</p><p>🤔 Well … <strong>WPF </strong>is not easy.</p><h4>Script usage:</h4><p>You choose the course that has at least one <strong>portal </strong>acquired and then you can inspect images in a <strong>fancy </strong><a href="https://github.com/oxyplot/oxyplot"><strong>Oxyplot</strong></a><strong> </strong><a href="https://oxyplot.readthedocs.io/en/latest/models/series/HeatMapSeries.html"><strong>heatmap</strong></a><strong> </strong>(that matches the Eclipse UI, except for windowing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*vnrRZSR9I5yHOXm_1v0M3w.png" /><figcaption>WPF UI to export portal images, textbox that checks all the images acquired, Oxyplot heatmap canvas, button to export the images, dropdown to choose course, dropdown to choose the image.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*Gogj0sTNSKTVGarlg1etxg.png" /><figcaption>Choice of course</figcaption></figure><p>After checking the images, press the green button (<strong>Export Portal Images</strong>) and choose the folder to Export via <strong>CommonOpenFileDialog.</strong></p><p>This dialog is not the <strong>FolderBrowserDialog</strong>, it is actually an abstraction of the <strong>OpenFileDialog</strong>, using the following line of code:</p><pre><strong>using (var fbd = new CommonOpenFileDialog())</strong></pre><pre><strong>{</strong></pre><pre><strong>fbd.IsFolderPicker = true;<br>....</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*Ue-hzH8TZRye-t6lzUfVaw.png" /></figure><p>After a few seconds you should be able to see the <strong>csv </strong>(<em>comma separated values</em>) files popping inside the folder you’ve selected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*pO8Kl0sh5tE9NCTYL_rzyg.png" /></figure><p>Those files are the exported images for all frames found in the selected course.</p><p>To test if the image matrices are indeed exported, I’ll plot them using a python script (Here I’m using a jupyter notebook at <a href="https://colab.research.google.com/">Google’s Colab</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*s85FwBHkdtYjoajR5n-zbg.png" /><figcaption>Python notebook</figcaption></figure><h4>Asynchronous:</h4><p>This project freezes the UI in the long operation to convert voxels values to calibration units (CU) and export it as csv. The loading cursor will pop, but the script is not <strong>crashing</strong>, it is just waiting.</p><p>One thing to add to this project, is moving the export process to an asynchronous task, this would solve the <strong>UI </strong>freeze problem. I’ll leave this task for a later post!</p><h4>Is information about PD API easy to get?</h4><p>They’re harder than ESAPI…<br>I’ve searched in <strong>github </strong>for projects:</p><p><a href="https://github.com/UNLV-MedicalPhysics/PD_AdvancedAnalysis">https://github.com/UNLV-MedicalPhysics/PD_AdvancedAnalysis</a></p><p><a href="https://github.com/Kiragroh/ESAPI_DataMiner_PortalDosimetry">https://github.com/Kiragroh/ESAPI_DataMiner_PortalDosimetry</a></p><p>And looked the Example projects of <strong>Eclipse Script Wizard</strong> (They’re located in the same folder as the dlls).</p><p>Thanks to Jonas for reviewing the post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d63177e7ed9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for VVectors and Structures in ESAPI]]></title>
            <link>https://jhmcastelo.medium.com/tips-for-vvectors-and-structures-in-esapi-575bc623074a?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/575bc623074a</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[medical-physics]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[radiation-therapy]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 19:32:23 GMT</pubDate>
            <atom:updated>2021-09-30T23:37:43.299Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys!</p><p>Today I will write about some shortcuts and interesting things I’ve learned when playing with structures and <strong>VVectors</strong> in ESAPI.</p><p>All the code will be shared at my<strong> </strong><a href="https://github.com/joecastelo"><strong>GitHub page</strong>!</a> So don’t worry about copy and paste today!</p><p>What are <strong>VVectors</strong>?</p><p>The <strong>VVector </strong>class is a recipient to the coordinates in the X, Y and Z direction in the <strong>CT DICOM</strong>. You can perform the usual vector operations, such as <strong>dot product, vector product, scalar product, addition, subtraction</strong>.</p><h4><strong>How do I access the coordinates:</strong></h4><p>You can access via <strong>vVector.x</strong>, <strong>vVector.y</strong> and <strong>vVector.z</strong></p><p>It’s interesting that you can also treat it like a <strong>C#</strong> array, <strong>vVector[0]</strong> (access <strong>x</strong> coordinates) and so on.</p><h4>Where is the origin?</h4><p>For <strong>VVectors</strong>, the <strong>origin </strong>is placed in the <strong>lower left corner</strong> of a <strong>Head First Supine Image</strong> and it is called <strong>Dicom Origin</strong>, it grows in <strong>millimeters</strong> from<strong> feet to head</strong>, <strong>top to bottom </strong>and <strong>left to right</strong>. When you want to locate a point in <strong>Script</strong>, remember that the<strong> UI </strong>coordinates are based on the <strong>User Origin (variable), </strong>but the <strong>ESAPI </strong>coordinates are based on the <strong>DICOM Origin (fixed).</strong></p><blockquote>the DICOM coordinates of the center point of the upper-left hand corner voxel of the first image plane.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*Nu0KwwdPbkdTtxbBMFUgjQ.png" /></figure><h4>In which Slice this VVector is?</h4><p>It depends on the image and Structure set you are accessing:</p><pre><strong>public static int _GetSlice(double z, StructureSet SS)       {                       var imageRes = SS.Image.ZRes;<br>return Convert.ToInt32((z - SS.Image.Origin.z) / imageRes);  <br>}</strong></pre><h4>How can I get the user’s coordinates:</h4><p>Imagine you’re automating a plan creation, you should return information to the user in the coordinate system he’s used to, ESAPI class <strong>Image </strong>has a dedicated method to do this:</p><pre><strong>Image.DicomToUser(vVector, plan) //Outputs the User Coordinates</strong></pre><h4>How to access a Structure:</h4><p>Via <strong>context</strong>, using <strong>Id </strong>to find the structure:</p><pre><strong>var ptv = scriptContext.StructureSet.Structures.First(e =&gt; e.Id == &quot;PTV&quot;);</strong></pre><h4>In which slice is the center point of a structure?</h4><p>You can access the Center Point via the Strucuture Properties:</p><pre><strong>ptv.CenterPoint; // VVector</strong></pre><h4>Where does it ends and begins, introducing MeshGeometry:</h4><p>Every structure segment is bounded within a box accessible via structure properties called <strong>MeshGeometry</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*Uh5AWnjoWO_UGfp57zfcJw.png" /><figcaption>MeshGeometry representation</figcaption></figure><p>You can get the list of slices of the structure is using the following method:</p><pre><strong>public static IEnumerable&lt;int&gt; _GetMeshBounds(Structure structure, StructureSet SS)       { <br>var mesh = structure.MeshGeometry.Bounds; <br>var meshLow = _GetSlice(mesh.Z, SS);<br>var meshUp = _GetSlice(mesh.Z + mesh.SizeZ, SS) + 1;            return Enumerable.Range(meshLow, meshUp);<br>}</strong></pre><h4><strong>WPF ViewPort3D:</strong></h4><p>You can use the <strong>MeshGeometry </strong>to plot the structures via <strong>WPF</strong>.</p><p>We’ll use it to perform some checks later in this article.</p><p>You can check the code in my <a href="https://github.com/joecastelo"><strong>GitHub page</strong></a>. This binary plugin called <a href="https://github.com/joecastelo/StructureOnWPF"><strong>StructureOnWPF </strong></a>can copy and move structures based on the selected structure.</p><blockquote><strong>Remember to run this code on TBOX… It’s just a test, and it’s not recommended for clinical use.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*WtdUxwj3lmTW1dSZ-4-0AQ.png" /><figcaption>StructureOnWPF Project, Left Slider (Zoom), Right Sliders (Rotation), The text box, fields for displacements in mm</figcaption></figure><h4>A structure contour is a List of VVectors:</h4><p>If you want to get a structure contour, be prepared to play with the infamous <strong>VVector[][].</strong></p><pre><strong>ptv.GetContoursOnImagePlane(plane);</strong></pre><p>It is an <strong>array </strong>of <strong>arrays </strong>of <strong>VVectors 😥</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ej1rZaX2em-MGj-d8AyCOQ.png" /></figure><p>You can access the x,y and z positions of the points via <strong>MeshGeometry.</strong></p><p>It is simpler than the former alternative, and you can transform it into <strong>VVectors</strong>.</p><pre><strong>contours = ptv.MeshGeometry.Points.Select(e=&gt;new VVector(e.x,e.y,e.z));</strong></pre><h4>How to draw a structure?</h4><p>To be able to create your own structures, you have to work with this method:</p><pre><strong>ptv.AddContourOnImagePlane(arrayOfVvector, slice);</strong></pre><p>This is interesting… Even knowing that your <strong>VVectors </strong>have the <strong>Z </strong>coordinates, <strong>ESAPI </strong>needs you to explicitly tell which slice to draw, and it will use only the X and Y coordinates.</p><h4>Be careful with high resolution:</h4><p>From what I’ve experienced, a <strong>high resolution structure</strong> has 3 times more points than a default accuracy structure. One interesting thing is that when using the AddContourOnImagePlane, if you add all the points that exists in a high resolution structure, it will convert to default and you’ll miss the contour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*-uU1WtXaHNikxZx14QquIA.png" /><figcaption>Drawing the structure, but not converting to high resolution before.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iOX6m8yVg5kunuOiq1QaAg.png" /></figure><h4>DicomTypes:</h4><blockquote>Possible values are “AVOIDANCE”, “CAVITY”, “CONTRAST_AGENT”, “CTV”, “EXTERNAL”, “GTV”, “IRRAD_VOLUME”, “ORGAN”, “PTV”, “TREATED_VOLUME”, “SUPPORT”, “FIXATION”, “CONTROL”, and “DOSE_REGION”.</blockquote><h4>How to operate between structures:</h4><p>This can easily be performed using the <strong>SegmentVolume </strong>property:</p><pre><strong>var ss =  scriptContext.StructureSet;<br>var overlap = ss.<br>AddStructure(&quot;CONTROL&quot;,CheckStructureIds(ss,&quot;organ_ovl&quot;);<br>overlap.SegmentVolume = ptv.SegmentVolume.And(oar.SegmentVolume);</strong></pre><p>Check for high resolution, you can’t operate in ESAPI between default and high resolution segment volumes.</p><h4><strong>Contouring vs ESAPI:</strong></h4><p>If you’ve ever wondered if <strong>ESAPI </strong>and contouring operations yields the same results, <strong>unfortunately </strong>they do not.</p><p>Since operations in <strong>ESAPI </strong>are done with a different <strong>engine, </strong>they lead to a different result, however this has little optimization impact (this could be a nice science experiment). Here is an overlap example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Neu35xqOHf8R2EqoQ1pNFg.png" /><figcaption>Script Overlap is in blue, it’s statistics are represented in the left. The magenta is the contouring Overlap, it’s statistics are represented in the right.</figcaption></figure><h4>Be careful with Structure Id max length:</h4><p>Sometimes we’re so focused in getting the code to work that we forget the maximum chars for structures in ESAPI. It is always possible to limit and escape this kind of exception with simple functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/215ca1061268d1d37b0fabb406b84fee/href">https://medium.com/media/215ca1061268d1d37b0fabb406b84fee/href</a></iframe><h4>Structure Color:</h4><p>You simply can’t change the structure color via <strong>ESAPI</strong>.</p><h4>Maximum number of Structures:</h4><p>You can have <strong>99 </strong>structures at maximum inside your <strong>StructureSet</strong>, I’ve never knew about this number, but I got few errors in my last project due to this limitation.</p><h4>Moving a structure:</h4><p>In the code below, I share a helper class. I use this code whenever I need to move a structure.</p><p>It uses all the previous concepts we’ve been discussing in this article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/337bc3e5f45cca36524c0e58d9af87d9/href">https://medium.com/media/337bc3e5f45cca36524c0e58d9af87d9/href</a></iframe><h4>Real number coordinates versus CT resolution:</h4><p>You can assign any real number to a <strong>VVector</strong>. This can lead to errors during the code execution, here I’m trying to add a contour point at position <strong>(1000,1000,1000)</strong>. Although I’m not prohibited to create this <strong>VVector </strong>I can’t add this contour to the Structure, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*foJRvi8RLLZqhOUDd6rA4A.png" /></figure><h4>If you try to displace below the CT resolution:</h4><p>In this example the CT X and Y resolutions are 0.7 mm, then we displace 0.4 mm in those axes; The Z resolution is 1 mm, then we displace 0.8 mm in that axis;</p><p>For my own surprise, the structure is indeed displaced, but the results are not linear, some points do arrange and others don’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Slnxiv7cNucz84Frot228Q.png" /></figure><p>Here is the result if you displace with the CT resolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nevIkrhX7y_zCcn8tXB4DQ.png" /></figure><p>The result makes more sense.</p><h4>More on operation between structures:</h4><p>Here I’ll leave a link to Max’s <a href="https://github.com/Kiragroh/ESAPI_SimpleGUI_ContourUnions"><strong>SimpleGUI_ContourUnions</strong></a><strong> </strong>repo on <strong>GitHub.</strong></p><p>It is a simple user interface of <strong>PTV and GTV </strong>unions that can get you insight in how to develop your own optimization structures routine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DfbqYhT7D5OjRJzj" /><figcaption>Photo by <a href="https://unsplash.com/@yapics?utm_source=medium&amp;utm_medium=referral">Leon Seibert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Thanks for reading!</p><p>See you next <strong>time</strong>!</p><p>What do you guys think it is a <strong>good </strong>topic for my next post?</p><p>Are you used to use <strong>GitHub</strong>?</p><p>Thanks to Jonas to review this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=575bc623074a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing in the Eclipse database: Change the field’s Id based on Gantry angle.]]></title>
            <link>https://jhmcastelo.medium.com/writing-in-the-eclipse-database-change-the-fields-id-based-on-gantry-angle-312462f8fc67?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/312462f8fc67</guid>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[radiotherapy]]></category>
            <category><![CDATA[medical-physics]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 19:55:15 GMT</pubDate>
            <atom:updated>2020-07-28T19:55:15.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys!</p><p>This is the first article of the blog about an interesting feature that most of us always wanted, using the <strong>writing </strong>capacities of <strong>ESAPI</strong>.</p><blockquote>Everything I’m sharing here is for educational purposes, I advise you to learn first and then implement any script on the clinical environment. This is not a recommendation or a clinical validated script.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O6oF2bxiN-4RXPQk" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is important to acknowledge that, in the clinical environment, writing via <strong>ESAPI </strong>is allowed in versions of Eclipse above <strong>15.1.1.</strong></p><h4>Script Approvals and TBOX:</h4><p>Varian Testing Station, also known as TBOX, has a mimic of the clinical environment, in which you can test your scripts freely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*kWj4QNpQYjti7SNfkRMJqg.png" /><figcaption>Version 15.6 guide to each permission</figcaption></figure><p>In my <a href="https://medium.com/@jhmcastelo/esapi-guide-5-steps-to-start-scripting-including-citrix-users-e72108b2b50c">initial guide for ESAPI</a>, I showed how to build single file, binary plugins and executables for read-only scripts. Writable plugins keep the same properties, but if they are going to be used in the clinic, they need to be <strong>approved in the Eclipse UI</strong>, and you <strong>can’t approve a single file plugin</strong>.</p><h4>Declaring we are going to write in the database:</h4><p>In <strong>executables </strong>we declare in the start of the code the <strong>[STAThread]</strong> flag. ESAPI needs in <strong>any file </strong>of the code you are building (<strong>executable or binary</strong>) to exist the following flag:</p><pre><strong>[assembly: ESAPIScript(IsWriteable = true)]</strong></pre><p>And run the <strong>Patient.BeginModification()</strong> method before modifying any property of a patient’s object.</p><pre><strong>scriptContext.Patient.BeginModifications();</strong></pre><p>Remember to use both.</p><p>I’ve noticed that in <strong>TBOX</strong> the later is not needed. But it surely is in clinical environment.</p><h4><strong>Template:</strong></h4><p>For binary plugins this should be the code to begin with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ade067387a38bcc0b33df26aa1f2dfd7/href">https://medium.com/media/ade067387a38bcc0b33df26aa1f2dfd7/href</a></iframe><p>For executables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc2c3c3ecec1bd5537d80dc3c3adc8d5/href">https://medium.com/media/cc2c3c3ecec1bd5537d80dc3c3adc8d5/href</a></iframe><p>Remember you can save via script in Executables, in Plugins you have to save in the <strong>UI</strong> after the script finished its task.</p><p>If you really want to automate a task and have no human contact, but run each patient at a time, you can always emulate a <strong>plugin </strong>via executables (<strong>see </strong><a href="https://medium.com/@jhmcastelo/how-to-emulate-plugins-with-executables-in-esapi-97f5213f4560">How to emulate a plugin</a>).</p><h3>Pipeline:</h3><p>We will cover the following steps of a clinical acceptance of a <strong>writable binary plugin</strong>:</p><ol><li>Script Development</li><li>Testing the script in <strong>TBOX</strong> using Carlos Anderson’s <strong>Eclipse Plugin Runner</strong></li><li>Evaluate the script function in Clinical Environment</li><li>Approve it</li></ol><h4>Dev Work:</h4><p><strong>What’s the problem?</strong></p><p>Suppose that when you start planning a <strong>3DCRT</strong> case, you add multiple fields and do not assign ID or name to them. Then you start doing <strong>Field in Fields and Complementary Fields, </strong>and in the end you get this <strong>lovely</strong> picture<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7hx_YNOJLF2e_tK6cASPw.png" /></figure><p><strong>What’s the solution?</strong></p><p>We will <strong>automatically</strong> assign <strong>Id’s to the </strong>static fields based on their <strong>gantry angle</strong>. And also add a <strong>FF</strong> or <strong>Comp</strong> flag, if the field is one of them.</p><p>Wanted result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2s5cpUBRO5HJbiChMgnbEQ.png" /></figure><h4>Code:</h4><p>We’ll create a binary plugin, so create a new <strong>.NET Framework 4.5 Class Library</strong> solution called <strong>FieldIdFromGantry</strong>. Change the assembly name to <strong>FieldIdFromGantry.esapi</strong> and the CPU config to <strong>x64</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*SNreKWVm8YzgZV5pracLzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*gVAH7sLW_BA6r2mCtHBmiA.png" /></figure><p>In this project, we’ll create a single class called <strong>BeamIdChanger</strong>. Create a new .cs class File (<strong>Ctrl + Shift + A</strong>), called <strong>BeamIdChanger.cs :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_St0_5Z3-cFxIUdMtS_Ug.png" /></figure><p>Also rename <strong>Class1.cs</strong> to<strong> Script.cs:</strong></p><p>You should have this two files now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*kckMFsT051T5Ckbzo61jXw.png" /></figure><p>Reference the VMS.TPS libraries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*o4PYjnJEJ2FQhuXmxS0Qsw.png" /></figure><p>Paste the following code in <strong>BeamIdChanger.cs</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90fa75769eacab6ffe1bbee5a7ebebbf/href">https://medium.com/media/90fa75769eacab6ffe1bbee5a7ebebbf/href</a></iframe><p>And in Script.cs, paste:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e57a3f550d9e6b555d4bc9ce81425c58/href">https://medium.com/media/e57a3f550d9e6b555d4bc9ce81425c58/href</a></iframe><p>The following <strong>flowchart </strong>describes the decision making process that happens in Beam Id Changer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rVbkfiSVItpOgKHAwkYB1Q.png" /></figure><h4>Testing on TBOX:</h4><p>We could just build the code in visual studio, and run it on any valid calculated dose plan in <strong>TBOX</strong>. However, you may not be interested in copying and pasting, but rather <strong>creating </strong>and <strong>testing </strong>your writable scripts and test during <strong>development</strong>. In my <a href="https://medium.com/@jhmcastelo/esapi-guide-5-steps-to-start-scripting-including-citrix-users-e72108b2b50c">ESAPI initial guide</a>, I briefly discuss about the need to <strong>restart eclipse</strong> or <strong>change the assembly name</strong> each time we want to test a binary plugin. We can solve this problem using <a href="https://medium.com/@jhmcastelo/how-to-emulate-plugins-with-executables-in-esapi-97f5213f4560"><strong>executables</strong></a>, or when testing in TBOX we can simply use <a href="http://www.carlosjanderson.com/introducing-esapi-essentials/"><strong>Carlos Anderson’s plugin Runner</strong></a> solution.</p><h4>Carlos Anderson’s ESAPI Plugin Runner and Git:</h4><p>In my opinion, the best suited option to test your scripts is to create a solution that contains the <strong>NuGet</strong> packages <strong>ESAPI Plugin Runner and ESAPI Essentials</strong>, and every <strong>new project</strong> you get into, you <strong>branch </strong>the Plugin Tester solution via <strong>Git</strong> and add the project you’re working as an external reference.</p><p>The plugin runner allows on the run <strong>Debug</strong>, this is very very helpful.</p><p>By doing that way, you do not need to reference this testing libraries in your clinical script.</p><p>Let’s test our project with <strong>ESAPI plugin Runner</strong>.</p><p>Close the <strong>FieldIdFromGantry </strong>solution:</p><p>Create a new .<strong>NET Framework 4.5 WPF </strong>solution, called <strong>PluginTester</strong>.</p><p>Change to <strong>x64</strong> architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*egJv556Y5xWb7cUI7DRfpw.png" /></figure><p>Remove the <strong>MainWindow.xaml</strong> file from the project!</p><p>Install the highlighted libraries from NuGet Manager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-76R5thR2S49GRgpIwEBA.png" /></figure><p>After installing the packages, reference the <strong>VMS.TPS</strong> libraries.</p><p>Your <strong>solution explorer</strong> should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Gpjjv1YgWePKxOfUx5mJBQ.png" /></figure><p>Create a file called <strong>ScriptTesting.cs.</strong></p><blockquote><strong>You can use the shortcut </strong>(<strong>Ctrl + Shift + A</strong>).</blockquote><p>Insert the following code in this file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/918cc1b742d428b535b7f2ae177934c5/href">https://medium.com/media/918cc1b742d428b535b7f2ae177934c5/href</a></iframe><p>Now this is an <strong>important part!</strong></p><p>Since we removed <strong>MainWindow.xaml from the project</strong>, we need to rewrite <strong>App.xaml</strong> by changing the line:</p><pre>....<br><strong>StartupUri=&quot;MainWindow.xaml&quot;&gt;</strong></pre><p>To:</p><pre><strong>....<br>Startup=&quot;App_OnStartup&quot;&gt;</strong></pre><p>In the <strong>App.xaml.cs</strong>, we will create the <strong>App_OnStartup</strong> Method:</p><p>This should be it’s content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1529228ac932ce0b5c26d00075d9ff12/href">https://medium.com/media/1529228ac932ce0b5c26d00075d9ff12/href</a></iframe><p>This is the template for Eclipse Plugin Runner.</p><p>Now create the git repo, using the visual git tool in Visual Studio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*17Z8E7M9xvifBanF-hgr_Q.png" /></figure><h4>Branching and testing:</h4><p>Create a new branch from the master via git.</p><p>Call it based on the <strong>FieldIdFromGantry</strong> solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*MAumjt-Vmld_mhTgCn-I0A.png" /></figure><p>In the new branch reference FieldIdFromGantry project, right clicking in the solution name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*ds8VxYnrc0jMl1qiJHGZ9Q.png" /></figure><p>Find the project folder, and click open on the <strong>FieldIdFromGantry.csproj</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*H6mZkNIqU7GSnbzu-DrneA.png" /></figure><p>Check the solution explorer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*ervs5D_-6I-MUeRMOyYDXw.png" /></figure><p>Inside the<strong> ScriptTesting.cs </strong>file, add the following lines inside the <strong>Run</strong> Method:</p><pre><strong>BeamIdChanger changer = new BeamIdChanger(scriptContext.PlanSetup);</strong></pre><pre><strong>changer.ChangeBeamsIdsFromGantryAngles();</strong></pre><pre><strong>MessageBox.Show(changer.Log);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*kVYCX4mEnnPFxDazMR5DHA.png" /></figure><p>Use the <strong>Ctrl + .</strong> shortcut to solve the reference to <strong>FieldIdFromGantry</strong>.</p><p>Add and Commit the changes…</p><p>We’re finally testing it:</p><p>Press <strong>Ctrl + F5 </strong>or press Run, the Eclipse Runner connects to the Eclipse <strong>DB</strong> in <strong>TBOX</strong>:</p><p>Find a plan you wish to test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*yG4Uj0yxy-AnW2O_T4ioMg.png" /></figure><p>There’s the result we wanted!</p><p>Using Plugin Runner you can also Debug your code via <strong>Visual Studio (installed on TBOX):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*iVWksqcs3zxE3ovjkRnL5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*oCCTYcqkxLliIpA7PPkuBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUAvcihrShYQlw4XHwWqmA.png" /></figure><p>Now that we’ve already tested in the Plugin Runner, we should test it in the Eclipse UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcXMt_KdV60c76q_TWznPg.png" /></figure><p>It’s all good!</p><h4>Script Approval:</h4><p>After your tests, you should be confident to start to use it in the clinic.</p><p>Now you as physicist should check the authorization for script usage of the users in <strong>varian</strong> service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*socYozHQwluwuhm90z5cig.png" /><figcaption><a href="https://github.com/VarianAPIs/Varian-Code-Samples/issues/54">https://github.com/VarianAPIs/Varian-Code-Samples/issues/54</a></figcaption></figure><p>If everything is okay for the users privileges, you should go to .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*h7BdrL50kvaaUqO9yot6Dg.png" /></figure><p>The black approval window will pop, then you should <strong>register the new script.</strong></p><p>Thanks for reading!</p><blockquote>Thanks to Jonas for reviewing this post.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=312462f8fc67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESAPI Guide: 5 steps to start scripting, including Citrix users]]></title>
            <link>https://jhmcastelo.medium.com/esapi-guide-5-steps-to-start-scripting-including-citrix-users-e72108b2b50c?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/e72108b2b50c</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[radiotherapy]]></category>
            <category><![CDATA[medical-physics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 14:13:58 GMT</pubDate>
            <atom:updated>2020-08-11T21:16:23.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys!</p><p>In this article, I’ll show what in<strong> my experience</strong> are the <strong>basics</strong> to start <strong>writing</strong> and <strong>running</strong> your scripts with <strong>ESAPI </strong>(Eclipse Scripting API). The following lines are coded for <strong>Eclipse v15.6</strong> libraries, but they should be reusable in most versions <strong>above 11</strong>.0<br>All items are based on simple <strong>read only</strong> projects covering how to <strong>write </strong>and run:</p><ol><li><strong>Hello World</strong> in<strong> Visual Studio</strong>.</li><li><strong>A Single file script</strong> in Eclipse for <strong>single patient running </strong>in <strong>Eclipse</strong> user interface;</li><li><strong>A Compiled </strong>script as library (a.k.a <strong>Binary Plugin</strong>) for <strong>single patient in Eclipse</strong> UI;</li><li><strong>An Executable</strong> that iterate in <strong>multiple patients</strong> from the planning database (using citrix);</li><li>The Usage of <strong>Visual Studio Git</strong> to manage two versions of the previous <strong>executable</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jh_KtXAXPTf5HDR-" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>You don’t have be a code master to script in Eclipse. Simply google it, try it, make mistakes, try again until you write one that works. Definitely you’ll need to learn C #. And there are cheap courses on </em><a href="https://www.udemy.com/"><em>Udemy</em></a><em> that are more than enough.</em></p><p>First of all let’s download the <strong>visual studio IDE </strong>which is basically <strong>mandatory</strong>. You can download it on your personal computer or on your work computer if <strong>IT </strong>allows.</p><p><a href="https://visualstudio.microsoft.com/">Visual Studio: IDE and Code Editor for Software Development</a></p><p>Install it along with the following <strong>workloads</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*a58QvvtldPzCb0X_3WFyYQ.png" /></figure><h3>The C# very basics:</h3><p>Printing hello world in <strong>Visual Studio and C #:</strong></p><p>Open visual studio and create a <strong>new project</strong>:</p><p>Check that is a Console (.NET Framework) solution.</p><p>We’ll choose .NET Framework version 4.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Oyzy4C-f2a1F44vARaAhwA.png" /></figure><p>Check the <strong>Program.cs</strong> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIxvBA97lfLG3IHmlq3ehg.png" /></figure><h3>Declaring a variable:</h3><p>Inside the brackets, insert the following line:</p><pre><strong>string message = &quot;Hello World&quot;;</strong></pre><p>In this statement you’re telling the system to store in the <strong>memory</strong> a <strong>string</strong> that has <strong>message</strong> as it’s name.<br>Every time you want to reuse the message <strong>“Hello World”</strong> you can refer to the <strong>message</strong> variable.<br>First we will print the message on the <strong>console (cmd)</strong>.</p><pre><strong>Console.WriteLine(message);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*_EKc4IlzW4pQim_D8ZQIcg.png" /></figure><p>Press <strong>Ctrl + F5</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*la4hFYXJB4qfqq0s0eyvrQ.png" /></figure><p>It’s done, your first program is running!</p><h4>MessageBox</h4><p>Until our first <strong>executable</strong> program with <strong>ESAPI</strong>, we are not using the command line to print our results. Instead the windows <strong>MessageBox</strong> will help us with this task.</p><p>Append the following line:</p><pre><strong>MessageBox.Show(message);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*qF3IFrTLoTkzzFk068yT3w.png" /></figure><p>Right click the error in red:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*CVSOtmeI0BCNwU_zMZ_Amg.png" /></figure><p>Left click <strong>Quick Actions and Refactorings</strong> or <strong>Ctrl</strong>+<strong>. (This is an useful shortcut);</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PszyCa_nJoMpmhziF1J5qQ.png" /></figure><p>Add the reference to the <strong>Presentation Framework</strong>:</p><p>Check the start of the file Program.cs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*HWAD__jZiMGGD3Yd9Ktd7Q.png" /></figure><p>Now it contains the reference to the Presentation Framework library.</p><p>And the error goes away! Press <strong>Ctrl + F5</strong> once more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*WPsmDS4jbbb1EouIbVqJRQ.png" /></figure><p>You have just successfully used the <strong>MessageBox</strong> from the Windows Presentation Framework, and you no longer need the console to understand your code outputs for now.</p><h4>Digging in ESAPI:</h4><p>ESAPI <strong>libraries </strong>link the TPS to C# in the same way that the windows Presentation Framework library connects C # to OS’s presentation features. The libraries contain code that intermediate two or more systems so we don’t have to worry about it. In ESAPI there are classes that connect the Eclipse objects to the code presented to the user. So if we want to get information about the patient’s name with ESAPI, we have to access a C# <strong>Patient</strong> <strong>object</strong>.</p><h4>What is an Object:</h4><p>In short, it is the instance of a more complex data structure than the basic <strong>types</strong>. It comes from a <strong>class</strong>. Every <strong>class</strong> is traced to basic types like <strong>numbers</strong>, <strong>strings</strong>, <strong>booleans</strong>. The cool thing about visual studio is that when you have an <strong>object</strong>, you can access its <strong>properties names </strong>before <strong>compiling</strong> the code.</p><p>Here is an example, I`ll create a class</p><p>and it will have an <strong>ID</strong>, <strong>age </strong>and <strong>priority</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c041fdf2790ec0127a4cebbd4b475cd9/href">https://medium.com/media/c041fdf2790ec0127a4cebbd4b475cd9/href</a></iframe><p>Now we are going to create an instance of the patient, referenced by the variable <strong>jack</strong>.</p><pre><strong>Patient jack = new Patient(&quot;123&quot;,56,1);</strong></pre><p>Hence, jack has id 123, 56 years old and priority 1.</p><p>This was assigned to <strong>jack</strong> via the class <strong>constructor</strong>, by the 3 <strong>arguments </strong>inside<strong> </strong>the parentheses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cPw5L29FI-VHthIn5QjAoA.png" /></figure><p>We can access the properties and functions using a <strong>dot</strong> after the object, the <strong>intellisense</strong> helps a lot<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*U3Rou8OhZb7Tv467j0JVEA.png" /></figure><p>If you’re a bit lost, this is the <strong>code </strong>you want to run.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18828bf89fa2789b19aa420aa20f00a8/href">https://medium.com/media/18828bf89fa2789b19aa420aa20f00a8/href</a></iframe><p>In visual studio press <strong>Ctrl + F5</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*Qms7vOWftbtAXNjB4D7JAw.png" /><figcaption>Result of the last MessageBox, this is jack info.</figcaption></figure><h3>ESAPI in practice:</h3><p>This is a table that summarizes what I think are the most important features of each type of ESAPI scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*IZ74-4cB4_siFWFweDMX4w.png" /></figure><h4>Plugins:</h4><p>Every script relies on the Eclipse installed in a workstation. If you run a script from within the eclipse, it only accesses the information from the patient whom UI window is open. There is an object called <strong>ScriptContext</strong> that links the <strong>patient elements</strong> to C #.<br>When using plugins, Eclipse itself compiles the code, hence we are not going to use the Main () function as entry to the code, rather it is going to be the <strong>Execute</strong> function, in the <strong>Script </strong>class nested in the namespace <strong>VMS.TPS</strong>.</p><h4>ESAPI Visual Studio Project from Scratch:</h4><p>To explore our first plugin, create a new project in the same way as hello world. However it will now be a <strong>Class Library</strong> (.<strong>NET Framework</strong>) named <strong>HelloWorldPlugin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*152egLRnU4GBQa3cghNHMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*qiHJboPp9ad0-FWxrsyhNw.png" /></figure><p>Being the project created, right click in <strong>references</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*91sC-d1piIlck0c7LALMiw.png" /></figure><p>Now you have to find the libraries that connect Eclipse to C#.</p><p>In general, the VMS.TPS library is located on the computer that Eclipse is installed. In the following folder:<br><strong>C: / Program Files (x86) / Varian / RTM / version / esapi / API</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*IAhIfz4D0W3hplT2ZqyHlg.png" /></figure><p>If you are a CITRIX user this can help you find the files:</p><h4><strong>Access the CITRIX computer (Useful Trick)</strong></h4><p>In the eclipse UI, open <strong>External Beam Planning / Tools / Scripts</strong></p><p>Left click on <strong>Open Folder</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*Jd1HHbXjNkbURuntqsWreA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*WpfshJqmn6anFl_Arydsvg.png" /></figure><p>Copy the files to your local disk where your visual studio is installed. They should be at the same path we described before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*gvpebOQPWrUODnnEcjf67w.png" /></figure><h4>Now we are ready to write the first lines of the script:</h4><p>It is mandatory for ESAPI plugins to have this template, so feel free to reuse this:</p><p>Replace the original code in <strong>Class1.cs</strong> with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d630907a64ed29f55c8817ad579698/href">https://medium.com/media/73d630907a64ed29f55c8817ad579698/href</a></iframe><p>The same thing that happened to the <strong>MessageBox </strong>is happening to <strong>ScriptContext</strong>! Visual studio will complain that it does not exist. Then click <strong>Ctrl +.</strong> and solve the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*9CKDBeUozFL23viCqg-A4g.png" /></figure><p>Now you have the reference to the library that connects Eclipse to C#.</p><p>You can also add the following line before the VMS.TPS namespace:</p><pre><strong>using VMS.TPS.Common.Model.Types;</strong></pre><p>The <strong>VMS.TPS.Common.Model.Types </strong>library has classes related to VMS.TPS special data structures, like VVectors, DoseValuePresentation and others.</p><h4>Explaining the Script:</h4><p>Let’s write the first lines in the single file plugin. And then run it on <strong>Eclipse (Tools/Scripts)</strong>.</p><p>The code will do the following: The <strong>context</strong>, which is the <strong>open window</strong>, has an <strong>External Radiotherapy plan</strong> that is <strong>currently </strong>open. We will access this plan through the script and we will create a message variable with the name of the plan. Then use a <strong>MessageBox</strong> to print that plan name.<br>This is the <strong>final</strong> code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e337b9ebb8d1ef810b608fbbfaa19c00/href">https://medium.com/media/e337b9ebb8d1ef810b608fbbfaa19c00/href</a></iframe><p>Use the windows forms from the Presentation Framework, not from <strong>Windows Forms, it won’t work because this library is not loaded in Eclipse Assembly</strong>.</p><p>Open a patient through <strong>External Beam Planning</strong>. Anyone who has a calculated dose plan:<br>In my case a <strong>Radiosurgery </strong>with multiple targets:</p><h4>First Test:</h4><p>Locate where the <strong>Class1.cs</strong> file you’ve just edited is. If you’re a citrix user, you must transfer the file to the client or the <strong>virtual computer</strong> that citrix is connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*dlA1W7Xw32R93AEWOfwRSA.png" /></figure><p>Run the <strong>Class1.cs</strong> file, double clicking the file or pressing run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*_mwZx0DUG80WdEOVrFUImg.png" /></figure><p>We successfully ran our first single file script.<br>Now try changing the string that contains only the Id of the plan to the last name of the patient and the plan.<br>Replace the line that declares message with this line:</p><pre><strong>string message  = context.Patient.LastName + &quot; &quot; + plan.Id;</strong></pre><p>Save and run it again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*o59FuGhfhGaz8YYaSijkrw.png" /></figure><p>This template can be as complex as you can get in one file!</p><h4>Single File Plugin Limitations:</h4><p><strong>You cannot reference libraries that are not pre-installed in Eclipse</strong>. This means that if you want to make a plot directly in C# you won’t be able to, since it needs an external library. (In <a href="https://medium.com/@jhmcastelo/2-steps-to-plot-your-esapi-script-data-80d3e56e7cd?source=friends_link&amp;sk=2a72d3d04762997c36b9fa32befb262f"><strong>other article</strong></a> I show how you could do indirectly).<br><strong>Limit yourself to a single file</strong>. Code separation is very important in C # and this is completely blocked by the structure of the single file plugin. There are files that should be separated that are together, generating <strong>10,000 </strong>line scripts.</p><p><strong>We will often need to make graphical interfaces for our applications</strong>. <strong>WPF</strong> is a good solution, however it does needs two or more files, then single file scripts are not suited to this task.<br>To solve this problem, Varian allows you to create <strong>compiled scripts</strong>, meaning you can transform your code into a <strong>fake library</strong>. Which has an <strong>entry point</strong> equal to the <strong>single file plugin </strong>and is called a <strong>binary plugin</strong>.</p><h4>Script Wizard:</h4><p>In this guide, I’m not using the <strong>ScriptWizard </strong>program from <strong>Varian</strong>, because I do not like the <strong>split</strong> of the <strong>project from plugin</strong> files it does. However, it is simple enough to create a <strong>project </strong>with it.</p><p>You can find it in the computer that Eclipse is installed:</p><p><strong>C: / Program Files (x86) / Varian / RTM / version / esapi /ScriptWizard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*53bSpVTPZ-KQ2sdmAJ3pig.png" /></figure><p>Warning: If you’re a <strong>Citrix </strong>user, remember to save the project in the <strong>Client disk</strong>, so you can open it with Visual Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*vSdK0h4ANLiHNmIuEtZLJA.png" /><figcaption>This two folders are created</figcaption></figure><p>Acess the <strong>Projects folder</strong> and open the .csproj file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*Wi0fD4q0f7AFycNPY11A-g.png" /></figure><p>There it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*bBZKLsH3-LO_rp4EcdwtKg.png" /></figure><p>You still have to reference the libraries by copying them to the computer Visual Studio is installed if your Eclipse is not local.</p><h4>Creating our first Binary Plugin:</h4><p>To enforce our rhetoric, we’ll use a external library called <strong>RandomNameGenerator</strong> to test this binary plugin.</p><p>Continue with the <strong>HelloWorldPlugin and the Patient you are testing:</strong></p><p>Right click references again, but now click in <strong>Manage NuGet Packages:</strong></p><p>Go to browse and search for <strong>RandomNameGeneratorLibrary.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*wI5wCPxMxNZC3Cf6uyydpw.png" /></figure><p>Install it</p><p>Now change the code in Class1.cs to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36d7bee7d4e8a33ab4492f4ac2211beb/href">https://medium.com/media/36d7bee7d4e8a33ab4492f4ac2211beb/href</a></iframe><h4>Footnote:</h4><p>Notice that I accessed the patient’s name through the Plan / Course / Patient, no longer from the <strong>Context</strong>. Ideally, you should use as little context as possible to be able to reuse code in <strong>executables</strong>, where there is no <strong>context</strong>.</p><h4>Testing what I’ve said:</h4><p>After I saved the Class1.cs and then tried to run, it gave me an exception. And referencing to the lack of the <strong>RandomNameGenerator</strong> Library.</p><h4>Building the code (very important):</h4><p>Go to project properties or press <strong>Alt + Enter</strong> and Change the project <strong>assembly name </strong>to HelloWorldPlugin.esapi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YC0v8px2dsMv9rYfFci73g.png" /></figure><p>In the <strong>Build</strong> options tab, change the <strong>platform target</strong> to <strong>x64, also change the Output Path to blank</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsEJmXqOZoV1FbJK6rneog.png" /></figure><p>Save it (<strong>Ctrl + S</strong>), press <strong>Build</strong>/<strong>Build Solution </strong>or Ctrl + Shift + B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Lr2aLMq6J3DIlEpI9TWIAA.png" /></figure><p>If you changed the path of output to blank, the projected was built in the same folder of <strong>Class1.cs. </strong>If not it should be in<strong> bin/x64/Debug</strong></p><p>Run it via Eclipse UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*qa1ariy4p92-CLGGTxUG8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*6dFNI6nKrhQj7u3mPkKeKA.png" /></figure><p>Run it one more time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*VFoQo_uslrHQXbbbe8sl0Q.png" /></figure><p>Looks like the <strong>random function </strong>is really <strong>random</strong> (pseudo) hahaha!</p><p>The folder of the solution now has a lot of files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*-MIK3txrnZia9qhTPG4bvw.png" /></figure><p><strong>KEEP THE FILES THAT THE SCRIPT REFERENCES IN THE SAME FOLDER.</strong></p><h4><strong>Weird Bugs and Memory in Binary Plugins?</strong></h4><p>If any of these dlls is missing, the code would crash if you reboot Eclipse. If you keep it open, the script will keep working because the script is loaded in the assembly memory.</p><p>This also means that if you build one more time it is not going to change the script functionality. As much as you want and think this is weird, if visual studio is building into the folder you’re getting the file, it <strong>will not build</strong>, a message of block by ARIA RadOnc will pop while you build.</p><p>The solution is to reboot eclipse or change the <strong>project assembly name</strong>.</p><h4><strong>Take home message:</strong></h4><p>Binaries solve the problem of external libraries and code separation, <strong>they allow the creation of WPF applications, meaning that you can create your desired graphical interface.</strong></p><p>The downside is the n<strong>eed to restart eclipse or change the assembly name for rebuilding after any change;</strong></p><h3>Executables:</h3><p>If you’ve made this far, you are interested in exploring the database.<br>The <strong>executables </strong>work just like the first example of C # that you <strong>build</strong> and run <strong>directly </strong>from the <strong>computer. It</strong> opens the <strong>console </strong>or a <strong>window </strong>to log about the <strong>execution</strong>, so we finally will get rid of the <strong>MessageBox</strong>.</p><p>The VMS.TPS library connects C # to patients via the VMS.TPS.Common.Model.API.<strong>Application</strong> class object. This library finds the database inside the computer that has Eclipse installed, so for CITRIX users you will compile on your computer with visual studio installed, and copy all the files that come with the compilation to the CITRIX computer.</p><h4>Coding:</h4><p>Let’s create a new <strong>.NET Framework console application</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Rvai-Kbv_DzyRBOfMvBaEg.png" /></figure><p>Reference once more the VMS.TPS libraries, just like in every example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*9GekgE7Yp6B8PVNMDVCukQ.png" /></figure><p>Write the code for the executable that search all patients in the database and prints the Id of the plans in which the <strong>calculated dose is valid </strong>on the console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fdae84f897ea48efc8036d8c9a13963/href">https://medium.com/media/8fdae84f897ea48efc8036d8c9a13963/href</a></iframe><p>The <strong>[STAThread]</strong> flag is <strong>important</strong>, to secure we are only using a single trhead, mandatory in ESAPI.</p><p>Use the same <strong>build</strong> configurations from the binary project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsEJmXqOZoV1FbJK6rneog.png" /></figure><p>Save it and build with <strong>Ctrl + Shift + B</strong>.</p><p>If you have a <strong>local eclipse</strong>, you just check the executable in the folder and double click it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*QkfnA4FmoxtIL5m68TtGtQ.png" /></figure><p>However, if the eclipse is CITRIX you’ll have to copy the folder to the Citrix computer.<br><strong>Use the same trick taught before to both copy and execute.</strong></p><blockquote><strong>ExternalBeamPlanning /Tools /Scripts /SystemScripts/OpenFolder → Ensures access to the CITRIX file explorer that has Eclipse installed.</strong></blockquote><p>Double-click it. The script will print the name of the plans which have valid dose <strong>for each</strong> patient. For each enter that the user <strong>presses</strong> it iterates to the next <strong>patient</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gLbNrgYLeeDjVli63lyEkQ.png" /></figure><blockquote>Note #1: The executable needs to run in the local disk of the computer that has an Eclipse installed.</blockquote><blockquote>Note #2: Every patient needs to be closed after the iteration. That’s the reason of the line <strong>app.ClosePatient()</strong>.</blockquote><p>We are pretty advanced now with our <strong>executable</strong>, but imagine if you want to get those plans for a group of patients that you have already saved in a <strong>spreadsheet</strong>. These patients have a unique ID. And you’ve exported the IDs line by line to a text file, <strong>Ids.txt</strong>:</p><pre>1235<br>225<br>12358<br>7777<br>8880<br>5555</pre><p>This is where <strong>git</strong> management will become important!</p><h3>Using git to save time:</h3><p>We won’t need to create another project, we’ll just create another <strong>version </strong>of the <strong>MultiPatientExecutable solution</strong>.</p><p>This other version will be a <strong>branch</strong> of our original code.</p><p>To start <strong>branching</strong> our project, left click on the blue lower-right corner arrow in visual studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*AKZ4AHQ_BpF4wnhk8DoOkw.png" /></figure><p>Click in Git:</p><p>The following screen will pop in the solution tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*QBabyNDVn1sR3wdlib0iPQ.png" /></figure><p>And this will show where the Add Source Control was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*QE57ngoLDklrXsH0XqOT3Q.png" /></figure><p>Left click, on the upper arrow in the <strong>master</strong> side, and start a new branch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*FC_Ba_71y0kwD3xu_TA1Dg.png" /></figure><p>The branch will be named <strong>ListOfPatients</strong>, and is going be branched from the recently created <strong>master</strong>. Go ahead and click <strong>Create Branch</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*yI8gnZXLc2TdE_qeNVZvqg.png" /></figure><p>Now you are in the <strong>ListOfPatients </strong>branch, and all <strong>changes </strong>in the code will be affecting only <strong>this </strong>branch and not the <strong>master </strong>branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*qdXpPTN0WVonxFRqjWtoeQ.png" /></figure><p>Now what you can do, and should, is that in each change in the project, you should not save with <strong>Ctrl+S</strong> anymore, but rather <strong>add </strong>the changes to the git version control, and if you are comfortable with them, they should be <strong>committed</strong>.</p><p>Let’s make a radical change:</p><p>Replace the <strong>Program.cs</strong> file content to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67949d9b7f2697199f457d8dc5387c2e/href">https://medium.com/media/67949d9b7f2697199f457d8dc5387c2e/href</a></iframe><p>Now add clicking on this pencil:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*gKZjg4OJLdh-TxMrCNXg6w.png" /></figure><p>Write a message to be the commit’s description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*Ft9_fOXSiZItTypE29Olzg.png" /></figure><p>Check the changes, click in<strong> Program.cs</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwuZpC8cxTyoHB5NmHhvbA.png" /></figure><p>Press <strong>commit</strong> <strong>all</strong>:</p><p>Now your branch is updated.</p><p>Build it again with <strong>Ctrl+Shift+B.</strong></p><p>Run the program again:</p><p>Find the file containing the Ids:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*oufr36Gp3xjbNwKsftECZQ.png" /></figure><p>And check the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*denT5awSvRq3KySGl3o25Q.png" /></figure><p>It’s finally over !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jpo4BJhub0rzW3b4" /><figcaption>Photo by <a href="https://unsplash.com/@xangriffin?utm_source=medium&amp;utm_medium=referral">Xan Griffin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Thank you for your attention and hope you’ve learned something!</blockquote><p>Check the other two articles I’ve written.</p><p><strong>Don’t</strong> cry <strong>trying</strong> to learn WPF.</p><p><a href="https://medium.com/@jhmcastelo/2-steps-to-plot-your-esapi-script-data-80d3e56e7cd">2 steps to plot your ESAPI script data.</a></p><p><strong>Executables</strong> are <strong>overpowered</strong>:</p><p><a href="https://medium.com/@jhmcastelo/how-to-emulate-plugins-with-executables-in-esapi-97f5213f4560">How to emulate plugins with executables in ESAPI.</a></p><p>References:</p><ul><li><a href="https://github.com/VarianAPIs/Varian-Code-Samples">VarianAPIs/Varian-Code-Samples</a></li><li><a href="https://github.com/mattcschmidt/EC301-BJ">mattcschmidt/EC301-BJ</a></li><li><a href="http://www.carlosjanderson.com/">Carlos Anderson</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e72108b2b50c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to emulate plugins with executables in ESAPI.]]></title>
            <link>https://jhmcastelo.medium.com/how-to-emulate-plugins-with-executables-in-esapi-97f5213f4560?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/97f5213f4560</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[medical-physics]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[radiotherapy]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 15:08:14 GMT</pubDate>
            <atom:updated>2020-06-29T15:08:14.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JihQaqAYDZs5xICi" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello!</p><p>Often we are caught up with an executable script that should work with the context of some patient.</p><p><a href="https://www.carlosjanderson.com/">Carlos Anderson</a> came up with a solution to this problem when he created the <a href="https://github.com/redcurry/EsapiEssentials"><strong>ESAPI Essentials Package</strong>.</a></p><p>However there’s some limitation of the extent of the StandaloneContext library. One would need to perform the same code over and over to launch the <strong>executable </strong>that should be the <strong>first</strong> in the folder that you are launching the binary plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*joIPP6ZHd-SYjcL2PW481A.png" /><figcaption><a href="https://github.com/redcurry/EsapiEssentials/blob/master/src/EsapiEssentials/Standalone/StandaloneRunner/StandaloneRunner.cs">https://github.com/redcurry/EsapiEssentials/blob/master/src/EsapiEssentials/Standalone/StandaloneRunner/StandaloneRunner.cs</a></figcaption></figure><p>If you’re a <strong>CITRIX </strong>user, you should be used to open a <strong>patient </strong>to launch an executable. So it will not bother your normal proccess.</p><p>Basically this post will be dedicated to fix the issue of running always the first executable in the folder. And pass the <strong>ScriptContext</strong> via <strong>CommandLine arguments </strong>to any executable we click with an <strong>OpenFileDialog</strong>.</p><p>This is the <strong>pipeline</strong> described:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Q0VtbJDrsx86Key-aBC3bQ.png" /></figure><h4>Starting</h4><p>Let`s start a fresh <strong>.NET Framework Library solution </strong>in Visual Studio called <strong>ContextStandalone.</strong></p><p>Remember to reference the <strong>VMS.TPS</strong> libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*gqlHT0iAadD-0c_O6b87Lg.png" /></figure><p>In the project <strong>properties</strong>, change to<strong> x64</strong> compilation, and to change the project <strong>assembly name</strong> to <strong>ContextStandalone.esapi</strong> , this will be important, when you compile the name of the binarty will be <strong>ContextStandalone.esapi.dll</strong></p><p>Rename the first file, from <strong>Class1.cs</strong> to <strong>Script.cs</strong></p><p>Code the following lines into the <strong>Script.cs</strong> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbb5c2274e6b2f394592edab12e4a840/href">https://medium.com/media/bbb5c2274e6b2f394592edab12e4a840/href</a></iframe><p>Next, add the <strong>CommandLineParser </strong>library<strong> </strong>via <strong>NuGet Package Manager</strong> to your project.</p><p>Now we are going to replicate Carlos Anderson`s code creating a <strong>ScriptContextArgs.cs </strong>file and coding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cb6f42e707dbde2aefef153e17014a7/href">https://medium.com/media/8cb6f42e707dbde2aefef153e17014a7/href</a></iframe><p>Create another .cs file, called <strong>RunStandalone.cs</strong> and code the following lines into this file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a30c6a7bfc1595e2fbc65618b8178f/href">https://medium.com/media/e0a30c6a7bfc1595e2fbc65618b8178f/href</a></iframe><p>Compile those 3 files into <strong>ContextStandalone.esapi.dll</strong> using the <strong>Ctrl+Shift+B</strong> shortcut in <strong>Visual Studio</strong>.</p><p>Now you can simply run any <strong>Standalone </strong>with context.</p><h4>Testing a simple Standalone</h4><p>Let’s do a simple test right now. Creating a new <strong>.NET Console Application</strong> solution called <strong>LogPatientFields.</strong></p><p>In the project properties, change to<strong> x64</strong> compilation. Remember to reference the <strong>VMS.TPS</strong> libraries.</p><p>Add <strong>CommandLineParser </strong>to the project via <strong>NuGet Package Manager</strong>.</p><p>Add the <strong>ScriptContextArgs.cs </strong>to this project as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*ji-XycHXdUS7iv8Ym9hAgw.png" /></figure><p>Copy the following code to <strong>Program.cs:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e2ace77f98f90d9e4f433ff8698764/href">https://medium.com/media/46e2ace77f98f90d9e4f433ff8698764/href</a></iframe><p>Compile your project via <strong>Visual Studio</strong> pressing <strong>Ctrl+Shift+B</strong>.</p><h4>Running the emulated plugin:</h4><p>Open Eclipse ExternalBeamPlanning in any plan you wish to <strong>print </strong>the beams information. Click in <strong>Tools/Scripts/Folder/Change Folder.</strong></p><p>Find the folder you compile <strong>ContextStandalone.esapi.dll</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*dBtkI-gTElphsaM3aK6vJA.png" /></figure><p>Run the script:</p><p>Select the Executable Compiled <strong>LogPatientFields.exe and open</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*MNAAM-2Gq3nUMy6Xq3hyHQ.png" /></figure><p>This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*IP51Iw982LJClPEt2kRxPg.png" /></figure><p>Now you can do it with all your executables. Even if they don’t have ScriptContext the ContextStandalone.esapi.dll works too. So you don’t have to copy the files to the local disk and run.</p><p>Thanks for the attention !</p><p>😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97f5213f4560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 passos para começar seus scripts no Eclipse com e sem Citrix.]]></title>
            <link>https://jhmcastelo.medium.com/5-passos-para-come%C3%A7ar-seus-scripts-no-eclipse-com-e-sem-citrix-236ad6d002f3?source=rss-3c314038f737------2</link>
            <guid isPermaLink="false">https://medium.com/p/236ad6d002f3</guid>
            <category><![CDATA[medical-physics]]></category>
            <category><![CDATA[varian]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[radiotherapy]]></category>
            <dc:creator><![CDATA[João Castelo]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 14:48:11 GMT</pubDate>
            <atom:updated>2020-07-11T17:48:54.108Z</atom:updated>
            <content:encoded><![CDATA[<p>Fala pessoal tudo bem ?<br>Vou tentar explicar o mínimo para começar a fazer seus scripts no ESAPI (Eclipse Scripting API). Estarei usando o Eclipse v15.6 , mas todos os scripts neste artigo serão reutilizáveis na maior parte das versões acima da 11, pois não iremos editar informações, apenas pegá-las.</p><p>Todas as explicações serão baseadas projetos simples cobrindo como fazer e rodar :</p><p>Rodar um<strong> hello world</strong> no Visual Studio.</p><p>Scripts de arquivo único direto no eclipse para usar em um paciente por vez;</p><p>Scripts compilados em biblioteca para um paciente por vez (direto do Eclipse).</p><p>Executáveis para rodar todo o banco de dados (usando <strong>citrix</strong>);</p><p>Gerenciar duas versões do executável com o <strong>Git </strong>e testá-las.</p><figure><img alt="Figura de tres telas, só para decoração" src="https://cdn-images-1.medium.com/max/1024/0*r1GFkKzru6NmbX8e" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Você não precisa saber programar pra fazer um script pro Eclipse. Simplesmente procurar no Google, tentar e errar, tentar e errar até fazer o primeiro que da certo. A linguagem que somos obrigados a usar é o C#, existem cursos baratos no udemy que são mais que suficientes.</h4><p>Antes de tudo vamos baixar o IDE do visual studio que é basicamente obrigatório. Você pode baixar no seu computador mesmo ou no computador do trabalho se a TI deixar.</p><h4>Baixe o visual studio comunity 2019 nesse link:</h4><p><a href="https://visualstudio.microsoft.com/pt-br/vs/">Visual Studio 2019 | Baixar gratuitamente</a></p><h4>Quais pacotes instalar:</h4><p>Os mais importantes são desenvolvimento para desktop com .NET e desenvolvimento com plataforma universal windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*dsw-P-mDjNkRXAQxTO5QaA.png" /></figure><h3>O básico do básico do C#</h3><p>Dando um olá mundo com visual studio e C#.</p><p>Abra o visual studio e crie um novo projeto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW5eLhGKxxhAD4dnfaldjQ.png" /></figure><p>Escolha um aplicativo de console para .NET Framework</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTmVKpkDswlTaVGL7QtrCA.png" /></figure><p>Escolha um nome para o projeto e inicie ele:</p><p>Use o framework 4.5;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*NKKbPyp2NbqzYS0gmU4TNA.png" /></figure><p>Ele vai iniciar assim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*sg-gUFTqTPAhqFwxWaZbqQ.png" /></figure><h4>Declarando uma variável</h4><p>Dentro dos colchetes da função Main, escreva:</p><pre><strong>string message = &quot;Hello World&quot;;</strong></pre><p>Você está declarando pro sistema alocar memória para uma <strong>string </strong>que tem nome <strong>message.</strong></p><p>Toda vez que você quiser reutilizar a mensagem <strong>“Hello World”</strong> você pode se referir a variável <strong>message</strong>.</p><p>Primeiro a gente vai imprimir a mensagem no console.</p><pre><strong>Console.WriteLine(message);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*_EKc4IlzW4pQim_D8ZQIcg.png" /></figure><p><strong>Aperte Ctrl+F5</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*vr6bRC6LjcVFA8OUvdwIwQ.png" /></figure><p>Seu primeiro programa já está funcionando.</p><h4><strong>MessageBox</strong></h4><p>Até nossa aplicação do ESAPI Executável, não usaremos o console. Então vamos usar o MessageBox do windows para imprimir algumas informações.</p><p>Para usar o MessageBox faça o seguinte:</p><p>Adicione a seguinte linha de comando abaixo do seu código original:</p><pre>MessageBox.Show(message);</pre><p>Ao fazer isso perceberemos um erro:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*nntB3FZYB5rxOkA-Tu0UOg.png" /></figure><p>Clique com o botão direito no erro:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*XCmdlvWU1XmOXQeQwZQiTg.png" /></figure><p>Pressione <strong>Ações Rápidas e Refatorações</strong> ou <strong>Ctrl</strong>+<strong>. (Esse comando é muito útil);</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*WLHoT7lLcM0daSkRdzSEdA.png" /></figure><p>Adicione o a referência a biblioteca do Windows Form.</p><p>Ela vai aparecer lá em cima agora:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*cMMuhpOuRfYOqRiM3nMz-Q.png" /></figure><p>Aperte Ctrl + F5 novamente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*WPsmDS4jbbb1EouIbVqJRQ.png" /></figure><p>Você acabou de usar a biblioteca MessageBox com sucesso, e não precisa mais do console pra entender as saídas do seu código por enquanto.</p><h4>Avançando um pouco e iniciando :</h4><p>O ESAPI é uma biblioteca que liga o sistema de planejamento ao C#, da mesma forma que a biblioteca windows form conecta o C# a extensão de janelas do sistema operacional. As bibliotecas contém linhas de programação que fazem essa intermediação sem que nós precisemos nos preocupar com isso. No ESAPI existem <strong>classes </strong>que ligam o objetos do Eclipse ao código apresentado ao <strong>usuário </strong>(NÓS). Então se queremos pegar informação do nome do paciente temos que acessar o <strong>objeto </strong>do <strong>Paciente </strong>(Patient).</p><h4>Objeto</h4><p>Resumidamente é a <strong>instancia </strong>de um tipo de uma variável mais elaborado. Ele vem de uma <strong>classe </strong>que é feita por alguém. Toda classe é rastreada a tipos básicos como números, strings, booleanos. O legal do visual studio é que quando você tem um objeto, você pode acessar suas propriedades antes da compilação do código.</p><p>Exemplo de objeto</p><p>Crio a <strong>classe </strong>para uma pessoa:</p><pre><strong>class Pessoa</strong></pre><pre><strong>{</strong></pre><pre><strong>public string Nome { get; set; }</strong></pre><pre><strong>public string SobreNome { get; set; }</strong></pre><pre><strong>public int Idade { get; set; }</strong></pre><pre><strong>public void Print()</strong></pre><pre><strong>{</strong></pre><pre><strong>MessageBox.Show(Nome + &quot; &quot; + SobreNome + &quot; &quot; + Idade.ToString());</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><p>Instancio uma nova pessoa (<strong>objeto</strong>), agora temos uma variável do tipo <strong>Pessoa </strong>com nome <strong>pessoa </strong>que tem o conteúdo seguinte:</p><pre><strong>Pessoa pessoa = <br>new Pessoa { Nome = &quot;Joseph&quot;, SobreNome = &quot;Logan&quot;, Idade = 44 };</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*4j-4xy6KqrANOhjFEaBtRg.png" /><figcaption>Analisando as possíveis funções e propriedades de um objeto do tipo Pessoa</figcaption></figure><p>Agora posso usar a função print da <strong>pessoa</strong>:</p><pre><strong>pessoa.Print();</strong></pre><p>Ctrl + F5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nat2g9AyLTOli_kmXhBSTQ.png" /></figure><h3>Como o ESAPI na prática funciona:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hkn15d-rEr8omYFQFfPm2A.png" /></figure><h4><strong>Plugins</strong></h4><p>O script depende do eclipse instalado no computador. Se você roda um script de dentro do eclipse, ele só acessa a informação do paciente que tem a janela aberta. Existe um objeto da <strong>classe ScriptContext </strong>que faz a intermediação ao<strong> C# </strong>dos elementos abertos no caso<strong>.</strong></p><p>O eclipse que compila o código dentro dele nesses casos, então não vamos usar a função <strong>Main()</strong> como entrada.</p><p>Para explorar nosso <strong>primeiro </strong>plugin, Crie um novo projeto da mesma forma que o hello world. Porém ele será agora uma <strong>Biblioteca de Classes(.NET Framework)</strong> Com nome <strong>HelloWorldPlugin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Xc4cooYUBQWYua3y70aw-A.png" /></figure><p>Na sua solução, clique com o botão direito em referências:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*PLGeTwKoeSkeOMvCNPHzkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*NPQPxg61oX37YIUHo0J7Jg.png" /></figure><p>Pressione em Procurar para achar a referência dos VMS.TPS que fará a conexão do computador que o eclipse está instalado ao compilador do C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*vm6s1bm47doZ_psOTUsQUQ.png" /></figure><p>No geral, a biblioteca VMS.TPS está localizada no computador que o Eclipse está instalado. Na seguinte pasta:</p><p>C:/Arquivos de Programas(x86)/Varian/RTM/versao/esapi/API</p><h4>Se seu eclipse é local:</h4><p>Localize essa pasta e adicione as referências:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*Tob2ojHyLqkJWcGFTiBjlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*jiKurvU7eJrHE8I9K6CUvw.png" /></figure><h4>Se CITRIX:</h4><p>Se você possui <strong>CITRIX</strong>, o eclipse está instalado no computador virtual, a possibilidade nesse caso é copiar os arquivos que estão na estação virtual.</p><h4>Lembre da dica (vamos usar esse atalho mais vezes) :</h4><p>Abra o Planejamento Externo (External Beam Planning)/Tools/Scripts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*Jd1HHbXjNkbURuntqsWreA.png" /></figure><p>Pressione Open Folder em System Scripts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*WpfshJqmn6anFl_Arydsvg.png" /></figure><p>Abrirá o explorer do computador virtual que tem o Eclipse instalado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*gvpebOQPWrUODnnEcjf67w.png" /></figure><p>Copie os seguintes arquivos uma pasta qualquer do computador que tem o visual studio instalado.</p><p><strong>AlgumaPasta/(VMS.TPS.Common.Model.API.dll)</strong></p><p><strong>AlgumaPasta/(VMS.TPS.Common.Model.Types.dll)</strong></p><p>E realize os mesmos passos após as dlls estarem copiadas localmente para adicionar a referência. Elas podem estar em qualquer pasta agora.</p><h4>Vamos ao código:</h4><p>O ESAPI <strong>SEMPRE </strong>precisa da seguinte forma para os plugins, exatamente estes nomes:</p><pre><strong>namespace VMS.TPS{<br>public class Script{</strong></pre><pre><strong>public void Execute(ScriptContext context){</strong></pre><pre><strong>//Code here</strong></pre><pre><strong>}<br>}<br>}</strong></pre><p>Note que vai acontecer a mesma coisa do MessageBox com o ScriptContext! Ele vai reclamar que ele não existe. Então clique <strong>Ctrl </strong>+<strong> . </strong>e<strong> </strong>resolva o problema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*trLDqtI9fsOUx4B8XfcVZg.png" /></figure><p>Note que ele adiciona a dll do API.</p><p>Se você quiser, antes de qualquer código escrito, escrever esses comando no início do programa.</p><pre><strong>using VMS.TPS.Common.Model.API;<br>using VMS.TPS.Common.Model.Types;</strong></pre><p>Também resolveria o problema. Mas aprender a consertar os bugs com <strong>Ctrl + .</strong> é muito importante.</p><h4>Quase lá</h4><p>Vamos escrever as primeiras linhas no <strong>single file</strong> plugin. E aprender a rodar no Eclipse.</p><p>Vamos agora abrir um paciente pelo<strong> Planejamento Externo</strong>. Qualquer um que tenha um plano com dose calculada:</p><p>No meu caso, uma <strong>radiocirurgia </strong>de múltiplas lesões:</p><p>O código fará o seguinte: O contexto, que é a janela aberta, possui um plano de <strong>Radioterapia Externa</strong> que está aberto no momento. Vamos acessar esse plano pelo script e iremos criar uma variável de mensagem com o nome do plano. Depois usar um MessageBox para imprimir esse nome de plano.</p><p>Adicione as seguintes linhas à função <strong><em>Execute(ScriptContext context):</em></strong></p><pre><strong>ExternalPlanSetup plan = context.ExternalPlanSetup;<br></strong> //objeto do plano</pre><pre>string message = plan.Id;</pre><pre><strong>MessageBox.Show(message);<br> // Mostrar a mensagem</strong></pre><p>Conserte o problema do <strong>MessageBox</strong> (<strong>Ctrl + .</strong>) com a biblioteca <strong>Presentation Framework</strong>, diferentemente da <strong>windows forms</strong> que usamos anteriormente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*Aogvd0OyakmJY7ehKMVzVA.png" /></figure><p>O <strong>Forms </strong>não vai funcionar no plugin de arquivo único porque essa biblioteca não existe na memória do eclipse.</p><h4>Primeiro teste:</h4><p>No parte de ferramentas e scripts (/Tools/Scripts), utilize o marcador de <strong>Open Folder</strong> e localize onde está o arquivo <strong>Class1.cs </strong>e clique duas vezes nele.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*OqPvLlmGTvSOZbeKBJNxQA.png" /><figcaption>Pasta onde o arquivo Class1.cs está</figcaption></figure><p>Lembre que se você está usando o <strong>Citrix</strong>, você tem que por o arquivo onde o computador do <strong>Citrix que o eclipse está instalado </strong>possa achá-lo. Se o client é o computador onde você programou, então fica fácil. Se não use um pendrive ou uma pasta compartilhada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*4EHPOerF3LK1beanlxfr0Q.png" /></figure><p>Clique em Run ou duas vezes em Class1.cs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*i7fp9m6cxgAjVIg9tJsGgg.png" /></figure><p>Com sucesso rodamos nosso primeiro script de arquivo único.</p><p>Experimente agora trocar, a string de somente o nome do plano para o sobrenome do paciente e do plano.</p><p><strong>Substitua </strong>a linha que declara <strong>message </strong>por essa linha:</p><pre>string message  = context.Patient.LastName + &quot; &quot; + plan.Id;</pre><p>Salve e rode novamente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*o59FuGhfhGaz8YYaSijkrw.png" /></figure><p>Agora você usar essa estrutura pra fazer quase tudo. Porém temos algumas limitações.</p><h4><strong>Limitações do plugin de arquivo único:</strong></h4><p><strong>Não pode ter bibliotecas que não estão pre-instaladas no Eclipse</strong>. Isso significa que se queremos fazer um gráfico por exemplo não vamos conseguir. Já que não existe ferramenta integrada de gráficos no C#. (Farei um post de como fazer gráficos).</p><p><strong>Se limitar a um arquivo único</strong>. Separação de código é muito importante em C# e isso é completamente travado pela estrutura do single file plugin. Existem arquivos que deveriam estar separados que estão juntos, gerando scripts de 10000 linhas. Muitas vezes vamos precisar fazer interfaces gráficas para nossas aplicações, e o WPF que é muito bom nisso, precisa que tenha mais de um arquivo para funcionar.</p><p>Para solucionar essa problemática, a Varian permite que você crie scripts compilados, isto é, transformar seu código em uma biblioteca fake. Que tem um ponto de entrada igual ao <strong>single file plugin</strong> e é chamado de <strong>binary plugin</strong>.</p><h4><strong>Criando nosso primeiro binary plugin:</strong></h4><p>Para reforçar que estamos usando bibliotecas externas que não existem no eclipse, vamos baixar um biblioteca chamada RandomNameGenerator.</p><p>Na aba de solução, clique com o botão direito em referências:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*q-pUdZTAMviOdsh50jJA2w.png" /></figure><p>Logo, aperte em gerenciar pacotes do NuGet. É a fonte de onde vem bibliotecas externas no C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*L0BbMp0Q_-348uv6K6EdCg.png" /></figure><p>Procure por <strong>RandomNameGeneratorLibrary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N73xdFi9SJTLQ9Ed1H-9VA.png" /></figure><p>Clique em instalar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*EcuJmezH0RdnCguSf4c_Mg.png" /></figure><p>Agora podemos usar essa biblioteca externa.</p><p>Agora deixe seu código deste jeito:</p><pre><strong>namespace VMS.TPS</strong></pre><pre><strong>{</strong></pre><pre><strong>public class Script</strong></pre><pre><strong>{</strong></pre><pre><strong>public void Execute(ScriptContext context)</strong></pre><pre><strong>{</strong></pre><pre><strong>ExternalPlanSetup plan = context.ExternalPlanSetup;</strong></pre><pre><strong>//objeto do plano</strong></pre><pre><strong>var personGenerator = new PersonNameGenerator();</strong></pre><pre><strong>var name = personGenerator.GenerateRandomFirstAndLastName();</strong></pre><pre><strong>string message = &quot;The patient last name is not &quot; + name + &quot;his last name is &quot; + plan.Course.Patient.LastName;</strong></pre><pre><strong>MessageBox.Show(message);</strong></pre><pre><strong>// Mostrar a mensagem</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><p>Use o Ctrl + . para importar a biblioteca <strong>RandomNameGeneratorLibrary</strong>;</p><pre><strong>using RandomNameGeneratorLibrary;</strong></pre><p>Ou adicione isso antes do namespace.</p><h4>Pequena nota:</h4><p>Perceba que eu acessei o nome do paciente pelo Plano/Curso/Paciente. Não mais pelo Contexto. O ideal é que você use o mínimo possível do <strong>contexto</strong> para poder reaproveitar código nos <strong>executáveis</strong>, onde <strong>não existe contexto</strong>.</p><h4>Testando se é verdade o que eu falei:</h4><p>Salve o arquivo <strong>Class1.cs</strong> e tente rodar ele no paciente novamente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*eRV46LHp1rdWGF2Y-g0cvA.png" /></figure><p>Ele reclama exatamente da biblioteca externa.</p><h4>Compilação:</h4><p>No visual studio, na aba de solução, clique com botao direito no nome do projeto e clique em <strong>Propriedades</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*PftBL5JYJ18r4m6HzDi3_Q.png" /></figure><p>Essa tela será apresentada:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h9QWLQg9COmOWYyvu0Gufg.png" /></figure><p>Troque o nome do projeto de Algo para Algo.esapi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*UgCRYFyUVXfftj-jYZSSfA.png" /></figure><p>Na aba compilar, mude destino da plataforma para x64 e mude o caminho de saída para vazio (opcional):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*UadcxU3KYwujuBYUHOTkSg.png" /></figure><p>Salve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*jTMRKob3HYjD9uZ3wwf0dg.png" /></figure><p>E compile, com Ctrl+Shift+B. Ou no menu compilação, <strong>compilar solução.</strong></p><p>Se voce mudou o caminho da pasta para vazio, seu projeto foi compilado na mema pasta que está o arquivo <strong>Class1.cs.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*qa1ariy4p92-CLGGTxUG8g.png" /></figure><p>Rode o arquivo .esapi.dll:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*6dFNI6nKrhQj7u3mPkKeKA.png" /></figure><p>Rode mais uma vez:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*VFoQo_uslrHQXbbbe8sl0Q.png" /></figure><p>Estamos certos de que a biblioteca <strong>RandomNameGeneratorLibrary </strong>está sendo aleatória mesmo!</p><p>O que aconteceu agora, foi que ao compilar nosso código tem acesso a biblioteca que também foi compilada, em que ambos estão na <strong>mesma pasta</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*-MIK3txrnZia9qhTPG4bvw.png" /></figure><p>Se você retira o arquivo <strong>RandomNameGeneratorLibrary.</strong>dll<strong>, e reinicia o Eclipse:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*-fGYgoadtMN_MmuSas5c3w.png" /></figure><p>Se não tivesse reiniciado o Eclipse, o código continuaria rodando normal. Vamos entender o por quê agora.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ali16p7Bqs_FfoXFJ5491g.png" /></figure><p>Quando um programa é carregado na memória do ESAPI durante a existência daquela sessão do eclipse no nosso computador, o nome de assembly e dos assemblies que o programa que você rodou é dependente, ficam guardados durante a sessão como algo imutável. Então, se a gente fizer qualquer mudança e tentar recompilar no visual studio. Olha o que vai acontecer.</p><p>Adicionando ao código:</p><pre>message += &quot;\n Nonono&quot;;<br>MessageBox.Show(message);</pre><p>Compilo novamente (Ctrl + Shift + B):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6OC5KWfzIDi7eaPLJJePg.png" /></figure><p>Aquele nome de assembly está bloqueado.</p><p>Como resolver isso:</p><p><strong>Reiniciar o Eclipse (Close all);</strong></p><p>Se o assembly do <strong>RandomNameGeneratorLibrary </strong>não estivesse sendo chamado e dado na memória como não encontrado. Como acontece na maior parte dos casos.</p><p>Poderiamos apenas:</p><p><strong>Mudar o nome do assembly;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*G_Mu0tbg8Kz-9HxYxvWYcg.png" /></figure><p>Compilo novamente (Ctrl + Shift + B):</p><p>Rodo o novo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*qxqs0jonurUU7QpKhUUe6A.png" /></figure><p>E funcionaria novamente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*R6VizvZwwCVXDmPajJnm5A.png" /></figure><h4>O que levar pra casa:</h4><p>Binários resolvem o problema de bibliotecas externas e dos arquivos sem separação de responsabilidade, porém vem com diversos como:</p><p>Necessidade de reiniciar o eclipse ou mudar o nome de assembly para recompilação a cada mudança;</p><p>Eles permitem a realização de aplicativos WPF para criação de <strong>interface gráfica</strong>.</p><h3>Executáveis:</h3><p>Se você chegou até aqui, você está interessado em varrer o banco de dados.</p><p>Os executáveis funcionam igual ao primeiro exemplo de C# você compila e roda direto do computador, ele abre o console ou uma janela pra te informar sobre a execução, então vamos nos livrar do <strong>MessageBox</strong>. A biblioteca VMS.TPS conecta o C# aos pacientes pelo objeto da classe VMS.TPS.Application. Essa biblioteca acha o banco de dados dentro do computador que tem o Eclipse instalado, então para usuários de <strong>CITRIX </strong>você vai compilar no seu computador com visual studio, e copiar todos os arquivos que vem junto com a compilação pro computador do <strong>CITRIX.</strong></p><p>Vamos criar um novo aplicativo do <strong>console .NET Framework</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTmVKpkDswlTaVGL7QtrCA.png" /></figure><p>Vou chamá-lo de MultiPatientExecutable.</p><p>Vamos pegar as referências que nem nos plugins para as bibliotecas do VMS.TPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*jiKurvU7eJrHE8I9K6CUvw.png" /></figure><p>E vamos montar o template de código para o executável que varre todos os pacientes do banco de dados e imprime no console o Id dos planos em que a dose calculada é valida:</p><pre><strong>using VMS.TPS.Common.Model.API;</strong></pre><pre><strong>using VMS.TPS.Common.Model.Types;</strong></pre><pre><strong>namespace MultiPatientExecutable</strong></pre><pre><strong>{</strong></pre><pre><strong>class Program</strong></pre><pre><strong>{</strong></pre><pre><strong>[STAThread]</strong></pre><pre><strong>public static void Main(string[] args)</strong></pre><pre><strong>{</strong></pre><pre><strong>try</strong></pre><pre><strong>{</strong></pre><pre><strong>using (Application app = Application.CreateApplication())</strong></pre><pre><strong>{</strong></pre><pre><strong>Execute(app);</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>catch (Exception e)</strong></pre><pre><strong>{</strong></pre><pre><strong>Console.Error.WriteLine(e.ToString());</strong></pre><pre><strong>Console.Read();</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>public static void Execute(Application app)</strong></pre><pre><strong>{</strong></pre><pre><strong>//Console.Read();</strong></pre><pre><strong>foreach (var summary in app.PatientSummaries)</strong></pre><pre><strong>{</strong></pre><pre><strong>Patient patient = app.OpenPatient(summary);</strong></pre><pre><strong>// Code here</strong></pre><pre><strong>IEnumerable&lt;PlanSetup&gt; isDoseOk = <br>patient.Courses.SelectMany(e =&gt; e.PlanSetups).Where(e =&gt; e.IsDoseValid);</strong></pre><pre><strong>string message = string.Join(&quot;\n&quot;, isDoseOk.Select(e =&gt; e.Id));</strong></pre><pre><strong>Console.WriteLine(message);<br>Console.ReadLine();<br>app.ClosePatient();</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><p>Vamos compilar com as seguintes configurações de compilação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*EQKiLYYetDzN8EwU99589A.png" /></figure><p>Compilamos com Ctrl+Shift+B.</p><p>Se o eclipse é local você roda simplesmente o arquivo executável, clicando duas vezes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*QkfnA4FmoxtIL5m68TtGtQ.png" /></figure><p>Se o eclipse for <strong>CITRIX </strong>tem que copiar a pasta bin para o disco local do computador onde o citrix ta instalado.</p><p>Use o mesmo truque ensinado lá em cima tanto para copiar quanto pra executar.</p><p>ExternalBeamPlanning/Tools/Scripts/SystemScripts/OpenFolder/ → Garante acesso ao explorador de arquivos do citrix que possui o Eclipse instalado.</p><p>De um clique duplo e o script irá imprimir o nome dos planos com dose válida para cada paciente. A cada enter que o usuário da ele vai para o próximo paciente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gLbNrgYLeeDjVli63lyEkQ.png" /></figure><blockquote>Nota1: O programa deve ser rodado no disco local do computador que o CITRIX está instalado</blockquote><blockquote>Nota: Todo paciente que é aberto tem que ser fechado antes de abrir o próximo. Por isso o app.ClosePatient().</blockquote><p>Estamos bem avançados agora com o nosso executável, porém imagine que você quer pegar esses planos para determinados pacientes que você já tem guardado numa planilha. Esses pacientes possuem um ID único. E você exportou os IDs linha por linha pra um arquivo de texto,<strong> Ids.txt</strong>.</p><pre>1235<br>225<br>12358<br>7777<br>8880<br>5555</pre><p>Como agora eu uso essa lista de pacientes para fazer isso?</p><h4>Gerenciando versões do código com o GIT direto do visual studio.</h4><p>Nós não precisamos criar outro projeto. Vamos fazer o seguinte, criar uma cópia do código no mesmo projeto com o Git.</p><p>Guia de Git : (<a href="https://rogerdudler.github.io/git-guide/index.pt_BR.html">https://rogerdudler.github.io/git-guide/index.pt_BR.html</a>).</p><p>Pro git, essa cópia que tem o nome de branch (ramificação).</p><p>Vamos iniciar o repositório no canto direito inferior em Adicionar ao controle de Código-Fonte:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAa4ctj0wqSaGEwzDahzqg.png" /></figure><p>Pressione controle do Git:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*VeObnh-rn-leHDkmaMMRdA.png" /></figure><p>Será apresentado para você essa visão:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*lW9Xwadc2IQZnNrQtWCWKg.png" /></figure><p>E essa :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*vzI5QWAD_p9rzg9zqmZRVQ.png" /></figure><p>Clique no simbolo ao lado do nome master e selecione <strong>novo branch</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*EQmMoV4s1t-Y6wxwXAgFpA.png" /></figure><p>Vamos colocar o nome da branch como patient_list e pressionar em criar ramificação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*EoxgmNA5o62xDsAGMmEMQQ.png" /></figure><p>Agora você está na branch patient_list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*qTGfDKsJglPOo52n3TEdbQ.png" /></figure><p>Da pra alternar entre master e patient_list e quantas branches você quiser.</p><p>Agora a branch atual sofrerá as modificações que queremos. Agora ao invés de salvar com Ctrl+S, você pode commitar suas mudanças de código através do lápis e reportar o que você mudou no código. Como vamos fazer.</p><h4><strong>Adicionando o controle de quais pacientes vão ser abertos:</strong></h4><p>Vamos fazer mudanças substanciais, mas não se assuste:</p><p>Copie o código abaixo e cole em cima do conteúdo do arquivo <strong>Program.cs.</strong></p><pre><strong>using System;</strong></pre><pre><strong>using System.Collections.Generic;</strong></pre><pre><strong>using System.IO;</strong></pre><pre><strong>using System.Linq;</strong></pre><pre><strong>using System.Text;</strong></pre><pre><strong>using System.Threading.Tasks;</strong></pre><pre><strong>using System.Windows.Forms;</strong></pre><pre><strong>using VMS.TPS.Common.Model.API;</strong></pre><pre><strong>using VMS.TPS.Common.Model.Types;</strong></pre><pre><strong>using Application = VMS.TPS.Common.Model.API.Application;</strong></pre><pre><strong>namespace MultiPatientExecutable</strong></pre><pre><strong>{</strong></pre><pre><strong>class Program</strong></pre><pre><strong>{</strong></pre><pre><strong>[STAThread]</strong></pre><pre><strong>public static void Main(string[] args)</strong></pre><pre><strong>{</strong></pre><pre><strong>try</strong></pre><pre><strong>{</strong></pre><pre><strong>using (Application app = Application.CreateApplication())</strong></pre><pre><strong>{</strong></pre><pre><strong>SelectPatientList(app);</strong></pre><pre><strong>(app);</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>catch (Exception e)</strong></pre><pre><strong>{</strong></pre><pre><strong>Console.Error.WriteLine(e.ToString());</strong></pre><pre><strong>Console.Read();</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>public static void SelectPatientList(Application app)</strong></pre><pre><strong>{</strong></pre><pre><strong>Console.WriteLine(&quot;Select the folder that contain the txt with the patients IDs.&quot;);</strong></pre><pre><strong>var file = &quot;&quot;;</strong></pre><pre><strong>OpenFileDialog openFileDialog1 = new OpenFileDialog();</strong></pre><pre><strong>if (openFileDialog1.ShowDialog() == DialogResult.OK)</strong></pre><pre><strong>{</strong></pre><pre><strong>file = openFileDialog1.FileName;</strong></pre><pre><strong>}</strong></pre><pre><strong>try</strong></pre><pre><strong>{</strong></pre><pre><strong>Execute(app, file);</strong></pre><pre><strong>}</strong></pre><pre><strong>catch (Exception)</strong></pre><pre><strong>{</strong></pre><pre><strong>MessageBox.Show($&quot;Failed for file {file}, maybe it is empty&quot;);</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>public static void Execute(Application app, string file)</strong></pre><pre><strong>{</strong></pre><pre><strong>var readAll = File.ReadAllLines(file).ToList();</strong></pre><pre><strong>//Console.Read();</strong></pre><pre><strong>foreach (var id in readAll)</strong></pre><pre><strong>{</strong></pre><pre><strong>Patient patient = app.OpenPatientById(id);</strong></pre><pre><strong>// Code here</strong></pre><pre><strong>IEnumerable&lt;PlanSetup&gt; isDoseOk =</strong></pre><pre><strong>patient.Courses.SelectMany(e =&gt; e.PlanSetups).Where(e =&gt; e.IsDoseValid);</strong></pre><pre><strong>string message = string.Join(&quot;\n&quot;, isDoseOk.Select(e =&gt; e.Id));</strong></pre><pre><strong>Console.WriteLine(message);</strong></pre><pre><strong>Console.ReadLine();</strong></pre><pre><strong>app.ClosePatient();</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><pre><strong>}</strong></pre><p>Agora vamos salvar com o commit:</p><p>Clique no botão no lápis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*QiA3-ankVWQkjku8mM9QxA.png" /></figure><p>Escreva sua mensagem de commit:</p><blockquote>Mudei meu código para escolher os pacientes</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*f7FnrC-VxJ0Y9qLkUwV-_Q.png" /></figure><p>Se você quiser saber as alterações feitas de antes para agora clique duas vezes em Program.cs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drW6TT-8j0AXop3lvO9oJw.png" /><figcaption>Tela de mudanças no arquivo Program.cs, verde foi adicionado e vermelho foi retirado</figcaption></figure><p>Pressione confirmar tudo e salve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*s1TVBkqrrJEa3CHux5YoMw.png" /></figure><p>Você fez seu commit, seu código está salvo!</p><p>Compile novamente com Ctrl+Shift+B:</p><p>Rode o programa de novo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*oufr36Gp3xjbNwKsftECZQ.png" /></figure><p>Selecione o arquivo:</p><p>Esse é o output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*denT5awSvRq3KySGl3o25Q.png" /></figure><blockquote>Obrigado pela atenção.</blockquote><h4>Executáveis com contexto:</h4><p>Uma coisa que talvez você não saiba: Executáveis podem até simular um plugin, aí você escapa dos problemas de assembly do eclipse pros binários, tendo um binário que executa e passa as informações do contexto para o executável (.exe), que não vai ter esse problema. <strong>Isso ficará pra outro post</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236ad6d002f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>