Beispiel #1
0
        internal static string GetResourceString(string resourceName, string languageTag)
        {
            try
            {
                var language = new UtilityHelper().LanguageToLanguageTag(languageTag);
                if (ApplicationLanguages.PrimaryLanguageOverride != language)
                {
                    ApplicationLanguages.PrimaryLanguageOverride = language;
                    ResourceContext.GetForViewIndependentUse().Reset();
                }
                var         resourceContext = new ResourceContext();
                ResourceMap libmap          = ResourceManager.Current.MainResourceMap.GetSubtree("ApplicationConstants.Resources");
                var         resourceString  = libmap.GetValue(resourceName, resourceContext).ValueAsString;
                return(resourceString);
                //var language = new UtilityHelper().LanguageToLanguageTag(languageTag);
                //var resourceManager = new System.Resources.ResourceManager("ApplicationConstants.Resources", typeof(Helper).GetTypeInfo().Assembly);


                //CultureInfo ci = new CultureInfo(language);

                //var resourceString = resourceManager.GetString(resourceName,ci);

                //return resourceString;
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 编辑模板
        /// </summary>
        public void Edit_GET()
        {
            string tpl = Request["tpl"];

            if (String.IsNullOrEmpty(tpl))
            {
                tpl = base.CurrentSite.Tpl;
            }
            StringBuilder sb = new StringBuilder();

            DirectoryInfo dir = new DirectoryInfo(String.Format("{0}templates/{1}/", AppDomain.CurrentDomain.BaseDirectory, tpl));

            if (!dir.Exists)
            {
                Response.Redirect(Request.Path + "?module=template&action=templates", true);
                return;
            }

            EachClass.IterialTemplateFiles(dir, sb, tpl);

            base.RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Template_Edit), new
            {
                tplfiles = sb.ToString(),
                tpl      = tpl
            });
        }
        static partial void PlatformInit()
        {
            Location = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            ResourceContext = new Windows.ApplicationModel.Resources.Core.ResourceContext();
            FileResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Files");
        }
Beispiel #4
0
        /// <summary>
        /// 分类扩展信息设置
        /// </summary>
        /// <returns></returns>
        public void Category_Check()
        {
            var         categoryId = int.Parse(Request.Query("category_id"));
            IList <int> extendIds  = new List <int>();
            var         list       = ExtendFieldCacheManager.GetExtendFields(CurrentSite.SiteId);
            var         category   = ServiceCall.Instance.SiteService.GetCategory(SiteId, categoryId);

            foreach (var extend in category.ExtendFields)
            {
                extendIds.Add(extend.GetDomainId());
            }

            var json = JsonSerializer.Serialize(list);

            category.ExtendFields = null;
            var categoryJson = JsonSerializer.Serialize(new
            {
                ID        = category.ID,
                Path      = category.Path,
                Name      = category.Name,
                ExtendIds = extendIds
            });

            RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Site_Extend_Category_Check), new
            {
                url      = Request.GetEncodedUrl(),
                json     = json,
                category = categoryJson
            });
        }
Beispiel #5
0
        public string Category_Clone()
        {
            int targetSiteId;

            int.TryParse(Request.Query("target_site"), out targetSiteId);

            string siteOpt;
            var    targetSite = default(SiteDto);

            IDictionary <string, string> dict = new Dictionary <string, string>();

            foreach (var e in SiteCacheManager.GetAllSites())
            {
                if (e.SiteId != targetSiteId)
                {
                    dict.Add(e.SiteId.ToString(), e.Name);
                }
                else
                {
                    targetSite = e;
                }
            }
            siteOpt = Helper.GetOptions(dict, null);

            ViewData["site_opt"]    = siteOpt;
            ViewData["target_name"] = targetSite.Name;
            ViewData["target_site"] = targetSite.SiteId;

            return(RequireTemplate(ResourceMap.GetPageContent(ManagementPage.Assistant_Category_Clone)));
        }
Beispiel #6
0
        /// <summary>
        /// 系统设置
        /// </summary>
        public void Config()
        {
            object data = new
            {
                license_name              = Settings.LICENSE_NAME,
                license_key               = Settings.LICENSE_KEY,
                site_domain               = Request.GetHost(),
                sys_www_rd                = Settings.SYS_WWW_RD,
                sys_force_https           = Settings.SYS_FORCE_HTTPS,
                sys_admin_tag             = Settings.SYS_ADMIN_TAG,
                sys_encode_conf           = Settings.SYS_ENCODE_CONF_FILE,
                db_prefix                 = Settings.DB_PREFIX,
                perm_index_cache_second   = (Settings.PERM_INDEX_CACHE_SECOND / 60).ToString(),
                opti_client_cache_seconds = (Settings.Opti_ClientCacheSeconds / 60).ToString(),
                opti_gc_collect_interval  = Settings.opti_gc_collect_interval / 3600000,
                opti_debug                = Settings.OPTI_DEBUG_MODE,
                sys_use_upload_raw_path   = Settings.SYS_USE_UPLOAD_RAW_NAME,
                server_static             = Settings.SERVER_STATIC,
                server_upgrade            = Settings.SERVER_UPGRADE,
                server_static_enabled     = Settings.SERVER_STATIC_ENABLED,
                tpl_full_url_path         = Settings.TPL_FULL_URL_PATH,
                tpl_use_compress          = Settings.TPL_USE_COMPRESS,
                tpl_use_cache             = Settings.TPL_USE_CACHE,
            };

            RenderTemplate(ResourceMap.GetPageContent(ManagementPage.App_Config), new
            {
                json = JsonSerializer.Serialize(data)
            });
        }
Beispiel #7
0
        /// <summary>
        /// 系统设置
        /// </summary>
        public void AppConfig_GET()
        {
            object data = new
            {
                license_name             = Settings.License_NAME,
                license_key              = Settings.License_KEY,
                site_domain              = Request.Url.Host,
                sys_autowww              = Settings.SYS_AUTOWWW,
                sys_admin_tag            = Settings.SYS_ADMIN_TAG,
                sys_encode_conf          = Settings.SYS_ENCODE_CONF_FILE,
                db_prefix                = Settings.DB_PREFIX,
                opti_IndexCacheSeconds   = (Settings.Opti_IndexCacheSeconds / 60).ToString(),
                opti_ClientCacheSeconds  = (Settings.Opti_ClientCacheSeconds / 60).ToString(),
                Opti_GC_Collect_Interval = (Settings.Opti_GC_Collect_Interval / 3600000),
                opti_debug               = Settings.Opti_Debug,
                server_static            = Settings.SERVER_STATIC,
                server_upgrade           = Settings.SERVER_UPGRADE,
                server_static_enabled    = Settings.SERVER_STATIC_ENABLED,
                tpl_usefullpath          = Settings.TPL_UseFullPath,
                tpl_usecompress          = Settings.TPL_UseCompress
            };

            base.RenderTemplate(ResourceMap.GetPageContent(ManagementPage.App_Config), new
            {
                json = JsonSerializer.Serialize(data)
            });
        }
Beispiel #8
0
        public string Fields_GET()
        {
            string form = EntityForm.Build <ExtendFieldDto>(new ExtendFieldDto());

            ViewData["form"] = form;
            return(base.RequireTemplate(ResourceMap.GetPageContent(ManagementPage.Site_Extend_List)));
        }
Beispiel #9
0
        /// <summary>
        /// 模板设置
        /// </summary>
        public void Settings_GET()
        {
            string tpl = Request["tpl"];

            if (String.IsNullOrEmpty(tpl))
            {
                tpl = base.CurrentSite.Tpl;
            }

            var tplSetting = Cms.TemplateManager.Get(tpl);

            base.ViewData["json"] = JsonConvert.SerializeObject(new
            {
                //模板
                tpl_CFG_OutlineLength        = tplSetting.CfgOutlineLength.ToString(),
                tpl_CFG_AllowAmousComment    = tplSetting.CFG_AllowAmousComment,
                tpl_CFG_CommentEditorHtml    = tplSetting.CFG_CommentEditorHtml,
                tpl_CFG_ArchiveTagsFormat    = tplSetting.CFG_ArchiveTagsFormat,
                tpl_CFG_FriendLinkFormat     = tplSetting.CFG_FriendLinkFormat,
                tpl_CFG_FriendShowNum        = tplSetting.CFG_FriendShowNum,
                tpl_CFG_NavigatorLinkFormat  = tplSetting.CFG_NavigatorLinkFormat,
                tpl_CFG_NavigatorChildFormat = tplSetting.CFG_NavigatorChildFormat,
                tpl_CFG_SitemapSplit         = tplSetting.CFG_SitemapSplit,
                tpl_CFG_TrafficFormat        = tplSetting.CFG_TrafficFormat,
                tpl_CFG_Enabled_Mobi         = tplSetting.CfgEnabledMobiPage?"1":"0",
                tpl_CFG_Show_Error           = tplSetting.CfgShowError ? "1" : "0",
            });
            base.RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Template_Setting));
        }
        /// <summary>
        /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
        /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
        /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
        /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
        /// audio input.
        /// </summary>
        /// <param name="e">Unused navigation parameters</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Keep track of the UI thread dispatcher, as speech events will come in on a separate thread.
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            // Prompt the user for permission to access the microphone. This request will only happen
            // once, it will not re-prompt if the user rejects the permission.
            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();

            if (permissionGained)
            {
                btnContinuousRecognize.IsEnabled = true;
            }
            else
            {
                resultTextBlock.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
            }


            Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
            string   langTag        = speechLanguage.LanguageTag;

            speechContext           = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { langTag };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

            PopulateLanguageDropdown();

            // Initialize the recognizer. Since the recognizer is disposed on scenario exit, we need to make sure we re-initialize it on scenario
            // entrance, as the xaml page may not get destroyed between openings of the scenario.
            await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
        }
Beispiel #11
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            try {
                await intializeCamera();
            }
            catch (Exception ex)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                await messageDialog.ShowAsync();
            }
            string welcome = "Welcome to the add product page. To capture a photo of your product, say capture";


            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();

            if (permissionGained)
            {
                btnContinuousRecognize.IsEnabled = true;
                speechContext     = ResourceContext.GetForCurrentView();
                speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
                play(welcome);
            }
            else
            {
                this.resultTextBlock.Visibility  = Visibility.Visible;
                this.resultTextBlock.Text        = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
                btnContinuousRecognize.IsEnabled = false;
            }
        }
Beispiel #12
0
        /// <summary>
        /// 编辑模板
        /// </summary>
        public void Edit()
        {
            string tpl = Request.Query("tpl");

            if (string.IsNullOrEmpty(tpl))
            {
                tpl = CurrentSite.Tpl;
            }
            var sb = new StringBuilder();

            var dir = new DirectoryInfo($"{EnvUtil.GetBaseDirectory()}/templates/{tpl}/");

            if (!dir.Exists)
            {
                Response.Redirect(Request.GetPath() + "?module=template&action=templates", false);
                return;
            }

            EachClass.WalkTemplateFiles(dir, sb, tpl);

            RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Template_Edit), new
            {
                tplfiles = sb.ToString(),
                tpl      = tpl
            });
        }
Beispiel #13
0
        /// <summary>
        /// 所有栏目
        /// </summary>
        public string All()
        {
            var siteDto = CurrentSite;

            ViewData["site_id"] = siteDto.SiteId;
            return(RequireTemplate(ResourceMap.GetPageContent(ManagementPage.Category_List)));
        }
        public static async Task WriteCodeFile(this IMatrixProject project, StorageFolder folder, IBuildService buildService)
        {
            // ***
            // *** Get the template from the resource file.
            // ***
            buildService.FireBuildEvent(BuildEventArgs.BuildEventType.Information, "Reading code template.");
            ResourceContext   resourceContext = ResourceContext.GetForViewIndependentUse();
            ResourceMap       resourceMap     = ResourceManager.Current.MainResourceMap.GetSubtree("CodeBuilder/Code");
            ResourceCandidate resourceValue   = resourceMap.GetValue("cpp", resourceContext);
            string            template        = resourceValue.ValueAsString;

            // ***
            // *** Fill in the template parameters.
            // ***
            string contents = String.Format(template, project.Name,
                                            project.ColorMatrix.BackgroundColor.R,
                                            project.ColorMatrix.BackgroundColor.G,
                                            project.ColorMatrix.BackgroundColor.B,
                                            project.AccelerometerScaling,
                                            project.Elasticity,
                                            project.SortParticles.ToString().ToLower());

            // ***
            // *** Write the file.
            // ***
            buildService.FireBuildEvent(BuildEventArgs.BuildEventType.Information, $"Writing C++ code file '{project.CppFileName()}'.");
            StorageFile file = await folder.CreateFileAsync(project.CppFileName(), CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(file, contents, Windows.Storage.Streams.UnicodeEncoding.Utf8);
        }
Beispiel #15
0
 public Bindings Unify(Atom y, Bindings bindings, ResourceMap map)
 {
     if (null == bindings)
     {
         return(null);
     }
     else if (Equals(y))
     {
         return(bindings);
     }
     else if (y is Pattern)
     {
         return(GetObject().Unify(((Pattern)y).GetObject(),
                                  GetSubject().Unify(((Pattern)y).GetSubject(),
                                                     GetPredicate().Unify(((Pattern)y).GetPredicate(), bindings, map), map
                                                     ), map
                                  ));
     }
     else if (y is ResourceStatement)
     {
         return(GetObject().Unify(((ResourceStatement)y).GetObject(),
                                  GetSubject().Unify(((ResourceStatement)y).GetSubject(),
                                                     GetPredicate().Unify(((ResourceStatement)y).GetPredicate(), bindings, map), map
                                                     ), map
                                  ));
     }
     else
     {
         return(null);
     }
 }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();

            if (permissionGained)
            {
                // btnContinuousRecognize.IsEnabled = true;
                speechContext     = ResourceContext.GetForCurrentView();
                speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
                play(question.Text);
            }
            else
            {
                this.resultTextBlock.Visibility  = Visibility.Visible;
                this.resultTextBlock.Text        = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
                btnContinuousRecognize.IsEnabled = false;
            }


            var parameters = (addProductMaterial.ProductParams)e.Parameter;

            textBlock2.Text = parameters.Path;
            textBlock.Text  = parameters.Name;
            textBlock1.Text = parameters.Category;
            textBlock3.Text = parameters.Material;
        }
Beispiel #17
0
        public Pattern Resolve(ResourceMap map)
        {
            PatternTerm theSubject = MakeTerm(GetSubject(), map);

            if (theSubject == null)
            {
                throw new UnknownGraphMemberException(GetSubject());
            }


            PatternTerm thePredicate = MakeTerm(GetPredicate(), map);

            if (thePredicate == null)
            {
                throw new UnknownGraphMemberException(GetSubject());
            }

            PatternTerm theObject = MakeTerm(GetObject(), map);

            if (theObject == null)
            {
                throw new UnknownGraphMemberException(GetSubject());
            }

            return(new Pattern(theSubject, thePredicate, theObject));
        }
Beispiel #18
0
        public void Forword()
        {
            var id         = int.Parse(Request.Query("archive.id"));
            var archive    = ServiceCall.Instance.ArchiveService.GetArchiveById(SiteId, id);
            var fullDomain = CurrentSite.FullDomain;

            if (fullDomain.IndexOf("#", StringComparison.Ordinal) != -1)
            {
                fullDomain = fullDomain.Replace("#", WebCtx.Current.Host);
            }
            var url = Request.GetProto() + ":" + fullDomain + archive.Path + ".html";


            if (string.IsNullOrEmpty(archive.Outline))
            {
                archive.Outline = ArchiveUtility.GetOutline(archive.Content, 100);
            }

            object data = new
            {
                title           = archive.Title,
                outline         = archive.Outline,
                url             = url,
                forword_content = string.Format("<a href=\"{0}\" target=\"_blank\"><strong>{1}</strong><br />{2}</a>",
                                                url,
                                                archive.Title,
                                                archive.Outline),
                link_content = ""
            };

            RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Archive_Forword), data);
        }
Beispiel #19
0
        /// <summary>
        /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
        /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
        /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
        /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
        /// audio input.
        /// </summary>
        /// <param name="e">Unused navigation parameters</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Keep track of the UI thread dispatcher, as speech events will come in on a separate thread.
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            // Prompt the user for permission to access the microphone. This request will only happen
            // once, it will not re-prompt if the user rejects the permission.
            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();

            if (permissionGained)
            {
                // Initialize resource map to retrieve localized speech strings.
                Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
                string   langTag        = speechLanguage.LanguageTag;
                speechContext           = ResourceContext.GetForCurrentView();
                speechContext.Languages = new string[] { langTag };

                speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

                PopulateLanguageDropdown();
                await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);

                TurnRecognizer1();
            }
            else
            {
                this.resultTextBlock.Visibility = Visibility.Visible;
                this.resultTextBlock.Text       = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
                cbLanguageSelection.IsEnabled   = false;
                //luis
            }
        }
Beispiel #20
0
    private void OnUseContext(object sender, RoutedEventArgs e)
    {
        ResourceMap       map       = _resourceManager.MainResourceMap;
        ResourceCandidate candidate = map.TryGetValue("Resources/GoodEvening", _resourceContext);

        textGoodEvening.Text = candidate.ValueAsString;
    }
 public static void Start(ResourceMap a_resourceMap)
 {
     if (ValidateMap(a_resourceMap))
     {
         resourceMap = a_resourceMap;
     }
 }
Beispiel #22
0
        public string Pub_Archive()
        {
            int sourceSiteId;

            int.TryParse(Request.Query("source_site"), out sourceSiteId);

            string siteOpt;
            var    sourceSite = default(SiteDto);

            IDictionary <string, string> dict = new Dictionary <string, string>();

            foreach (var e in SiteCacheManager.GetAllSites())
            {
                if (e.SiteId != sourceSiteId)
                {
                    dict.Add(e.SiteId.ToString(), e.Name);
                }
                else
                {
                    sourceSite = e;
                }
            }
            siteOpt = Helper.GetOptions(dict, null);

            var path  = Request.GetPath();
            var query = Request.GetQueryString();

            ViewData["site_opt"]    = siteOpt;
            ViewData["source_name"] = sourceSite.Name;
            ViewData["source_site"] = sourceSite.SiteId;
            ViewData["id_array"]    = Request.Query("id_array")[0] ?? "";
            ViewData["post_url"]    = path + query;
            return(RequireTemplate(ResourceMap.GetPageContent(ManagementPage.Assistant_Archive_Clone_Pub)));
        }
