Beispiel #1
0
        public async Task <GlossaryTermResults> getAll(string dictionary, AudienceType audience, string language, int size = 10, int from = 0, string[] requestedFields = null)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must specify a dictionary, audience, and language.");
            }

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(404, "Unsupported Language. Please try either 'en' or 'es'");
            }

            if (size <= 0)
            {
                size = 20;
            }

            if (from < 0)
            {
                from = 0;
            }

            if (requestedFields == null || requestedFields.Length == 0)
            {
                requestedFields = new string[] { "TermName", "Pronunciation", "Definition" }
            }
            ;

            GlossaryTermResults res = await _termsQueryService.getAll(dictionary, audience, language, size, from, requestedFields);

            return(res);
        }
Beispiel #2
0
 public Audience(AudienceType type, String value)
 {
     switch (type)
     {
         case AudienceType.Android:
             AndroidDeviceId = value;
             break;
         case AudienceType.Ios:
             IosDeviceId = value;
             break;
         case AudienceType.Windows:
             WindowsId = value;
             break;
         case AudienceType.WindowsPhone:
             WindowsPhoneId = value;
             break;
         case AudienceType.Blackberry:
             BlackberryId = value;
             break;
         case AudienceType.Segment:
             SegmentId = value;
             break;
         case AudienceType.Alias:
             Alias = value;
             break;
         case AudienceType.Tag:
             Tag = value;
             break;
     }
 }
Beispiel #3
0
        /// <summary>
        /// Infrastructure method for retrieving the "dictionary" parameter, returning appropriate Audience-aware
        /// default values if dictionary is not otherwise set.
        /// </summary>
        /// <returns>The value of the "dictionary" parameter.</returns>
        protected DictionaryType GetDictionaryWithDefaults()
        {
            String rawValue = GetOptionalParameter("dictionary");

            rawValue = Strings.Clean(rawValue, "Unknown");

            DictionaryType val = ConvertEnum <DictionaryType> .Convert(rawValue, DictionaryType.Unknown);

            if (val == DictionaryType.Unknown)
            {
                // is dictionary is unknown, check Audience and set default value
                String audienceValue = GetOptionalParameter("audience");
                audienceValue = Strings.Clean(audienceValue, "Unknown");

                AudienceType audience = ConvertEnum <AudienceType> .Convert(audienceValue, AudienceType.Unknown);

                switch (audience)
                {
                case AudienceType.HealthProfessional:
                    val = DictionaryType.NotSet;
                    break;

                default:
                    val = DictionaryType.term;
                    break;
                }
            }
            return(val);
        }
Beispiel #4
0
        public async void Count_QueryValues(string dictionary, AudienceType audience, string language)
        {
            Mock <ITermsQueryService> querySvc   = new Mock <ITermsQueryService>();
            TermsController           controller = new TermsController(NullLogger <TermsController> .Instance, querySvc.Object);

            // Set up the mock query service to handle the GetCount() call.
            // The return value is unimportant for this test.
            querySvc.Setup(
                mock => mock.GetCount(
                    It.IsAny <string>(),
                    It.IsAny <AudienceType>(),
                    It.IsAny <string>()
                    )
                )
            .Returns(Task.FromResult(default(long)));

            long result = await controller.GetCount(dictionary, audience, language);

            // Verify that the service layer is called:
            //  a) with the expected values.
            //  b) exactly once.
            querySvc.Verify(
                svc => svc.GetCount(dictionary, audience, language),
                Times.Once
                );
        }
Beispiel #5
0
        public async Task <GlossaryTermResults> Expand(string dictionary, AudienceType audience, string language, string character,
                                                       [FromQuery] int size = 100, [FromQuery] int from = 0, [FromQuery] bool includeAdditionalInfo = false)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience and language");
            }

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(400, "Unsupported Language. Please try either 'en' or 'es'");
            }

            if (size <= 0)
            {
                size = 100;
            }

            if (from < 0)
            {
                from = 0;
            }

            GlossaryTermResults res = await _termsQueryService.Expand(dictionary, audience, language, character, size, from, includeAdditionalInfo);

            return(res);
        }
        /// <summary>
        /// Performs a query for items from the DictionaryEntryMetadata list that are valid in the database..
        /// </summary>
        /// <param name="entriesList">A list of DictionaryEntryMetadata items, whose existence in the DB will be checked.</param>
        /// <returns>A list of DictionaryEntryMetadata items.</returns>
        public List <DictionaryEntryMetadata> DoDictionaryEntriesExist(List <DictionaryEntryMetadata> entriesList)
        {
            // In the initial implementation, the audience is implied by the particular dictionary being used.
            foreach (DictionaryEntryMetadata entry in entriesList)
            {
                AudienceType audience = GetDefaultAudienceFromDictionaryType(entry.Dictionary);
                entry.Audience = audience;
            }

            // Query that returns which DictionaryEntryMetadata items in the given list are valid in the database
            DictionaryQuery query   = new DictionaryQuery();
            DataTable       results = query.DoDictionaryEntriesExist(entriesList);

            List <DictionaryEntryMetadata> validEntries = new List <DictionaryEntryMetadata>();

            // Converts the datatable of entries into a list of DictionaryEntryMetadata items
            foreach (DataRow row in results.Rows)
            {
                DictionaryEntryMetadata entry = new DictionaryEntryMetadata();
                entry.CDRID      = row.Field <int>("CDRID");
                entry.Dictionary = (DictionaryType)System.Enum.Parse(typeof(DictionaryType), row.Field <string>("Dictionary"));
                entry.Language   = (Language)System.Enum.Parse(typeof(Language), row.Field <string>("Language"));
                entry.Audience   = (AudienceType)System.Enum.Parse(typeof(AudienceType), row.Field <string>("Audience"));

                validEntries.Add(entry);
            }

            return(validEntries);
        }
        /// <summary>
        /// Perform a search for terms with names or aliases that start with searchText, sorted by the  matched term name or alias.
        /// </summary>
        /// <param name="searchText">text to search for.</param>
        /// <param name="includeTypes">A filter for the types of name aliases to include.  Multiple values are separated by the pipe character (|).
        /// If no filter is supplied, the result </param>
        /// <param name="offset">Offset into the list of matches for the first result to return.</param>
        /// <param name="numResults">The maximum number of results to return. Must be at least 10.</param>
        /// <param name="dictionary">The dictionary to retreive the Term from.
        ///     Valid values are
        ///        Term - Dictionary of Cancer Terms
        ///        drug - Drug Dictionary
        ///        genetic - Dictionary of Genetics Terms
        /// </param>
        /// <param name="language">The Term's desired language.
        ///     Supported values are:
        ///         en - English
        ///         es - Spanish
        /// </param>
        /// <param name="version">String identifying which vereion of the JSON structure to retrieve.</param>
        /// <returns>An object structure containing the results of the search and various metadata.</returns>
        public SearchReturn Expand(String searchText, String includeTypes, int offset, int numResults, DictionaryType dictionary, Language language, String version)
        {
            log.Debug("Enter ValidateSearchSuggest().");

            // Sanity check for the offset and numResults
            if (offset < 0)
            {
                offset = 0;
            }
            if (numResults < 10)
            {
                numResults = 200;
            }

            // In the initial implementation, the audience is implied by the particular dictionary being used.
            AudienceType audience = GetDefaultAudienceFromDictionaryType(dictionary);

            // Convert delimited list to an array of distinct values.
            String[] includeFilter = Strings.ToListOfTrimmedStrings(includeTypes, LIST_DELIMITER);

            DictionaryQuery query   = new DictionaryQuery();
            SearchResults   results = query.Expand(searchText, includeFilter, offset, numResults, dictionary, language, audience, version);

            return(BuildSearchResultsStructure(results, language, audience, offset));
        }
        public async Task <Suggestion[]> GetSuggestions(string dictionary, AudienceType audience, string language, string query,
                                                        [FromQuery] bool contains = false, [FromQuery] int size = 20, [FromQuery] int from = 0)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience and language.");
            }

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(404, "Unsupported Language. Valid values are 'en' and 'es'.");
            }

            if (size <= 0)
            {
                size = 20;
            }

            if (from < 0)
            {
                from = 0;
            }


            return(await _autosuggestQueryService.GetSuggestions(dictionary, audience, language, query, contains, size, from));
        }
        /// <summary>
        /// Get Term details based on the input values
        /// <param name="dictionary">The value for dictionary.</param>
        /// <param name="audience">Patient or Healthcare provider</param>
        /// <param name="language">The language in which the details needs to be fetched</param>
        /// <param name="id">The Id for the term</param>
        /// <returns>An object of GlossaryTerm</returns>
        /// </summary>
        public async Task <GlossaryTerm> GetById(string dictionary, AudienceType audience, string language, long id)
        {
            IGetResponse <GlossaryTerm> response = null;

            try
            {
                string idValue = $"{id}_{dictionary?.ToLower()}_{language?.ToLower()}_{audience.ToString().ToLower()}";
                response = await _elasticClient.GetAsync <GlossaryTerm>(new DocumentPath <GlossaryTerm>(idValue),
                                                                        g => g.Index( this._apiOptions.AliasName ).Type("terms"));
            }
            catch (Exception ex)
            {
                String msg = $"Could not search dictionary '{dictionary}', audience '{audience}', language '{language}' and id '{id}.";
                _logger.LogError($"Error searching index: '{this._apiOptions.AliasName}'.");
                _logger.LogError(ex, msg);
                throw new APIErrorException(500, msg);
            }

            if (!response.IsValid)
            {
                String msg = $"Invalid response when searching for dictionary  '{dictionary}', audience '{audience}', language '{language}' and id '{id}.";
                _logger.LogError(msg);
                throw new APIErrorException(500, msg);
            }

            if (null == response.Source)
            {
                string msg = $"No match for dictionary '{dictionary}', audience '{audience}', language '{language}' and id '{id}.";
                _logger.LogDebug(msg);
                throw new APIErrorException(404, msg);
            }

            return(response.Source);
        }
        public async void Verify_Argument_passing(string dictionary, AudienceType audience, string language, string queryText, MatchType matchType)
        {
            const int expecedSizeRequest = 20;

            Mock <IAutosuggestQueryService> querySvc   = new Mock <IAutosuggestQueryService>();
            AutosuggestController           controller = new AutosuggestController(querySvc.Object);

            // Set up the mock query service to return an empty array.
            querySvc.Setup(
                autoSuggestQSvc => autoSuggestQSvc.GetSuggestions(
                    It.IsAny <string>(),
                    It.IsAny <AudienceType>(),
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <MatchType>(),
                    It.IsAny <int>()
                    )
                )
            .Returns(Task.FromResult(new Suggestion[] { }));

            Suggestion[] result = await controller.GetSuggestions(dictionary, audience, language, queryText, matchType);

            // Verify that the service layer is called:
            //  a) with the exact values passed to the controller.
            //  b) exactly once.
            querySvc.Verify(
                svc => svc.GetSuggestions(dictionary, audience, language, queryText, matchType, expecedSizeRequest),
                Times.Once
                );

            Assert.Empty(result);
        }
