Beispiel #1
0
    public static bool UploadZip(string RcaseId, string studyId, string zipPath, string username, string DbCaseId, string stydyUid)
    {
        try
        {
            var    fi   = new FileInfo(zipPath);
            byte[] data = File.ReadAllBytes(zipPath);
            string responseFromServer = null;
            try
            {
                var api  = ACFG.GetSiteApiDetails();
                var user = AOA.GetUserRefreshIfNecessary(username, DbCaseId);
                //WebRequest request = WebRequest.Create(api.cases_url + RcaseId + "/studies/" + studyId + "/images");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(api.cases_url + RcaseId + "/studies/" + studyId + "/images");
                request.ContentType = "application/zip";
                request.Method      = "POST";
                request.ServicePoint.Expect100Continue = true;
                request.Timeout     = 60 * 60 * 1000;
                request.Method      = "POST";
                request.ContentType = "application/zip";
                request.Headers.Add("Authorization", "Bearer " + user.access_token);

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                WebResponse            response   = request.GetResponse();
                var                    dataStream = response.GetResponseStream();
                System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        string errorResponse = reader.ReadToEnd();
                        LOG.InsertEvent("Unable to upload zip: " + fi.Name, "API", errorResponse, DbCaseId, stydyUid);
                    }
                return(false);
            }

            var respObj = JsonConvert.DeserializeObject <UploadResponse>(responseFromServer);
            LOG.Write("Uploaded Filename: " + respObj.filename);
            LOG.InsertEvent("Successfully uploaded ZIP", "API", responseFromServer, DbCaseId, stydyUid);
            return(true);
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "API", ex.Message, DbCaseId, stydyUid);
            return(false);
        }
        finally { GC.Collect(); }
    }
Beispiel #2
0
        static void Main(string[] args)
        {
            //Debug2();
            //Console.Write("Done Debug");
            //Console.Read();
            //return;

            LOG.Write("Radiopaedia Upload Agent");
            LOG.Write("Created by Andy Le of The Royal Melbourne Hospital");
            LOG.Write("Built: " + LOG.RetrieveLinkerTimestamp().ToString("dd MMMM yyyy | HH:mm:ss"));
            //LOG.Write("Press 'ctrl+c' to quit.");


            try
            {
                HostFactory.Run(x =>
                {
                    x.Service <ServiceController>(s =>
                    {
                        s.ConstructUsing(name => new ServiceController());
                        s.WhenStarted(nc => nc.Start());
                        s.WhenStopped(nc => nc.Stop());
                    });
                    x.RunAsLocalSystem();
                    x.SetDescription("Radiopaedia Uploader Agent");
                    x.SetDisplayName("Radiopaedia Uploader Agent");
                    x.SetServiceName("Radiopaedia Uploader Agent");
                });
            }
            catch (Exception ex)
            {
                LOG.Write(ex.Message);
                LOG.Write(Newtonsoft.Json.JsonConvert.SerializeObject(ex));
            }
        }
        public static void TestSetupIfAny()
        {
            MultiresTestComponent testMultires = GameObject.FindObjectOfType <MultiresTestComponent>();

            Assert.IsTrue(GameObject.FindObjectsOfType <MultiresTestComponent>().Length <= 1);
            if (testMultires != null)
            {
                // set test multires
                if (testMultires.enableResolutionTest)
                {
                    Assert.IsTrue(testMultires.resolution != MultiresKind.Uninitialized);
                    if (testMultires.resolution != MultiresKind.Uninitialized)
                    {
                        Multires.Folder = testMultires.resolution;
                                                #if LOG_VERBOSE_MULTIRES
                        LOG.Write("App.AwakeOwn : Multires : using TEST MULTIRES folder=" + Multires.Folder);
                                                #endif
                    }
                }
                else
                {
                                        #if LOG_VERBOSE_MULTIRES
                    LOG.Write("App.AwakeOwn : Multires : TEST MULTIRES DISABLED");
                                        #endif
                }
            }
            else
            {
                                #if LOG_VERBOSE_MULTIRES
                LOG.Write("App.AwakeOwn : Multires : TEST MULTIRES NOT FOUND");
                                #endif
            }
        }
Beispiel #4
0
        static void Debug()
        {
            //AUP.UploadZip("44186", "47777", @"d:\temp\1.3.12.2.1107.5.1.4.65115.3000001603240736279390001264491.zip", "henryknipe", "20160411091821_henryknipe", "1.3.12.2.1107.5.8.9.13.26.65.26.126.218.77882191");
            APetaPoco.SetConnectionString("cn1");
            var bm    = APetaPoco.PpRetrieveOne <DbCase>("Cases", "[case_id] = '20160607180814_frank'");
            var pcase = (DbCase)bm.Data;

            bm = APetaPoco.PpRetrieveList <DbStudy>("Studies", "[case_id] = '20160607180814_frank'");
            pcase.study_list = (List <DbStudy>)bm.Data;
            foreach (var st in pcase.study_list)
            {
                bm        = APetaPoco.PpRetrieveList <DbSeries>("Series", "[case_id] = '20160607180814_frank' AND [study_uid] = '" + st.study_uid + "'");
                st.series = (List <DbSeries>)bm.Data;
                //ADCM.DownloadStudy(st);
                LOG.Write("Converting DCM to PNG...");
                AIMG.MultiFrameProcess(st);
                bool convertComplete = AIMG.ConvertDcmToPng(st);
                //if (!convertComplete)
                //{
                //    ACASE.ClearCaseFiles(pcase);
                //    throw new Exception("Unable to convert study to PNG");
                //}
                LOG.Write("Completed image conversion");

                LOG.Write("Optimizing PNG's for study...");
                AIMG.OptiPng(st);
                LOG.Write("Completed optimization.");
                //AIMG.ZipSeries(st);
            }
            //ACASE.ProcessCase(pcase);
        }
Beispiel #5
0
    public static bool MarkCaseComplete(string RcaseId, string username, string DbCaseId)
    {
        try
        {
            var        user    = AOA.GetUserRefreshIfNecessary(username, DbCaseId);
            var        api     = ACFG.GetSiteApiDetails();
            WebRequest request = WebRequest.Create(api.cases_url + RcaseId + "/mark_upload_finished");
            request.Method = "PUT";
            //request.ContentType = "application/json";
            request.Headers.Add("Authorization", "Bearer " + user.access_token);

            WebResponse            response           = request.GetResponse();
            var                    dataStream         = response.GetResponseStream();
            System.IO.StreamReader reader             = new System.IO.StreamReader(dataStream);
            string                 responseFromServer = reader.ReadToEnd();
            if (string.IsNullOrEmpty(responseFromServer))
            {
                throw new Exception("Unable to get response from server when marking case complete");
            }
            reader.Close();
            dataStream.Close();
            response.Close();
            var respObj = JsonConvert.DeserializeObject <CaseResponse>(responseFromServer);
            LOG.InsertEvent("Successfully marked study as completed on Radiopaedia", "API", responseFromServer, DbCaseId);
            return(true);
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "API", ex.Message, DbCaseId);
            return(false);
        }
    }
Beispiel #6
0
    public static bool UploadZip2(string RcaseId, string studyId, string zipPath, string username, string DbCaseId, string stydyUid)
    {
        var api  = ACFG.GetSiteApiDetails();
        var user = AOA.GetUserRefreshIfNecessary(username, DbCaseId);
        // Build request
        var request = (HttpWebRequest)WebRequest.Create(api.cases_url + RcaseId + "/studies/" + studyId + "/images");

        request.Method = WebRequestMethods.Http.Post;
        request.AllowWriteStreamBuffering = false;
        request.ContentType      = "application/zip";
        request.Timeout          = 60 * 60 * 1000;
        request.ReadWriteTimeout = 60 * 60 * 1000;
        string fileName = Path.GetFileName(zipPath);

        request.Headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", fileName);
        request.Headers.Add("Authorization", "Bearer " + user.access_token);

        try
        {
            // Open source file
            using (var fileStream = File.OpenRead(zipPath))
            {
                // Set content length based on source file length
                request.ContentLength = fileStream.Length;

                // Get the request stream with the default timeout
                using (var requestStream = request.GetRequestStream())
                {
                    // Upload the file with no timeout
                    fileStream.CopyTo(requestStream);
                }
            }
            using (var response = request.GetResponse())
                using (var responseStream = response.GetResponseStream())
                    using (var reader = new StreamReader(responseStream))
                    {
                        var respObj = JsonConvert.DeserializeObject <UploadResponse>(reader.ReadToEnd());
                        LOG.Write("Uploaded Filename: " + respObj.filename);
                        LOG.InsertEvent("Successfully uploaded ZIP", "API", reader.ReadToEnd(), DbCaseId, stydyUid);
                    }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.Timeout)
            {
                //LogError(ex, "Timeout while uploading '{0}'", fileName);
                LOG.InsertEvent("Timeout While uploading: " + zipPath, "API", ex.Message, DbCaseId, stydyUid);
                LOG.Write("Timeout Uploading");
                LOG.Write(ex.Message);
            }
            else
            {
                LOG.InsertEvent("Error While uploading: " + zipPath, "API", ex.Message, DbCaseId, stydyUid);
                LOG.Write("Error Uploading");
                LOG.Write(ex.Message);
            }
            return(false);
        }
        return(true);
    }
Beispiel #7
0
 public static User GetUserRefreshIfNecessary(string username, string caseid)
 {
     try
     {
         APetaPoco.SetConnectionString("cn1");
         var bm = APetaPoco.PpRetrieveOne <User>("Users", "[username] = '" + username + "'");
         if (!bm.Success)
         {
             throw new Exception("Unable to retrieve user details for case: " + username);
         }
         var user = (User)bm.Data;
         if (DateTime.Now > user.expiry_date.Value.AddMinutes(-30))
         {
             RefreshToken(user.refresh_token, caseid);
             bm = APetaPoco.PpRetrieveOne <User>("Users", "[username] = '" + username + "'");
             if (!bm.Success)
             {
                 throw new Exception("Unable to retrieve UPDATED user details for case: " + username);
             }
             user = (User)bm.Data;
         }
         return(user);
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
         LOG.InsertEvent(errorString, "API", ex.Message, caseid);
         return(null);
     }
     finally { GC.Collect(); }
 }
Beispiel #8
0
 public static void InsertEvent(string msg, string type, string data = null, string dcase = null, string dstudy = null, string dseries = null)
 {
     try
     {
         Event e = new Event();
         e.Type      = type;
         e.Message   = msg;
         e.TimeStamp = DateTime.Now;
         e.Data      = data;
         if (dcase != null)
         {
             e.InternalId = dcase;
         }
         if (dstudy != null)
         {
             e.StudyUid = dstudy;
         }
         if (dseries != null)
         {
             e.SeriesUid = dseries;
         }
         APetaPoco.SetConnectionString("cn1");
         var bm = APetaPoco.PpInsert(e);
         if (!bm.Success)
         {
             LOG.Write(bm.Message);
         }
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
     }
 }
Beispiel #9
0
        /// <summary>
        /// Azzera l'enumeratore degli elementi
        /// e la Display List
        /// </summary>
        public void ClearElements()
        {
#if (DEBUG)
            LOG.Write(@"ClearElements()");
#endif
            elEnum = null;
            dl.Reset();
        }
Beispiel #10
0
 public static void RefreshToken(string refreshToken, string caseid)
 {
     try
     {
         var    api = ACFG.GetSiteApiDetails();
         string responseFromServer = null;
         try
         {
             WebRequest request = WebRequest.Create(api.oauth_url + "token?client_id=" + api.site_id + "&client_secret=" + api.site_secret + "&refresh_token=" + refreshToken + "&grant_type=refresh_token");
             request.Method = "POST";
             WebResponse            response   = request.GetResponse();
             var                    dataStream = response.GetResponseStream();
             System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
             responseFromServer = reader.ReadToEnd();
             reader.Close();
             dataStream.Close();
             response.Close();
         }
         catch (WebException ex)
         {
             using (var stream = ex.Response.GetResponseStream())
                 using (var reader = new System.IO.StreamReader(stream))
                 {
                     string errorResponse = reader.ReadToEnd();
                     LOG.InsertEvent("Unable to upload zip", "API", errorResponse, caseid);
                 }
             GC.Collect();
             return;
         }
         var tokenResp = JsonConvert.DeserializeObject <TokenResponse>(responseFromServer);
         if (tokenResp == null || tokenResp == default(TokenResponse))
         {
             throw new Exception("Unable to retrieve valid token response");
         }
         APetaPoco.SetConnectionString("cn1");
         var bm = APetaPoco.PpRetrieveOne <User>("Users", "[refresh_token] = '" + refreshToken + "'");
         if (bm.Success)
         {
             var user = (User)bm.Data;
             user.access_token  = tokenResp.access_token;
             user.refresh_token = tokenResp.refresh_token;
             user.expiry_date   = DateTime.Now.AddSeconds(tokenResp.expires_in - 10);
             bm = APetaPoco.PpUpdate(user);
             if (!bm.Success)
             {
                 throw new Exception("Unable to update user details with new token");
             }
         }
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
         LOG.InsertEvent(errorString, "API", ex.Message, caseid);
     }
     finally { GC.Collect(); }
 }
Beispiel #11
0
        public void Pan(Point2D pan)
        {
#if DEBUG
            LOG.Write("Pan()");
#endif
            centro = centro - pan;
            RecalcSzWlorld();
            dl.IsUpdated = false;
        }
Beispiel #12
0
        public void Resize()
        {
#if DEBUG
            LOG.Write("Resize");
#endif
            szClient  = p.ClientSize;
            cenClient = new Point(szClient.Width / 2, szClient.Height / 2);
            RecalcSzWlorld();
            dl.IsUpdated = false;
        }
Beispiel #13
0
        public void Start()
        {
            LOG.Write("Radiopaedia Upload Agent");
            LOG.Write("Created by Andy Le of The Royal Melbourne Hospital");
            LOG.Write("Built: " + LOG.RetrieveLinkerTimestamp().ToString("dd MMMM yyyy | HH:mm:ss"));
            LOG.Write("Service Started");
            var sl = new ServiceLoop();

            System.Threading.Thread listenerCaller = new System.Threading.Thread(new System.Threading.ThreadStart(sl.StartHttp));
            listenerCaller.Start();
        }
Beispiel #14
0
    public void StartServer()
    {
        LOG.Write("Starting HTTP.");
        var server = new RESTServer();

        server.Start();

        while (server.IsListening)
        {
            System.Threading.Thread.Sleep(300);
        }
    }
Beispiel #15
0
        /// <summary>
        /// Svuota la Display List e la riduce
        /// </summary>
        public void Reset()
        {
            count = 0;
            indxList.Clear();
            if (com.Length > Def.FREE_MAX)
            {
                Array.Resize <Command>(ref com, Def.FREE_MAX);
#if (DEBUG)
                LOG.Write($"DisplayList.Command[{com.Length}]-");
#endif
            }
        }
Beispiel #16
0
        public void Zoom(double x)
        {
            if ((x > 0.05) && (x < 20))
            {
#if DEBUG
                LOG.Write("Zoom()");
#endif
                scalaXY = scalaXY * x;
                RecalcSzWlorld();
                dl.IsUpdated = false;
            }
        }
Beispiel #17
0
        static Multires()
        {
            int screenWidth = Screen.width;

            // list of common device screen resolutions (WxH):
            // 240x320(A), 240x400(A), 320x480(A), 360x640(A), 480x800/854(A), 540x960(A), 640x960/1136(i), 720x1280(A), 750x1334(i), 768x1024(i), 1080x1920(A/i), 1242x2208(i), 1440x2560(A), 1536x2048(i), 2048x2732(i)
            // multires kind is determined using screen width now, but this depends on app - for landscape apps change this code accordingly
            Assert.IsTrue(screenWidth < Screen.height);
            // use screen "dominant" dimension to determine multires kind
            Folder = screenWidth < 320 ? MultiresKind.Res256 : screenWidth < 540 ? MultiresKind.Res512 : MultiresKind.Res1024;
                        #if LOG_VERBOSE_MULTIRES
            LOG.Write("Multires.(static)ctor: MultiresFolder=" + Folder);
                        #endif
        }
Beispiel #18
0
        /// <summary>
        /// Imposta l'enumeratore degli elementi
        /// Genera un'eccezione se è null
        /// </summary>
        /// <param name="elementnumerator">IEnumerable<Elemento></param>
        public void SetElements(IEnumerable <Elemento> elementnumerator)
        {
            if (elementnumerator != null)
            {
#if (DEBUG)
                LOG.Write(@"SetElements()");
#endif
                elEnum = elementnumerator;
            }
            else
            {
                throw new Exception("L'enumeratore IEnumerable<Elemento> non può essere nullo");
            }
        }
Beispiel #19
0
        /// <summary>
        /// Ridisegna il contenuto della vista
        /// senza aggiornare la Display List
        /// Chiama DisplayList.Play(), che aggiorna gli elementi evidenziati
        /// </summary>
        public void Redraw(bool clear = true)
        {
#if (DEBUG)
            LOG.Write(@"Redraw()");
#endif
            g = p.CreateGraphics();
            if (clear)
            {
                g.Clear(Stile.BackgroundColor);
            }
            g.DrawRectangle(clrs.PEN[(int)Stile.Colore.Nodo], 1, 1, p.Width - 2, p.Height - 2); // Cornice
            grid.Draw(g, this, clrs.PEN[(int)Stile.Colore.Griglia]);
            DrawWorldAxes(g);                                                                   // Assi
            dl.Play(g, ref cursor, raggioSq, filter);                                           // Disegna la D.L.
            g.Dispose();
        }
Beispiel #20
0
 public void DoLoop()
 {
     while (true)
     {
         var list = ACASE.GetPendingCases();
         if (list != null)
         {
             foreach (var c in list)
             {
                 LOG.Write("Found new pending case: " + c.case_id);
                 ACASE.ProcessCase(c);
             }
         }
         System.Threading.Thread.Sleep(1 * 1000 * 60);
     }
 }
Beispiel #21
0
            public static void Take()
            {
                // try to use private methods to get game view size, sometimes Screen.width/height have wrong values
                // get type of "game" window
                Type gameViewType = typeof(UnityEditor.EditorWindow).Assembly.GetType("UnityEditor.GameView");

                Assert.IsNotNull(gameViewType);
                if (gameViewType == null)
                {
                                        #if LOG_ERROR
                    LOG.Write("ExtensionUNITY.Screenshot.Take: unable to get UnityEditor.GameView type");
                                        #endif
                    return;
                }
                // focus "game" window before trying to get view size
                EditorWindow.GetWindow(gameViewType).Focus();
                Vector2    gameViewSize;
                MethodInfo getSizeUsingPrivateMethod = gameViewType.GetMethod("GetSizeOfMainGameView", BindingFlags.NonPublic | BindingFlags.Static);
                if (getSizeUsingPrivateMethod != null)
                {
                    gameViewSize = (Vector2)getSizeUsingPrivateMethod.Invoke(null, null);
                }
                else
                {
                                        #if LOG_ERROR
                    LOG.Write("ExtensionUNITY.Screenshot.Take: unable to get GetSizeOfMainGameView method, fallback to GetMainGameViewTargetSize method");
                                        #endif
                    getSizeUsingPrivateMethod = gameViewType.GetMethod("GetMainGameViewTargetSize", BindingFlags.NonPublic | BindingFlags.Static);
                    if (getSizeUsingPrivateMethod != null)
                    {
                        gameViewSize = (Vector2)getSizeUsingPrivateMethod.Invoke(null, null);
                    }
                    else
                    {
                                                #if LOG_ERROR
                        LOG.Write("ExtensionUNITY.Screenshot.Take: unable to get GetMainGameViewTargetSize method, fallback to Screen.width and Screen.height");
                                                #endif
                        gameViewSize = new Vector2(Screen.width, Screen.height);
                    }
                }
#if LOG_VERBOSE
                Log.Write("ExtensionUNITY.Screenshot.Take: gameViewSize=" + gameViewSize.x + "," + gameViewSize.y + " Screen.width,height=" + Screen.width + "," + Screen.height);
                                #endif
                // create actual screenshot
                CaptureScreenDefault(gameViewSize);
            }
