2013年10月31日 星期四

File.WriteAllBytes

File.WriteAllBytes

將存放在SQL2008的image型態欄位的檔案,轉成實體檔案
ps:以下程式在windows form測試

private void button1_Click(object sender, EventArgs e)
{
DataTable dt = ds.Tables["resultTable"];
DataRow dr = dt.rows[0];

File.WriteAllBytes(@"C:\" + dr["filename"].ToString(), (byte[])dr["data"]);
}

2013年10月30日 星期三

簡易AD驗証

簡易AD驗証


C#:

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Web;
  8.  
  9. using System.Web.UI;
  10.  
  11. using System.Web.UI.WebControls;
  12.  
  13. using System.DirectoryServices;
  14.  
  15.  
  16.  
  17. public partial class Test_tsLDAP : System.Web.UI.Page
  18.  
  19. {
  20.  
  21.     protected void Page_Load(object sender, EventArgs e)
  22.  
  23.     {
  24.  
  25.  
  26.  
  27.     }
  28.  
  29.     /// <summary>
  30.  
  31.     /// Button1 Event
  32.  
  33.     /// </summary>
  34.  
  35.     /// <param name="sender"></param>
  36.  
  37.     /// <param name="e"></param>
  38.  
  39.     protected void Button1_Click(object sender, EventArgs e)
  40.  
  41.     {
  42.  
  43.         try
  44.  
  45.         {
  46.  
  47.             string a;
  48.  
  49.             a = isADauth("user1", "pass1");
  50.  
  51.             Response.Write(a.ToString());
  52.  
  53.         }
  54.  
  55.         catch (Exception ex)
  56.  
  57.         {
  58.  
  59.             Response.Write(ex.Message);
  60.  
  61.             //throw ex;
  62.  
  63.         }
  64.  
  65.        
  66.  
  67.     }
  68.  
  69.  
  70.  
  71.     /// <summary>
  72.  
  73.     /// AD驗証
  74.  
  75.     /// </summary>
  76.  
  77.     /// <param name="uid">帳號</param>
  78.  
  79.     /// <param name="passwd">密碼</param>
  80.  
  81.     /// <returns></returns>
  82.  
  83.     public static string isADauth(string uid, string passwd)
  84.  
  85.     {
  86.  
  87.         string authentic = "";
  88.  
  89.         try
  90.  
  91.         {
  92.  
  93.             DirectoryEntry entry = new DirectoryEntry("LDAP://DC01", uid, passwd);
  94.  
  95.             object nativeObject = entry.NativeObject;
  96.  
  97.             authentic = "LOGIN_SUCCESSFUL";
  98.  
  99.         }
  100.  
  101.         catch (DirectoryServicesCOMException dscom_ex)
  102.  
  103.         {
  104.  
  105.             //authentic = "LOGIN_FAILED";
  106.  
  107.             throw dscom_ex;
  108.  
  109.         }
  110.  
  111.         return authentic;
  112.  
  113.     }
  114.  
  115. }
  116.  

2013年10月24日 星期四

擷取元件 (CLSID 為 {00024500-0000-0000-C000-000000000046}) 的 COM Class Factory 失敗

擷取元件 (CLSID {00024500-0000-0000-C000-000000000046}) COM Class Factory 失敗,因為發生下列錯誤: 80040154 類別未登錄 (發生例外狀況於 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
描述: 在執行目前 Web 要求的過程中發生未處理的例外狀況。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。

例外狀況詳細資訊: System.Runtime.InteropServices.COMException: 擷取元件 (CLSID {00024500-0000-0000-C000-000000000046}) COM Class Factory 失敗,因為發生下列錯誤: 80040154 類別未登錄 (發生例外狀況於 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

以下嘗試的解決方式:

1. Start->run->regedit 
Find 00024500-0000-0000-C000-000000000046 ->資料夾按右鍵內容,安全性加入NETWORK SERVICE給予權限,找遍所有00024500-0000-0000-C000-000000000046相關的機碼全部設了Network service IIS_IUSRS完全控制的權限,結果失敗

2. Start -> run -> DCOMCNFG
來想照著以上說明去「元件服務」設定DCOM元件,竟然沒有Microsoft Excel Application。因為Excel32位元,64位元的作業系統看不到該元件,結果失敗

3.web.config 加入
<configuration>
<system.web>
<identity impersonate="true" userName="adminUser" password="adminUserPassword" />
帳號密碼請先使用本機administrator帳號試比較沒問題
若是 Server 2008 x64 請建立下述資料夾
C:\Windows\SysWOW64\config\systemprofile\Desktop
若是 Server 2008 x86 請建立下述資料夾
C:\Windows\System32\config\systemprofile\Desktop
以上的設定。結果成功

4. Start -> run -> mmc comexp.msc /32
元件服務 -> 電腦 ->我的電腦 ->DCOM設定 ->Microsoft Excel Application ->安全性->啟動和啟用權限&存取權限->自訂權限加入Network service與IIS_IUSRS完全控制權限, 識別身份用互動式使用者。結果成功

2013年10月23日 星期三

Could not load file or assembly 'Microsoft.ReportViewer.ProcessingObjectModel

無法載入檔案或組件 'Microsoft.ReportViewer.ProcessingObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

Could not load file or assembly 'Microsoft.ReportViewer.ProcessingObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Install the following:
Microsoft Report Viewer 2010 SP1 Redistributable Package
Microsoft Report Viewer Redistributable 2010 SP1 Language Pack

http://www.microsoft.com/en-us/download/details.aspx?id=6610
http://www.microsoft.com/en-us/download/details.aspx?id=24932

無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組

無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。
描述: 在執行目前 Web 要求的過程中發生未處理的例外狀況。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。

例外狀況詳細資訊: System.IO.FileNotFoundException: 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。

原始程式錯誤:
在執行目前 Web 要求期間,產生未處理的例外狀況。如需有關例外狀況來源與位置的資訊,可以使用下列的例外狀況堆疊追蹤取得。

堆疊追蹤:

[FileNotFoundException: 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +258
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9874840
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254




版本資訊: Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.0.30319.18055


Please try:

1.Install Microsoft Visual C++ 2010 Redistributable Package (x86)  and 
Microsoft Visual C++ 2010 Redistributable Package (x64) 

2. IIS Setting / Application Pool / Advanced Settings / Enable 32-Bit Applications = True



2013年10月17日 星期四

Exchange Service Binding

使用Exchange Service Send Mail

C#

  1. public void SendMessage(ExchangeServiceBinding ewsServiceBinding, ItemIdType iiCreateItemid)
  2.  
  3.         {
  4.  
  5.             SendItemType siSendItem = new SendItemType();
  6.  
  7.             siSendItem.ItemIds = new BaseItemIdType[1];
  8.  
  9.             siSendItem.SavedItemFolderId = new TargetFolderIdType();
  10.  
  11.             DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
  12.  
  13.             siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
  14.  
  15.             siSendItem.SavedItemFolderId.Item = siSentItemsFolder;
  16.  
  17.             siSendItem.SaveItemToFolder = true;
  18.  
  19.  
  20.  
  21.  
  22.  
  23.             siSendItem.ItemIds[0] = (BaseItemIdType)iiCreateItemid;
  24.  
  25.             SendItemResponseType srSendItemReponseMessage = ewsServiceBinding.SendItem(siSendItem);
  26.  
  27.             if (srSendItemReponseMessage.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
  28.  
  29.             {
  30.  
  31.                 Console.WriteLine("Error Occured");
  32.  
  33.                 Console.WriteLine(srSendItemReponseMessage.ResponseMessages.Items[0].MessageText);
  34.  
  35.             }
  36.  
  37.             else
  38.  
  39.             {
  40.  
  41.                 Console.WriteLine("Message Sent");
  42.  
  43.             }
  44.  
  45.         }
  46.  
  47.  
  48.  
  49.         public string SendMail_ex2007(String Sender, String reciver, String subject, String content)
  50.  
  51.         {
  52.  
  53.  
  54.  
  55.             ExchangeServiceBinding esb = new ExchangeServiceBinding();
  56.  
  57.             esb.Url = "https://mail.xxx.com/EWS/Exchange.asmx";
  58.  
  59.             servicea = esb;
  60.  
  61.             //System.Net.ServicePointManager.ServerCertificateValidationCallback =
  62.  
  63.             System.Net.ServicePointManager.ServerCertificateValidationCallback = (Object obj, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) => true;
  64.  
  65.             esb.Credentials = new NetworkCredential("USERNAME", "PASSWORD", "SMTP");
  66.  
  67.             MessageType emailMessage = new MessageType();
  68.  
  69.             emailMessage.From = new SingleRecipientType();
  70.  
  71.             //set up a single sender
  72.  
  73.             //寄件者
  74.  
  75.             emailMessage.From.Item = new EmailAddressType();
  76.  
  77.             emailMessage.From.Item.EmailAddress = Sender;
  78.  
  79.             //標題
  80.  
  81.             emailMessage.Subject = subject;
  82.  
  83.             emailMessage.Body = new Microsoft.ServiceModel.Channels.Mail.ExchangeWebService.Exchange2007.BodyType();
  84.  
  85.             emailMessage.Body.BodyType1 = BodyTypeType.Text;
  86.  
  87.             //本文
  88.  
  89.             emailMessage.Body.BodyType1 = BodyTypeType.HTML;
  90.  
  91.             emailMessage.Body.Value = content;
  92.  
  93.             //將email寄出
  94.  
  95.             emailMessage.Sender = new SingleRecipientType();
  96.  
  97.             emailMessage.Sender.Item = new EmailAddressType();
  98.  
  99.             emailMessage.Sender.Item.EmailAddress = Sender;
  100.  
  101.             emailMessage.ToRecipients = new EmailAddressType[1];
  102.  
  103.             emailMessage.ToRecipients[0] = new EmailAddressType();
  104.  
  105.             emailMessage.ToRecipients[0].EmailAddress = reciver;
  106.  
  107.             emailMessage.Sensitivity = SensitivityChoicesType.Normal;
  108.  
  109.             //建立附件
  110.  
  111.             ItemIdType iiCreateItemid = CreateDraftMessage(esb, emailMessage);
  112.  
  113.             //iiCreateItemid = CreateAttachment(esb, iiCreateItemid);
  114.  
  115.             SendMessage(esb, iiCreateItemid);
  116.  
  117.             return "sendok";
  118.  
  119.         }
  120.  
  121.  
  122.  
  123.         protected void Button1_Click(object sender, EventArgs e)
  124.  
  125.         {
  126.  
  127. SendMail_ex2007("SenderName", "xxx@gmail.com", "smtp.xxx.com", "subject", "Content");
  128.  
  129.         }

非同步執行緒寄送郵件

非同步執行緒寄送郵件

C#

  1. #region 非同步執行緒寄送郵件
  2.  
  3.  
  4.  
  5.     //1-1.建立非同步委派簽章
  6.  
  7.     delegate string AsyncSendMail();
  8.  
  9.     //1-2.建立了一個具有IAsyncResult參數的Callback方法
  10.  
  11.     void EndCallback(IAsyncResult ar)
  12.  
  13.     {
  14.  
  15.         AsyncSendMail asynDelegate = ar.AsyncState as AsyncSendMail;
  16.  
  17.     }
  18.  
  19.     //1-3.建立執行主體程式
  20.  
  21.     string SendMailAsync()
  22.  
  23.     {
  24.  
  25.         try
  26.  
  27.         {
  28.  
  29.             #region 寄送郵件執行緒-Start
  30.  
  31.             //宣告執行緒
  32.  
  33.             System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
  34.  
  35.             sw.Reset();
  36.  
  37.             //開始執行緒
  38.  
  39.             sw.Start();
  40.  
  41.  
  42.  
  43.             //發送郵件
  44.  
  45.             System.Net.Mail.MailMessage message = new MailMessage();
  46.  
  47.             SmtpClient smtp = new SmtpClient();
  48.  
  49.             message.From = new MailAddress(strFrom);
  50.  
  51.             message.To.Add(new MailAddress(strTo));
  52.  
  53.             message.SubjectEncoding = System.Text.Encoding.UTF8;
  54.  
  55.             message.Subject = "Test";
  56.  
  57.             message.Body = strBody;
  58.  
  59.             smtp.Host = "192.168.1.1";
  60.  
  61.             smtp.Port = "25";
  62.  
  63.             smtp.Send(message);
  64.  
  65.  
  66.  
  67.             //停止執行緒
  68.  
  69.             sw.Stop();
  70.  
  71.  
  72.  
  73.             #endregion  執行緒-End
  74.  
  75.             return "successful";
  76.  
  77.         }
  78.  
  79.         catch (Exception)
  80.  
  81.         {
  82.  
  83.             return "failed";
  84.  
  85.             //throw;
  86.  
  87.         }
  88.  
  89.     }
  90.  
  91.  
  92.  
  93.     protected void Button1_Click(object sender, EventArgs e)
  94.  
  95.     {
  96.  
  97.  
  98.  
  99.         //1-4.實體化委派
  100.  
  101.         AsyncSendMail asynDelegate = new AsyncSendMail(SendMailAsync);
  102.  
  103.         //1-5.開始非同步作業
  104.  
  105.         asynDelegate.BeginInvoke(EndCallback, asynDelegate);
  106.  
  107.  
  108.  
  109.     }
  110.  
  111.  
  112.  
  113. #endregion 非同步執行緒寄送郵件
  114.  

HTTP Error 404.0 - Not Found

Create New IIS Web Site HTTP Error 404.0 - Not Found
解決方法:Application Pools / Advanced Settings / Enable 32-Bit Applications = true
-------------------------------

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.



Please try the next...