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#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;

public partial class Test_tsLDAP : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// Button1 Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string a;
            a = isADauth("user1", "pass1");
            Response.Write(a.ToString());
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            //throw ex;
        }
       
    }

    /// <summary>
    /// AD驗証
    /// </summary>
    /// <param name="uid">帳號</param>
    /// <param name="passwd">密碼</param>
    /// <returns></returns>
    public static string isADauth(string uid, string passwd)
    {
        string authentic = "";
        try
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://DC01", uid, passwd);
            object nativeObject = entry.NativeObject;
            authentic = "LOGIN_SUCCESSFUL";
        }
        catch (DirectoryServicesCOMException dscom_ex)
        {
            //authentic = "LOGIN_FAILED";
            throw dscom_ex;
        }
        return authentic;
    }
}

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#

public void SendMessage(ExchangeServiceBinding ewsServiceBinding, ItemIdType iiCreateItemid)
        {
            SendItemType siSendItem = new SendItemType();
            siSendItem.ItemIds = new BaseItemIdType[1];
            siSendItem.SavedItemFolderId = new TargetFolderIdType();
            DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
            siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
            siSendItem.SavedItemFolderId.Item = siSentItemsFolder;
            siSendItem.SaveItemToFolder = true;


            siSendItem.ItemIds[0] = (BaseItemIdType)iiCreateItemid;
            SendItemResponseType srSendItemReponseMessage = ewsServiceBinding.SendItem(siSendItem);
            if (srSendItemReponseMessage.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
            {
                Console.WriteLine("Error Occured");
                Console.WriteLine(srSendItemReponseMessage.ResponseMessages.Items[0].MessageText);
            }
            else
            {
                Console.WriteLine("Message Sent");
            }
        }

        public string SendMail_ex2007(String Sender, String reciver, String subject, String content)
        {

            ExchangeServiceBinding esb = new ExchangeServiceBinding();
            esb.Url = "https://mail.xxx.com/EWS/Exchange.asmx";
            servicea = esb;
            //System.Net.ServicePointManager.ServerCertificateValidationCallback =
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (Object obj, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) => true;
            esb.Credentials = new NetworkCredential("USERNAME", "PASSWORD", "SMTP");
            MessageType emailMessage = new MessageType();
            emailMessage.From = new SingleRecipientType();
            //set up a single sender
            //寄件者
            emailMessage.From.Item = new EmailAddressType();
            emailMessage.From.Item.EmailAddress = Sender;
            //標題
            emailMessage.Subject = subject;
            emailMessage.Body = new Microsoft.ServiceModel.Channels.Mail.ExchangeWebService.Exchange2007.BodyType();
            emailMessage.Body.BodyType1 = BodyTypeType.Text;
            //本文
            emailMessage.Body.BodyType1 = BodyTypeType.HTML;
            emailMessage.Body.Value = content;
            //將email寄出
            emailMessage.Sender = new SingleRecipientType();
            emailMessage.Sender.Item = new EmailAddressType();
            emailMessage.Sender.Item.EmailAddress = Sender;
            emailMessage.ToRecipients = new EmailAddressType[1];
            emailMessage.ToRecipients[0] = new EmailAddressType();
            emailMessage.ToRecipients[0].EmailAddress = reciver;
            emailMessage.Sensitivity = SensitivityChoicesType.Normal;
            //建立附件
            ItemIdType iiCreateItemid = CreateDraftMessage(esb, emailMessage);
            //iiCreateItemid = CreateAttachment(esb, iiCreateItemid);
            SendMessage(esb, iiCreateItemid);
            return "sendok";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
SendMail_ex2007("SenderName", "xxx@gmail.com", "smtp.xxx.com", "subject", "Content");
        }

非同步執行緒寄送郵件

非同步執行緒寄送郵件

C#

#region 非同步執行緒寄送郵件
 
    //1-1.建立非同步委派簽章
    delegate string AsyncSendMail();
    //1-2.建立了一個具有IAsyncResult參數的Callback方法
    void EndCallback(IAsyncResult ar)
    {
        AsyncSendMail asynDelegate = ar.AsyncState as AsyncSendMail;
    }
    //1-3.建立執行主體程式
    string SendMailAsync()
    {
        try
        {
            #region 寄送郵件執行緒-Start
            //宣告執行緒
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            //開始執行緒
            sw.Start();

            //發送郵件
            System.Net.Mail.MailMessage message = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            message.From = new MailAddress(strFrom);
            message.To.Add(new MailAddress(strTo));
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Subject = "Test";
            message.Body = strBody;
            smtp.Host = "192.168.1.1";
            smtp.Port = "25";
            smtp.Send(message);

            //停止執行緒
            sw.Stop();

            #endregion  執行緒-End
            return "successful";
        }
        catch (Exception)
        {
            return "failed";
            //throw;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        //1-4.實體化委派
        AsyncSendMail asynDelegate = new AsyncSendMail(SendMailAsync);
        //1-5.開始非同步作業
        asynDelegate.BeginInvoke(EndCallback, asynDelegate);

    }

#endregion 非同步執行緒寄送郵件

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...