Beispiel #22
0
            /// <summary>Take screenshot using Unity API. Uses fileNameResolution only for fileName, screenshot is taken from Game's view with it's current resolution, regardless of fileNameResolution.</summary>
            private static void CaptureScreenDefault(Vector2 fileNameResolution)
            {
                try {
                    CreateScreenshotsFolderInNotExists();
                    string filePath = FilePath((int)fileNameResolution.x, (int)fileNameResolution.y);
                    ScreenCapture.CaptureScreenshot(filePath, 1);
#if LOG_VERBOSE
                    Log.Write("ExtensionUNITY.Screenshot.CaptureScreenDefault: screenshot saved in " + filePath);
                                        #endif
                } catch (Exception exception) {
#if LOG_ERROR
                    LOG.Write("ExtensionUNITY.Screenshot.CaptureScreenDefault: " + exception.ToString());
#endif
                    Log.Write(exception.ToString());
                    throw;
                }
            }
Beispiel #23
0
        /// <summary>
        /// Rigenera la DisplayList, se non è aggiornata.
        /// Ridisegna la vista, se richiesto
        /// Aggiorna l'enumeratore degli elementi, se presente
        /// </summary>
        /// <param name="redraw">true per ridisegnare la vista</param>
        /// <param name="elementEnumerator"></param>
        public void RegenDL(bool redraw, IEnumerable <Elemento> elementEnumerator = null)
        {
            if (elementEnumerator != null)
            {
                SetElements(elementEnumerator);
            }
            filter = Def.Shape.Tutti;
            dl.indxList.Clear();
            if (elEnum != null)
            {
#if (DEBUG)
                LOG.Write(@"RegenDL()");
                uint _debug_clipped = 0;
#endif
                if (!dl.IsUpdated)
                {
                    dl.Clear();
                    ClipElementi();

                    foreach (Elemento e in elEnum)
                    {
                        if (e.Clipped == Def.ClipFlag.Inside)
                        {
                            e.Regen(this);
                        }
                        else
                        {
#if (DEBUG)
                            _debug_clipped++;
#endif
                        }
                    }
                    dl.IsUpdated = true;
                }
#if (DEBUG)
                if (_debug_clipped > 0)
                {
                    LOG.Write(@"RegenDL(): eseguito clip su " + _debug_clipped.ToString() + " elementi");
                }
#endif
            }
            if (redraw)
            {
                Redraw();
            }
        }
Beispiel #24
0
            /// <summary>Take screenshot using RenderTexture and Camera. Uses size for both fileName and texture resolution.</summary>
            public static void CaptureScreenWithRenderingToTexture(Vector2 size)
            {
                int           width         = (int)size.x;
                int           height        = (int)size.y;
                RenderTexture renderTexture = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);

                // TODO: Customize anti-aliasing value. Anti-aliasing value must be one of (1, 2, 4 or 8), indicating the number of samples per pixel.
                renderTexture.antiAliasing = 4;
                RenderTexture activePreviously = RenderTexture.active;

                RenderTexture.active = renderTexture;
                Camera        cam    = Camera.main;
                RenderTexture target = cam.targetTexture;

                cam.targetTexture = renderTexture;
                cam.Render();
                Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);

                // Read screen contents into the texture
                tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
                tex.Apply();
                // Encode texture into PNG
                var bytes = tex.EncodeToPNG();

                try {
                    CreateScreenshotsFolderInNotExists();
                    string filePath = FilePath(width, height);
                    File.WriteAllBytes(filePath, bytes);
#if LOG_VERBOSE
                    Log.Write("ExtensionUNITY.Screenshot.CaptureScreenWithRenderingToTexture: screenshot saved in " + filePath);
                                        #endif
                } catch (System.Exception exception) {
#if LOG_ERROR
                    LOG.Write("ExtensionUNITY.Screenshot.CaptureScreenWithRenderingToTexture: " + exception.ToString());
#endif
                    Log.Write(exception.ToString());
                    throw;
                }
                RenderTexture.active = activePreviously;
                cam.targetTexture    = target;
                UnityEngine.Object.DestroyImmediate(tex);
                UnityEngine.Object.DestroyImmediate(renderTexture);
            }
Beispiel #25
0
        public readonly List <int> indxList;        // Lista indici evidenziati nell'ultimo Play()

        /// <summary>
        /// Costruttore
        /// </summary>
        public DisplayList(Vista v)
        {
            vista    = v;
            indxList = new List <int>();                    // Crea la lista degli indici

            /*
             * brush = new Brush[]
             *      {
             *      new SolidBrush(Def.ColourSelected),			// Selected
             *      new SolidBrush(Def.ColourHighlighed),		// Highlighted
             *      new SolidBrush(Def.ColourNodo),				// Nodi
             *      new SolidBrush(Def.ColourRamo),				// Rami
             *      new SolidBrush(Color.Green),
             *      new SolidBrush(Color.Blue),
             *      new SolidBrush(Def.ColourBackground)
             *      };
             * pen = new Pen[]
             *      {
             *      new Pen(Def.ColourSelected, 1),				// Come sopra
             *      new Pen(Def.ColourHighlighed, 1),
             *      new Pen(Def.ColourNodo, 1),
             *      new Pen(Def.ColourRamo, 1),
             *      new Pen(Color.Green, 1),
             *      new Pen(Color.Blue, 1),
             *      new Pen(Def.ColourBackground)
             *      };
             * font = new Font[]
             *      {
             *      new Font(Def.FONT_NAME, Def.FONT_SIZE)
             *      };
             *
             * if(pen.Length != Enum.GetNames(typeof(Def.Colori)).Length)
             *      throw new Exception("Pen array and Color enum do not match");
             * if(brush.Length != Enum.GetNames(typeof(Def.Colori)).Length)
             *      throw new Exception("Brush array and Color enum do not match");
             */

            com = new Command[Def.FREE_MAX];                            // Array
#if (DEBUG)
            LOG.Write($"DisplayList.Command[{com.Length}]");
#endif
            count = 0;
        }
Beispiel #26
0
        /// <summary>
        /// Aggiunge un elemento alla Display List
        /// Ridimensiona array se necessario
        /// </summary>
        /// <param name="shape">Forma</param>
        /// <param name="colour">Colore</param>
        /// <param name="x1">Primo punto: X...</param>
        /// <param name="y1">...e Y</param>
        /// <param name="x2">Secondo punto: X...</param>
        /// <param name="y2">...e Y</param>
        public void Add(Elemento element, Def.Shape shape, int cx, int cy)
        {
            com[count].elemento = element;
            com[count].shape    = shape;
            //com[count].colour = colour;
            com[count].center.X = cx;
            com[count].center.Y = cy;
            if (element != null)
            {
                count++;                                // Aggiunge all'array solo le l'elemento non è nullo
            }
            if (com.Length - count < Def.FREE_MIN)
            {
                Array.Resize <Command>(ref com, count + Def.FREE_MAX);
#if (DEBUG)
                LOG.Write($"DisplayList.Command[{com.Length}]+");
#endif
            }
            return;
        }
Beispiel #27
0
 public static bool ZipSeries(DbStudy study)
 {
     try
     {
         string scpPath    = ADCM.GetStoreString();
         string outputPath = Path.Combine(scpPath, "OUTPUT", study.case_id, study.study_uid);
         if (!Directory.Exists(outputPath))
         {
             throw new Exception("Output path not found: " + outputPath);
         }
         var seriesPaths = Directory.GetDirectories(outputPath);
         foreach (var s in seriesPaths)
         {
             //ReorderImages(s);
             var    seriesUID = s.Substring(s.LastIndexOf(Path.DirectorySeparatorChar) + 1);
             string zipPath   = Path.Combine(outputPath, seriesUID + ".zip");
             using (ZipFile zip = new ZipFile())
             {
                 zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                 zip.AddDirectory(s);
                 zip.Save(zipPath);
             }
             FileInfo zipInfo   = new FileInfo(zipPath);
             double   megabytes = Math.Round((zipInfo.Length / 1024f) / 1024f, 2);
             LOG.Write("Zip created: " + zipInfo.Name + ", " + megabytes + " MB");
             LOG.InsertEvent("Zip created: " + zipInfo.Name + " - " + megabytes + "MB", "IMG", null, study.case_id, study.study_uid, seriesUID);
             System.Threading.Thread.Sleep(500);
         }
         LOG.InsertEvent("Successfully created ZIP files for all series in study", "IMG", null, study.case_id, study.study_uid);
         return(true);
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
         LOG.InsertEvent(errorString, "IMG", ex.Message, study.case_id, study.study_uid);
         return(false);
     }
 }
