示例#1
0
        public QueryOutput QueryStudies(QueryInput input)
        {
            var criteria = new DicomAttributeCollection();

            criteria[DicomTags.QueryRetrieveLevel].SetStringValue("STUDY");
            criteria[DicomTags.PatientId].SetStringValue(input.PatientId);
            criteria[DicomTags.AccessionNumber].SetStringValue(input.AccessionNumber);
            criteria[DicomTags.PatientsName].SetStringValue(input.PatientsName);
            criteria[DicomTags.StudyDate].SetDateTime(0, input.StudyDate);
            criteria[DicomTags.StudyDescription].SetStringValue(input.StudyDescription);
            criteria[DicomTags.PatientsBirthDate].SetStringValue("");
            criteria[DicomTags.ModalitiesInStudy].SetStringValue(input.ModalitiesInStudy);
            criteria[DicomTags.SpecificCharacterSet].SetStringValue("");
            criteria[DicomTags.StudyInstanceUid].SetStringValue(input.StudyInstanceUID);

            var reader  = DataAccessLayer.GetIDataStoreReader();
            var results = reader.Query(criteria);

            return(new QueryOutput(
                       CollectionUtils.Map(results,
                                           delegate(DicomAttributeCollection result)
            {
                var item = new StudyProperties();
                item.PatientId = result[DicomTags.PatientId].ToString();
                item.PatientsName = result[DicomTags.PatientsName].ToString();
                item.StudyDate = result[DicomTags.StudyDate].GetDateTime(0);
                item.StudyDescription = result[DicomTags.StudyDescription].ToString();
                item.ModalitiesInStudy = result[DicomTags.ModalitiesInStudy].ToString();
                item.AccessionNumber = result[DicomTags.AccessionNumber].ToString();
                item.StudyInstanceUID = result[DicomTags.StudyInstanceUid].ToString();
                return item;
            })));
        }
示例#2
0
        public IDictionary <string, object> ExecuteQuery(QueryInput input)
        {
            var sw = new Stopwatch();

            sw.Start();
            var contextResult = _databaseContextService.GetDatabaseContext(input.ConnectionString);
            var assmName      = Guid.NewGuid().ToIdentifierWithPrefix("a");
            var programSource = _template
                                .Replace("##SOURCE##", input.Text)
                                .Replace("##NS##", assmName)
                                .Replace("##DB##", contextResult.Type.ToString());
            var e1 = sw.Elapsed.TotalMilliseconds;

            sw.Reset();
            sw.Start();
            var result          = _compiler.LoadType(programSource, assmName, contextResult.Reference);
            var method          = result.Type.GetMethod("Run");
            var programInstance = Activator.CreateInstance(result.Type);
            var e2 = sw.Elapsed.TotalMilliseconds;

            sw.Reset();
            sw.Start();
            var res = method.Invoke(programInstance, new object[] { }) as IDictionary <string, object>;
            var e3  = sw.Elapsed.TotalMilliseconds;

            //res.Add("Performance", new { DbContext = e1, Loading = e2, Execution = e3 });
            return(res);
        }
示例#3
0
        public TemplateResult GetTemplate(QueryInput input)
        {
            var assmName  = Guid.NewGuid().ToIdentifierWithPrefix("a");
            var schemaSrc = _schemaService.GetSchemaSource(input.ConnectionString, assmName, withUsings: false);

            var src = _template
                      .Replace("##NS##", assmName)
                      .Replace("##DB##", "Proxy");

            var srcToken  = "##SOURCE##";
            var regex     = new Regex(@"$", RegexOptions.Multiline);
            var srcIdx    = src.IndexOf(srcToken);
            var srcOffset = src.Substring(0, srcIdx);
            var ms        = regex.Matches(srcOffset);

            src = src + schemaSrc;
            var fullSrc = src.Replace(srcToken, "");
            var header  = src.Substring(0, srcIdx);
            var footer  = src.Substring(srcIdx + srcToken.Length);

            Console.WriteLine("regex matches", ms.Count);
            // the usage of the template should not require mapping the column value
            return(new TemplateResult {
                Template = fullSrc,
                Header = header,
                Footer = footer,
                Namespace = assmName,
                ColumnOffset = 0,
                LineOffset = ms.Count // todo magic bullshit
            });
        }
示例#4
0
 protected override Task <Option[]> GetOptions(QueryInput input)
 {
     return(Task.FromResult(new Option[]
     {
         new Option
         {
             DisplayValue = "Equals",
             Value = "=",
             Type = "character varying"
         },
         new Option
         {
             DisplayValue = "Does not equal",
             Value = "!=",
             Type = "character varying"
         },
         new Option
         {
             DisplayValue = "Greater than",
             Value = ">",
             Type = "character varying"
         },
         new Option
         {
             DisplayValue = "Lesser than",
             Value = "<",
             Type = "character varying"
         }
     }));
 }
    private void Start()
    {
        //Linear16 is for .wav files which are supported by this program
        //and it needs to have a sample rate of 16000 or 16K Hz
        outputAudioConfig = new OutputAudioConfig()
        {
            AudioEncoding          = OutputAudioEncoding.Linear16,
            SampleRateHertz        = 16000,
            SynthesizeSpeechConfig = new SynthesizeSpeechConfig()
            {
                Voice = new VoiceSelectionParams()
                {
                    SsmlGender = SsmlVoiceGender.Female
                }
            }
        };

        //Defines what kind of audio bytes we are sending
        inputAudioConfig = new InputAudioConfig()
        {
            AudioEncoding   = AudioEncoding.Linear16,
            LanguageCode    = "en-US",
            SampleRateHertz = 16000
        };


        //Specifies the audio config to show that the input is audio bytes
        query = new QueryInput()
        {
            AudioConfig = inputAudioConfig
        };

        session = string.Format("projects/{0}/agent/sessions/{1}", agent, sessionId);
    }
        public static QueryInput GetQueryParameters(this SimpleContext context)
        {
            var query      = context.Request.Query;
            var parameters = new QueryInput();

            foreach (var key in query.Keys)
            {
                int number;
                switch (key.ToLowerInvariant())
                {
                case "skip":
                    parameters.Skip = int.TryParse(query[key].LastOrDefault(), out number) ? number : 0;
                    break;

                case "take":
                    parameters.Take = int.TryParse(query[key].LastOrDefault(), out number) ? number : 0;
                    break;

                case "q":
                    parameters.Query = QueryParser.Parse(query[key].LastOrDefault());
                    break;
                }
            }
            return(parameters);
        }
示例#7
0
        public static string DetectIntent(string text)
        {
            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = text,
                    LanguageCode = "ru"
                }
            };

            var sessionId = Guid.NewGuid().ToString();
            var agent     = "smalltalkbot-atvxnh";
            var creds     = IntentDetector.Creds;
            var channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                                                  creds.ToChannelCredentials());

            var client = SessionsClient.Create(channel);

            var dialogFlow = client.DetectIntent(
                new SessionName(agent, sessionId),
                query
                );

            channel.ShutdownAsync();
            return(dialogFlow.QueryResult.FulfillmentText);
        }
示例#8
0
        private void ListQuery(string selecteditem)
        {
            if (selecteditem == null)
            {
                return;
            }

            switch (ListingType)
            {
            case ListingType.Albums:
                DoQuery(QueryInput.AlbumQuery(selecteditem));
                break;

            case ListingType.Artists:
                DoQuery(QueryInput.ArtistQuery(selecteditem));
                break;

            case ListingType.Genre:
                DoQuery(QueryInput.GenerireQuery(selecteditem));
                break;

            case ListingType.Years:
                DoQuery(QueryInput.YearQuery(Convert.ToUInt32(selecteditem)));
                break;

            case ListingType.Query:
                DoQuery(DataBase.Instance.GetQueryByName(selecteditem));
                break;
            }
        }
示例#9
0
        private DetectIntentRequest CreateQuery(Request request)
        {
            var session = new SessionName(_configuration.ProjectId, request.SessionId);

            var eventInput = ResolveEvent(request);

            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = request.Text,
                    LanguageCode = _configuration.LanguageCode
                },
            };

            if (eventInput != null)
            {
                query.Event = eventInput;
            }

            var intentRequest = new DetectIntentRequest
            {
                SessionAsSessionName = session,
                QueryInput           = query
            };

            return(intentRequest);
        }
示例#10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = "cc",
                    LanguageCode = "en-us"
                }
            };

            var sessionId = "SomeUniqueId";
            var agent     = "test5";
            var creds     = GoogleCredential.FromJson(@"D:/test5.json");
            var channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                                                  creds.ToChannelCredentials());

            var client = SessionsClient.Create(channel);

            var dialogFlow = client.DetectIntent(
                new SessionName(agent, sessionId),
                query
                );

            channel.ShutdownAsync();
        }
示例#11
0
        private void DoQuery(QueryInput queryInput)
        {
            var items = DataBase.Instance.Execute(queryInput);

            DisplayItems.Clear();
            DisplayItems.AddRange(items);
        }
示例#12
0
        public async Task <IActionResult> sendtext(string text, string sessionId)
        {
            var result = new RequestResult();

            try
            {
                var query = new QueryInput {
                    Text = new TextInput {
                        Text = text, LanguageCode = "ru-ru"
                    }
                };

                var agent   = "small-talk-1-cdboby";
                var creds   = GoogleCredential.FromFile($"{_env.WebRootPath}\\DFCredits.json");
                var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());

                var client     = SessionsClient.Create(channel);
                var dialogFlow = await client.DetectIntentAsync(new SessionName(agent, sessionId), query);

                await channel.ShutdownAsync();

                result.IsSuccess = true;
                result.Data      = string.IsNullOrEmpty(dialogFlow?.QueryResult?.FulfillmentText) ? GetRandomDontKnow() : dialogFlow.QueryResult.FulfillmentText;
            }
            catch (Exception err)
            {
                result.IsSuccess = false;
                result.Data      = "Упс... что-то пошло не так...";
                result.Error     = $"Ошбика: {err.Message}";
            }

            return(new JsonResult(result));
        }
示例#13
0
        public async Task Collect(QueryInput input)
        {
            Console.WriteLine(GetInputMessage());

            Option[] options = await GetOptions(input);

            for (int optionIndex = 0; optionIndex < options.Length; optionIndex++)
            {
                Option option = options[optionIndex];
                Console.WriteLine($"{optionIndex+1}: {option.DisplayValue}");
            }

            string userInput = Console.ReadLine();

            if (int.TryParse(userInput, out int selectedIndex) &&
                selectedIndex - 1 >= 0 &&
                selectedIndex - 1 < options.Length)
            {
                Option selectedOption = options[selectedIndex - 1];
                SetInputValue(input, selectedOption);
            }
            else
            {
                Console.WriteLine("Please enter the number corresponding to your value");
                await Collect(input);
            }
        }
示例#14
0
 /// <summary>
 /// Processes a natural language query and returns structured, actionable data
 /// as a result. This method is not idempotent, because it may cause contexts
 /// and session entity types to be updated, which in turn might affect
 /// results of future queries.
 /// </summary>
 /// <param name="session">
 /// Required. The name of the session this query is sent to. Format:
 /// `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API
 /// caller to choose an appropriate session ID. It can be a random number or
 /// some type of user identifier (preferably hashed). The length of the session
 /// ID must not exceed 36 bytes.
 /// </param>
 /// <param name="queryInput">
 /// Required. The input specification. It can be set to:
 ///
 /// 1.  an audio config
 ///     which instructs the speech recognizer how to process the speech audio,
 ///
 /// 2.  a conversational query in the form of text, or
 ///
 /// 3.  an event that specifies which intent to trigger.
 /// </param>
 /// <param name="cancellationToken">
 /// A <see cref="st::CancellationToken"/> to use for this RPC.
 /// </param>
 /// <returns>
 /// A Task containing the RPC response.
 /// </returns>
 public virtual stt::Task <DetectIntentResponse> DetectIntentAsync(
     string session,
     QueryInput queryInput,
     st::CancellationToken cancellationToken) => DetectIntentAsync(
     session,
     queryInput,
     gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
        protected override async Task <ILabeledUtterance> TestAsync(string utterance, CancellationToken cancellationToken)
        {
            var sessionId   = this.SessionId ?? Guid.NewGuid().ToString();
            var sessionName = new SessionName(this.ProjectId, sessionId);
            var queryInput  = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = utterance,
                    LanguageCode = "en",
                }
            };

            return(await RetryAsync(
                       async() =>
            {
                var client = await this.GetSessionClientAsync(cancellationToken).ConfigureAwait(false);
                var result = await client.DetectIntentAsync(sessionName, queryInput, cancellationToken).ConfigureAwait(false);
                return new LabeledUtterance(
                    result.QueryResult.QueryText,
                    result.QueryResult.Intent.DisplayName,
                    result.QueryResult.Parameters?.Fields.SelectMany(GetEntities).ToList())
                .WithScore(result.QueryResult.IntentDetectionConfidence)
                .WithTextScore(result.QueryResult.SpeechRecognitionConfidence)
                .WithTimestamp(DateTimeOffset.Now);
            },
                       cancellationToken)
                   .ConfigureAwait(false));
        }
示例#16
0
        public ChatbotManager()
        {
            /* 환경변수
             * GOOGLE_APPLICATION_CREDENTIALS
             * D:\Programs\Google\Small-Talk-ab19e1b0105f.json
             */
            var        client    = SessionsClient.Create();
            QueryInput tempInput = new QueryInput();
            TextInput  tempText  = new TextInput
            {
                Text         = "야나두",
                LanguageCode = "ko"
            };

            tempInput.Text = tempText;
            var response = client.DetectIntent(new SessionName("small-talk-7a50b", "sess-01"), tempInput);

            var queryResult = response.QueryResult;

            Console.WriteLine($"Query text: {queryResult.QueryText}");
            Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
            Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
            Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
            Console.WriteLine();
        }
示例#17
0
        public async Task <IActionResult> QueryAsync([FromQuery] QueryInput input)
        {
            var repository = _factory.CreateInstance(HttpTrackerInstance.InstanceName);

            var response = await repository.QueryAsync(input);

            return(Json(response));
        }
示例#18
0
        public void PreprocessForQuery(ref QueryInput <Person> input)
        {
            if (input == null)
            {
                input = new QueryInput <Person>();
            }

            input.Order = person => person.OrderByDescending(x => x.Name);
        }
示例#19
0
 /// <summary>
 /// Processes a natural language query and returns structured, actionable data
 /// as a result. This method is not idempotent, because it may cause contexts
 /// and session entity types to be updated, which in turn might affect
 /// results of future queries.
 /// </summary>
 /// <param name="session">
 /// Required. The name of the session this query is sent to. Format:
 /// `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API
 /// caller to choose an appropriate session ID. It can be a random number or
 /// some type of user identifier (preferably hashed). The length of the session
 /// ID must not exceed 36 bytes.
 /// </param>
 /// <param name="queryInput">
 /// Required. The input specification. It can be set to:
 ///
 /// 1.  an audio config
 ///     which instructs the speech recognizer how to process the speech audio,
 ///
 /// 2.  a conversational query in the form of text, or
 ///
 /// 3.  an event that specifies which intent to trigger.
 /// </param>
 /// <param name="callSettings">
 /// If not null, applies overrides to this RPC call.
 /// </param>
 /// <returns>
 /// The RPC response.
 /// </returns>
 public virtual DetectIntentResponse DetectIntent(
     string session,
     QueryInput queryInput,
     gaxgrpc::CallSettings callSettings = null) => DetectIntent(
     new DetectIntentRequest
 {
     Session    = gax::GaxPreconditions.CheckNotNullOrEmpty(session, nameof(session)),
     QueryInput = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)),
 },
     callSettings);
示例#20
0
 /// <summary>
 /// Processes a natural language query and returns structured, actionable data
 /// as a result. This method is not idempotent, because it may cause contexts
 /// and session entity types to be updated, which in turn might affect
 /// results of future queries.
 /// </summary>
 /// <param name="session">
 /// Required. The name of the session this query is sent to. Format:
 /// `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;`. It's up to the API
 /// caller to choose an appropriate session ID. It can be a random number or
 /// some type of user identifier (preferably hashed). The length of the session
 /// ID must not exceed 36 bytes.
 /// </param>
 /// <param name="queryInput">
 /// Required. The input specification. It can be set to:
 ///
 /// 1.  an audio config
 ///     which instructs the speech recognizer how to process the speech audio,
 ///
 /// 2.  a conversational query in the form of text, or
 ///
 /// 3.  an event that specifies which intent to trigger.
 /// </param>
 /// <param name="callSettings">
 /// If not null, applies overrides to this RPC call.
 /// </param>
 /// <returns>
 /// A Task containing the RPC response.
 /// </returns>
 public virtual stt::Task <DetectIntentResponse> DetectIntentAsync(
     SessionName session,
     QueryInput queryInput,
     gaxgrpc::CallSettings callSettings = null) => DetectIntentAsync(
     new DetectIntentRequest
 {
     SessionAsSessionName = gax::GaxPreconditions.CheckNotNull(session, nameof(session)),
     QueryInput           = gax::GaxPreconditions.CheckNotNull(queryInput, nameof(queryInput)),
 },
     callSettings);
示例#21
0
        Request(QueryInput queryInput)
            : this()
        {
            _queryInput = queryInput;

            if (string.IsNullOrWhiteSpace(_queryInput.QueryString))
            {
                _exception = new ArgumentException($"Empty query string");
            }
        }
示例#22
0
        public void QueryInput_SetsBasicInputTypes()
        {
            var queryInputNumeric = new QueryInput("@UserId", System.Data.SqlDbType.Int);

            Assert.AreEqual("number", queryInputNumeric.InputType);

            var queryInputText = new QueryInput("@ProductCode", System.Data.SqlDbType.NVarChar);

            Assert.AreEqual("text", queryInputText.InputType);
        }
        public string Query(string Question)
        {
            if (channel != null)
            {
                if(channel.State == Grpc.Core.ChannelState.Shutdown ||
                    channel.State == Grpc.Core.ChannelState.TransientFailure)
                {
                    channel = null;                   
                }
            }
            if (channel == null) Init();

            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text = Question,
                    LanguageCode = "en-us"
                }
            };

            DetectIntentResponse dialogFlow =null;
            try
            {
                dialogFlow = client.DetectIntent(
                               new SessionName(AgentID, sessionId),
                               query
                           );
            }
            catch (Exception ex)
            {
                NetworkError.Message = ex.Message;
                NetworkError.StackTrace = ex.ToString();
                return "I am unable to access the internet network. Can you please make sure your network is online?";
            }
           

            dialogFlowString = dialogFlow.ToString();
            Response.CreateResponseObject(dialogFlowString);
             
            QueryResult = dialogFlow.QueryResult.ToString();
            FulfillmentText = dialogFlow.QueryResult.FulfillmentText;

            if (FulfillmentText.Trim() == "") FulfillmentText = "I am sorry, I do not have a comment at this moment. Can you try again?";

            if (IsChannelKeepAlive == false)
            {
                channel.ShutdownAsync();                
            }

            return FulfillmentText;

        }
示例#24
0
        public void PostprocessForQuery(Page page, QueryInput <Home> input, ref PagedCollection <Home> result)
        {
            if (result?.Data == null)
            {
                return;
            }

            foreach (var home in result.Data)
            {
                home.Address = home.Address + ", België";
            }
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent()
 {
     // Snippet: DetectIntent(string, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     string     session    = "projects/[PROJECT]/locations/[LOCATION]/agent/sessions/[SESSION]";
     QueryInput queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntentResourceNames()
 {
     // Snippet: DetectIntent(SessionName, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     SessionName session    = SessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]");
     QueryInput  queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
 protected override Task <Option[]> GetOptions(QueryInput input)
 {
     return(Task.FromResult(new Option[]
     {
         new Option
         {
             DisplayValue = "Localhost",
             Value = "User ID=postgres;Password=postgres;Host=localhost;Port=5432;Database=postgres;",
             Type = "character varying"
         }
     }));
 }
示例#28
0
        public void PostprocessForQuery(QueryInput <Home> input, ref IEnumerable <Home> result)
        {
            if (result == null)
            {
                return;
            }

            foreach (var home in result)
            {
                home.Address = home.Address + ", België";
            }
        }
        protected override async Task <Option[]> GetOptions(QueryInput input)
        {
            using (NpgsqlConnection connection = new NpgsqlConnection(input.DatabaseConnectionString))
            {
                IEnumerable <Option> result = await connection.QueryAsync <Option>(
                    $@"select distinct ""{input.Column.Value}"" as ""DisplayValue"", ""{input.Column.Value}"" as ""Value"", 'character varying' as ""Type""
                    from ""{input.Table.Value}""
                    order by ""{input.Column.Value}"";"
                    );

                return(result.ToArray());
            }
        }
示例#30
0
        public async Task TestMethod_Query_By_LastName_NoMatch()
        {
            ISignup    signup     = new SignMeUp();
            QueryInput queryInput = new QueryInput()
            {
                FunEvent = 0, LastName = "NO FOUND"
            };

            queryInput.CurrentPage = 0;

            var r = await signup.Query(queryInput);

            Assert.IsTrue(r.Records.Count == 0);
        }
示例#31
0
        public void StartLoad(BackgroundWorker worker)
        {
            var useParams = false;

            var badParams = new List<string>();
            foreach (var theKey in _paramMappings.Keys)
            {
                if ((_paramMappings[theKey] == null) || (_paramMappings[theKey].Length == 0))
                {
                    badParams.Add(theKey);
                }
            }

            foreach (var theKey in badParams)
            {
                _paramMappings.Remove(theKey);
            }

            //Need some parameters?
            if (_paramMappings.Count > 0)
            {
                ParamServer.Initialize(_paramQuery, _paramConnectionString, _paramMappings);
                useParams = true;
            }

            //Initialize the connection pool            
            var conn = new SqlConnection(_connectionString);
            //TODO: use this or not??
            SqlConnection.ClearPool(conn);
            conn.Open();
            conn.Dispose();

            //make sure the run cancelled flag is not set
            QueryInput.RunCancelled = false;

            //Spin up the load threads
            for (var i = 0; i < _threads; i++)
            {
                conn = new SqlConnection(_connectionString);

                //TODO: Figure out how to make this option work (maybe)
                //conn.FireInfoMessageEventOnUserErrors = true;

                SqlCommand statsComm = null;

                var queryComm = new SqlCommand {CommandTimeout = _commandTimeout, Connection = conn, CommandText = _query};

                if (useParams)
                {
                    queryComm.Parameters.AddRange(ParamServer.GetParams());
                }

                var setStatistics = (_collectIoStats ? @"SET STATISTICS IO ON;" : "") + (_collectTimeStats ? @"SET STATISTICS TIME ON;" : "");

                if (setStatistics.Length > 0)
                {
                    statsComm = new SqlCommand {CommandTimeout = _commandTimeout, Connection = conn, CommandText = setStatistics};
                }

                //Queue<queryOutput> queryOutInfo = new Queue<queryOutput>();

                var input = new QueryInput(statsComm, queryComm,
//                    this.queryOutInfo,
                    _iterations, _forceDataRetrieval);

                var theThread = new Thread(input.StartLoadThread) {Priority = ThreadPriority.BelowNormal};

                _threadPool.Add(theThread);
                _commandPool.Add(queryComm);
                //queryOutInfoPool.Add(queryOutInfo);
            }

            //Start the load threads
            for (var i = 0; i < _threads; i++)
            {
                _threadPool[i].Start();
            }

            //Start reading the queue...
            var finishedThreads = 0;
            var cancelled = false;

            while (finishedThreads < _threads)
            {
//                for (int i = 0; i < threads; i++)
//                {
                // try
                // {
                QueryOutput theOut = null;
                //lock (queryOutInfoPool[i])
                lock (QueryOutInfo)
                {
                    //if (queryOutInfoPool[i].Count > 0)
                    //theOut = (queryOutput)queryOutInfoPool[i].Dequeue();
                    if (QueryOutInfo.Count > 0)
                        theOut = QueryOutInfo.Dequeue();
                    else
                        Monitor.Wait(QueryOutInfo);
                }

                if (theOut != null)
                {
                    //Report output to the UI
                    worker.ReportProgress((int) (finishedThreads / (decimal) _threads * 100), theOut);

                    //TODO: Make this actually remove the queue from the pool so that it's not checked again -- maintain this with a bitmap, perhaps?
                    if (theOut.Finished)
                        finishedThreads++;
                }
                /* }
                    catch (InvalidOperationException e)
                    {
                    }
                    */

                /*
                        if (theOut != null)
                            Thread.Sleep(200);
                        else
                            Thread.Sleep(10);
                     */
                //               }

                //TODO: Remove this ?
                GC.Collect();

                if (worker.CancellationPending && !cancelled)
                {
                    QueryInput.RunCancelled = true;

                    //First, kill connections as fast as possible
                    SqlConnection.ClearAllPools();

                    //for each 20 threads, create a new thread dedicated
                    //to killing them
                    var threadNum = _threadPool.Count;

                    var killerThreads = new List<Thread>();
                    while (threadNum > 0)
                    {
                        var i = threadNum <= 20 ? 0 : threadNum - 20;

                        var killThreads = new Thread[threadNum - i < 1 ? threadNum : threadNum - i];
                        var killCommands = new SqlCommand[threadNum - i < 1 ? threadNum : threadNum - i];

                        _threadPool.CopyTo(i, killThreads, 0, killThreads.Length);
                        _commandPool.CopyTo(i, killCommands, 0, killCommands.Length);

                        for (var j = threadNum - 1; j >= i; j--)
                        {
                            _threadPool.RemoveAt(j);
                            _commandPool.RemoveAt(j);
                        }

                        var kill = new ThreadKiller(killThreads, killCommands);
                        var killer = new Thread(kill.KillEm);
                        killer.Start();
                        Thread.Sleep(0);

                        killerThreads.Add(killer);

                        threadNum = i;
                    }

                    //wait for the kill threads to return
                    //before exiting...
                    foreach (var theThread in killerThreads)
                    {
                        theThread.Join();
                    }

                    cancelled = true;
                }
            }

            //clear any remaining messages -- these are almost certainly
            //execeptions due to thread cancellation
            //queryOutInfo.Clear();
        }
示例#32
0
		public QueryOutput QueryStudies(QueryInput input)
		{
			var criteria = new DicomAttributeCollection();
			criteria[DicomTags.QueryRetrieveLevel].SetStringValue("STUDY");
			criteria[DicomTags.PatientId].SetStringValue(input.PatientId);
			criteria[DicomTags.AccessionNumber].SetStringValue(input.AccessionNumber);
			criteria[DicomTags.PatientsName].SetStringValue(input.PatientsName);
			criteria[DicomTags.StudyDate].SetDateTime(0, input.StudyDate);
			criteria[DicomTags.StudyDescription].SetStringValue(input.StudyDescription);
			criteria[DicomTags.PatientsBirthDate].SetStringValue("");
			criteria[DicomTags.ModalitiesInStudy].SetStringValue(input.ModalitiesInStudy);
			criteria[DicomTags.SpecificCharacterSet].SetStringValue("");
			criteria[DicomTags.StudyInstanceUid].SetStringValue(input.StudyInstanceUID);

			var reader = DataAccessLayer.GetIDataStoreReader();
			var results = reader.Query(criteria);

			return new QueryOutput(
				CollectionUtils.Map(results,
					delegate(DicomAttributeCollection result)
					{
						var item = new StudyProperties();
						item.PatientId = result[DicomTags.PatientId].ToString();
						item.PatientsName = result[DicomTags.PatientsName].ToString();
						item.StudyDate = result[DicomTags.StudyDate].GetDateTime(0);
						item.StudyDescription = result[DicomTags.StudyDescription].ToString();
						item.ModalitiesInStudy = result[DicomTags.ModalitiesInStudy].ToString();
						item.AccessionNumber = result[DicomTags.AccessionNumber].ToString();
						item.StudyInstanceUID = result[DicomTags.StudyInstanceUid].ToString();
						return item;
					}));
		}