Windows 7, IIS 7上 ASP.Net 使用 Office DCOM元件 Powerpoint, Excel, Impersonate, Permission, Process

有一個需求,使用者上傳 Powerpoint 投影片檔案之後,要把每一張投影片匯出成 jpg。

這個在WinForm很簡單,程式碼如下:

   1:  Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
   2:  Presentation ppPre = ppApp.Presentations.Open(PptPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
   3:  string OutputPath = Path.Combine(OutputRootPath, Path.GetFileNameWithoutExtension(PptPath));
   4:  for (int i = 1; i <= ppPre.Slides.Count; i++)
   5:        ppPre.Slides[i].Export(Path.Combine(OutputPath, i + ".jpg"), "jpg", 640, 480);



接著移到WebForm上,使用Visual Studio 2010按下F5,也可以正常執行。


但當Porting 到 IIS之後,就會出現下面兩種錯誤了。


第一個錯誤比較簡單


System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {91493441-5A91-11CF-8700-00AA0060263B} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).


解決方法:執行 dcomcnfg,展開我的電腦,選到DCOM找到,Microsoft Powerpoint Slide,進去把Security開成 Everyone。


這時候錯誤訊息就會變成


System.Runtime.InteropServices.COMException (0x80004005): PowerPoint could not open the file. at Microsoft.Office.Interop.PowerPoint.Presentations.Open(String FileName, MsoTriState ReadOnly, MsoTriState Untitled, MsoTriState WithWindow)


此時解法我只找到一種,因為Visual Studio 啟動的 IIS Express可以正常執行,所以只能判斷是權限的問題。


對於 ASP.Net impersonate的方法,我有找到四種:


1. 直接設定 Application Pool 的 Identity成本機使用者,不能使用Network Service, Local Service, Local System. 按右鍵的進階設定

2. 設定 web.config的impersonate 屬性

3. 在程式碼中使用LogonUser WinAPI轉換使用者

4. 在程式碼中使用 Process.UserName 來啟動Process然後去使用Office元件

在程式碼中我們可以用 Environment.UserName 跟 User.Identity.Name 來看,第一個是 w3wp的執行權限,也就是工作管理員中看到w3wp Process的UserName,也就是你的asp.net程式碼可以存取檔案系統或是使用DCOM元件的權限,第二個就是一般網站的登入機制,是在ASP.NET應用程式層的登入權限。

這次為了讓其可以執行Office元件,四種方法都試過,只能使用第一種,二三四都沒用。

 

待解問題一:

設了第一種之後,如果用二三把Enviroment.UserName 給換掉,還是可以正常使用 DCOM元件,不知道為什麼。

 

待解問題二: 如何透過IIS把WinForm程式顯示在桌面上,我啟動的結果只會跑在背景,然後World Wide Web Publishing Service 我有勾選 Allow ervice to interact with desktop。但還是沒反應Orz


 


附註:如果想使用 Powerpoint 轉換成 wmv (CreateVideo) 的功能,記得也要一併設 Windows Media Encode DCOM 的權限


 


最新補充:


因為Office設計為桌面應用,所以一定要桌面登入某一個使用者才行,可以使用control userpasswords2這個指令去設定自動登入,這樣才可以避免Powerpoint 元件無法執行,缺點就是登錄檔裡面會存密碼的明碼。


參考資料:http://www.west-wind.com/weblog/posts/2153.aspx

留言

這個網誌中的熱門文章

好貴的東元冷氣維修--馬達啟動電容

台大醫院 婁培人 耳鼻喉科 就診

機車無法充電之整流器壞掉--$650