Beispiel #11
0
        /// <summary>
        /// Translates values of type NCI.Web.Dictionary.AudienceType.
        /// to values of the type NCI.Services.Dictionary.AudienceType.
        /// </summary>
        /// <param name="dictionary">The NCI.Web.Dictionary.AudienceType value to be translated.</param>
        /// <returns>A value of type NCI.Services.Dictionary.AudienceType.</returns>
        public static svcAudienceType Translate(AudienceType xlate)
        {
            svcAudienceType audience;

            switch (xlate)
            {
            case AudienceType.Unknown:
                audience = svcAudienceType.Unknown;
                break;

            case AudienceType.HealthProfessional:
                audience = svcAudienceType.HealthProfessional;
                break;

            case AudienceType.Patient:
                audience = svcAudienceType.Patient;
                break;
                break;

            default:
                throw new ArgumentException(String.Format("Uknown type '{0}'.", xlate));
            }

            return(audience);
        }
Beispiel #12
0
        /// <summary>
        /// Infrastructure method for retrieving the "audience" parameter, returning appropriate Dictionary-aware
        /// default values if audience is not otherwise set.
        /// </summary>
        /// <returns>The value of the "audience" parameter.</returns>
        protected AudienceType GetAudienceWithDefaults()
        {
            String rawValue = GetOptionalParameter("audience");

            rawValue = Strings.Clean(rawValue, "Unknown");

            AudienceType val = ConvertEnum <AudienceType> .Convert(rawValue, AudienceType.Unknown);

            if (val == AudienceType.Unknown)
            {
                // is dictionary is unknown, check Audience and set default value
                String dictionaryValue = GetOptionalParameter("dictionary");
                dictionaryValue = Strings.Clean(dictionaryValue, "Unknown");

                DictionaryType dictionary = ConvertEnum <DictionaryType> .Convert(dictionaryValue, DictionaryType.Unknown);

                switch (dictionary)
                {
                case DictionaryType.NotSet:
                case DictionaryType.genetic:
                    val = AudienceType.HealthProfessional;
                    break;

                default:
                    val = AudienceType.Patient;
                    break;
                }
            }
            return(val);
        }
Beispiel #13
0
        public async Task <GlossaryTermResults> GetAll(string dictionary, AudienceType audience, string language, int size = 100, int from = 0, bool includeAdditionalInfo = false)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience and language.");
            }

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(400, "Unsupported Language. Valid values are 'en' and 'es'.");
            }

            if (size <= 0)
            {
                size = 100;
            }

            if (from < 0)
            {
                from = 0;
            }

            GlossaryTermResults res = await _termsQueryService.GetAll(dictionary, audience, language, size, from, includeAdditionalInfo);

            return(res);
        }
Beispiel #14
0
        public async Task <GlossaryTermResults> Search(string dictionary, AudienceType audience, string language, string query,
                                                       [FromQuery] MatchType matchType = MatchType.Begins, [FromQuery] int size = 100, [FromQuery] int from = 0, [FromQuery] bool includeAdditionalInfo = false)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience and language.");
            }

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(400, "Unsupported Language. Valid values are 'en' and 'es'.");
            }

            if (!Enum.IsDefined(typeof(MatchType), matchType))
            {
                throw new APIErrorException(400, "Invalid value for the 'matchType' parameter.");
            }

            if (size <= 0)
            {
                size = 100;
            }

            if (from < 0)
            {
                from = 0;
            }

            // query uses a catch-all route, make sure it's been decoded.
            query = WebUtility.UrlDecode(query);

            GlossaryTermResults res = await _termsQueryService.Search(dictionary, audience, language, query, matchType, size, from, includeAdditionalInfo);

            return(res);
        }
        public async Task <Suggestion[]> GetSuggestions(string dictionary, AudienceType audience, string language, string searchText,
                                                        [FromQuery] MatchType matchType = MatchType.Begins, [FromQuery] int size = 20)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience and language.");
            }

            if (!Enum.IsDefined(typeof(MatchType), matchType))
            {
                throw new APIErrorException(400, "The 'matchType' parameter must be either 'Begins' or 'Contains'.");
            }

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(400, "Unsupported Language. Valid values are 'en' and 'es'.");
            }

            if (size <= 0)
            {
                size = 20;
            }

            // searchText uses a catch-all route, make sure it's been decoded.
            searchText = WebUtility.UrlDecode(searchText);

            return(await _autosuggestQueryService.GetSuggestions(dictionary, audience, language, searchText, matchType, size));
        }
        /// <summary>
        /// Get Term deatils based on the input values
        /// <param name="dictionary">The value for dictionary.</param>
        /// <param name="audience">Patient or Healthcare provider</param>
        /// <param name="language">The language in which the details needs to be fetched</param>
        /// <param name="id">The Id for the term</param>
        /// <param name="requestedFields"> The list of fields that needs to be sent in the response</param>
        /// <returns>An object of GlossaryTerm</returns>
        /// </summary>
        public async Task <GlossaryTerm> GetById(string dictionary, AudienceType audience, string language, long id, string[] requestedFields)
        {
            IGetResponse <GlossaryTerm> response = null;

            try
            {
                string idValue = id + "_" + dictionary + "_" + language + "_" + audience.ToString().ToLower();
                response = await _elasticClient.GetAsync <GlossaryTerm>(new DocumentPath <GlossaryTerm>(idValue),
                                                                        g => g.Index( this._apiOptions.AliasName ).Type("terms"));
            }
            catch (Exception ex)
            {
                String msg = String.Format("Could not search dictionary '{0}', audience '{1}', language '{2}' and id '{3}.", dictionary, audience, language, id);
                _logger.LogError(msg, ex);
                throw new APIErrorException(500, msg);
            }

            if (!response.IsValid)
            {
                String msg = String.Format("Invalid response when searching for dictionary '{0}', audience '{1}', language '{2}' and id '{3}.", dictionary, audience, language, id);
                _logger.LogError(msg);
                throw new APIErrorException(500, msg);
            }

            if (null == response.Source)
            {
                string msg = String.Format("Empty response when searching for dictionary '{0}', audience '{1}', language '{2}' and id '{3}.", dictionary, audience, language, id);
                _logger.LogError(msg);
                throw new APIErrorException(200, msg);
            }

            return(response.Source);
        }
Beispiel #17
0
        /// <summary>
        /// Calls the database to retrieve a single dictionary term based on its specific Term ID.
        /// Similar, but not identical, to GetTerm().  Instead of retrieving the term for a specific
        /// dictionary, the term is fetched for a preferred audience.  If no records are available for that audience,
        /// then any other avaiable records are returned instead.
        /// </summary>
        /// <param name="termId">The ID of the Term to be retrieved</param>
        /// <param name="language">The Term's desired language.
        ///     Supported values are:
        ///         en - English
        ///         es - Spanish
        /// </param>
        /// <param name="preferredAudience">Preferred target audieince for the definition.</param>
        /// <param name="version">String identifying which vereion of the API to match.</param>
        /// <returns></returns>
        public DataTable GetTermForAudience(int termId, Language language, AudienceType preferredAudience, String version)
        {
            log.DebugFormat("Enter GetTermForAudience( {0}, {1}, {2}, {3} ).", termId, language, preferredAudience, version);

            DataTable results = null;

            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter("@TermID", SqlDbType.Int)
                {
                    Value = termId
                },
                new SqlParameter("@Language", SqlDbType.NVarChar)
                {
                    Value = language.ToString()
                },
                new SqlParameter("@PreferredAudience", SqlDbType.NVarChar)
                {
                    Value = preferredAudience.ToString()
                },
                new SqlParameter("@ApiVers", SqlDbType.NVarChar)
                {
                    Value = version
                },
            };

            using (SqlConnection conn = SqlHelper.CreateConnection(DBConnectionString))
            {
                results = SqlHelper.ExecuteDatatable(conn, CommandType.StoredProcedure, SP_GET_DICTIONARY_TERM_FOR_AUDIENCE, parameters);
            }

            return(results);
        }
