Ejemplo n.º 1
0
        public MisskeyClient(Credential credential, HttpClientHandler innerHandler = null) : base(credential, new MisskeyAuthenticationHandler(innerHandler), RequestMode.Json)
        {
            BinaryParameters = new List <string> {
                "file"
            };

            Aggregation   = new AggregationClient(this);
            Ap            = new ApClient(this);
            Admin         = new AdminClient(this);
            App           = new MisskeyAppClient(this);
            Auth          = new AuthClient(this);
            Blocking      = new BlockingClient(this);
            Charts        = new ChartsClient(this);
            Drive         = new DriveClient(this);
            Federation    = new FederationClient(this);
            Following     = new FollowingClient(this);
            Hashtags      = new HashtagsClient(this);
            I             = new IClient(this);
            Messaging     = new MessagingClient(this);
            Mute          = new MuteClient(this);
            My            = new MyClient(this);
            Notes         = new NotesClient(this);
            Notifications = new NotificationsClient(this);
            Streaming     = new StreamingClient(this);
            Username      = new UsernameClient(this);
            Users         = new UsersClient(this);
        }
Ejemplo n.º 2
0
        public MastodonClient(string domain) : base($"https://{domain}", AuthMode.OAuth2, RequestMode.FormUrlEncoded)
        {
            Domain           = domain;
            BinaryParameters = new List <string> {
                "avatar", "header", "file"
            };

            Account        = new AccountsClient(this);
            Apps           = new AppsClient(this);
            Auth           = new AuthClient(this);
            Blocks         = new BlocksClient(this);
            CustomEmojis   = new CustomEmojisClient(this);
            DomainBlocks   = new DomainBlocksClient(this);
            Endorsements   = new EndorsementsClient(this);
            Favorites      = new FavoritesClient(this);
            Filters        = new FiltersClient(this);
            FollowRequests = new FollowRequestsClient(this);
            Follows        = new FollowsClient(this);
            Instance       = new InstanceClient(this);
            Lists          = new ListsClient(this);
            Media          = new MediaClient(this);
            Notifications  = new NotificationsClient(this);
            Push           = new PushClient(this);
            Reports        = new ReportsClient(this);
            SearchV1       = new SearchV1Client(this);
            SearchV2       = new SearchV2Client(this);
            Statuses       = new StatusesClient(this);
            Streaming      = new StreamingClient(this);
            Suggestions    = new SuggestionsClient(this);
            Timelines      = new TimelinesClient(this);
        }
Ejemplo n.º 3
0
        public MastodonClient(Credential credential, HttpClientHandler innerHandler = null) : base(credential, new OAuth2HttpClientHandler(innerHandler), RequestMode.FormUrlEncoded)
        {
            BinaryParameters = new List <string> {
                "avatar", "header", "file"
            };

            Account           = new AccountsClient(this);
            Apps              = new AppsClient(this);
            Auth              = new AuthClient(this);
            Blocks            = new BlocksClient(this);
            Conversations     = new ConversationsClient(this);
            CustomEmojis      = new CustomEmojisClient(this);
            DomainBlocks      = new DomainBlocksClient(this);
            Endorsements      = new EndorsementsClient(this);
            Favorites         = new FavoritesClient(this);
            Filters           = new FiltersClient(this);
            FollowRequests    = new FollowRequestsClient(this);
            Follows           = new FollowsClient(this);
            Instance          = new InstanceClient(this);
            Lists             = new ListsClient(this);
            Media             = new MediaClient(this);
            Notifications     = new NotificationsClient(this);
            Push              = new PushClient(this);
            Reports           = new ReportsClient(this);
            ScheduledStatuses = new ScheduledStatusesClient(this);
            SearchV1          = new SearchV1Client(this);
            SearchV2          = new SearchV2Client(this);
            Statuses          = new StatusesClient(this);
            Streaming         = new StreamingClient(this);
            Suggestions       = new SuggestionsClient(this);
            Timelines         = new TimelinesClient(this);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Closes the stream
        /// </summary>
        public void CloseStream()
        {
            IsStreamClosed = true;

            if (StreamingClient != null)
                StreamingClient.CancelPendingRequests();
        }
Ejemplo n.º 5
0
        void listener_MessageReceived(object sender, StreamingClient.MessageEventArgs<CIAPI.DTO.PriceDTO> e)
        {

            Dispatcher.BeginInvoke(() =>
            {
                listBox1.Items.Add(e.Data.MarketId);
            });
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Closes the stream
        /// </summary>
        public void CloseStream()
        {
            IsStreamClosed = true;

            if (StreamingClient != null)
            {
                StreamingClient.Dispose();
            }
        }
Ejemplo n.º 7
0
        private void RestartPriceListener(params int[] markets)
        {
            if (_pricesListener != null)
            {
                KillPriceListener();
            }

            _pricesListener = StreamingClient.BuildPricesListener(markets);
            _pricesListener.MessageReceived += (PricesListenerMessageReceived);
        }
Ejemplo n.º 8
0
        public void HandleResponse(RpcStreamingResponseMessage rpcStreamingResponse)
        {
            lock (_lockingObject)
            {
                if (rpcStreamingResponse.Method == null)
                {
                    if (rpcStreamingResponse.Id.ToString() == SubscribeRequestId.ToString())
                    {
                        if (rpcStreamingResponse.HasError)
                        {
                            HandleSubscribeResponseError(GetException(rpcStreamingResponse));
                        }
                        else
                        {
                            var result = rpcStreamingResponse.GetStreamingResult <string>();
                            this.SubscriptionState = SubscriptionState.Subscribed;
                            this.SubscriptionId    = result;
                            StreamingClient.AddSubscription(SubscriptionId, this);
                            HandleSubscribeResponse(result);
                        }
                    }

                    if (!string.IsNullOrEmpty(UnsubscribeRequestId) && rpcStreamingResponse.Id.ToString() == UnsubscribeRequestId)
                    {
                        if (rpcStreamingResponse.HasError)
                        {
                            HandleUnsubscribeResponseError(GetException(rpcStreamingResponse));
                        }
                        else
                        {
                            var result = rpcStreamingResponse.GetStreamingResult <bool>();
                            if (result)
                            {
                                this.SubscriptionState = SubscriptionState.Unsubscribed;
                                StreamingClient.RemoveSubscription(SubscriptionId);
                            }
                            HandleUnsubscribeResponse(result);
                        }
                    }
                }
                else
                {
                    if (rpcStreamingResponse.HasError)
                    {
                        HandleDataResponseError(GetException(rpcStreamingResponse));
                    }
                    else
                    {
                        var result = rpcStreamingResponse.GetStreamingResult <TSubscriptionDataResponse>();
                        HandleDataResponse(result);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        // only listening to one news topic at a time. right now options are US, UK and ALL.

        public void SetNewsTopic(string topic)
        {
            if (_newsListener != null)
            {
                _newsListener.MessageReceived -= NewsListenerMessageReceived;
                _newsListener.Stop();
                _newsListener = null;
            }

            _newsListener = StreamingClient.BuildNewsHeadlinesListener(topic);
            _newsListener.MessageReceived += NewsListenerMessageReceived;
        }
Ejemplo n.º 10
0
        protected Task SubscribeAsync(RpcRequest rpcRequest)
        {
            if (SubscriptionState != SubscriptionState.Idle)
            {
                throw new Exception("Invalid state to start subscription, current state: " + SubscriptionState.ToString());
            }

            SubscribeRequestId = rpcRequest.Id;

            this.SubscriptionState = SubscriptionState.Subscribing;

            return(StreamingClient.SendRequestAsync(rpcRequest, this));
        }
Ejemplo n.º 11
0
 public IFramePixelData LoadFramePixelData(LoadFramePixelDataArgs args)
 {
     try
     {
         var client = new StreamingClient(_wadoUri);
         var result = client.RetrievePixelData(_aeTitle, args.StudyInstanceUid, args.SeriesInstanceUid, args.SopInstanceUid, args.FrameNumber - 1);
         return(new ImageServerFramePixelData(result));
     }
     catch (Exception e)
     {
         throw TranslateStreamingException(e);
     }
 }
 public IFramePixelData LoadFramePixelData(LoadFramePixelDataArgs args)
 {
     try
     {
         var uri    = new Uri(string.Format(StreamingSettings.Default.FormatWadoUriPrefix, _hostName, _wadoServicePort));
         var client = new StreamingClient(uri);
         var result = client.RetrievePixelData(_aeTitle, args.StudyInstanceUid, args.SeriesInstanceUid, args.SopInstanceUid, args.FrameNumber - 1);
         return(new ImageServerFramePixelData(result));
     }
     catch (Exception e)
     {
         throw TranslateStreamingException(e);
     }
 }
Ejemplo n.º 13
0
        public Task UnsubscribeAsync()
        {
            if (SubscriptionState != SubscriptionState.Subscribed && SubscriptionState != SubscriptionState.Unsubscribed) //allow retrying? what happens when it returns false the unsubscription
            {
                throw new Exception("Invalid state to unsubscribe, current state: " + SubscriptionState.ToString());
            }

            UnsubscribeRequestId = Guid.NewGuid().ToString();
            var request = UnsubscribeSubscriptionRpcRequestBuilder.BuildRequest(SubscriptionId, UnsubscribeRequestId);

            this.SubscriptionState = SubscriptionState.Unsubscribing;

            return(StreamingClient.SendRequestAsync(request, this));
        }
Ejemplo n.º 14
0
        public DicomFile LoadDicomFile(LoadDicomFileArgs args)
        {
            try
            {
                var client = new StreamingClient(_wadoUri);
                var file   = new DicomFile();
                using (var stream = client.RetrieveImageHeader(_aeTitle, args.StudyInstanceUid, args.SeriesInstanceUid, args.SopInstanceUid))
                {
                    file.Load(stream);
                }

                return(file);
            }
            catch (Exception e)
            {
                throw TranslateStreamingException(e);
            }
        }
        public DicomFile LoadDicomFile(LoadDicomFileArgs args)
        {
            try
            {
                Uri uri    = new Uri(string.Format(StreamingSettings.Default.FormatWadoUriPrefix, _hostName, _wadoServicePort));
                var client = new StreamingClient(uri);
                var file   = new DicomFile();
                using (var stream = client.RetrieveImageHeader(_aeTitle, args.StudyInstanceUid, args.SeriesInstanceUid, args.SopInstanceUid))
                {
                    file.Load(stream);
                }

                return(file);
            }
            catch (Exception e)
            {
                throw TranslateStreamingException(e);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates a new instance of the <see cref="NestClient"/>.
        /// </summary>
        public NestClient(RestConfig restConfig)
        {
            var messageParser = new MessageParser(new ObjectModelMapper(notifier));

            var httpClient          = new HttpClient();
            var streamingHttpClient = new HttpClient(new HttpClientHandler {
                AllowAutoRedirect = true, MaxAutomaticRedirections = 10,
            }, true);

            //.connectTimeout(10, TimeUnit.SECONDS)
            streamingHttpClient.Timeout = TimeSpan.FromSeconds(60);//.readTimeout(60, TimeUnit.SECONDS)

            restClient      = new RestClient(httpClient, restConfig.GetUrl(), messageParser);
            streamingClient = new RestStreamClient(streamingHttpClient, restConfig, messageParser,
                                                   exceptionHandler: exception => { StreamingError?.Invoke(exception); });

            cameras     = new CameraSetter(restClient);
            structures  = new StructureSetter(restClient);
            thermostats = new ThermostatSetter(restClient);
        }
Ejemplo n.º 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                Thread t = new Thread(delegate(object parm)
                {
                    StreamingClient client =
                        new StreamingClient(new Uri("http://localhost:1000/wado"));
                    do
                    {
                        Stream image = client.RetrieveImage("ImageServer",
                                                            "1.2.840.113619.2.5.1762583153.215519.978957063.78",
                                                            "1.2.840.113619.2.5.1762583153.215519.978957063.79",
                                                            "1.2.840.113619.2.5.1762583153.215519.978957063.89"
                                                            );
                    } while (true);
                });

                t.Start();
            }
        }
Ejemplo n.º 18
0
        public void CanServe()
        {
            ConsoleLogger logger = new ConsoleLogger {
                AddDetails = false
            };
            Encoding encoding = Encoding.UTF8;
            int      port     = RandomNumber.Between(8081, 65535);

            logger.StartLoggingThread();
            TestBinaryServer server = new TestBinaryServer(logger, port);

            server.Start();

            StreamingClient   client   = new StreamingClient("localhost", port);
            StreamingResponse response = client.SendWrappedMessage((object)"this is a test");

            Console.WriteLine("Response: " + response.Body);
            response = client.SendWrappedMessage((object)"second message");
            Console.WriteLine("Second resposne: " + response.Body);
            Thread.Sleep(1000);
        }
Ejemplo n.º 19
0
 static void newsStream_MessageReceived(object sender, StreamingClient.MessageEventArgs<CIAPI.DTO.NewsDTO> e)
 {
     Console.WriteLine(e.Data.Headline);
 }
Ejemplo n.º 20
0
 public PleromaClient(Credential credential, HttpClientHandler innerHandler = null) : base(credential, innerHandler)
 {
     Pleroma   = new PleromaApi(this);
     Streaming = new StreamingClient(this);
 }
Ejemplo n.º 21
0
 public DownloadController(StreamingClient client)
 {
     _client = client;
 }
Ejemplo n.º 22
0
 public PleromaClient(string domain) : base(domain)
 {
     Pleroma   = new PleromaApi(this);
     Streaming = new StreamingClient(this);
 }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            //get server details from args
            _cmdLine = new TestStreamingClientCommandLine();
            try
            {
                _cmdLine.Parse(args);

                //perform query for studies; maybe optional search parameters in xml?

                _studies = new List <StudyInfo>();

                Console.WriteLine("Querying for study list from AE: {0} (Host: {1} / Port: {2})", _cmdLine.AeTitle, _cmdLine.Host, _cmdLine.DicomServicePort);

                CFindSCU cfind = new CFindSCU();
                cfind.AETitle           = "TESTSTREAM";
                cfind.OnResultReceive  += new CFindSCU.ResultReceivedHandler(cfind_OnResultReceive);
                cfind.OnQueryCompleted += new CFindSCU.QueryCompletedHandler(cfind_OnQueryCompleted);
                cfind.Query(_cmdLine.AeTitle, _cmdLine.Host, _cmdLine.DicomServicePort);
                _waitHandle.WaitOne();

                if (_studies != null && _studies.Count > 0)
                {
                    foreach (StudyInfo s in _studies)
                    {
                        //iterate through in thread:
                        //  fetching header
                        //  fetching each sop
                        //  log after each sop

                        Console.WriteLine("Retrieving header for Study: {0}", s.StudyUid);
                        XmlDocument doc = RetrieveHeaderXml(s.StudyUid);

                        Uri             uri    = new Uri(String.Format("http://{0}:{1}/WADO", _cmdLine.Host, _cmdLine.WadoServicePort));
                        StreamingClient client = new StreamingClient(uri);
                        byte[]          pixelData;

                        Console.WriteLine("Streaming images for Study: {0}", s.StudyUid);
                        StudyXml studyXml = new StudyXml(s.StudyUid);
                        studyXml.SetMemento(doc);

                        foreach (SeriesXml seriesXml in studyXml)
                        {
                            foreach (InstanceXml instanceXml in seriesXml)
                            {
                                pixelData = client.RetrievePixelData(
                                    _cmdLine.AeTitle,
                                    s.StudyUid,
                                    seriesXml.SeriesInstanceUid,
                                    instanceXml.SopInstanceUid,
                                    0).GetPixelData();
                            }
                        }
                    }
                }
            }
            catch (CommandLineException e)
            {
                Console.WriteLine(e.Message);
                _cmdLine.PrintUsage(Console.Out);
            }
        }
Ejemplo n.º 24
0
        void client_StatusUpdate(object sender, StreamingClient.ConnectionStatusEventArgs e)
        {

        }
Ejemplo n.º 25
0
        public void GetStudy(string studyInstanceUid, Uri baseUri, string serverAE, bool singleImage)
        {
            Console.WriteLine("[{0}] : Loading {1}", _id, studyInstanceUid);
            string           uri      = String.Format("http://{0}:{1}/HeaderStreaming/HeaderStreaming", "localhost", 50221);
            EndpointAddress  endpoint = new EndpointAddress(uri);
            BasicHttpBinding binding  = new BasicHttpBinding(BasicHttpSecurityMode.None);

            binding.TransferMode           = TransferMode.Streamed;
            binding.MessageEncoding        = WSMessageEncoding.Mtom;
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.TextEncoding           = Encoding.UTF8;

            HeaderStreamingServiceClient headerClient = new HeaderStreamingServiceClient(binding, endpoint);

            using (headerClient)
            {
                HeaderStreamingParameters parms = new HeaderStreamingParameters();
                parms.StudyInstanceUID = studyInstanceUid;
                parms.ReferenceID      = Guid.NewGuid().ToString();
                parms.ServerAETitle    = "ImageServer";
                Stream stream = headerClient.GetStudyHeader("TEST", parms);

                XmlDocument doc = new XmlDocument();
                StudyXmlIo.ReadGzip(doc, stream);
                _studyXml = new StudyXml(studyInstanceUid);
                _studyXml.SetMemento(doc);
                stream.Close();
                headerClient.Close();
            }

            if (singleImage)
            {
                ulong           size   = 0;
                StreamingClient client = new StreamingClient(baseUri);
                foreach (SeriesXml series in _studyXml)
                {
                    foreach (InstanceXml instance in series)
                    {
                        do
                        {
                            Stream image =
                                client.RetrieveImage(serverAE, studyInstanceUid, series.SeriesInstanceUid,
                                                     instance.SopInstanceUid);
                            byte[] buffer = new byte[image.Length];
                            image.Read(buffer, 0, buffer.Length);
                            image.Close();
                            Console.Write(".");
                        } while (true);
                    }

                    Console.WriteLine("\n[{0}] : Finish Loading {1} [{2}]", _id, studyInstanceUid,
                                      ByteCountFormatter.Format(size));
                }
            }
            else
            {
                Random ran = new Random();
                do
                {
                    ulong           size   = 0;
                    StreamingClient client = new StreamingClient(baseUri);
                    foreach (SeriesXml series in _studyXml)
                    {
                        foreach (InstanceXml instance in series)
                        {
                            Stream image =
                                client.RetrieveImage(serverAE, studyInstanceUid, series.SeriesInstanceUid,
                                                     instance.SopInstanceUid);

                            byte[] buffer = new byte[image.Length];
                            image.Read(buffer, 0, buffer.Length);
                            image.Close();
                            size += (ulong)buffer.Length;
                            Console.Write(".");
                        }

                        Console.WriteLine("\n[{0}] : Finish Loading {1} [{2}]", _id, studyInstanceUid,
                                          ByteCountFormatter.Format(size));
                    }

                    Thread.Sleep(ran.Next(1000, 5000));
                } while (true);
            }
        }
Ejemplo n.º 26
0
        private static void RetrieveImages(string serverAE, string studyPath)
        {
            Console.WriteLine("server={0}", serverAE);
            string          baseUri         = String.Format("http://{0}:{1}", serverHost, serverPort);
            StreamingClient client          = new StreamingClient(new Uri(baseUri));
            int             totalFrameCount = 0;

            DirectoryInfo directoryInfo = new DirectoryInfo(studyPath);
            string        studyUid      = directoryInfo.Name;

            RateStatistics        frameRate    = new RateStatistics("Speed", "frame");
            RateStatistics        speed        = new RateStatistics("Speed", RateType.BYTES);
            AverageRateStatistics averageSpeed = new AverageRateStatistics(RateType.BYTES);
            ByteCountStatistics   totalSize    = new ByteCountStatistics("Size");

            frameRate.Start();
            speed.Start();

            Console.WriteLine("\n------------------------------------------------------------------------------------------------------------------------");

            string[] seriesDirs = Directory.GetDirectories(studyPath);
            foreach (string seriesPath in seriesDirs)
            {
                DirectoryInfo dirInfo       = new DirectoryInfo(seriesPath);
                string        seriesUid     = dirInfo.Name;
                string[]      objectUidPath = Directory.GetFiles(seriesPath, "*.dcm");

                foreach (string uidPath in objectUidPath)
                {
                    FileInfo fileInfo = new FileInfo(uidPath);
                    string   uid      = fileInfo.Name.Replace(".dcm", "");
                    Console.Write("{0,-64}... ", uid);

                    try
                    {
                        Stream imageStream;
                        StreamingResultMetaData      imageMetaData;
                        FrameStreamingResultMetaData frameMetaData;

                        switch (type)
                        {
                        case ContentTypes.Dicom:
                            imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                            totalFrameCount++;
                            averageSpeed.AddSample(imageMetaData.Speed);
                            totalSize.Value += (ulong)imageMetaData.ContentLength;

                            Console.WriteLine("1 dicom sop [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                            break;

                        case ContentTypes.RawPixel:
                            TimeSpanStatistics elapsedTime = new TimeSpanStatistics();
                            elapsedTime.Start();
                            ulong instanceSize = 0;
                            int   frameCount   = 0;
                            do
                            {
                                RetrievePixelDataResult result = client.RetrievePixelData(serverAE, studyUid, seriesUid, uid, frameCount);
                                frameMetaData = result.MetaData;
                                totalFrameCount++;
                                frameCount++;
                                averageSpeed.AddSample(frameMetaData.Speed);
                                totalSize.Value += (ulong)frameMetaData.ContentLength;
                                instanceSize    += (ulong)frameMetaData.ContentLength;
                            } while (!frameMetaData.IsLast);

                            elapsedTime.End();
                            Console.WriteLine("{0,3} frame(s) [{1,10}] in {2,12}\t[mime={3}]", frameCount, ByteCountFormatter.Format(instanceSize), elapsedTime.FormattedValue, frameMetaData.ResponseMimeType);
                            break;

                        default:

                            imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                            totalFrameCount++;
                            averageSpeed.AddSample(imageMetaData.Speed);
                            totalSize.Value += (ulong)imageMetaData.ContentLength;

                            Console.WriteLine("1 object [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            HttpWebResponse rsp = ((ex as WebException).Response as HttpWebResponse);

                            string msg = String.Format("Error: {0} : {1}", rsp.StatusCode, HttpUtility.HtmlDecode(rsp.StatusDescription)
                                                       );
                            Console.WriteLine(msg);
                        }
                        else
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            frameRate.SetData(totalFrameCount);
            frameRate.End();
            speed.SetData(totalSize.Value);
            speed.End();


            Console.WriteLine("\nTotal {0,3} image(s)/frame(s) [{1,10}] in {2,12}   ==>  [ Speed: {3,12} or {4,12}]",
                              totalFrameCount, totalSize.FormattedValue,
                              TimeSpanFormatter.Format(frameRate.ElapsedTime),
                              frameRate.FormattedValue,
                              speed.FormattedValue
                              );
        }
Ejemplo n.º 27
0
            private RetrievePixelDataResult TryClientRetrievePixelData(out Exception lastRetrieveException)
            {
                // retry parameters
                const int maxRetryCount = 10;
                const int retryTimeout  = 1500;
                int       retryDelay    = 50;
                int       retryCounter  = 0;

                StreamingClient         client = new StreamingClient(this.BaseUrl);
                RetrievePixelDataResult result = null;

                lastRetrieveException = null;

                CodeClock timeoutClock = new CodeClock();

                timeoutClock.Start();

                while (true)
                {
                    try
                    {
                        if (retryCounter > 0)
                        {
                            Platform.Log(LogLevel.Info, "Retrying retrieve pixel data for Sop '{0}' (Attempt #{1})", this.SopInstanceUid, retryCounter);
                        }

                        CodeClock statsClock = new CodeClock();
                        statsClock.Start();

                        result = client.RetrievePixelData(this.AETitle, this.StudyInstanceUid, this.SeriesInstanceUid, this.SopInstanceUid, this.FrameNumber - 1);

                        statsClock.Stop();

                        Platform.Log(LogLevel.Debug, "[Retrieve Info] Sop/Frame: {0}/{1}, Transfer Syntax: {2}, Bytes transferred: {3}, Elapsed (s): {4}, Retries: {5}",
                                     this.SopInstanceUid, this.FrameNumber, this.TransferSyntaxUid,
                                     result.MetaData.ContentLength, statsClock.Seconds, retryCounter);

                        break;
                    }
                    catch (Exception ex)
                    {
                        lastRetrieveException = ex;

                        timeoutClock.Stop();
                        if (timeoutClock.Seconds * 1000 >= retryTimeout || retryCounter >= maxRetryCount)
                        {
                            // log an alert that we are aborting (exception trace at debug level only)
                            int elapsed = (int)(1000 * timeoutClock.Seconds);
                            Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Aborting after {1} attempts in {2} ms", this.SopInstanceUid, retryCounter, elapsed);
                            Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Abort] Sop/Frame: {0}/{1}, Retry Attempts: {2}, Elapsed: {3} ms", this.SopInstanceUid, this.FrameNumber - 1, retryCounter, elapsed);
                            break;
                        }
                        timeoutClock.Start();

                        retryCounter++;

                        // log the retry (exception trace at debug level only)
                        Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Retrying in {1} ms", this.SopInstanceUid, retryDelay);
                        Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Retry] Sop/Frame: {0}/{1}, Retry in: {2} ms", this.SopInstanceUid, this.FrameNumber - 1, retryDelay);
                        MemoryManager.Collect(retryDelay);
                        retryDelay *= 2;

                        if (retryDelay > MaxRetryDelay)
                        {
                            retryDelay = MaxRetryDelay; // cap it to avoid overflow, which will cause exception when calling MemoryManager.Collect()
                        }
                    }
                }

                return(result);
            }
Ejemplo n.º 28
0
        public bool StartResource(string resourceName, string father = null)
        {
            try
            {
                if (RunningResources.Any(res => res.DirectoryName == resourceName))
                {
                    return(false);
                }

                Program.Output("Starting " + resourceName);

                if (!Directory.Exists("resources" + Path.DirectorySeparatorChar + resourceName))
                {
                    throw new FileNotFoundException("Resource does not exist.");
                }

                var baseDir = "resources" + Path.DirectorySeparatorChar + resourceName + Path.DirectorySeparatorChar;

                if (!File.Exists(baseDir + "meta.xml"))
                {
                    throw new FileNotFoundException("meta.xml has not been found.");
                }

                var          xmlSer = new XmlSerializer(typeof(ResourceInfo));
                ResourceInfo currentResInfo;
                using (var str = File.OpenRead(baseDir + "meta.xml"))
                    currentResInfo = (ResourceInfo)xmlSer.Deserialize(str);

                var ourResource = new Resource();
                ourResource.Info              = currentResInfo;
                ourResource.DirectoryName     = resourceName;
                ourResource.Engines           = new List <ScriptingEngine>();
                ourResource.ClientsideScripts = new List <ClientsideScript>();

                if (ourResource.Info.Info != null && ourResource.Info.Info.Type == ResourceType.gamemode)
                {
                    if (Gamemode != null)
                    {
                        StopResource(Gamemode.DirectoryName);
                    }
                    Gamemode = ourResource;
                }

                if (currentResInfo.ResourceACL != null && ACLEnabled)
                {
                    var aclHead = AccessControlList.ParseXml("resources" + Path.DirectorySeparatorChar + resourceName + Path.DirectorySeparatorChar + currentResInfo.ResourceACL.Path);
                    ACL.MergeACL(aclHead);
                }

                if (currentResInfo.Includes != null)
                {
                    foreach (var resource in currentResInfo.Includes)
                    {
                        if (string.IsNullOrWhiteSpace(resource.Resource) || resource.Resource == father)
                        {
                            continue;
                        }
                        StartResource(resource.Resource, resourceName);
                    }
                }

                FileModule.ExportedFiles.Set(resourceName, new List <FileDeclaration>());

                foreach (var filePath in currentResInfo.Files)
                {
                    using (var md5 = MD5.Create())
                        using (var stream = File.OpenRead("resources" + Path.DirectorySeparatorChar + resourceName + Path.DirectorySeparatorChar + filePath.Path))
                        {
                            var myData = md5.ComputeHash(stream);

                            var keyName = ourResource.DirectoryName + "_" + filePath.Path;

                            string hash = myData.Select(byt => byt.ToString("x2")).Aggregate((left, right) => left + right);

                            if (FileHashes.ContainsKey(keyName))
                            {
                                FileHashes[keyName] = hash;
                            }
                            else
                            {
                                FileHashes.Add(keyName, hash);
                            }

                            FileModule.ExportedFiles[resourceName].Add(new FileDeclaration(filePath.Path, hash, FileType.Normal));
                        }
                }

                if (currentResInfo.ConfigFiles != null)
                {
                    foreach (var filePath in currentResInfo.ConfigFiles.Where(cfg => cfg.Type == ScriptType.client))
                    {
                        using (var md5 = MD5.Create())
                            using (var stream = File.OpenRead("resources" + Path.DirectorySeparatorChar + resourceName + Path.DirectorySeparatorChar + filePath.Path))
                            {
                                var myData = md5.ComputeHash(stream);

                                var keyName = ourResource.DirectoryName + "_" + filePath.Path;

                                string hash = myData.Select(byt => byt.ToString("x2")).Aggregate((left, right) => left + right);

                                if (FileHashes.ContainsKey(keyName))
                                {
                                    FileHashes[keyName] = hash;
                                }
                                else
                                {
                                    FileHashes.Add(keyName, hash);
                                }

                                FileModule.ExportedFiles[resourceName].Add(new FileDeclaration(filePath.Path, hash, FileType.Normal));
                            }
                    }
                }

                if (currentResInfo.settings != null)
                {
                    if (string.IsNullOrEmpty(currentResInfo.settings.Path))
                    {
                        ourResource.Settings = LoadSettings(currentResInfo.settings.Settings);
                    }
                    else
                    {
                        var ser2 = new XmlSerializer(typeof(ResourceSettingsFile));

                        ResourceSettingsFile file;

                        using (var stream = File.Open(currentResInfo.settings.Path, FileMode.Open))
                            file = ser2.Deserialize(stream) as ResourceSettingsFile;

                        if (file != null)
                        {
                            ourResource.Settings = LoadSettings(file.Settings);
                        }
                    }
                }

                // Load assembly references
                if (currentResInfo.References != null)
                {
                    foreach (var ass in currentResInfo.References)
                    {
                        AssemblyReferences.Set(ass.Name,
                                               "resources" + Path.DirectorySeparatorChar + resourceName + Path.DirectorySeparatorChar + ass.Name);
                    }
                }


                var csScripts = new List <ClientsideScript>();

                var cSharp = new List <string>();
                var vBasic = new List <string>();

                bool multithreaded = false;

                if (ourResource.Info.Info != null)
                {
                    multithreaded = ourResource.Info.Info.Multithreaded;
                }

                foreach (var script in currentResInfo.Scripts)
                {
                    if (script.Language == ScriptingEngineLanguage.javascript)
                    {
                        var scrTxt = File.ReadAllText(baseDir + script.Path);
                        if (script.Type == ScriptType.client)
                        {
                            var csScript = new ClientsideScript()
                            {
                                ResourceParent = resourceName,
                                Script         = scrTxt,
                                //Filename = Path.GetFileNameWithoutExtension(script.Path)?.Replace('.', '_'),
                                Filename = script.Path,
                            };

                            string hash;

                            using (var md5 = MD5.Create())
                            {
                                var myData = md5.ComputeHash(Encoding.UTF8.GetBytes(scrTxt));
                                hash             = myData.Select(byt => byt.ToString("x2")).Aggregate((left, right) => left + right);
                                csScript.MD5Hash = hash;

                                if (FileHashes.ContainsKey(ourResource.DirectoryName + "_" + script.Path))
                                {
                                    FileHashes[ourResource.DirectoryName + "_" + script.Path] = hash;
                                }
                                else
                                {
                                    FileHashes.Add(ourResource.DirectoryName + "_" + script.Path, hash);
                                }
                            }

                            FileModule.ExportedFiles[resourceName].Add(new FileDeclaration(script.Path, hash, FileType.Script));

                            ourResource.ClientsideScripts.Add(csScript);
                            csScripts.Add(csScript);
                            continue;
                        }
                    }
                    else if (script.Language == ScriptingEngineLanguage.compiled)
                    {
                        try
                        {
                            Program.DeleteFile(baseDir + script.Path + ":Zone.Identifier");
                        }
                        catch
                        {
                        }
                        Assembly ass;

                        if (ourResource.Info.Info.Shadowcopy)
                        {
                            byte[] bytes = File.ReadAllBytes(baseDir + script.Path);
                            ass = Assembly.Load(bytes);
                        }
                        else
                        {
                            ass = Assembly.LoadFrom(baseDir + script.Path);
                        }

                        var instances = InstantiateScripts(ass);
                        ourResource.Engines.AddRange(instances.Select(sss => new ScriptingEngine(sss, sss.GetType().Name, ourResource, multithreaded)));
                    }
                    else if (script.Language == ScriptingEngineLanguage.csharp)
                    {
                        var scrTxt = File.ReadAllText(baseDir + script.Path);
                        cSharp.Add(scrTxt);
                    }
                    else if (script.Language == ScriptingEngineLanguage.vbasic)
                    {
                        var scrTxt = File.ReadAllText(baseDir + script.Path);
                        vBasic.Add(scrTxt);
                    }
                }



                if (cSharp.Count > 0)
                {
                    var csharpAss = CompileScript(cSharp.ToArray(), currentResInfo.References.Select(r => r.Name).ToArray(), false);
                    ourResource.Engines.AddRange(csharpAss.Select(sss => new ScriptingEngine(sss, sss.GetType().Name, ourResource, multithreaded)));
                }

                if (vBasic.Count > 0)
                {
                    var vbasicAss = CompileScript(vBasic.ToArray(), currentResInfo.References.Select(r => r.Name).ToArray(), true);
                    ourResource.Engines.AddRange(vbasicAss.Select(sss => new ScriptingEngine(sss, sss.GetType().Name, ourResource, multithreaded)));
                }

                CommandHandler.Register(ourResource);

                var randGen = new Random();

                if (ourResource.ClientsideScripts.Count > 0 || currentResInfo.Files.Count > 0)
                {
                    foreach (var client in Clients)
                    {
                        var downloader = new StreamingClient(client);

                        if (!UseHTTPFileServer)
                        {
                            foreach (var file in currentResInfo.Files)
                            {
                                var fileData = new StreamedData();
                                fileData.Id   = randGen.Next(int.MaxValue);
                                fileData.Type = FileType.Normal;
                                fileData.Data =
                                    File.ReadAllBytes("resources" + Path.DirectorySeparatorChar +
                                                      ourResource.DirectoryName +
                                                      Path.DirectorySeparatorChar +
                                                      file.Path);
                                fileData.Name     = file.Path;
                                fileData.Resource = ourResource.DirectoryName;
                                fileData.Hash     = FileHashes.ContainsKey(ourResource.DirectoryName + "_" + file.Path)
                                    ? FileHashes[ourResource.DirectoryName + "_" + file.Path]
                                    : null;

                                downloader.Files.Add(fileData);
                            }
                        }
                        else
                        {
                            var msg = Server.CreateMessage();
                            msg.Write((byte)PacketType.RedownloadManifest);
                            client.NetConnection.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.FileTransfer);
                        }

                        foreach (var script in ourResource.ClientsideScripts)
                        {
                            var scriptData = new StreamedData();
                            scriptData.Id       = randGen.Next(int.MaxValue);
                            scriptData.Data     = Encoding.UTF8.GetBytes(script.Script);
                            scriptData.Type     = FileType.Script;
                            scriptData.Resource = script.ResourceParent;
                            scriptData.Hash     = script.MD5Hash;
                            scriptData.Name     = script.Filename;
                            downloader.Files.Add(scriptData);
                        }

                        var endStream = new StreamedData();
                        endStream.Id   = randGen.Next(int.MaxValue);
                        endStream.Data = new byte[] { 0xDE, 0xAD, 0xF0, 0x0D };
                        endStream.Type = FileType.EndOfTransfer;
                        downloader.Files.Add(endStream);

                        Downloads.Add(downloader);
                    }
                }

                if (ourResource.Info.Map != null && !string.IsNullOrWhiteSpace(ourResource.Info.Map.Path))
                {
                    ourResource.Map = new XmlGroup();
                    ourResource.Map.Load("resources\\" + ourResource.DirectoryName + "\\" + ourResource.Info.Map.Path);

                    LoadMap(ourResource, ourResource.Map, ourResource.Info.Map.Dimension);

                    if (ourResource.Info.Info.Type == ResourceType.gamemode)
                    {
                        if (CurrentMap != null)
                        {
                            StopResource(CurrentMap.DirectoryName);
                        }
                        ourResource.Engines.ForEach(cs => cs.InvokeMapChange(ourResource.DirectoryName, ourResource.Map));
                    }
                    else if (ourResource.Info.Info.Type == ResourceType.map)
                    {
                        if (string.IsNullOrWhiteSpace(ourResource.Info.Info.Gamemodes))
                        {
                        }
                        else if (ourResource.Info.Info.Gamemodes?.Split(',').Length != 1 && Gamemode == null)
                        {
                        }
                        else if (ourResource.Info.Info.Gamemodes?.Split(',').Length == 1 && (Gamemode == null || !ourResource.Info.Info.Gamemodes.Split(',').Contains(Gamemode.DirectoryName)))
                        {
                            if (CurrentMap != null)
                            {
                                StopResource(CurrentMap.DirectoryName);
                            }
                            StartResource(ourResource.Info.Info.Gamemodes?.Split(',')[0]);

                            CurrentMap = ourResource;
                            Gamemode.Engines.ForEach(cs => cs.InvokeMapChange(ourResource.DirectoryName, ourResource.Map));
                        }
                        else if (Gamemode != null && ourResource.Info.Info.Gamemodes.Split(',').Contains(Gamemode.DirectoryName))
                        {
                            Program.Output("Starting map " + ourResource.DirectoryName + "!");
                            if (CurrentMap != null)
                            {
                                StopResource(CurrentMap.DirectoryName);
                            }
                            CurrentMap = ourResource;
                            Gamemode.Engines.ForEach(cs => cs.InvokeMapChange(ourResource.DirectoryName, ourResource.Map));
                        }
                    }
                }

                if (ourResource.Info.ExportedFunctions != null)
                {
                    var     gPool       = ExportedFunctions as IDictionary <string, object>;
                    dynamic resPool     = new System.Dynamic.ExpandoObject();
                    var     resPoolDict = resPool as IDictionary <string, object>;

                    foreach (var func in ourResource.Info.ExportedFunctions)
                    {
                        ScriptingEngine engine;
                        if (string.IsNullOrEmpty(func.Path))
                        {
                            engine = ourResource.Engines.SingleOrDefault();
                        }
                        else
                        {
                            engine = ourResource.Engines.FirstOrDefault(en => en.Filename == func.Path);
                        }

                        if (engine == null)
                        {
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(func.EventName))
                        {
                            ExportedFunctionDelegate punchthrough = new ExportedFunctionDelegate((ExportedFunctionDelegate)
                                                                                                 delegate(object[] parameters)
                            {
                                return(engine.InvokeMethod(func.Name, parameters));
                            });
                            resPoolDict.Add(func.Name, punchthrough);
                        }
                        else
                        {
                            var eventInfo = engine._compiledScript.GetType().GetEvent(func.EventName);

                            if (eventInfo == null)
                            {
                                Program.Output("WARN: Exported event " + func.EventName + " has not been found!");
                                if (LogLevel > 0)
                                {
                                    Program.Output("Available events:");
                                    Program.Output(string.Join(", ", engine._compiledScript.GetType().GetEvents().Select(ev => ev.Name)));
                                }
                            }
                            else
                            {
                                resPoolDict.Add(func.EventName, null);

                                ExportedEvent punchthrough = new ExportedEvent((ExportedEvent)
                                                                               delegate(dynamic[] parameters)
                                {
                                    ExportedEvent e = resPoolDict[func.EventName] as ExportedEvent;

                                    if (e != null)
                                    {
                                        e.Invoke(parameters);
                                    }
                                });

                                eventInfo.AddEventHandler(engine._compiledScript, punchthrough);
                            }
                        }
                    }

                    gPool.Add(ourResource.DirectoryName, resPool);
                }

                foreach (var engine in ourResource.Engines)
                {
                    engine.InvokeResourceStart();
                }

                var oldRes = new List <Resource>(RunningResources);
                lock (RunningResources) RunningResources.Add(ourResource);

                foreach (var resource in oldRes)
                {
                    resource.Engines.ForEach(en => en.InvokeServerResourceStart(ourResource.DirectoryName));
                }

                Program.Output("Resource " + ourResource.DirectoryName + " started!");
                return(true);
            }
            catch (Exception ex)
            {
                Program.Output("ERROR STARTING RESOURCE " + resourceName);
                Program.Output(ex.ToString());
                return(false);
            }
        }
Ejemplo n.º 29
0
        private DicomFile TryClientRetrieveImageHeader(out Exception lastRetrieveException)
        {
            // retry parameters
            const int retryTimeout = 1500;
            int       retryDelay   = 50;
            int       retryCounter = 0;

            Uri             uri    = new Uri(string.Format(StreamingSettings.Default.FormatWadoUriPrefix, _host, _wadoServicePort));
            StreamingClient client = new StreamingClient(uri);
            DicomFile       result = null;

            lastRetrieveException = null;

            CodeClock timeoutClock = new CodeClock();

            timeoutClock.Start();

            while (true)
            {
                try
                {
                    if (retryCounter > 0)
                    {
                        Platform.Log(LogLevel.Info, "Retrying retrieve headers for Sop '{0}' (Attempt #{1})", this.SopInstanceUid, retryCounter);
                    }

                    using (Stream imageHeaderStream = client.RetrieveImageHeader(_aeTitle, this.StudyInstanceUid, this.SeriesInstanceUid, this.SopInstanceUid))
                    {
                        DicomFile imageHeader = new DicomFile();
                        imageHeader.Load(imageHeaderStream);
                        result = imageHeader;
                    }

                    break;
                }
                catch (Exception ex)
                {
                    lastRetrieveException = ex;

                    timeoutClock.Stop();
                    if (timeoutClock.Seconds * 1000 >= retryTimeout)
                    {
                        // log an alert that we are aborting (exception trace at debug level only)
                        int elapsed = (int)(1000 * timeoutClock.Seconds);
                        Platform.Log(LogLevel.Warn, "Failed to retrieve headers for Sop '{0}'; Aborting after {1} attempts in {2} ms", this.SopInstanceUid, retryCounter, elapsed);
                        Platform.Log(LogLevel.Debug, ex, "[GetHeaders Fail-Abort] Sop: {0}, Retry Attempts: {1}, Elapsed: {2} ms", this.SopInstanceUid, retryCounter, elapsed);
                        break;
                    }
                    timeoutClock.Start();

                    retryCounter++;

                    // log the retry (exception trace at debug level only)
                    Platform.Log(LogLevel.Warn, "Failed to retrieve headers for Sop '{0}'; Retrying in {1} ms", this.SopInstanceUid, retryDelay);
                    Platform.Log(LogLevel.Debug, ex, "[GetHeaders Fail-Retry] Sop: {0}, Retry in: {1} ms", this.SopInstanceUid, retryDelay);

                    MemoryManager.Collect(retryDelay);
                    retryDelay *= 2;
                }
            }

            return(result);
        }
Ejemplo n.º 30
0
        void listener_MessageReceived(object sender, StreamingClient.MessageEventArgs<PriceDTO> e)
        {

        }