การเชื่อมต่อกับ LDAP

0 comments

ในตัวอย่างนี้ผมทดสอบ ดึง username,password มาจาก Window Server ในส่วนของ OU นะครับ
ซึ่งใน OU (Organization Unit ) นี้ผมได้เก็บชื่อ user ต่างๆมากมายรวมถึงเก็บ สิทธิ์ในการ login เข้าเข้าสู่ window server
ผมได้สร้าง web form ขึ้นมา หน้านึง ที่มีหน้าตาดังรูป

จากนั้น ก็คลิกที่ปุ่ม Submit แล้วเขียนโค้ดดังนี้
(ก่อนที่จะใช้งาน DirectoryEntry ให้ไป add reference  library ที่ชื่อ System.DirectoryServices ก่อน  
จากนั้นก็เรียกใช้ using System.DirectoryServices;
และในการติดต่อ ldap สิ่งแรกคือจะต้องรู้ LDAP Server ก่อนนะครับ )

ตัวอย่างโค้ด

protected void Button1_Click(object sender, EventArgs e)

    {

        string username = txtUsername.Text;

        string password = txtPassword.Text;

        string path = "192.x.x.x"; //ip ของ window server ที่จะติดต่อ

        DirectoryEntry direct_entry = new DirectoryEntry();

        direct_entry.Path = path;

        direct_entry.Username = username;

        direct_entry.Password = password;

        if (IsCheckUserExist(username)) //ถ้ามี user อยู่ในระบบจริงก็ให้ไปที่หน้า hellomember.aspx

        {

          Response.Redirect("hellomember.aspx");

        }

        else

        {

            Response.Write("กรุณาใส่ username,password ให้ถูกต้อง");

        }

    }

      public bool IsCheckUserExist(string username)

    {

        DirectoryEntry direct_entry = GetDirectoryEntry();

        DirectorySearcher direct_search = new DirectorySearcher();

        direct_search.SearchRoot = direct_entry;

        direct_search.Filter = "(&(ObjectClass=user)(SAMAccountName=" + username + "))"; //ตรวจสอบเฉพาะ username ที่ใส่เข้ามาทาง textbox

        SearchResultCollection result_col = direct_search.FindAll();

        return result_col.Count > 0; //ถ้ามี username ชื่อนี้อยู่ในระบบ server จริงก็ให้ ส่งค่า true ไปที่ event ที่ชื่อ Button1_Click

    }

  public DirectoryEntry GetDirectoryEntry()

    {

        DirectoryEntry direct_entry = new DirectoryEntry("LDAP://192.x.x.x",txtUsername.Text,txtPassword.Text);//กำหนด LDAP Server , username,password

        direct_entry.AuthenticationType = AuthenticationTypes.Secure;

        return direct_entry;

    }

นี้เป็นตัวอย่างโค้ดที่ผมเขียนขึ้นเพื่อติดต่อ LDAP ผมเขียนใน Website นะครับถ้าจะทำเป็น web service ก็เขียนคล้ายกับตัวอย่างนี้ลองเอาไปประยุกต์ใช้ดูครับ

โดยสิ่งสำคัญหลักๆใน ตัวอย่างนี้คือ ให้ผู้ใช้ สามารถ login ผ่านหน้า web site ได้ โดยผู้ใช้งานจะต้องมี username,password อยู่ใน ส่วนของ OU ใน Window server ก่อน

แล้วพอกดปุ่ม Submit ทางโปรแกรมก็จะติดต่อ เพื่อตรวจสอบ username,password ผ่าน protocal : LDA

การเขียน Event Delegate ใน ASP.NET

0 comments

You're totally right... actually there does need to be a lot more added to your user control...

public delegate void btnWUCClickedHandler(object sender, EventArgs e);

[Category("Action")]
public event btnWUCClickedHandler btnWUCClicked;
protected virtual void OnBtnWUCClicked(EventArgs e){
        if (btnWUCClicked != null){
btnWUCClicked(this, e);
        }
}

protected void btnWUC_Click(object sender, EventArgs e)
{ //whatever else you want to be done in your user control
OnBtnWUCClicked(e);
}

in addition to the

btnWUC.Click += new System.EventHandler(this.btnWUC_Click);

in the page load. Then, in your default.aspx:

<SB:WebUserControl ID="btn" runat="server"  OnBtnWUCClicked="btn_T"/>

----------------------------------------------------------------------------------------------------

a. Code behind of Web User Control
//Create an event handler
public event EventHandler OnButtonClick;
//Create an new event on the click of button
public void Button1_Click(object sender, EventArgs e)
{
this.OnButtonClick(this, new EventArgs());
}
b. Code behind of Web Form of ASP.NET
//On the page load event use the following code
this.WebUserControl1.OnButtonClick+=new EventHandler(WebUserControl1.OnButtonClick);
//Define the method that handles the event now
void WebUserControl1.ButtonClick(object sender, EventArgs e)
{
///custom code goes here.
}

การกำหนด Connection ใน web.config สำหรับ |DataDirectory|

0 comments

<connectionStrings>
    <remove name="LocalSqlServer" />
    <add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
    <add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

การแทรก web user control ผ่านการเขียนโค้ด

0 comments

public partial class WebForm1 : System.Web.UI.Page

    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Control objCtr1;
            objCtr1 = LoadControl("WebUserControl1.ascx");
            this.PlaceHolder1.Controls.Add(objCtr1);
        }
    }

WebPage1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebAppTest.TestModule.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div id="TestModule1">

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

    </div>

    </form>

</body>

</html>

How to Configure Windows Authentication on Windows Vista / 7 Premium

0 comments

Step 1: Turn ON All Windows Features at Programs and Features in Control Panel:
---------------------------------------------------------------------------------------

Or at Least Those related with Internet Information Services,
in alternative run the following command

start /w pkgmgr 
/iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ASP;IIS-CGI;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-Security;IIS-BasicAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;IIS-IPSecurity;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;IIS-LegacyScripts;IIS-LegacySnapIn;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI

Step 2: Check for available files:
---------------------------------------------------------------------------------------

(The Basic Authentication is available here to guidance, 
if file don't exist you must get it from another version of vista)

- Basic Authentication  (needs C:\Windows\System32\inetsrv\authbas.dll)
- Windows Authentication (needs C:\Windows\System32\inetsrv\authsspi.dll)
- Digest Authentication (needs C:\Windows\System32\inetsrv\authmd5.dll)
- IISCertificateMapping Authentication (needs C:\Windows\System32\inetsrv\authmap.dll)
- CertificateMapping Authentication (needs C:\Windows\System32\inetsrv\authcert.dll)

Step 3: Enable Registry Entries for:
---------------------------------------------------------------------------------------

Check if exists and change or create the keys:

(You must take ownership of this key as administrators group and give it full permissions, 
at the end restore the ownership to NT SERVICE\TrustedInstaller and the permissions changed)

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\Components]
"BasicAuthenticationBinaries"=dword:00000001
"BasicAuthentication"=dword:00000001
"WindowsAuthenticationBinaries"=dword:00000001
"WindowsAuthentication"=dword:00000001
"DigestAuthentication"=dword:00000001
"IISCertificateMappingAuthentication"=dword:00000001
"ClientCertificateMappingAuthentication"=dword:00000001

step 4: Change C:\Windows\System32\inetsrv\config\applicationHost.config
--------------------------------------------------------------------------------------

Check if exists and change or create the keys:

            <authentication>

            ...

                <basicAuthentication enabled="false" />

                <windowsAuthentication enabled="false">
                    <providers>
                        <add value="Negotiate" />
                        <add value="NTLM" />
                    </providers>
                </windowsAuthentication>

                <digestAuthentication enabled="false" />

                <iisClientCertificateMappingAuthentication enabled="false">
                </iisClientCertificateMappingAuthentication>

                <clientCertificateMappingAuthentication enabled="false" />

            ...

            </authentication>

        <globalModules>

            ...

            <add name="BasicAuthenticationModule" image="%windir%\System32\inetsrv\authbas.dll" />
            <add name="WindowsAuthenticationModule" image="%windir%\System32\inetsrv\authsspi.dll" />
            <add name="DigestAuthenticationModule" image="%windir%\System32\inetsrv\authmd5.dll" />
            <add name="IISCertificateMappingAuthenticationModule" image="%windir%\System32\inetsrv\authmap.dll" />
            <add name="CertificateMappingAuthenticationModule" image="%windir%\System32\inetsrv\authcert.dll" />

            ...

        </globalModules>

step 5: Change C:\Windows\System32\inetsrv\config\schema\IIS_schema.xml
--------------------------------------------------------------------------------------

Check if exists and change or create the keys:

(You must take ownership of this key as administrators group and give it full permissions,
at the end restore the ownership to NT SERVICE\TrustedInstaller and the permissions changed)

  <sectionSchema name="system.webServer/security/authentication/windowsAuthentication">
    <attribute name="enabled" type="bool" defaultValue="false" />
    <element name="providers">
      <collection addElement="add" clearElement="clear" removeElement="remove">
        <attribute name="value" type="string" isUniqueKey="true" />
      </collection>
    </element>
    <attribute name="authPersistSingleRequest" type="bool" defaultValue="false" />
    <attribute name="authPersistNonNTLM" type="bool" defaultValue="false" />
    <attribute name="useKernelMode" type="bool" defaultValue="true" />
    <attribute name="useAppPoolCredentials" type="bool" defaultValue="false" />
  </sectionSchema>

Verbatim String by @”string text”

0 comments

ปกติเวลาจะใส่ไฟล์พาธก็จะต้องใช้ \\ เช่น “C:\\Path” แต่เมื่อใดก็ตามที่ใช้ @ เราจะทำแบบนี้ได้ @”C:\Path” คือ มันจะไม่แปล Escape String ใน Text

MSDTC on server 'XXX' is unavailable

0 comments

You need to turn the MSDTC service on.


You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.