Beispiel #28
0
    public static bool DownloadOneSeries(string studyuid, string seriesuid, int retryCount = 0)
    {
        var node   = GetSelectedNode();
        var cstore = new DicomSCP(node.LocalAe, 104);

        try
        {
            LOG.Write("Retry Count: " + retryCount);

            StudyRootFindScu findScu      = new StudyRootFindScu();
            SeriesQueryIod   queryMessage = new SeriesQueryIod();
            queryMessage.SetCommonTags();
            queryMessage.StudyInstanceUid  = studyuid;
            queryMessage.SeriesInstanceUid = seriesuid;
            IList <SeriesQueryIod> results = findScu.Find(node.LocalAe, node.AET, node.IP, node.Port, queryMessage);
            if (results.Count != 1)
            {
                throw new Exception(string.Format("Unable to query study on PACS: [{0}]", studyuid));
            }

            int expectedFiles = (int)results[0].NumberOfSeriesRelatedInstances;

            if (!System.IO.Directory.Exists(node.LocalStorage))
            {
                System.IO.Directory.CreateDirectory(node.LocalStorage);
            }
            cstore.Start();
            while (!cstore.IsRunning)
            {
                System.Threading.Thread.Sleep(1000);
            }

            MoveScuBase moveScu = new StudyRootMoveScu(node.LocalAe, node.AET, node.IP, node.Port, node.LocalAe);
            moveScu.ReadTimeout  = 600000;
            moveScu.WriteTimeout = 600000;
            moveScu.AddStudyInstanceUid(studyuid);
            moveScu.AddSeriesInstanceUid(seriesuid);

            DateTime started = DateTime.Now;

            moveScu.Move();
            System.Threading.Thread.Sleep(2000);
            if (moveScu.Status == ScuOperationStatus.AssociationRejected || moveScu.Status == ScuOperationStatus.Canceled ||
                moveScu.Status == ScuOperationStatus.ConnectFailed || moveScu.Status == ScuOperationStatus.Failed ||
                moveScu.Status == ScuOperationStatus.NetworkError || moveScu.Status == ScuOperationStatus.TimeoutExpired ||
                moveScu.Status == ScuOperationStatus.UnexpectedMessage || moveScu.FailureSubOperations != 0)
            {
                if (retryCount > 4)
                {
                    throw new Exception(string.Format("Failed moving study [{0}] | Status : {1} | Failed Operations: {2}", studyuid, moveScu.Status, moveScu.FailureSubOperations));
                }
                retryCount += 1;
                if (cstore.IsRunning)
                {
                    cstore.Stop();
                }
                DownloadOneSeries(studyuid, seriesuid, retryCount);
            }

            string downloadFolder = GetStoreString();
            downloadFolder = Path.Combine(downloadFolder, studyuid, seriesuid);
            bool direxist = Directory.Exists(downloadFolder);
            while (!direxist)
            {
                if ((DateTime.Now - started).TotalMinutes > 3)
                {
                    if (cstore.IsRunning)
                    {
                        cstore.Stop();
                    }
                    throw new Exception("Waited too long for images to come in");
                }
                //LOG.Write("Waiting for images to come in...");
                System.Threading.Thread.Sleep(1 * 1000);
                direxist = Directory.Exists(downloadFolder);
            }

            var dcmfiles = Directory.GetFiles(downloadFolder, "*.dcm");
            var dcmCount = dcmfiles.Length;
            while (dcmCount < expectedFiles)
            {
                if ((DateTime.Now - started).TotalMinutes > 3)
                {
                    if (cstore.IsRunning)
                    {
                        cstore.Stop();
                    }
                    throw new Exception("Waited too long for images to come in");
                }
                //LOG.Write("Waiting for images to come in...");
                System.Threading.Thread.Sleep(1 * 1000);
                dcmfiles = Directory.GetFiles(downloadFolder, "*.dcm");
                if (dcmfiles.Length != dcmCount)
                {
                    if (dcmfiles.Length >= expectedFiles)
                    {
                        break;
                    }
                    dcmCount = dcmfiles.Length;
                    started  = DateTime.Now;
                }
            }

            if (cstore.IsRunning)
            {
                cstore.Stop();
            }
            LOG.Write("Series successfully downloaded from PACS");
            return(true);
        }
        catch (Exception ex)
        {
            if (cstore.IsRunning)
            {
                cstore.Stop();
            }
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            return(false);
        }
    }
Beispiel #29
0
    public static bool DownloadStudy(DbStudy study, int retryCount = 0)
    {
        foreach (var se in study.series)
        {
            bool success = DownloadOneSeries(study.study_uid, se.series_uid);
            if (!success)
            {
                return(false);
            }
        }
        return(true);

        //LOG.Write(string.Format("Downloading study [{0}] - {1} ({2})", study.modality, study.description, study.images));
        //LOG.Write("Retry Count: " + retryCount);
        //var node = GetSelectedNode();
        //var cstore = new DicomSCP(node.LocalAe, 104);

        //StudyRootFindScu findScu = new StudyRootFindScu();
        //StudyQueryIod queryMessage = new StudyQueryIod();
        //queryMessage.SetCommonTags();
        //queryMessage.StudyInstanceUid = study.study_uid;
        //IList<StudyQueryIod> results = findScu.Find(node.LocalAe, node.AET, node.IP, node.Port, queryMessage);
        //if (results.Count != 1)
        //    throw new Exception(string.Format("Unable to query study on PACS: [{0}]", study.study_uid));

        //if (!System.IO.Directory.Exists(node.LocalStorage))
        //    System.IO.Directory.CreateDirectory(node.LocalStorage);
        //cstore.Start();
        //while (!cstore.IsRunning)
        //    System.Threading.Thread.Sleep(1000);
        //string singleSeriesOnly = System.Configuration.ConfigurationManager.AppSettings["singleSeries"];

        //MoveScuBase moveScu = new StudyRootMoveScu(node.LocalAe, node.AET, node.IP, node.Port, node.LocalAe);
        //moveScu.ReadTimeout = 600000;
        //moveScu.WriteTimeout = 600000;
        //moveScu.AddStudyInstanceUid(study.study_uid);
        //foreach (var se in study.series)
        //{
        //    moveScu.AddSeriesInstanceUid(se.series_uid);
        //    System.Diagnostics.Debug.WriteLine(se.series_uid);
        //}
        //moveScu.Move();
        //System.Threading.Thread.Sleep(2000);
        //if (moveScu.Status == ScuOperationStatus.AssociationRejected || moveScu.Status == ScuOperationStatus.Canceled ||
        //    moveScu.Status == ScuOperationStatus.ConnectFailed || moveScu.Status == ScuOperationStatus.Failed ||
        //    moveScu.Status == ScuOperationStatus.NetworkError || moveScu.Status == ScuOperationStatus.TimeoutExpired ||
        //    moveScu.Status == ScuOperationStatus.UnexpectedMessage || moveScu.FailureSubOperations != 0)
        //{
        //    if (retryCount > 4)
        //        throw new Exception(string.Format("Failed moving study [{0}] | Status : {1} | Failed Operations: {2}", study.study_uid, moveScu.Status, moveScu.FailureSubOperations));
        //    retryCount += 1;
        //    if (cstore.IsRunning)
        //        cstore.Stop();
        //    DownloadStudy(study, retryCount);
        //}
        //else
        //{
        //    System.Threading.Thread.Sleep(2000);
        //    cstore.Stop();
        //}
        //if (cstore.IsRunning)
        //    cstore.Stop();
        //LOG.InsertEvent("Successfully downloaded study: " + study.description, "DICOM", null, study.case_id, study.study_uid);
        //return true;

        try
        {
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "DICOM", ex.Message, study.case_id, study.study_uid);
            return(false);
        }
    }
Beispiel #30
0
    public void HandleAllGetRequests(HttpListenerContext context)
    {
        var    rc        = new ResponseClass();
        string studyuid  = context.Request.QueryString["studyuid"];
        string seriesuid = context.Request.QueryString["seriesuid"];
        string check     = context.Request.QueryString["check"];

        if (!string.IsNullOrEmpty(check))
        {
            rc.Success = true;
            rc.Message = "";
            rc.Data    = true;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(rc);
            this.SendTextResponse(context, json);
            return;
        }
        var node = ADCM.GetSelectedNode();

        try
        {
            LOG.Write("New request");
            if (string.IsNullOrEmpty(studyuid) || string.IsNullOrEmpty(seriesuid))
            {
                throw new Exception("No studyuid or seriesuid provided");
            }
            bool downloaded = ADCM.DownloadOneSeries(studyuid, seriesuid);
            if (!downloaded)
            {
                throw new Exception("Unable to download study");
            }
            string seriesPath = Path.Combine(node.LocalStorage, studyuid, seriesuid);
            if (!Directory.Exists(seriesPath))
            {
                throw new Exception("Series path not found: " + seriesPath);
            }
            var     dcmFiles  = Directory.GetFiles(seriesPath, "*.dcm");
            string  filetouse = null;
            decimal mid       = dcmFiles.Length / 2;
            int     index     = (int)Math.Ceiling(mid);
            for (int i = index; i < dcmFiles.Length; i++)
            {
                var dcm = dcmFiles[i];
                ClearCanvas.Dicom.DicomFile dcmFile = new ClearCanvas.Dicom.DicomFile(dcm);
                dcmFile.Load();
                ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource localds = new ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource(dcmFile);
                if (!localds.IsImage)
                {
                    continue;
                }
                else
                {
                    filetouse = dcm;
                    break;
                }
            }
            if (string.IsNullOrEmpty(filetouse))
            {
                for (int i = 0; i < dcmFiles.Length; i++)
                {
                    var dcm = dcmFiles[i];
                    ClearCanvas.Dicom.DicomFile dcmFile = new ClearCanvas.Dicom.DicomFile(dcm);
                    dcmFile.Load();
                    ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource localds = new ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource(dcmFile);
                    if (!localds.IsImage)
                    {
                        continue;
                    }
                    else
                    {
                        filetouse = dcm;
                        break;
                    }
                }
            }
            if (string.IsNullOrEmpty(filetouse))
            {
                throw new Exception("Unable to find image in downloaded DICOM files");
            }
            if (!File.Exists(filetouse))
            {
                throw new Exception("Unable to find DICOM file to use");
            }

            string base64String = Convert.ToBase64String(AIMG.GetImageBytesFromDcm(filetouse));
            base64String = "data:image/jpeg;base64," + base64String;
            rc.Success   = true;
            rc.Message   = "";
            rc.Data      = base64String;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(rc);
            this.SendTextResponse(context, json);
        }
        catch (Exception ex)
        {
            LOG.Write("ERROR: " + ex.Message);
            rc.Data    = null;
            rc.Success = false;
            rc.Message = ex.Message;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(rc);
            this.SendTextResponse(context, json);
        }
        finally
        {
            string studypath = Path.Combine(node.LocalStorage, studyuid);
            if (Directory.Exists(studypath))
            {
                Directory.Delete(studypath, true);
            }
        }
    }