Beispiel #18
0
        /// <summary>
        /// Retrieves a portion of the overall set of glossary terms for a given combination of dictionary, audience, and language.
        /// </summary>
        /// <param name="dictionary">The specific dictionary to retrieve from.</param>
        /// <param name="audience">The target audience.</param>
        /// <param name="language">Language (English - en; Spanish - es).</param>
        /// <param name="size">The number of records to retrieve.</param>
        /// <param name="from">The offset into the overall set to use for the first record.</param>
        /// <param name="requestedFields">The fields to retrieve.  If not specified, defaults to TermName, Pronunciation, and Definition.</param>
        /// <returns>A GlossaryTermResults object containing the desired records.</returns>
        public async Task <GlossaryTermResults> getAll(string dictionary, AudienceType audience, string language, int size, int from, string[] requestedFields)
        {
            // Dummy return for now.
            GlossaryTermResults results = new GlossaryTermResults()
            {
                Meta = new ResultsMetadata()
                {
                    TotalResults = 200,
                    From         = 20
                },
                Links = new Metalink()
                {
                    Self = new System.Uri("https://www.cancer.gov")
                },
                Results = new GlossaryTerm[]
                {
                    new GlossaryTerm()
                    {
                        TermId        = 43966,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.HealthProfessional,
                        TermName      = "stage II cutaneous T-cell lymphoma",
                        PrettyUrlName = "stage-ii-cutaneous-t-cell-lymphoma",
                        Pronunciation = new Pronunciation()
                        {
                            Key   = "kyoo-TAY-nee-us T-sel lim-FOH-muh",
                            Audio = "https://www.cancer.gov/PublishedContent/Media/CDR/media/703959.mp3"
                        },
                        Definition = new Definition()
                        {
                            Html = "Stage II cutaneous T-cell lymphoma may be either of the following: (1) stage IIA, in which the skin has red, dry, scaly patches but no tumors, and lymph nodes are enlarged but do not contain cancer cells; (2) stage IIB, in which tumors are found on the skin, and lymph nodes are enlarged but do not contain cancer cells.",
                            Text = "Stage II cutaneous T-cell lymphoma may be either of the following: (1) stage IIA, in which the skin has red, dry, scaly patches but no tumors, and lymph nodes are enlarged but do not contain cancer cells; (2) stage IIB, in which tumors are found on the skin, and lymph nodes are enlarged but do not contain cancer cells."
                        }
                    },
                    new GlossaryTerm()
                    {
                        TermId        = 43971,
                        Language      = "en",
                        Dictionary    = "Cancer.gov",
                        Audience      = AudienceType.Patient,
                        TermName      = "bcl-2 antisense oligodeoxynucleotide G3139",
                        PrettyUrlName = "bcl-2-antisense-oligodeoxynucleotide-g3139",
                        Pronunciation = new Pronunciation()
                        {
                            Key   = "AN-tee-sents AH-lih-goh-dee-OK-see-NOO-klee-oh-tide",
                            Audio = "https://www.cancer.gov/PublishedContent/Media/CDR/media/703968mp3"
                        },
                        Definition = new Definition()
                        {
                            Html = "A substance being studied in the treatment of cancer. It may kill cancer cells by blocking the production of a protein that makes cancer cells live longer and by making them more sensitive to anticancer drugs. It is a type of antisense oligodeoxyribonucleotide. Also called augmerosen, Genasense, and oblimersen sodium.",
                            Text = "A substance being studied in the treatment of cancer. It may kill cancer cells by blocking the production of a protein that makes cancer cells live longer and by making them more sensitive to anticancer drugs. It is a type of antisense oligodeoxyribonucleotide. Also called augmerosen, Genasense, and oblimersen sodium."
                        }
                    }
                }
            };

            return(results);
        }
Beispiel #19
0
        private void MainDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            AudienceType audiencetype = (AudienceType)MainDataGridView.Rows[e.RowIndex].DataBoundItem;
            Teacher      teacher      = audiencetype.Teacher;
            Corps        corps        = audiencetype.Corps;

            ShowAddAudience(audiencetype, teacher, corps);
        }
Beispiel #20
0
 /// <summary>
 /// Initialization.  Use Invoker.Create() with method set to ApiMethodType.GetTerm
 /// to instanatiate an GetTermInvoker object.
 /// </summary>
 /// <param name="request">The current request object.</param>
 public GetTermInvoker(HttpRequest request)
     : base(request)
 {
     TermID       = GetTermID();
     Dictionary   = GetDictionaryWithDefaults();
     Language     = GetLanguage();
     AudienceType = GetAudienceWithDefaults();
 }
Beispiel #21
0
        private void AddAudienceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AudienceType audience = new AudienceType();
            Teacher      teacher  = new Teacher();
            Corps        corps    = new Corps();

            ShowAddAudience(audience, teacher, corps);
        }
Beispiel #22
0
        public async Task <GlossaryTerm> GetById(string dictionary, AudienceType audience, string language, long id, bool useFallback = false)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || id <= 0)
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience, language and id");
            }

            // Lowercase the dictionary argument for use in fallback option checks and ES query
            dictionary = dictionary.ToLower();

            if (language.ToLower() != "en" && language.ToLower() != "es")
            {
                throw new APIErrorException(400, "Unsupported Language. Please try either 'en' or 'es'");
            }

            if (useFallback == false)
            {
                return(await _termsQueryService.GetById(dictionary, audience, language, id));
            }
            // Implement fallback logic.
            // Depending on the given Dictionary and Audience inputs, loop through the fallback logic options until a term is found.
            // If the given fallback combination does not exist, then throw an error.
            // If none of the options return a term, then throw an error.
            else
            {
                // Set order of fallback options based on current audience.
                var fallbackOptions = audience == AudienceType.Patient ? _fallbackOptionsPatient : _fallbackOptionsHP;

                Tuple <string, AudienceType> requestedOptions        = new Tuple <string, AudienceType>(dictionary, audience);
                LinkedListNode <Tuple <string, AudienceType> > start = fallbackOptions.Find(requestedOptions);

                if (start == null)
                {
                    string msg = $"Could not find initial fallback combination with dictionary '{dictionary}' and audience '{audience}'.";
                    _logger.LogError(msg);
                    throw new APIErrorException(404, msg);
                }

                LinkedListNode <Tuple <string, AudienceType> > current = start;

                do
                {
                    try {
                        return(await _termsQueryService.GetById(current.Value.Item1, current.Value.Item2, language, id));
                    }
                    catch (Exception ex) {
                        // Swallow this Exception and move to the next combination.
                        string msg = $"Could not find fallback term with ID '{id}', dictionary '{current.Value.Item1}', audience '{current.Value.Item2}', and language '{language}'.";
                        _logger.LogDebug(ex, msg);
                    }
                    current = current.Next == null ? fallbackOptions.First : current.Next;
                } while (current != start);

                string message = $"Could not find fallback term with ID '{id}' for any combination of dictionary and audience.";
                _logger.LogError(message);
                throw new APIErrorException(404, message);
            }
        }
Beispiel #23
0
        public async Task <long> GetCount(string dictionary, AudienceType audience, string language)
        {
            if (String.IsNullOrWhiteSpace(dictionary) || String.IsNullOrWhiteSpace(language) || !Enum.IsDefined(typeof(AudienceType), audience))
            {
                throw new APIErrorException(400, "You must supply a valid dictionary, audience and language.");
            }

            return(await _termsQueryService.GetCount(dictionary, audience, language));
        }
 public ActionResult Edit([Bind(Include = "AudienceTypeID,TypeOfAudience")] AudienceType audienceType)
 {
     if (ModelState.IsValid)
     {
         db.Entry(audienceType).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(audienceType));
 }
Beispiel #25
0
        /// <summary>
        /// Search for Terms based on the search criteria.
        /// <param name="dictionary">The value for dictionary.</param>
        /// <param name="audience">Patient or Healthcare provider</param>
        /// <param name="language">The language in which the details needs to be fetched</param>
        /// <param name="query">The search query</param>
        /// <param name="matchType">Defines if the search should begin with or contain the key word</param>
        /// <param name="size">Defines the size of the search</param>
        /// <param name="from">Defines the Offset for search</param>
        /// <param name="requestedFields"> The list of fields that needs to be sent in the response</param>
        /// <returns>A list of GlossaryTerm</returns>
        /// </summary>
        public async Task <List <GlossaryTerm> > Search(string dictionary, AudienceType audience, string language, string query, string matchType, int size, int from, string[] requestedFields)
        {
            // Temporary Solution till we have Elastic Search
            List <GlossaryTerm> glossaryTermList = new List <GlossaryTerm>();

            glossaryTermList.Add(GenerateSampleTerm(requestedFields));
            glossaryTermList.Add(GenerateSampleTerm(requestedFields));

            return(glossaryTermList);
        }
        /// <summary>
        /// Lightweight method to search for terms matching searchText. This method is intended for use with autosuggest
        /// and returns a maximum of 10 results
        /// </summary>
        /// <param name="searchText">text to search for.</param>
        /// <param name="searchType">The type of search to perform.
        ///     Valid values are:
        ///         Begins - Search for terms beginning with searchText.
        ///         Contains - Search for terms containing searchText.
        ///         Magic - Search for terms beginning with searchText, followed by those containing searchText.
        /// </param>
        /// <param name="numResults">Maximum number of results to return.</param>
        /// <param name="dictionary">The dictionary to retreive the Term from.
        ///     Valid values are
        ///        Term - Dictionary of Cancer Terms
        ///        drug - Drug Dictionary
        ///        genetic - Dictionary of Genetics Terms
        /// </param>
        /// <param name="language">The Term's desired language.
        ///     Supported values are:
        ///         en - English
        ///         es - Spanish
        /// </param>
        /// <param name="version">String identifying which vereion of the JSON structure to retrieve.</param>
        /// <returns></returns>
        public SuggestReturn SearchSuggest(String searchText, SearchType searchType, int numResults, DictionaryType dictionary, Language language, String version)
        {
            log.DebugFormat("Enter ValidateSearchSuggest( {0}, {1}, {2}, {3}, {4}, {5}).", searchText, searchType, numResults, dictionary, language, version);

            // Sanity check for numResults
            if (numResults < 10)
            {
                numResults = 10;
            }

            // In the initial implementation, the audience is implied by the particular dictionary being used.
            AudienceType audience = GetDefaultAudienceFromDictionaryType(dictionary);

            DictionaryQuery   query   = new DictionaryQuery();
            SuggestionResults results = query.SearchSuggest(searchText, searchType, numResults, dictionary, language, audience, version);

            List <String> messages = new List <string>();

            int resultCount = results.MatchCount;

            // Report the count in a human-readable format.
            String message = String.Format("Found {0} results.", resultCount);

            log.Debug(message);
            messages.Add(message);

            // Retrieve results.  We already know the number of results, so let's preset the
            // list to the size we know we're going to need.
            List <DictionarySuggestion> foundTerms = new List <DictionarySuggestion>(resultCount);

            foreach (DataRow row in results.Data.Rows)
            {
                int    ID   = row.Field <int>("TermID");
                string term = row.Field <String>("TermName");
                DictionarySuggestion suggestion = new DictionarySuggestion(ID, term);
                foundTerms.Add(suggestion);
            }

            // Populate return metadata structure
            SuggestReturnMeta meta = new SuggestReturnMeta()
            {
                ResultCount = resultCount,
                Messages    = messages.ToArray()
            };

            // Combine meta and results to create the final return object.
            SuggestReturn suggestReturn = new SuggestReturn()
            {
                Result = foundTerms.ToArray(),
                Meta   = meta
            };

            return(suggestReturn);
        }
        public ActionResult Create([Bind(Include = "AudienceTypeID,TypeOfAudience")] AudienceType audienceType)
        {
            if (ModelState.IsValid)
            {
                db.AudienceTypes.Add(audienceType);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(audienceType));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string input_term;

            if (PageAssemblyContext.Current.DisplayVersion == DisplayVersions.Web)
            {
                urlArgs    = Request.Url.Query.Substring(1);
                input_term = Strings.Clean(Request.Params["term"]);
                CdrID      = Strings.IfNull(Strings.Clean(Request.Params["id"]), Strings.Clean(Request.Params["cdrid"]));
                AudienceType   audience   = GetAudienceType(Strings.Clean(Request.Params["version"]));
                DictionaryType dictionary = GetDictionaryType(Strings.Clean(Request.Params["dictionary"]));

                //load the definition
                DictionaryAppManager _dictionaryAppManager = new DictionaryAppManager();

                DictionaryTerm dataItem = null;

                if (!string.IsNullOrEmpty(CdrID))
                {
                    CdrID = Regex.Replace(CdrID, "^CDR0+", "", RegexOptions.Compiled);
                    // call appropriate method if dictionary type is known
                    // the language is set to English = en by default
                    if (dictionary == DictionaryType.Unknown)
                    {
                        dataItem = _dictionaryAppManager.GetTermForAudience(Convert.ToInt32(CdrID), dictionaryLanguage, "v1", audience);
                    }
                    else
                    {
                        dataItem = _dictionaryAppManager.GetTerm(Convert.ToInt32(CdrID), dictionary, dictionaryLanguage, "v1", audience);
                    }
                }

                if (dataItem != null && dataItem.Term != null)
                {
                    ActivateDefinitionView(dataItem);
                }
                else
                {
                    phDefinition.Visible = false;
                    phNoResult.Visible   = true;
                }

                // Web Analytics *************************************************
                WebAnalyticsPageLoad webAnalyticsPageLoad = new WebAnalyticsPageLoad();

                webAnalyticsPageLoad.SetChannel("Dictionary of Cancer Terms");
                webAnalyticsPageLoad.SetLanguage("en");

                webAnalyticsPageLoad.AddEvent(WebAnalyticsOptions.Events.event11); // Dictionary Term view (event11)
                litOmniturePageLoad.Text = webAnalyticsPageLoad.Tag();             // Load page load script
                // End Web Analytics *********************************************
            }
        }
Beispiel #29
0
        public Audience(AudienceType type, string value, bool isChannel = false)
        {
            switch (type)
            {
            case AudienceType.Android:
                if (isChannel)
                {
                    AndroidChannel = value;
                }
                else
                {
                    AndroidDeviceId = value;
                }
                break;

            case AudienceType.Ios:
                if (isChannel)
                {
                    IosChannel = value;
                }
                else
                {
                    IosDeviceId = value;
                }
                break;

            case AudienceType.Windows:
                WindowsId = value;
                break;

            case AudienceType.WindowsPhone:
                WindowsPhoneId = value;
                break;

            case AudienceType.Blackberry:
                BlackberryId = value;
                break;

            case AudienceType.Segment:
                SegmentId = value;
                break;

            case AudienceType.Alias:
                Alias = value;
                break;

            case AudienceType.Tag:
                Tag = value;
                break;
            }
        }
        // GET: AudienceTypes/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AudienceType audienceType = db.AudienceTypes.Find(id);

            if (audienceType == null)
            {
                return(HttpNotFound());
            }
            return(View(audienceType));
        }
        /// <summary>
        /// Retrieves a single dictionary Term based on its specific Term ID.
        /// </summary>
        /// <param name="termId">The ID of the Term to be retrieved</param>
        /// <param name="dictionary">The dictionary to retreive the Term from.
        ///     Valid values are
        ///        Term - Dictionary of Cancer Terms
        ///        drug - Drug Dictionary
        ///        genetic - Dictionary of Genetics Terms
        /// </param>
        /// <param name="language">The Term's desired language.
        ///     Supported values are:
        ///         en - English
        ///         es - Spanish
        /// </param>
        /// <returns></returns>
        public TermReturn GetTerm(int termId, DictionaryType dictionary, Language language)
        {
            log.DebugFormat("Enter GetTerm( {0}, {1}, {2}).", termId, dictionary, language);

            AudienceType audience = AudienceType.Patient;

            // determine what audience to use based on the dictionary
            DictionaryManager dictionaryManager = new DictionaryManager();

            audience = dictionaryManager.GetDefaultAudienceFromDictionaryType(dictionary);

            // route to GetTerm with all arguments
            return(GetTerm(termId, dictionary, language, audience));
        }
Beispiel #32
0
 public Audience(AudienceType type, string value, bool isChannel = false)
 {
     switch (type)
     {
         case AudienceType.Android:
             if (isChannel)
                 AndroidChannel = value;
             else
                 AndroidDeviceId = value;
             break;
         case AudienceType.Ios:
             if (isChannel)
                 IosChannel = value;
             else
                 IosDeviceId = value;
             break;
         case AudienceType.Windows:
             WindowsId = value;
             break;
         case AudienceType.WindowsPhone:
             WindowsPhoneId = value;
             break;
         case AudienceType.Blackberry:
             BlackberryId = value;
             break;
         case AudienceType.Segment:
             SegmentId = value;
             break;
         case AudienceType.Alias:
             Alias = value;
             break;
         case AudienceType.Tag:
             Tag = value;
             break;
     }
 }
Beispiel #33
0
 private AudienceTarget(AudienceType audienceType, HashSet<string> values)
 {
     this.audienceType = audienceType;
     this.valueBuilder = values;
 }
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Sets the "Broad Type", the audience for which the resource being archived is
		/// primarily intended. This is set automatically as a side-effect of setting the
		/// stage or type.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void SetAudience(AudienceType audienceType)
		{
			if (IsMetadataPropertySet(MetadataProperties.Audience))
			{
				if (_metsAudienceType != audienceType)
					throw new InvalidOperationException(string.Format("Audience has already been set and cannot be changed to a different value."));
				return; // Already added
			}

			MarkMetadataPropertyAsSet(MetadataProperties.Audience);
			_metsAudienceType = audienceType;

			string audience;
			switch (audienceType)
			{
				case AudienceType.Vernacular: audience = kAudienceVernacular; break;
				case AudienceType.Training: audience = kAudienceTraining; break;
				case AudienceType.Internal: audience = kAudienceInternal; break;
				case AudienceType.Wider: audience = kAudienceWide; break;
				default:
					throw new NotImplementedException("Need to add appropriate METS constant for audience type " + audienceType);
			}
			_metsPairs.Add(JSONUtils.MakeKeyValuePair(kAudience, audience));
		}
Beispiel #35
0
 public void SetAudience(AudienceType audienceType, String value)
 {
     Audience = new Audience(audienceType, value);
 }