今天開放 Windows Azure 儲存服務的時候碰到一個問題:
執行下面的初始化儲存代碼
// read account configuration settingsvar storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
拋出異常
網上找了一些資料 沒有收穫 於是回去看Windows azure 白皮書中的樣本描述,發現少了一段很重要的代碼
這是My Code
namespace WCFServiceWebRole{ public class WebRole : RoleEntryPoint { public override bool OnStart() { DiagnosticMonitor.Start("DiagnosticsConnectionString"); // 有關處理配置更改的資訊, // 請參見 http://go.microsoft.com/fwlink/?LinkId=166357 上的 MSDN 主題。 RoleEnvironment.Changing += RoleEnvironmentChanging; return base.OnStart(); } private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e) { // 如果配置設定發生更改, if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange)) { // 請將 e.Cancel 設定為 true 以重新啟動此角色執行個體 e.Cancel = true; } } }}
修改之後的代碼
namespace WCFServiceWebRole{ public class WebRole : RoleEntryPoint { public override bool OnStart() { DiagnosticMonitor.Start("DiagnosticsConnectionString"); // 有關處理配置更改的資訊, // 請參見 http://go.microsoft.com/fwlink/?LinkId=166357 上的 MSDN 主題。 RoleEnvironment.Changing += RoleEnvironmentChanging; // 當使用設定檔中ConfigurationSettings時必須調用CloudStorageAccount.SetConfigurationSettingPublisher // 來說明當設定檔在發布後被更改時將採取何種操作 Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => { configSetter(Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(configName)); RoleEnvironment.Changed += (sender, arg) => { if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>() .Any((change) => (change.ConfigurationSettingName == configName))) { if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName))) { RoleEnvironment.RequestRecycle(); } } }; return base.OnStart(); } private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e) { // 如果配置設定發生更改, if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange)) { // 請將 e.Cancel 設定為 true 以重新啟動此角色執行個體 e.Cancel = true; } } }}
原因就是少了這個方法SetConfigurationSettingPublisher,
vs2010建項目的時候該方法不會自動產生,導致後面雲端儲存賬戶失敗。
pos:目前雲端運算在windows azure國內剛起步,這方面的教程特別少 僅限於一般的入門級教程 碰到疑難問題最好google國外的技術資料