Beispiel #23
0
 public Mine(Vector2 position,
             Texture2D spritesheet,
             Texture2D basesprite,
             SpriteFont libSans12,
             ResourceMap resource,
             ref Director director,
             bool friendly = true)
     : base(position,
            spritesheet,
            basesprite,
            libSans12,
            ref director,
            EStructureType.Mine,
            -50,
            friendly)
 {
     mIPlatformActions.Add(new ProduceMineResource(platform: this, resourceMap: resource, director: ref mDirector));
     mCost       = GetResourceCosts(EStructureType.Mine);
     mType       = EStructureType.Mine;
     mSpritename = "Dome";
     Property    = JobType.Production;
     SetPlatfromParameters();
     mPlatformWidth  = 144;
     mPlatformHeight = 187;
 }
Beispiel #24
0
        public void TagsIndex_POST()
        {
            var siteId = CurrentSite.SiteId;

            var content = ResourceMap.GetPageContent(ManagementPage.Archive_Tags);
            // GetTags(siteId).ProcessRequest(HttpContext.Current, content);
        }
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            SetupPersonGroup();

            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            bool permissionGained = await RequestMicrophonePermission();

            if (!permissionGained)
                return; // No permission granted

            Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
            string langTag = speechLanguage.LanguageTag;
            speechContext = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { langTag };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

            await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);

            try
            {
                await speechRecognizer.ContinuousRecognitionSession.StartAsync();
            }
            catch (Exception ex)
            {
                var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                await messageDialog.ShowAsync();
            }

        }
        public IActionResult Add(string resource, [FromBody] JObject RequestData)
        {
            DataModel requestModel;

            try
            {
                requestModel = (DataModel)RequestData.ToObject(ResourceMap.TryGetResourceType(resource));
            }
            catch
            {
                return(StatusCode(400));
            }

            int insertID = 0;

            try
            {
                insertID = DBProvider.Insert(resource, requestModel);
            }
            catch (DBProviderExecuteException)
            {
                return(StatusCode(500));
            }

            return(Json(new KeyValuePair <string, int>(key: "insert id", value: insertID)));
        }
        /// <summary>
        /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
        /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to 
        /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
        /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow 
        /// audio input.
        /// </summary>
        /// <param name="e">Unused navigation parameters</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Keep track of the UI thread dispatcher, as speech events will come in on a separate thread.
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            // Prompt the user for permission to access the microphone. This request will only happen
            // once, it will not re-prompt if the user rejects the permission.
            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
            if (permissionGained)
            {
                btnContinuousRecognize.IsEnabled = true;
                
                // Initialize resource map to retrieve localized speech strings.
                Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
                string langTag = speechLanguage.LanguageTag;
                speechContext = ResourceContext.GetForCurrentView();
                speechContext.Languages = new string[] { langTag };

                speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

                PopulateLanguageDropdown();
                await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
            }
            else
            {
                this.resultTextBlock.Visibility = Visibility.Visible;
                this.resultTextBlock.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
                btnContinuousRecognize.IsEnabled = false;
                cbLanguageSelection.IsEnabled = false;
            }
        }
Beispiel #28
0
        /// <summary>
        /// 链接列表
        /// </summary>
        public string List()
        {
            var type = (SiteLinkType)Enum.Parse(typeof(SiteLinkType),
                                                Request.Query("type"), true);
            string linkTypeName;

            switch (type)
            {
            case SiteLinkType.FriendLink:
                linkTypeName = "友情链接";
                break;

            default:
            case SiteLinkType.CustomLink:
                linkTypeName = "自定义链接";
                break;

            case SiteLinkType.Navigation:
                linkTypeName = "网站导航";
                break;
            }


            ViewData["link_type"] = Request.Query("type");
            ViewData["type_name"] = linkTypeName;
            return(RequireTemplate(ResourceMap.GetPageContent(ManagementPage.Link_List)));
        }
        /// <summary>
        /// When activating the scenario, ensure we have permission from the user to access their microphone, and
        /// provide an appropriate path for the user to enable access to the microphone if they haven't
        /// given explicit permission for it. 
        /// </summary>
        /// <param name="e">The navigation event details</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
            if (permissionGained)
            {
                // Enable the recognition buttons.
                btnRecognizeWithUI.IsEnabled = true;
                btnRecognizeWithoutUI.IsEnabled = true;

                Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
                string langTag = speechLanguage.LanguageTag;
                speechContext = ResourceContext.GetForCurrentView();
                speechContext.Languages = new string[] { langTag };

                speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

                PopulateLanguageDropdown();
                await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
            }
            else
            {
                resultTextBlock.Visibility = Visibility.Visible;
                resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
                btnRecognizeWithUI.IsEnabled = false;
                btnRecognizeWithoutUI.IsEnabled = false;
                cbLanguageSelection.IsEnabled = false;
            }
        }
Beispiel #30
0
        /// <summary>
        /// When activating the scenario, ensure we have permission from the user to access their microphone, and
        /// provide an appropriate path for the user to enable access to the microphone if they haven't
        /// given explicit permission for it.
        /// </summary>
        /// <param name="e">The navigation event details</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();

            if (permissionGained)
            {
                // Enable the recognition buttons.
                btnRecognizeWithUI.IsEnabled    = true;
                btnRecognizeWithoutUI.IsEnabled = true;

                Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
                string   langTag        = speechLanguage.LanguageTag;
                speechContext           = ResourceContext.GetForCurrentView();
                speechContext.Languages = new string[] { langTag };

                speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

                PopulateLanguageDropdown();
                await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
            }
            else
            {
                resultTextBlock.Visibility      = Visibility.Visible;
                resultTextBlock.Text            = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
                btnRecognizeWithUI.IsEnabled    = false;
                btnRecognizeWithoutUI.IsEnabled = false;
                cbLanguageSelection.IsEnabled   = false;
            }
        }
Beispiel #31
0
 /// <summary>
 /// 服务器信息页面
 /// </summary>
 public void Summary()
 {
     //var env = HttpHosting.Context.Hosting.GetService<IHostingEnvironment>();
     RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Server_Summary), new
     {
         path        = GetPath(),
         shortServer = Server.ShortUrlServer,
         soft_ver    = Cms.Version,
         sys_alias   = Settings.LICENSE_NAME, // + "(KEY:" + Settings.SYS_KEY + ")",
         //server_name = env.EnvironmentName,
         server_os    = Environment.OSVersion.VersionString,
         server_local = CultureInfo.InstalledUICulture.EnglishName,
         server_ip    = WebCtx.Current.UserIpAddress,
         //server_host = Request.ServerVariables["SERVER_NAME"],
         //server_iis = Request.ServerVariables["Server_SoftWare"],
         server_netver =
             Environment.Version.Major + "." + Environment.Version.Minor + "." + Environment.Version.Build +
             "." +
             Environment.Version.Revision,
         server_https = Request.GetProto() == "https" ? "是" : "否",
         //server_port = Request.ServerVariables["Server_Port"],
         server_hour      = $"{(Environment.TickCount / 0x3e8 / 3600).ToString()}小时",
         server_time      = DateTime.Now.ToString(CultureInfo.InvariantCulture),
         server_cpu       = $"{Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER")},{Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS")}核",
         server_meory     = Environment.WorkingSet / 1024 / 1024 + "M",
         server_net_meory =
             ((double)Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + "M",
         //person_os = this.GetOSNameByUserAgent(base.Request.Headers.TryGetValue(UserAgent)),
         //person_ip = base.Request.UserHostAddress,
         //person_soft = base.Request.Browser.Browser,
         //person_softver = base.Request.Browser.Version,
         //person_cookie = base.Request.Browser.Cookies ? "支持" : "<span style=\"color:Red\">不支持</span>",
         // person_java = base.Request.Browser.EcmaScriptVersion.Major >= 1 ? "支持" : "<span style=\"color:Red\">不支持</span>",
     });
 }
Beispiel #32
0
        /// <summary>
        /// 分类扩展信息设置
        /// </summary>
        /// <returns></returns>
        public void Category_Check_GET()
        {
            int                    categoryId = int.Parse(base.Request["category_id"]);
            IList <int>            extendIds  = new List <int>();
            IList <ExtendFieldDto> list       = ExtendFieldCacheManager.GetExtendFields(base.CurrentSite.SiteId);
            CategoryDto            category   = ServiceCall.Instance.SiteService.GetCategory(this.SiteId, categoryId);

            foreach (IExtendField extend in category.ExtendFields)
            {
                extendIds.Add(extend.GetDomainId());
            }

            string json = JsonSerializer.Serialize(list);

            category.ExtendFields = null;
            string categoryJson = JsonSerializer.Serialize(new
            {
                ID        = category.ID,
                Path      = category.Path,
                Name      = category.Name,
                ExtendIds = extendIds
            });

            base.RenderTemplate(ResourceMap.GetPageContent(ManagementPage.Site_Extend_Category_Check), new
            {
                url      = base.Request.RawUrl,
                json     = json,
                category = categoryJson
            });
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral        = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            cortanaContext = ResourceContext.GetForViewIndependentUse();

            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            if (triggerDetails != null && triggerDetails.Name == "JeedomAppVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    var    userMessage = new VoiceCommandUserMessage();
                    string message     = "";


                    // Ajout d'une requet jeedom pour retrouver la commande
                    switch (voiceCommand.CommandName)
                    {
                    case "JeedomInteractList":
                        string CortanaVoiceCommande = voiceCommand.Properties["InteractList"][0];
                        await Jeedom.RequestViewModel.Instance.interactTryToReply(CortanaVoiceCommande);

                        message = Jeedom.RequestViewModel.Instance.InteractReply;
                        break;

                    default:
                        LaunchAppInForeground();
                        break;
                    }

                    userMessage.DisplayMessage = message;
                    userMessage.SpokenMessage  = message;


                    var response = VoiceCommandResponse.CreateResponse(userMessage);
                    response.AppLaunchArgument = message;


                    await voiceServiceConnection.ReportSuccessAsync(response);
                }
                catch (Exception ex)
                {
                    //System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            // This should match the uap:AppService and VoiceCommandService references from the 
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (triggerDetails != null && triggerDetails.Name == "AwfulVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                        case "didMyThreadsUpdate":
                            await CheckForBookmarksForUpdates();
                            break;
                        case "didMyPmUpdate":
                            await CheckPmsForUpdates();
                            break;
                        default:
                            // As with app activation VCDs, we need to handle the possibility that
                            // an app update may remove a voice command that is still registered.
                            // This can happen if the user hasn't run an app since an update.
                            LaunchAppInForeground();
                            break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
Beispiel #35
0
 public Model(Location location, Orientation orientation, Scale scale, Link link, ResourceMap resourceMap)
 {
     this.location = location;
     this.orientation = orientation;
     this.scale = scale;
     this.link = link;
     this.resourceMap = resourceMap;
 }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            cortanaContext = ResourceContext.GetForViewIndependentUse();

            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            if (triggerDetails != null && triggerDetails.Name == "DomojeeVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
                    var userMessage = new VoiceCommandUserMessage();
                    string message = "";


                    // Ajout d'une requet jeedom pour retrouver la commande
                    switch (voiceCommand.CommandName)
                    {
                        case "JeedomInteractList":
                            string CortanaVoiceCommande= voiceCommand.Properties["InteractList"][0];
                            await Jeedom.RequestViewModel.Instance.interactTryToReply(CortanaVoiceCommande);
                            message = Jeedom.RequestViewModel.Instance.InteractReply;
                            break;
                        default:
                            LaunchAppInForeground();
                            break;
                    }

                    userMessage.DisplayMessage = message;
                    userMessage.SpokenMessage = message;
                    

            var response = VoiceCommandResponse.CreateResponse(userMessage);
            response.AppLaunchArgument = message;


                await voiceServiceConnection.ReportSuccessAsync(response);
            }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
Beispiel #37
0
 public ResourceManagerImpl(string subtree)
 {
     /* Discover resources in the image
     foreach (var m in ResourceManager.Current.MainResourceMap)
     {
         System.Diagnostics.Debug.WriteLine(m);
     }
     */
     stringResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree(subtree);
     resourceContext = ResourceContext.GetForCurrentView();
 }
Beispiel #38
0
        public ResourceManager(Type resourceSource)
        {
            if (null == resourceSource)
            {
                throw new ArgumentNullException(nameof(resourceSource));
            }

            // Portable libraries resources are indexed under the type full name 
            _resourcesSubtree = resourceSource.FullName;
            _resourceMap = GetResourceMap(_resourcesSubtree);
        }
        public SynthesizeTextScenario()
        {
            InitializeComponent();
            synthesizer = new SpeechSynthesizer();
            
            speechContext = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");

            InitializeListboxVoiceChooser();
        }
Beispiel #40
0
        public ResourceManager(string baseName, Assembly assembly)
        {
            if (null == baseName)
            {
                throw new ArgumentNullException(nameof(baseName));
            }
            if (null == assembly)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            _resourcesSubtree = baseName;
            _resourceMap = GetResourceMap(_resourcesSubtree);
            _neutralResourcesCultureName = GetNeutralLanguageForAssembly(assembly);
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();


            if (triggerDetails != null && triggerDetails.Name == "HolVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    switch (voiceCommand.CommandName)
                    {
                        case "SayHello":
                            var userMessage = new VoiceCommandUserMessage();
                            userMessage.DisplayMessage = "Hello!";
                            userMessage.SpokenMessage = "Your app says hi. It is having a great time.";
                            var response = VoiceCommandResponse.CreateResponse(userMessage);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }

        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCancelled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService")
            {
                try
                {
                    voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    var client = await this.GetClient();

                    // Depending on the operation (defined in the VoiceCommands.xml file)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                        case "turnOnItem":
                            var onTarget = voiceCommand.Properties["target"][0];
                            await SendCompletionMessageForOnOff(client, onTarget, true);
                            break;
                        case "turnOffItem":
                            var offTarget = voiceCommand.Properties["target"][0];
                            await SendCompletionMessageForOnOff(client, offTarget, false);
                            break;
                        default:
                            // As with app activation VCDs, we need to handle the possibility that
                            // an app update may remove a voice command that is still registered.
                            // This can happen if the user hasn't run an app since an update.
                            //LaunchAppInForeground();
                            break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
Beispiel #43
0
        public ResourceItem(ConfigNode data, string resource, string body, string type, System.Random random)
        {
            DefaultResource defaultResource = DefaultLibrary.GetDefault(MapGenerator.DefaultName).GetBody(body).GetResourceOfType(resource, type);
            this.resource = PartResourceLibrary.Instance.GetDefinition(data.GetValue("name"));
            this.type = KRESUtils.GetResourceType(type);
            this.map = null;
            if (!data.TryGetValue("actualDensity", ref actualDensity))
            {
                actualDensity = KRESUtils.Clamp01(defaultResource.Density * (0.97d + (random.NextDouble() * 0.06d)));
            }

            if (!data.TryGetValue("actualError", ref actualError))
            {
                actualError = (random.NextDouble() * 2d) - 1d;
                data.AddValue("actualError", actualError);
            }
        }
       /* string dfa = "";
        class msgQueue { public string msg; };

        private async void dowork(object obj)
        {
            while (true)
            {
                string temp = conn.getMessage();
                if (temp != null)
                {
                    textToSynthesize.Text = temp;
                }
            }
        } */

        public SynthesizeTextScenario()
        {
            InitializeComponent();
            synthesizer = new SpeechSynthesizer();
            
            speechContext = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");

            
            conn = new azureConnector();
            //conn.sendSBMessageToTopic("Hello hello", "ordermeal");
            //conn.sendSBMessageToTopic("Oh Burger Burger", "ordermeal");
            conn.runSubscriptionReceiver("ordermeal", "orderMealSubscription");

            //workerThread msgChecker = new workerThread(this.dowork);
            //msgChecker.Start(new msgQueue() {msg = ""});
            InitializeListboxVoiceChooser();
        }
Beispiel #45
0
        public ResourceItem(ConfigNode data, string resource, string body, System.Random random)
        {
            DefaultResource defaultResource = DefaultLibrary.GetDefault(MapGenerator.DefaultName).GetBody(body).GetResourceOfType(resource, "ore");
            this.resource = PartResourceLibrary.Instance.GetDefinition(resource);
            this.type = ResourceType.ORE;
            double density = defaultResource.Density;
            this.map = new ResourceMap(defaultResource, body);
            if (!data.TryGetValue("actualDensity", ref actualDensity))
            {
                Texture2D texture = Map.GetTexture();
                actualDensity = texture.GetPixels().Count(p => p.a > 0) / mapResolution;
                Texture2D.Destroy(texture);
                data.AddValue("actualDensity", actualDensity);
            }

            if (!data.TryGetValue("actualError", ref actualError))
            {
                actualError = (random.NextDouble() * 2d) - 1d;
                data.AddValue("actualError", actualError);
            }
        }
        // Obtain instances of the Resource Map and Resource Context provided by
        // the Windows Modern Resource Manager (MRM).

        // Not thread-safe. Only call this once on one thread for each object instance.
        // For example, System.Runtime.ResourceManager only calls this from its constructors,
        // guaranteeing that this only gets called once, on one thread, for each new instance
        // of System.Runtime.ResourceManager.

        // Throws exceptions
        // Only returns true if the function succeeded completely.
        // Outputs exceptionInfo since it may be needed for debugging purposes
        // if an exception is thrown by one of Initialize's callees.
        public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo)
        {
            Debug.Assert(libpath != null);
            Debug.Assert(reswFilename != null);
            exceptionInfo = null;

            if (InitializeStatics())
            {
                // AllResourceMaps can throw ERROR_MRM_MAP_NOT_FOUND,
                // although in that case we are not sure for which package it failed to find
                // resources (if we are looking for resources for a framework package,
                // it might throw ERROR_MRM_MAP_NOT_FOUND if the app package
                // resources could not be loaded, even if the framework package
                // resources are properly configured). So we will not fill in the
                // exceptionInfo structure at this point since we don't have any
                // reliable information to include in it.

                IReadOnlyDictionary<String, ResourceMap>
                    resourceMapDictionary = s_globalResourceManager.AllResourceMaps;

                if (resourceMapDictionary != null)
                {
                    string packageSimpleName = FindPackageSimpleNameForFilename(libpath);

#if netstandard
                    // If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that
                    // an application may have packaged in its AppX. This is to enforce AppX apps to use PRI resources.
                    if (packageSimpleName != null)
                    {
                        if (packageSimpleName.EndsWith(".resources.dll", StringComparison.CurrentCultureIgnoreCase))
                        {
                            // Pretend we didnt get a package name. When an attempt is made to get resource string, GetString implementation
                            // will see that we are going to use modern resource manager but we dont have PRI and will thrown an exception indicating
                            // so. This will force the developer to have a valid PRI based resource.
                            packageSimpleName = null;
                        }
                    }
#endif //  netstandard
                    if (packageSimpleName != null)
                    {
                        ResourceMap packageResourceMap = null;

                        // Win8 enforces that package simple names are unique (for example, the App Store will not
                        // allow two apps with the same package simple name). That is why the Modern Resource Manager
                        // keys access to resources based on the package simple name.
                        if (resourceMapDictionary.TryGetValue(packageSimpleName, out packageResourceMap))
                        {
                            if (packageResourceMap != null)
                            {
                                // GetSubtree returns null when it cannot find resource strings
                                // named "reswFilename/*" for the package we are looking up.

                                reswFilename = UriUtility.UriEncode(reswFilename);
                                _resourceMap = packageResourceMap.GetSubtree(reswFilename);

                                if (_resourceMap == null)
                                {
                                    exceptionInfo = new PRIExceptionInfo();
                                    exceptionInfo._PackageSimpleName = packageSimpleName;
                                    exceptionInfo._ResWFile = reswFilename;
                                }
                                else
                                {
                                    _clonedResourceContext = s_globalResourceContext.Clone();

                                    if (_clonedResourceContext != null)
                                    {
                                        // Will need to be changed the first time it is used. But we can't set it to "" since we will take a lock on it.
                                        _clonedResourceContextFallBackList = ReadOnlyListToString(_clonedResourceContext.Languages);

                                        if (_clonedResourceContextFallBackList != null)
                                            return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
Beispiel #47
0
        public ResourceManagerImpl()
        {
            stringResourceMap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap.GetSubtree("Microsoft.Azure.Amqp.Uwp/AmqpResources.UWP");
//            resourceContext = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();
        }
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="Common.NavigationHelper.LoadState"/>
        /// and <see cref="Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);

            // Prompt the user for permission to access the microphone. This request will only happen
            // once, it will not re-prompt if the user rejects the permission.
            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();

            speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
            string langTag = speechLanguage.LanguageTag;
            // Initialize resource map to retrieve localized speech strings.
            speechContext = ResourceContext.GetForCurrentView();
            IReadOnlyList<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages;
            if (supportedLanguages.Count > 1)
            {
                if (Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride == "zh-Hans-CN")
                {
                    speechContext.Languages = new string[] { "zh-Hans-CN" };
                    speechLanguage = new Windows.Globalization.Language("zh-Hans-CN");
                }
                else
                {
                    speechContext.Languages = new string[] { "en-US" };
                    speechLanguage = new Windows.Globalization.Language("en-US");
                }
            }
            else
            {
                speechContext.Languages = new string[] { langTag };
            }
            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
            //Initia Command
            await InitializeRecognizer(speechLanguage);
            //Initia RecognizerNote
            await InitializeRecognizerNote(speechLanguage);
            if (speechRecognizer.State == SpeechRecognizerState.Idle && permissionGained)
            {
                try
                {
                    await speechRecognizer.ContinuousRecognitionSession.StartAsync();
                }
                catch (Exception ex)
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
                    await messageDialog.ShowAsync();
                }
            }
        }
Beispiel #49
0
 public ResourceManager(string resourcesName)
 {
     _resourcesSubtree = resourcesName;
     _resourceMap = GetResourceMap(_resourcesSubtree);
 }
        /// <summary>
        /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
        /// tag will invoke this when they are recognized by Cortana, passing along details of the 
        /// invocation. 
        /// 
        /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must 
        /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
        /// input). There is no execution time limit on the background task managed by Cortana,
        /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
        /// on the Cortana app package in order to prevent Cortana timing out the task during
        /// debugging.
        /// 
        /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
        /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
        /// in order to debug background task behaviors. In order to debug background tasks, open the
        /// project properties for the app package (not the background task project), and enable
        /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
        /// initial progress screen, and attach to the background task process while it executes.
        /// </summary>
        /// <param name="taskInstance">Connection to the hosting background service process.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            // This should match the uap:AppService and VoiceCommandService references from the 
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (triggerDetails != null && triggerDetails.Name == "BandOnTheRunVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
                    VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();

                    // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                        case "showbandinformation":
                            //hardcoded - needs to be hooked into real data flow.
                            userMessage.DisplayMessage = "Band 1 \n" +
                                                         "status: connected\n" +
                                                          "Motion: Jogging\n" +
                                                          "Speed: 10kph\n" +
                                                          "Skin Temp: 37\n" +
                                                           "UV: medium";
                            userMessage.SpokenMessage = "Showing band information";
;
                            var response = VoiceCommandResponse.CreateResponse(userMessage);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                    
                            break;
                 
                        default:
                     
                            break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
                finally
                {
                    if (this.serviceDeferral != null)
                    {
                        this.serviceDeferral.Complete();
                      
                    }
                }
            }
        }
 public ResourceManagerImpl()
 {
     stringResourceMap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap.GetSubtree("Microsoft.Azure.Devices.Client/Resources");
     resourceContext = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();
 }
        /// <summary>
        /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
        /// tag will invoke this when they are recognized by Cortana, passing along details of the 
        /// invocation. 
        /// 
        /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must 
        /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
        /// input). There is no execution time limit on the background task managed by Cortana,
        /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
        /// on the Cortana app package in order to prevent Cortana timing out the task during
        /// debugging.
        /// 
        /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
        /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
        /// in order to debug background task behaviors. In order to debug background tasks, open the
        /// project properties for the app package (not the background task project), and enable
        /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
        /// initial progress screen, and attach to the background task process while it executes.
        /// </summary>
        /// <param name="taskInstance">Connection to the hosting background service process.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            VoiceCommandResponse response = null;

            // This should match the uap:AppService and RuleVoiceCommandService references from the 
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (triggerDetails != null && triggerDetails.Name == this.GetType().Name)
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    HttpClient client = new HttpClient();

                    switch (voiceCommand.CommandName)
                    {
                        case "turnOnLight":

                            string postBody = JsonConvert.SerializeObject(new Settings
                            {
                                IsOn = false
                            });
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                            var webResponse = await client.PostAsync("http://hiremotemeetcortana.azurewebsites.net/api/settings", new StringContent(postBody, Encoding.UTF8, "application/json"));

                            if (webResponse.IsSuccessStatusCode)
                            {
                                var turnOnLightMessage = new VoiceCommandUserMessage
                                {
                                    DisplayMessage = "Wakeup Light has been turned on ",
                                    SpokenMessage = "Wakeup Light has been turned on "
                                };

                                response = VoiceCommandResponse.CreateResponse(turnOnLightMessage);
                                await voiceServiceConnection.ReportSuccessAsync(response);
                            } else
                            {
                                var turnOnLightMessage = new VoiceCommandUserMessage
                                {
                                    DisplayMessage = "Something went wrong",
                                    SpokenMessage = "Something went wrong"
                                };

                                response = VoiceCommandResponse.CreateResponse(turnOnLightMessage);
                                await voiceServiceConnection.ReportFailureAsync(response);
                            }
                            break;
                        case "turnOffLight":

                            string turnOffLightBody = JsonConvert.SerializeObject(new Settings
                            {
                                IsOn = false
                            });
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                            var saveRurnOffLight = await client.PostAsync("http://hiremotemeetcortana.azurewebsites.net/api/settings", new StringContent(turnOffLightBody, Encoding.UTF8, "application/json"));


                            if (saveRurnOffLight.IsSuccessStatusCode)
                            {
                                var turnOnLightMessage = new VoiceCommandUserMessage
                                {
                                    DisplayMessage = "Wakeup Light has been turned off ",
                                    SpokenMessage = "Wakeup Light has been turned off "
                                };

                                response = VoiceCommandResponse.CreateResponse(turnOnLightMessage);
                                await voiceServiceConnection.ReportSuccessAsync(response);
                            }
                            else
                            {
                                var turnOnLightMessage = new VoiceCommandUserMessage
                                {
                                    DisplayMessage = "Something went wrong",
                                    SpokenMessage = "Something went wrong"
                                };

                                response = VoiceCommandResponse.CreateResponse(turnOnLightMessage);
                                await voiceServiceConnection.ReportFailureAsync(response);
                            }
                            break;
                        default:
                            // As with app activation VCDs, we need to handle the possibility that
                            // an app update may remove a voice command that is still registered.
                            // This can happen if the user hasn't run an app since an update.
                            LaunchAppInForeground();
                            break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
        /// <summary>
        /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
        /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to 
        /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
        /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow 
        /// audio input.
        /// </summary>
        /// <param name="e">Unused navigation parameters</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Keep track of the UI thread dispatcher, as speech events will come in on a separate thread.
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            // Prompt the user for permission to access the microphone. This request will only happen
            // once, it will not re-prompt if the user rejects the permission.
            bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
            if (permissionGained)
            {
                btnContinuousRecognize.IsEnabled = true;
            }
            else
            {
                resultTextBlock.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
            }


            Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
            string langTag = speechLanguage.LanguageTag;
            speechContext = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { langTag };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");

            PopulateLanguageDropdown();

            // Initialize the recognizer. Since the recognizer is disposed on scenario exit, we need to make sure we re-initialize it on scenario
            // entrance, as the xaml page may not get destroyed between openings of the scenario.
            await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
        }
        public TeddyInterface()
        {
            this.InitializeComponent();

            //Listener
            isListening = false;
            dictatedTextBuilder = new StringBuilder();

            //Speaker
            synthesizer = new SpeechSynthesizer();

            speechContext = ResourceContext.GetForCurrentView();
            speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };

            speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");

            InitializeVoiceChooser();

        }
        /// <summary>
        /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
        /// tag will invoke this when they are recognized by Cortana, passing along details of the 
        /// invocation. 
        /// 
        /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must 
        /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
        /// input). There is no execution time limit on the background task managed by Cortana,
        /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
        /// on the Cortana app package in order to prevent Cortana timing out the task during
        /// debugging.
        /// 
        /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
        /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
        /// in order to debug background task behaviors. In order to debug background tasks, open the
        /// project properties for the app package (not the background task project), and enable
        /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
        /// initial progress screen, and attach to the background task process while it executes.
        /// </summary>
        /// <param name="taskInstance">Connection to the hosting background service process.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;
            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();
            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            // This should match the uap:AppService and VoiceCommandService references from the 
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            string actualName = triggerDetails.Name;
            string expectedName = typeof(TheVoiceCommandService).ToString();
            bool launchedByCortanaVoiceCommand = triggerDetails != null && expectedName.Contains( actualName );
            if ( launchedByCortanaVoiceCommand ) {
                try {
                    voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails( triggerDetails );
                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;
                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();


                    switch (voiceCommand.CommandName) {
                        default:
                            LaunchAppInForeground();
                            break;
                    }
                }
                catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }