[Silverlight][C#] 將Web.config的內容儲存在IsolatedStorage以讓OOB的Silvelright存取的方式

  • 4937
  • 0
  • C#
  • 2013-07-14

在[Silverlight][ASP.Net][C#]讓Silverlight也能讀取web.config的小撇步一文中跟大家介紹過了怎麼透過ASP.Net存取Web.config的內容,並且讓Silverlight也能存取得到裡面的值,不過最近有人跟我說這個方式行不通,一問之下,才發現原來他的環境不是純的Silverlight,而是透過OOB模式執行,那一定行不通的啊~~所以這次就來教個偷吃步,讓OOB的應用程式也能把Web.config中的內容存起來,以供後續使用的方式。

 

[Silverlight][ASP.Net][C#]讓Silverlight也能讀取web.config的小撇步一文中跟大家介紹過了怎麼透過ASP.Net存取Web.config的內容,並且讓Silverlight也能存取得到裡面的值,不過最近有人跟我說這個方式行不通,一問之下,才發現原來他的環境不是純的Silverlight,而是透過OOB模式執行,那一定行不通的啊~~所以這次就來教個偷吃步,讓OOB的應用程式也能把Web.config中的內容存起來,以供後續使用的方式。

這次的示範要使用到之前的專案,所以請有興趣的同學先行下載(不過為了區隔不同的專案,我在這次的範例中會將專案名稱改名以便區別)。

打開之前的專案之後,首先我們要做的事情是,把專案改成可以使用OOB的方式執行,方法為:在Silverlight的專案名稱上按下滑鼠右鍵 -> Properties -> 勾選Enable running application out of browser,並視需求按下下方的Out-of-Browser Settings…按鈕修改額外的屬性。

image image

 

做完上述的動作之後,Silverlight應用程式就具備脫離瀏覽器執行的功能了。再來我們必需修改App.xaml.cs檔,加入針對OOB模式的判斷,以決定是否需要將設定值寫入IsolatedStorage中,抑或要從IsolatedStorage中將設定值讀取出來。

在接著往下做之前,需要先引用System.Runtime.Serialization.dll類別庫(因為我們得靠它來處理設定值的序列化工作)。

image

 

接著就又是寫程式的時間啦,我們得把App.xaml.cs改為如下:

App.xaml.cs

using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Windows;

namespace SL_ReadConfigFile
{
    public partial class App : Application
    {
        private IDictionary<string , string> _configurations;
        public IDictionary<string , string> Configurations
        {
            get
            {
                return _configurations;
            }
        }

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup( object sender , StartupEventArgs e )
        {
            //這行要改成透過新增的Method來取得initParams,並且依照是否為OOB模式做不同的處理
            _configurations = LoadInitParams( e );

            this.RootVisual = new MainPage();
        }

        //這個Method是新增的部份,用來取代掉原來的Web.config取值方式。
        private static IDictionary<string , string> LoadInitParams( StartupEventArgs e )
        {
            IDictionary<string , string> initParams;

            //如果在OOB的環境下執行的話,則存取IsolatedStorage中的內容,否則的話則把資料寫入IsolatedStorage
            if( Application.Current.IsRunningOutOfBrowser )
            {
                using( IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() )
                {
                    using( IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream( "InitParams.txt" , System.IO.FileMode.Open , isolatedStorageFile ) )
                    {
                        DataContractSerializer dataContractSerializer = new DataContractSerializer( typeof( Dictionary<string , string> ) );
                        initParams = ( Dictionary<string , string> ) dataContractSerializer.ReadObject( isolatedStorageFileStream );
                    }
                }
            }
            else
            {
                initParams = e.InitParams;

                using( IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication() )
                {
                    using( IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream( "InitParams.txt" , System.IO.FileMode.Create , isolatedStorageFile ) )
                    {
                        DataContractSerializer dataContractSerializer = new DataContractSerializer( typeof( Dictionary<string , string> ) );
                        dataContractSerializer.WriteObject( isolatedStorageFileStream , initParams );
                    }
                }
            }
            return initParams;
        }


        private void Application_Exit( object sender , EventArgs e )
        {

        }

        private void Application_UnhandledException( object sender , ApplicationUnhandledExceptionEventArgs e )
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if( !System.Diagnostics.Debugger.IsAttached )
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke( delegate { ReportErrorToDOM( e ); } );
            }
        }

        private void ReportErrorToDOM( ApplicationUnhandledExceptionEventArgs e )
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace( '"' , '\'' ).Replace( "\r\n" , @"\n" );

                System.Windows.Browser.HtmlPage.Window.Eval( "throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");" );
            }
            catch( Exception )
            {
            }
        }
    }
}

Ok,搞定了~就這樣,就是這麼簡單!!

如果有Debug的需要的話,接下來有幾點要注意:

1. 要確認起始專案是否設定為ASP.Net的xxxx.Web專案,否則一進Debug模式就會直接進到OOB模式,沒辦法模擬使用者安裝之前的動作,也就沒辦法將設定值寫到IsolatedStorage中。

2. 當使用者安裝了之後,基本上OOB的應用程式就和Web專案脫勾了,所以除非使用者重新以瀏覽器瀏覽Web專案的Silverlight網頁,否則Web.config中的設定值有更新的話,OOB端的IsolatedStorage中的值是不會跟著改變的

接著來看看執行的結果吧!!


 

可以在上面Silverlight內容中按下滑鼠右鍵,點選「將SL_ReadConfigFile OOB安裝到此電腦…」,接著執行安裝好的OOB版,瞧~設定值還是讀得到!!

image image

 

開心的下課吧~最後一樣奉上專案原始檔,請自己取用: