제가 올렸던 WMI라이브러리,  MultipleSearchPattern 라이브러리를 보시면 chm 파일로 라이브러리에 대한 도움말 파일이 있는데 Sandcastle이라는 것을 이용해서 이 도움말 파일을 만드는 방법을 설명하겠습니다.

우선 이 작업을 위해서는 XML주석이 필요한데 컴파일 결과로 XML 파일을 생성해야 합니다.
(XML 주석과 관련해서는 http://msdn.microsoft.com/ko-kr/library/b2s063f7.aspx 를 참고하세요...)

C#의 프로젝트 옵션에서 Build -> Output 항목을 보면 "XML documentation file" 항목이 기본적으로 체크되있지 않은데 아래 화면처럼 체크를 한 뒤에 컴파일을 하면 XML 주석 내용이 *.XML 파일로 출력됩니다.

이제 이 xml 파일과 dll 등 프로젝트 결과물은 도움말 파일 만드는데 사용합니다.

우선 아래 2개의 사이트에서 파일을 받아서 설치합니다.

각각 대략적으로 설명하면 Sandcastle은 도움말 파일을 만들기 위한 라이브러리, SHFB(Sandcastle Help File Builder)은 도움말 파일을 만드는 툴 정도로 생각하시면 됩니다.
(이외에 chm 파일을 만들기 위해서 "HTML Help Workshop"가 필요하지만 vs 등을 설치하면 기본적으로 설치되니 별도의 설치는 필요 없을 듯 합니다. 혹시 설치가 안되있다면 인터넷에서 그냥 받아서 설치하면 됩니다.)

설치 후에 생성된 시작메뉴에서 "Sandcastle Help File Builder GUI"를 실행합니다.

프로그램 실행 후에 File -> New Project나 툴바메뉴에서 가장 왼쪽 아이콘을 눌러서 새프로젝트를 생성합니다.
(도움말 파일을 만들기 위한 정보, 결과물이 저장될 수 있도록 작업 경로를 만드는 작업으로 적당한 폴더를 정해주고파일명을 적어준 후 저장 버튼을 누릅니다.)

프로젝트를 만들고 나면 아래 화면의 오른쪽에 보이는 것처럼 Project Explorer에서 Documentation Sources 항목이 있는데 여기서 마우스 오른쪽 버튼을 눌러서 Add Documentation Sources를 눌러서 위에서 설명했던 xml 파일과 dll 등의 프로젝트 결과물을 추가해줍니다.
(이외에 Visual Studio의 솔루션, 프로젝트 파일 등 다른 방법으로도 추가가 가능합니다.)

파일 추가가 끝나면 아래 화면의 왼쪽에 있는 Project Properties에서 적당히 설정을 해주고 Visual Studio에서 볼 수 있는 빌드 아이콘을 클릭해서 빌드를 합니다.
(설정은 기본적으로 Language 정도만 해주면 될 것 같고 때에 따라서 포맷, 스타일 정도를 지정해 주면 될 것 같네요...그리고 빌드 버튼은 Documentation -> Build Project 메뉴로도 가능합니다.)

빌드가 성공하면 아래처럼 빌드가 성공했다는 메시지가 나옵니다.
(빌드 시간은 좀 걸립니다.)

빌드가 성공적으로 끝나면 처음에 프로젝트 만들었던 폴더를 보면 Documentation.chm 파일로 도움말 파일이 완성되고 열어보면 아래처럼 결과가 나옵니다.

참고로 위 샘플에 쓰인 코드는 아래와 같습니다. XML 주석 부분이랑 결과를 비교해보세요.

In this walkthrough you will learn how to create Web-Sites, Web Applications, Virtual Directories and Application Pools.

Introduction

The IIS PowerShell namespace consists of items like Web-Sites, Apps, Virtual Directories and Application Pools. Creating new namespace items and managing them is very easy using the built-in PowerShell cmdlets.

Creating Web-Sites

 If you are familiar with PowerShell you know that the New-Item cmdlet is used to create new items in the various PowerShell namespaces. The command "New-Item c:\TestDirectory" creates a new filesystem directory for example (most people use the "MD" or "MKDIR" alias for New-Item however). New-Item is also used to create new Web-Sites within the IIS 7.0 PowerShell namespace.

Parameters

Specifying the name of the directory is the only argument needed when you create a new file system directory. Unfortunately this is not enough when you create a Web-Site. Additional parameters like the file system path and network bindings are needed to create a Web-Site. Here is the command to create a new Web-Site followed by a dir command:

PS IIS:\Sites> New-Item iis:\Sites\TestSite -bindings @{protocol="http";bindingInformation=":80:TestSite"} -physicalPath c:\test

PS IIS:\Sites> dir

Name             ID   State      Physical Path                  Bindings
----             --   -----      -------------                  --------
Default Web Site 1    Started    f:\inetpub\wwwroot             http *:80:
TestSite         2    Started    c:\test                        http :80:TestSite 

Using the -physicalPath argument is pretty straightforward. But you might ask yourself why the -bindings argument looks so complex.

The construct used is a hashtable (go here to learn more about PowerShell hash tables). Within the hash table key=value pairs indicate the settings that reflect the attributes within the IIS site bindings section:

<bindings>
        <binding protocol="http" bindingInformation=":80:TestSite" />
</bindings>

Now here is the reason why we use a hash table: IIS configuration is completely extensible (see  here for more details) with additional sections and attributes. You can imagine that somebody extending the <binding> element with additional attributes. Key value pairs within a hash table provide the flexibility to incorporate these new attributes without having to completely rewrite the IIS PowerShell Snap-in.

Granted, the syntax is a bit complex. We are thinking about wrapping some typical tasks like creating sites with additional functions or scripts in a later Tech Preview.

Deleting Sites

Here is how you delete the site you just created.

PS IIS:\ >Remove-Item IIS:\Sites\TestSite

Creating Web Applications

Creating Web Applications is easier than creating sites. Here we go: 

PS IIS:\> New-Item 'IIS:\Sites\Default Web Site\DemoApp' -physicalPath c:\test -type Application

 

Name                     ApplicationPool          EnabledProtocols         PhysicalPath
----                     ---------------          ----------------         ------------
DemoApp                  DefaultAppPool           http                     c:\test

The only parameter you have to specify is the type (-type) because underneath a Web-Site you might want to create an Applications or a Virtual Directories. By specifying the -type parameter you tell the IIS Snap-in to create an application.

To delete the application you can also use Remove-Item.  

Creating Virtual Directories

To create a Virtual Directory you also use the New-Item cmdlet. Let's create a Virtual Directory underneath the 'Default Web Site' but and a second one underneath the Web Application we created in the previous step.

PS IIS:\> New-Item 'IIS:\Sites\Default Web Site\DemoVirtualDir1' -type VirtualDirectory -physicalPath c:\test\virtualDirectory1

Name                                              PhysicalPath
----                                              ------------
DemoVirtualDir1                                   c:\test\virtualDirectory1


PS IIS:\> New-Item 'IIS:\Sites\Default Web Site\DemoApp\DemoVirtualDir2' -type VirtualDirectory -physicalPath c:\test\virtualDirectory2

Name                                              PhysicalPath
----                                              ------------
DemoVirtualDir2                                   c:\test\virtualDirectory2

Creating Application Pools

But it gets even simpler. Creating a new AppPool only requires the name to be specified.

PS IIS:\> new-item AppPools\DemoAppPool

Name                     State
----                     -----
DemoAppPool              {}

Simple, wasn't it? Now let's put this together to an end-to-end scenario.

Putting it all Together

In the following end-to-end scenario we will execute the following step:

  1. Create a set of new file system directories for the sites, web applications and virtual directories we will create a little later.
  2. Copy some very simple web content into the newly created directories.
  3. Create new Application Pool
  4. Create a new site, a new application and two new virtual directories and assign them to newly created Application Pool.
  5. Request the web content via the web browser.

Step 1: Create New Directories

 We use the New-Item cmdlet to create four new file system directories. Execute the following commands (use 'md' instead of New-Item if you don't want to specify the -type parameter):

New-Item C:\DemoSite -type Directory

New-Item C:\DemoSite\DemoApp -type Directory

New-Item C:\DemoSite\DemoVirtualDir1 -type Directory

New-Item C:\DemoSite\DemoVirtualDir2 -type Directory

Step 2: Copy Content

Now let's write some simple html content to these directories:

Set-Content C:\DemoSite\Default.htm "DemoSite Default Page"

Set-Content C:\DemoSite\DemoApp\Default.htm "DemoSite\DemoApp Default Page"

Set-Content C:\DemoSite\DemoVirtualDir1\Default.htm "DemoSite\DemoVirtualDir1 Default Page"

Set-Content C:\DemoSite\DemoVirtualDir2\Default.htm "DemoSite\DemoApp\DemoVirtualDir2 Default Page"

Step 3: Create New Application Pool

Create the new Application Pool 'DemoAppPool' for the new site if you deleted the one we created in the previous sample.  

New-Item IIS:\AppPools\DemoAppPool

Step 4: Create New Sites, Web Applications and Virtual Directories and Assign to Application Pool

Here comes the beef. We create DemoSite, DemoApp and two Virtual Directories - DemoVirtualDir1 is directly underneath DemoSite and DemoVirtualDir2 is underneath DemoApp. We are assigning DemoSite and DemoApp to DemoAppPool created in the previous step. DemoSite is assigned to port 8080 to not conflict with the 'Default Web Site'

New-Item IIS:\Sites\DemoSite -physicalPath C:\DemoSite -bindings @{protocol="http";bindingInformation=":8080:"}

Set-ItemProperty IIS:\Sites\DemoSite -name applicationPool -value DemoAppPool

New-Item IIS:\Sites\DemoSite\DemoApp -physicalPath C:\DemoSite\DemoApp -type Application

Set-ItemProperty IIS:\sites\DemoSite\DemoApp -name applicationPool -value DemoAppPool

New-Item IIS:\Sites\DemoSite\DemoVirtualDir1 -physicalPath C:\DemoSite\DemoVirtualDir1 -type VirtualDirectory

New-Item IIS:\Sites\DemoSite\DemoApp\DemoVirtualDir2 -physicalPath C:\DemoSite\DemoVirtualDir2 -type VirtualDirectory

Voila. All that's left is to request the web content.

Step 5: Request the Web Content

You can of course open the browser and enter http://localhost:8080/ and all the other URLs. But its a PowerShell walkthrough and we'll use PowerShell to do it by using the .NET WebClient classes:

$webclient = New-Object Net.WebClient

$webclient.DownloadString("http://localhost:8080/");

$webclient.DownloadString("http://localhost:8080/DemoApp");

$webclient.DownloadString("http://localhost:8080/DemoVirtualDir1");

$webclient.DownloadString("http://localhost:8080/DemoApp/DemoVirtualDir2");

If you feeling adventurous you can also use Internet Explorer object itself:

$ie = new-object -com InternetExplorer.Application

$ie.Visible = $true

$ie.Navigate("http://localhost:8080/");

Summary

In this walkthrough you learned how to create Web-Sites, Web Applications, Virtual Directories and Application Pools with PowerShell. Additional PowerShell features were used to build a functional end-to-end scenario.

Related Content

자바 스크립트 내에서 XML 노드 Value값를 가져오는 방법이다.
처음에는 아래와 같이 jQuery를 이용하여 처리하고자 진행하였다.
var xml = '';
$(xml).find("id").each(function () {
   var id = $(this).find("id").text();
});
그러나 XML 노드에 CDATA 타입으로 지정되어 있으면 항상 ''로 리턴되어 사용할 수 없었다.
좀 더 테스트 해보니, Dom Parser 처리 후 조회해보니 값을 제대로 가져온다.ㅎ
var xml = '';

var xmlDoc;
if (window.ActiveXObject) {
    // IE일 경우
    xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
    xmlDoc.async = false;
    xmlDoc.loadXML(xml);
}
else if (window.XMLHttpRequest) {
    //Firefox, Netscape일 경우
    var xmlParser = new DOMParser();
    xmlDoc = xmlParser.parseFromString(xml, 'text/xml');
}
else {
    xmlDoc = null;
}

if (xmlDoc != null) {
    // #1. jQuery 방식 
    $(xmlDoc).find("To").each(function () {
        var id = $(this).find("dn").text();
    });

    // #2. Script 방식
    var nodes = xmlDoc.selectNodes("person/to");
    for (i = 0; i < nodes.length; i++) {
        var id = nodes[i].selectSingleNode("id").text;
    }
}

보통 ASP.NET 기반의 Web Application을 개발하다 보면, DLL들을 많이 이용하게 되는데,
만일 그 DLL의 일부 코드 수정을 반영 하려면 IIS 서비스를 다시 시작해야 한다.
그래서 보통 IISRESET.EXE 라는 명령어를 이용해 아예 서비스를 내렸다가,
다시 시작하곤 한다.

그러나 단순 DLL의 로직 몇가지 변경 때문에, IISRESET을 하기에는 비용이 비쌀 수 있다.
Web Publishing에 관련 된 대부분의 서비스를 내렸다가 다시 올리는 작업이기 때문에,
Reset 하는 시간도 많이 걸리는데다, IIS를 통해 데이터를 끌어 올리는 비용도 만만치 않다.

이에 IIS 6.0 대 부터는 Application Pool 이라는 것이 있어, 그 Application Pool 만 
정리해 주면 새로운 DLL로 올려줄 수 있도록 제공하게 된다.

보통은 INETMGR을 띄워 해당하는 Application Pool 에서 오른쪽
버튼을 클릭해서 재생(혹은 Recycle)을 선택하면 되는데, UI 도구를 사용하는 것이라, 조작이 좀 귀찮긴 하다.


이 작업을 명령줄로 실행하는 방법을 사용하게 되면, 시작 -> 실행 -> cmd 해서 나오는 도스창(명령 실행창)에서 실행되게 만들거나 Batch 파일로 만들면 더욱 편하게 작업할 수 있다. 

Recycle 할 때 사용하는 명령 줄은 아래와 같다.

IIS 6.0 : cscript //nologo C:\Windows\system32\iisapp.vbs /a "<웹응용프로그램이름>" /r
      예) cscript //nologo C:\Windows\system32\iisapp.vbs /a "SharePoint - 80" /r

IIS 7.0 : C:\Windows\System32\inetsrv\appcmd recycle apppool /apppool.name:"<웹응용프로그램이름>"
      예) C:\Windows\System32\inetsrv\appcmd recycle apppool /apppool.name:"SharePoint - 80"

I got requests may times and I thought I should write the steps to configuration of FBA with SharePoint 2010. I have detailed the steps in this blog.

SharePoint 2010 supports FBA, Like WSS 3.0 or MOSS 2007. It's a feature of ASP .Net which we use with SharePoint. SharePoint 2010 you can create web applications using Classic Based Authentication or Claims based Authentication. However, FBA can only be configured with web applications created using Claims Based Authentication.

What are the differences between Classic Mode Authentication and Claims based Authentication?

Classic Mode Authentication: It refers to the integrated windows authentication. You cannot configure the Forms based authentication if your web application is using Classic Mode Authentication. You can convert a web application from Classic Mode Authentication to Claims Based Authentication. However, that can only be done using PowerShell commands and its an irreversible process. I have detailed steps to convert the web application from Classic Mode authentication to Claims Based Authentication.

Claims Based Authentication: SharePoint 2010 is built on Windows Identity Foundation. It enables authentication from windows as well as non-windows based systems. This also provides the capability to have multiple authentication in a single URL.

Configuration of FBA with SharePoint 2010 involves 4 major steps. The steps to configure the FBA with SQL membership Provider are below:

I> Create or Convert existing web applications to use Claims Based Authentication

II> Create User IDs in SQL Database

III> Modify web.config file

IV> Give Permissions to users present in SQL database

Note: If you want to configure FBA with LDAP membership Provider then you can refer TechNet article.

Please find the detailed steps below:

I> Create or Convert existing web applications to use Claims Based Authentication

Note: - Web Application has to be created from the Central Administration console or PowerShell, however it should be using Claims Based Authentication.

A. Creating web application using Central administration

      • Open Central Administration Console.
      • Click on Manage Web application Under Application Management.
      • Click on new on the Ribbon.
      • Chose Claims based Authentication From the top of the page.
      • Choose the port no for the web application.
      • Click on Enable Forms Based Authentication (FBA) Under Claims Authentication Types. Windows Authentication is enabled by default and if you dont need windows authentication then you need to remove the check the box.
      • Add the Membership Provider & Role Manager Name
      • As soon as web application has been created please verify the Authentication Provider settings for the web application. I have the screenshot below:

clip_image002

Note:- If you want to use Windows Authentication and Forms Based Authentication in Single URL then you have to select Enable Windows Authentication and Enable Forms Based Authentication.

image

Note:- Just for understanding, i am using Membership Provider as “SQL-MembershipProvider” and Role Manager as “SQL-RoleManager”. You can use different names, however you need to remember the name so that you can refer them in web.config files. These names are case sensitive.

B. What if you already have a Web application created using Classic Mode Authentication or How to convert Web application from Classic Mode authentication to Claims based Authentication?

You don’t have to delete that web application. You can convert that web application from classic mode authentication to claims based authentication. However this can only be done using PowerShell and it’s an irreversible process. Follow PowerShell commands to convert the web application from Classic Mode Authentication to Claims based Authentication:

$App = get-spwebapplication “URL”

$app.useclaimsauthentication = “True”

$app.Update()

Example:-

$App = get-spwebapplication “http://sp1:8000”

$app.useclaimsauthentication = “True”

$app.Update()

Once you have the web application using Claims Based Authentication, you can create a site collection. Now if you access the web application, you can access the site choosing Windows Authentication or Forms Based Authentication as shown in below image.

clip_image004

Choose windows authentication and login to site. When you login your currently logged in credentials will be used. Make sure the account you are logged in with has access to SharePoint site; Otherwise, you will get access denied error.

II> Configure the Membership Provider and Role Manager.

  • On SharePoint 2010 server open the command prompt.
  • Navigate to C:\Windows\Micrsooft .Net\Framework64\v2.0.50727
  • Run “aspnet_regsql.exe”. This will open ASP .Net SQL Server Setup wizard. On this click on NEXT.

clip_image006

  • Click on “Configure SQL Server for Application Services”.
  • Specify the Database name. If you don’t specify the database name then it will create a database call aspnetdb.

clip_image008

  • Use membershipseeder tool to create the users in SQL database. You can find the tool and information on that from codeplex.

Note:- I have specified the database name as “SQL-Auth”.

III> Modify the web.config file for Membership Provider and Role Manager.

We need to modify 3 different web.config files for FBA to work. Web.config of FBA Web application, web.config of Central Administration Site & Web.config of STS.

A. Modify web.config of FBA web application.

  • Add connection String:

<connectionStrings>

<add name="SQLConnectionString" connectionString="data source=SQL;Integrated Security=SSPI;Initial Catalog=SQL-Auth" />

</connectionStrings>

Connection String has to be added after </SharePoint> and Before <system.web>

  • Add membership Provider and Role Manager:

<roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">

<providers>

<add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

<add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</roleManager>

<membership defaultProvider="i">

<providers>

<add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

<add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</membership>

</system.web>

B. Modify web.config of the Central Administration web application.

  • Add connection String:

<connectionStrings>

<add name="SQLConnectionString" connectionString="data source=SQL;Integrated Security=SSPI;Initial Catalog=SQL-Auth" />

</connectionStrings>

Connection String has to be added after </SharePoint> and before <system.web>

  • Add membership Provider and Role Manager:

<roleManager defaultProvider="AspNetWindowsTokenRoleProvider" enabled="true" cacheRolesInCookie="false">

<providers>

<add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</roleManager>

<membership defaultProvider="SQL-MembershipProvider">

<providers>

<add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</membership>

C. Modify web.config of STS. You can locate the STS web.config from %programfiles%\common files\Microsoft Shared\web server extensions\14\WebServices\SecurityToken

<connectionStrings>

<add name="SQLConnectionString" connectionString="data source=SQL;Integrated Security=SSPI;Initial Catalog=SQL-Auth" />

</connectionStrings>

<system.web>

<roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">

<providers>

<add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

<add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</roleManager>

<membership defaultProvider="i">

<providers>

<add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

<add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

</providers>

</membership>

</system.web>

Above has to be added before </configuration>

IV> Give permissions to users in SQL database.

  • Access Central Administration console and click on manage web applications under Application Management.
  • Select the web application and click on user Policy on ribbon.
  • Click on Add user and select Default Zone.
  • Now type the user name, add the user to the web application by defining appropriate permission.

Common Issues:

If you are using multiple service accounts as per TechNet article Administrative and service accounts required for initial deployment (SharePoint Server 2010) then you might not able to resolve the usernames or add the users to the web application. If you are using 3 different accounts (Farm Administrator account, Application pool account for web application and service application account) then you need to make sure that you have access to the SQL membership database (SQL-Auth).

Important:

What happens to FBA when we upgrade WSS 3.0 / MOSS 2007 to SharePoint 2010?

Before upgrading to SharePoint 2010 you need to remove the changes you have done to the web.config file. As soon as the process of upgrading finishes all the web applications will be upgraded; however, those will use Classic Mode Authentication. You can convert those web applications from Classic Mode Authentication to Claims Based Authentication.

  • ** Note: This FBA configuration method is based upon the pre-release version of SharePoint 2010 and may change in the final release **

    Setup your SharePoint 2010 site

    1. In Central Admin, create a new site. By default, this will use Windows Authentication. Since we haven’t setup FBA yet, we need to setup the Web Application first as a Windows site.
    2. Create the Web Application
    3. Create a default Site Collection, and make a windows user (below we’ve used the Administrator account) a Site Administrator.

    Setup your User Database

    1. Setup the ASP.NET Membership Database. Note: You can use custom membership stores, DotNetNuke, even Live! credentials. But the .NET membership database is very simple to setup. This requires the SQL Server database. You can use the integrated version that is supplied with SharePoint, Express or a fully featured SQL Server (Standard or Enterprise) Edition.
    2. Find the setup file aspnet_regsql.exe located at either of the following locations depending upon your OS:
      %windir%\Microsoft.NET\Framework\v2.0.5027
      %windir%\Microsoft.NET\Framework64\v2.0.5027
    3. When the ASP.NET SQL Server Setup Wizard appears, select “Configure SQL Server for application services”, then click Next
    4. Enter the SQL Server and Database name.
      sqldb
    5. Above, I have named the database FBADB
    6. Click Next and Finish

    Provide Access to the Membership Database

    As an administrator, you’ll be able to add and modify user accounts. But from the SharePoint runtime, we’ll have to provide access to the membership store. This can be done in two ways. If using SSPI (Integrated Security) for the connectionstring from SharePoint, you’ll need to determine the Service Account that runs the Application Pool. Then you’ll provide access to this windows (or service) account in SQL Server to the FBADB database. Or, if you don’t want to use SSPI, or don’t want to take the time to figure out the startup service account for SharePoint you can simply create a login to the FBADB database. Following are steps for the second approach.

    1. Open SQL Server Management Studio (SSMS 2008) and select Security , then Logins
    2. Right Click Logins and Select “New Login”
    3. Create a SQL Server account. Below, we’d created the account FBAService with password pw
      sqluser2
    4. Select “User Mapping”
    5. Mark the checkbox next to FBADB, and select the row.
    6. In “Database role membership”, make the user a dbo_owner.
      rolemember
    7. Click OK to save the new user.

    Setup IIS 7.0 Defaults

    1. Open up Internet Information Services Manager 
    2. Select the Web Server, then double click Connection Strings
      Cstring
    3. Click Add..
    4. Enter the Server (.), Database (FBADB) and the Credentials for the user FBAService (by clicking the Set button). If you want to use SSPI, simpy select “Use Windows Integrated Security” instead.
      cstring2
    5. Click OK to save
    6. Click to Select the Server from the Connections pane again, and double click Providers.
    7. On the Feature dropdown, select .NET Users. Your machine may take a while to respond while the configuration is read.
    8. On the Actions menu, click Add..
    9. On the Add Provider form, select SqlMembershipProvider as the Type
    10. Provide a name: FBA.
    11. Drop down ConnectionStringName and select FBADB
    12. Set any other parameters you’d like. I set some Password related options for user interaction later.
      provider
    13. Click OK to save
    14. From the Feature dropdown, select .NET Roles, then click Add..
    15. Provide a name: FBARole, and select TypeSqlRoleProvider
    16. Select the ConnectionStringName: FBADB
      roleprovider
    17. Click OK to save the .NET role.

    Setup the FBA Zone in SharePoint 2010

    1.  Browse to SharePoint 4.0 Central Administration, Select Security
      centraladmin
    2. In Application Security, select Specify Authentication Providers
      specificauthent
    3. Select the Web Application.
    4. Click the Default Zone.
      defaultzone
    5. Ensure the Web Application is the correct one on the next page!
    6. Change Authentication Type to Forms
    7. Check Enable Anonymous (* note that this does not immediately enable Anonymous access; it merely makes the option available on the front-end web application *
      zone1
      zone2

    1. Click Save.
    2. When the process is finished, the membership provider should now display FBA.

    What SharePoint has done behind the scenes is make the necessary changes to the IIS website to support Forms based authentication. But we still have a little problem. If we browse to the site right now, we won’t be prompted for Windows credentials anymore. Not only do we NOT have a user in the .NET membership database, but we have no FBA based administrators. Let’s tackle that next.

    IIS 7.0 Web Site Configuration for SharePoint 2010 FBA

    1. In IIS Manager, select the SharePoint site. In this example, we used the default site (80).
    2. Double click the .NET Users icon
    3. Click Set Default Provider from the actions pane on the left and select FBA
      dftuser
    4. Click OK to save.
    5. While we’re here, let’s add our first user. This will be used as an administrative account on the FBA site. Click Add..
      newuser
    6. Select a User, Email and Password. Depending upon parameters you defined earlier you may be prompted with challenge/response questions.
      ** The password may require some strength by default. If you receive an error message that states the “password is invalid”, simply add a number or non-alpha character.
    7. Next, select the SharePoint Central Administation v4 web site from the connections menu in IIS.
    8. Click .Net Users, then in the Actions menu select “Set Default Provider” and set that to FBA.

    Set the User as Site Administrator on the SharePoint 2010 Web Site

    1. In SharePoint Central Admin v4, go to Application Management
    2. In the Site Collections section, select “Change Site Collection Administrators
      siteadmins
    3. On the next page, select the Site Collection we’ve been using.
    4. You’ll note that the primary site collection administrator has a little red squiggly. Why? We don’t have Windows Authentication enabled for this site and therefore no way to resolve. Delete the Administator account.
    5. In the field type the user created above (we used fbaadmin), then click the Check Names button. You should see a black underline noting that the name was resolved.
      fbaadmin

     

    Test the site

    1. In a Web Browser, when you access the site http://localhost (if that’s what you used), you’ll be presented with the SharePoint login screen, not a Windows login pop-up. (Wow, and you thought SharePoint 2007 had a spartan login screen. Get a load of this !)
      login
    2. Login with the fbaadmin credentials and you should be able to access the site.
      homepage2

     

    Add the reference to the user friendly people picker

    You know the picker…so you can easily find those needles in the haystack. For that to work in Central Admin and this site against your .NET membership database, you need to add a reference to the provider.

    1. In IIS Manager, browse to the Central Admin web application. Explore the folder and find the web.config file. Open in Notepad.
    2. Find the <PeoplePickerWildcards> node and use the following:

     

    <PeoplePickerWildcards>
    <clear />
    <add key=”FBA” value=”%” />
     </PeoplePickerWildcards>

     

    Final Note

    If you plan to use the same membership database for multiple sharepoint sites AND you choose to encrypt the passwords, you’ll need to add one final step. In IIS 7,  on the first site, select the Machine Keys icon. Copy those keys. In the next site that you create, you’ll need to use the same machine keys and disable “Automtically Generate” and disable “Generate Unique Key”. This is crucial as the machine key is used to determine the encrypted password that is passed back to the .NET membership database.


WebService 내 DataTable 이용하여 로직 구현 후, JQuery로 데이터 가져오는 방법
페이지 코드
 

JQuery Demo Page



이름 나이
WebService 코드
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace TEST.WS
{
    /// 
    /// UserInfoWS의 요약 설명입니다.
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다. 
    [System.Web.Script.Services.ScriptService]
    public class UserInfoWS : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetUserInfo(string id)
        {
            DataTable dtUserInfo = new DataTable("UserInfo");

            dtUserInfo.Columns.Add("FirstName", typeof(string));
            dtUserInfo.Columns.Add("LastName", typeof(string));
            dtUserInfo.Columns.Add("Age", typeof(string));
            dtUserInfo.Columns.Add("ID", typeof(string));

            DataRow drUserInfo = dtUserInfo.NewRow();
            drUserInfo["FirstName"] = "길동";
            drUserInfo["LastName"] = "홍";
            drUserInfo["Age"] = "29";
            drUserInfo["ID"] = id;
            dtUserInfo.Rows.Add(drUserInfo);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List userInfos = new List();
            UserInfo userInfo = null;
            foreach (DataRow dr in dtUserInfo.Rows)
            {
                userInfo = new UserInfo();
                userInfo.FirstName = dr["FirstName"].ToString();
                userInfo.LastName = dr["LastName"].ToString();
                userInfo.Age = dr["Age"].ToString();
                userInfo.ID = dr["ID"].ToString();

                userInfos.Add(userInfo);
            }

            return serializer.Serialize(userInfos);
        }

        public class UserInfo
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Age { get; set; }
            public string ID { get; set; }
        }
    }
}
여기서 주의 할 점..

  1. WebMethod 내 JavaScriptSerializer 클래스를 통하여 DataTable 개체를 JSON 문자열로 변환하여 String으로 리턴하여야 함.
    -  
      Object 타입의 개체를 넘겨주어야 하므로, 위 소스에서는 별도의 클래스를 정의하여 개체로 넘김.
  2. 위 JSON 문자열로 처리 했다고 해서.. JQuery ajax 내에서 return.d 로만 처리하면 속성값을 찾지 못함.

    success: function (result) {
          data = $.parseJSON(result.d);
          
    $.each(data, function (i, item) {
                   //위처럼 선언 안하고, item.FirstName 속성 값을 가져오지 못함.
           }
    }; 

This post covers, how to hide the button from the Server Ribbon from SharePoint 2010,

We are going to use the Feature files to hide the SharePoint 2010. First we will create a Feature file and then we’ll create a element file.

Feature.xml

 
 
 
 
 

Elements.xml

 
 
 
 

There was a HideCustomAction element used to hide / remove the button from Server Ribbon Control. If we want to remove particular Button / Group / Tab we have to specify the respective Button’s Location ID on HideActionId attribute.

HideActionId – Specifies the Location ID of the custom action to hide

Location – Specifies the Parent location Id of the custom action to hide.

By using HideCustomAction, we can hide / remove the Button, Group, Tab.

Example

For example I have provided a element.xml for hiding the Upload Multiple button from the Document Library.

Elements.xml

 
 
 
 

The above xml file, used to remove the Upload Multiple Documents from the Server ribbon on Document Libraries.

I have added the code in codplex, http://iotapsp.codeplex.com/


9.1 Form 플러그인

9.1.1 폼 컨트롤 값 가져오기

  • 컨트롤 값 가져오기
    • fieldValue() - 확장 집합 내의 모든 전송 가능한 폼 컨트롤이 가진 값의 배열을 변환한다.
    • val() - 확장 집합내의 첫번째 전송 가능 폼 컨트롤 엘리먼트 값을 반환한다.
    • $(#testForm *').fieldValue()
    • $(#testForm *').fieldValue(false) - 전송 불가능한 컨트롤 제외하지 않음
  • 컨트롤 값 직렬화하기
    • 인코딩된 쿼리문자열로 만든다
    • formSerialize() - 확장집합내의 폼을 받아서 폼에 있는 전송 가능한 자식 컨트롤의 값을 모두 직렬화
    • fieldSerialize() - 확장집합내의 모든 컨트롤을 직렬화
    • $('#testForm').formSerialize()

9.1.2 폼 컨트롤의 값 지우고 재설정하기

  • clearForm() - 텍스트, 패스워드, 텍스트 영역 지운다. <select>엘리먼트 선택 취소, 체크박스 라디오버튼 해제
  • resetForm() - HTML 마크업 지정값으로 되돌림 (reset() 메서드 호출)

9.1.3 Ajax를 사용하여 폼 값 전송하기

  • Form플러그인의 formSerialize()메서드와 코어 Ajax함수를 조합하면 된다.
  • Form플러그인의 ajaxSubmit()커멘드를 쓰면 Ajax를 통한 전체 폼 전송이 더 쉽다.
  • $('#targetForm').ajaxSubmit(); - 폼 전송
  • $('#targetForm').ajaxSubmit(function(response){

      /* response와 함께 어떠한 작업 처리 */

});

  • ajaxForm() - 일반적인 의미의 이벤트로 발생한 폼 전송을 막고 요청을 모방하는 Ajax요청을 전송한다.
  • ajaxFormUnbind() - 폼이 일반적인 방식으로 전송될 수 있도록 화장 집합내의 폼에 전용된 기능을 제거한다.

9.1.4 파일 전송하기

  • Form플러그인은 file타입 입력 엘리먼트에 명시된 파일을 업로드하는 폼을 알아서 식별하고 처리한다.

9.2 Dimensions 플러그인

9.2.1 width height 메서드 확장하기

9.2.2 스크롤 크기 얻어내기

9.2.3 오프셋과 위치

9.3 Live Query 플러그인

  • 셀렉터와 일치하는 엘리먼트에 이벤트 핸들러를 할당한다.
  • 어떠한 엘리먼트가 셀렉터와 일치할 때 실행될 함수를 호출한다.
  • 더는 어떠한 엘리먼트 셀렉터와 일치하지 않을 때 실행될 함수를 호출한다.

9.3.1 이벤트 핸들러 미리 할당하기

9.3.2 일치리스너와 불일치 리스너 정의하기

9.3.3 Live Query를 강제로 적용하기

9.3.4 Live Query 리스너 제거하기

9.4 UI 플러그인 소개

9.4.1 마우스 상호작용

  • draggable(options)
  • ui.mouse.js, ui.draggable.js를 포함 해야 한다.
  • ui.draggable.ext.js 확장 옵션을 위해서 포함해야 함
  • $('#testSubject').draggable({});

9.4.2 위짓과 시각효과


8.1 Ajax 간략히 살펴보기

8.1.1 XHR 인스턴스 생성하기

8.1.2 요청 보내기

8.1.3 진행 상황 추적하기

8.1.4 응답 얻기

  • Ajax를 사용하는 개발자가 다뤄야할 고통
    • XHR 객체를 인스턴스화 하는데 브라우저에 종속적 코드 필요
    • 준비 핸들러는 필요없는 상태 변화를 걸러내야 한다.
    • 준비 핸들러는 XHR인스턴스를 호출하는 참조를 자동으로 얻지 못한다.
    • 응답결과는 형태에 따라 다양한 방법으로 다뤄야 한다.

8.2 엘리먼트에 콘텐츠 로드하기

  • Ajax를 사용하는 가장 빈번한 상황은 서버에서 콘텐츠를 가져와서 원하는 DOM 위치에 삽입하는 것이다.
  • 콘텐츠는 대상 컨테이너의 자식이 되는 HTML코드이거나 대상엘리먼트의 콘텐츠가 되는 보통 텍스트다.
  • $('#someContainer).load('/serverResource'); - 간단하다.

8.2.1 jQuery로 콘텐츠 로드하기

  • load(url, parameters, callback) - parameters 매개변수가 요청 매개변수로 제공되면 POST HTTP 메서드를 사용하여 요청을 만들고, 그렇지 않으면 GET 메서드로 요청을 만든다. (GET URL에 URI인코딩 형태의 쿼리문자열 추가)
  • $('.injectMe').load('/someResource #div'); - 응답 엘리먼트에서 오직 <div>엘리먼트만 삽입한다.
  • serialize() - 폼 컨트롤에서 요청 매개변수를 가져와 쿼리 문자열을 만들어줌(선택안된 체크박스 라디오버튼 드롭다운, 비활성화된 컨트롤과 같은 엘리먼트는 제외)
  • serializeArray() - 자바스크립트 배열형태로 폼데이터를 반환. 폼 컨트롤 이름과 값을 name 프로퍼티와 value 프로퍼티로 가짐

8.2.2 목록 데이터 동적으로 로드하기

  • $(function(){

             $('#styleDropdown')

                  .change(function(){   // 스타일 드롭다운을 감싸고 변경 핸들러를 바인딩한다.

                     var styleValue = $(this).val();

                     $('#detailsDisplay').load(

                            'getDetails.jsp',     // 선택된 스타일 데이터를 로드한다.

                            { style : styleValue } // GET 패러메터

                     );

                  })

                  .change();               // 변경 핸들러를 실행한다.

             });

8.3 GET과 POST 요청 만들기

  • GET은 멱등 요청이며 캐시에 적합하다.
  • POST는 데이터 전송에 주로 쓴다.

8.3.1 jQuery를 사용하여 데이터 얻기

  • $.get(url, parameters, callback) - 명시된 URL을 사용하여 GET요청을 전송
  • $.get( 'reflectData.jsp', {a:1, b:2, c:3}, function(data) {alert(data);} );

8.3.2 JSON 데이터 얻기

  • XML이 데이터 전송기법으로 적당하지 않을때 사용
  • $.getJSON(url, parameters, callback)

8.3.3 POST 요청 만들기

  • $.post(url, parameters, callback)

8.4 Ajax 요청 직접 제어하기

8.4.1 Ajax 요청 직접 설정하고 생성하기

8.4.2 요청에 기본값 설정하기

8.4.3 전역함수

 

 

7.1 확장을 사용하는 이유

  • 사이트 전체에 일관된 코드 스타일을 유지하는 데 도움을 줌
  • jQuery의 강력한 기능을 상속받아 사용 가능

7.2 jQuery 플러그인 제작 지침

7.2.1 필드와 함수 이름 짓기

  • 플러그인 개발시에 파일이름이 다른 파일과 충돌하지 않도록 만드는 방법
    • 접두어로 jquery.를 사용한다.
    • 이어서 플러그인 이름을 적는다.
    • .js로 파일 이름을 끝맺는다.
  • jquery.fred.js
  • http://docs.jquery.com/Plugins 페이지의 플러그인 목록을 살펴보는 것도 좋다.

7.2.2 $를 경계하라

  • 별칭 jQuery를 사용하는 방법도 있으나 $쪽이 훨신 편리하다.

7.2.3 복잡한 매개변수 목록을 단순하게 만들기

  • function complex(p1, p2, p3, p4, p5, p6, p7) {  - 매개변수가 많음
  • complex(valueA, null,null,null,null,null, valueB); - null 입력이 많음
  • complex(valueA, {p7:valueB}); - options hash를 이용하는 방법
  • complex(valueA, {p3:vlaueC, p4:valueD})); - 이런 방법도

7.3 사용자 정의 유틸리티 함수 작성하기

  • $.say = function(what) { alert('I say ' + what); }

7.3.1 데이터를 조작하는 유틸리티 함수 만들기

  • $.toFixedWidth(value, length, fill) - 전달된 값을 고정폭 필드로 채우는 함수를 만들어 보자
  • (function($){

   $.toFixedWidth = function(value, length, fill) {

        var result = value.toString();

        if(!fill) fill = '0;;

        var padding = length - result.length;

        if(padding < 0) {

             result = result.substr(-padding);

        }

        else {

             for(var n = 0; n < padding; n++)

                 result = fill + result;

        }

        return result;

   };

})(jQuery); - 이렇게 구현한다.

7.3.2 날짜 형식기 만들기

7.4 새로운 확장 메서드 추가하기

  • 확장 메서드를 추가하여 강력함을 필요한 만큼 확장할 수 있다.

7.4.1 확장메서드에 여러동작 적용하기

  • 두가지 이상 되는 기능을 수행하는 새로운 플러그인 메서드 개발

7.4.2. 확장메서드에서 상태 유지하기


6.1 jQuery 플래그 사용하기

  • $.browser, $.boxModel, $.styleFloat

6.1.1 사용자 에이전트 탐지하기

  • 브라우저 탐지가 해로운 이유 - 브라우저 탐지는 '증오스럽다'. 브라우저 탐지는 선택할 여지가 없을 때만 사용하는 기술이다. IE, firefox, opera, safari 등등 , 지원하지 않는 브라우저는 에러 발생 ,거대 중첩 조건문에 의해 확장성 떨어짐
  • $.browser - 에이전트가 속한 브라우저 종류를 찾으려고 사용하는 플래그 집합을 정의한다. msie, mozilla, safari, opera, version
  • $.browser.msie ? 2 : select.option[2] - 브라우저를 탐지하여 처리

6.1.2 박스 모델 확인하기

  • W3C 박스 모델은 패딩과 테두리 엘리먼트의 크기를 넓이에서 제외하지만 IE에서는 포함한다.
  • $.boxModel - W3C 표준 박스 모델이면 true, IE 박스모델은 false

6.1.3 정확한 float 스타일 탐지하기

  • element.style[$.styleFloat] = 'left';
  • $.styleFloat 플래그 값은 IE에서 styleFloat이며 다른 브라우저에서는 cssFloat이다.
  • 이 플래그를 일반적으로 직접 사용하는 일이 없다.

6.2 다른 라이브러리와 jQuery 함께 사용하기

  • $.noConflict() - 다른 라이브러리가 $를 사용하면 그 라이브러리에서 이변수를 사용할 수 있도록 만들어 주는 유틸리티 함수

6.3 자바스크립트 객체와 컬랙션 조작하기

6.3.1 문자열 다듬기

  • $.trim(value) - 앞뒤 공백 제거(폼피드, 개행, 리턴, 탭, 수직문자 등 포함)

6.3.2 프로퍼티와 컬렉션 순회하기

  • for-in루프 는 문법이 불필요하게 장황하고 복잡해짐
  • $.each(container, callback) - container는 순회할 아이템을 가진 배열 혹은 프로퍼티를 가진 객체, callback함수의 첫번째 매개변수는 배열의 인덱스 이거나 객체 프로퍼티의 이름이다.
  • var anArray = ['하나','둘','셋'];

$.each(anArray, function(n, value){

    // 여기서 작업한다.

});

  • $var anArray = {하나:1, 둘:2, 셋:3};

$.each(anObject, function(name, value){

    // 여기서 작업한다.

});

6.3.3 배열 필터링하기

  • 많은 양의 데이터를 다루는 애플리케이션에서 특정조건에 일치하는 엘리먼트를 찾으려면 빈번하게 배열을 순회하여야한다.
  • 특정경계에 속하거나 속하지 않는 아이템 혹은 특정 패턴에 일치하는 아이템을 찾기위해 필터링 작업을 한다.
  • $.grep(array, callback, invert) - 전달된 배열의 엘리먼트마다 콜백함수를 호출하면서 순회한다. invert 매개변수를 생략하거나 false이면 콜백의 값이 true일 경우 값이 수집된다. invert가 true라면 콜백의 값이 false일 때 값이 수집된다. 원본 배열은 변경되지 않는다.
  • var bigNumbers = $.grep(originalArray, function(value){

return value > 100;

}); - 배열중 100보다 큰 값으로 필터링

6.3.4 배열 변환하기

  • 데이터가 항상 필요한 형태로만 존재하지는 않는다. 데이터 중심 웨에플리케이션에서 자주 사용하는 주요 동작으로 값의 집합을 다른 집합으로 변환하는 연산이 있다.
  • $.map(array, callback) - 전달된 배열의 아이템마다 콜백함수를 호출하면서 순회하며 함수호출로 반환된 값은 새로운 배열로 수집된다.
  • var oneBased = $.map([0,1,2,3,4], function(value){return value+1;}); - 0 기반 인덱스에서 1기반 인덱스로 변경한다.
  • var oneBased = $.map([0,1,2,3,4], 'a+1'); - 위와 같은식, 간단하게 만드는 표현식 형태의 문자열을 전달 할 수 있다. a라는 매개변수를 값으로 전달 받았다.
  • var strings = ['1', '2', '3', '4', 'S', '6'];  // 5가 아니라 S

var values = $.map(strings, function(value){

var result = new Number(value);

return isNaN(result) ? null : result; // 숫자로 성곡적으로 변환했는지 점검 (자바스크립트 isNaN() 메서드), 실패시 null 반환

});

  • var characters = $.map(['this', 'that', 'other thing'],

function(value) { return value.split(''); }

);

==> ['t','h','i','s','t','h','a','t','o','t','h','e','r ',' ','t','h','i','n','g'] 합쳐서 분해 됨

6.3.5 자바스크립트 배열 재미있게 사용하기

  • $.inArray(value, array) - 전달된 값이 처음 나타나는 위치 인덱스 반환, value 배열에서 찾으려는 값, 찾을 대상 배열 , 찾지 못하면 -1 반환
  • var index = $.inArray(2,[1,2,3,4,5]);
  • $.makeArray(object) - 유사배열 객체를 자바스크립트 배열로 변환
  • $.unique(array) - DOM 엘리먼트의 배열이 주어지면, 원본 배열에서 고유한 엘리먼트로만 구성된 배열 반환.

6.3.6 객체 확장하기

  • $.extend(target, source1, source2, ...sourceN) - target에 전달될 객체를 함께 전달된 나머지 객체의 프로퍼티를 사용하여 확장한다. 같은 객체가 있을 때  뒤에 나오는 객체가 앞보다 우선함.

6.4 동적으로 스크립트 로드하기


5.1 엘리먼트를 나타내고 감추기

5.1.1 접을 수 있는 리스트 구현하기

  • show(), hide()

5.1.2 엘리먼트의 표시 상태 바꾸기

  • toggle()

5.2 엘리먼트 표시상태를 애니메이션으로 표현하기

5.2.1 엘리먼트를 점진적으로 보이고 감추기

  • hide(speed, callback) - 매개변수 없으면 display 스타일 프로퍼티 값이 즉시 none으로 설정, speed 는 1/1000초 설정, 또는 slow, normal, fast
  • show(speed, callback) - jQuery를 이용해 감췄다면 이전 값으로 설정한다. 그렇지 않으면 block으로 설정
  • toggle(speed, callback) - 감춰진 경우는 show()를 수행, 드러난 경우는 hide()를 수행

5.2.2 엘리먼트 페이드인 / 페이드 아웃/ 페이드 투하기

  • fadeOut(speed, callback) - 불투명도를 0%로 줄여가면서 화면에서 제거
  • fadeIn(speed, callback)
  • fadeTo(speed, opacity, callback) - 확장엘리먼트의 불투명도를 현재의 설정 값에서 opacity 매개변수 값으로 설정 한다. (0.0~1.0) 화면에서 제거하지는 않는다.

5.2.3 슬라이드 효과를 사용하여 엘리먼트를 나타내고 감추기

  • slideDown(speed, callback) - 감춰진 모든 일치하는 엘리먼트가 높이 값이 증가하면서 나타난다. (펼쳐지는...)
  • slideUp(speed, callback) - 드러나 있는 모든 일치하는 엘리먼트가 점차적으로 높이 값이 감소하면서 화면에서 제거된다.
  • slideToggle(speed, callback) - 감춰진 확장엘리먼트는 slideDown()을, 드러나 있는 확장 엘리먼트에는 slideUp()을 수행한다.

5.2.4 애니메이션 멈추기

  • stop() - 확장 집합에 있는 엘리먼트에 현재 진행하는 에니메이션을 중지한다.

5.3 사용자 정의 애니메이션 생성하기

  • 자신만의 애니메이션을 만들 수 있다.
  • animate(properties, duration, easing, callback)
  • animate(properties, options)

5.3.1 사용자 정의 스케일 애니메이션

  • $('.animateMe').each(function(){

    $(this).animate(

        {

            widh: $(this).width() * 2,

            height: $(this).height() * 2

        },

        2000

   );

});

5.3.2 사용자 정의 드롭 애니메이션

  • $('.animateMe').each(function(){

               $(this)

                  .css('position', 'relative')

                  .animate(

                       {

                            opacity: 0,

                            top: $(window).height() - $(this).height() - $(this).position().top

                        },

                        'slow',

                        function(){ $(this).hide(); });

           }); - 화면에서 떨어지는 효과

 

5.3.3 사용자 정의 퍼프 애니메이션

  • 담배 연기 같이 공중에 퍼지는 것처럼 보이게 하려고 한다.
  • $('.animateMe').each(function(){

    var position = $(this).position();

    $(this)

        .css({position:'absolute', top:position.top, left:position.left})

        .animate(

              {

                   opacity: 'hide',

                   width: $(this).width() * 5,

                   height: $(this).height() * 5,

                   top: position.top - ($(this).height() * 5 / 2 ),

                   left: position.left - ($(this).width() * 5 / 2)

              },

              'normal');

});

                    

 

jQuery in Action 정리 4장 - 이벤트 -모든것의 시작 | jQuery
전체공개 2010.12.29 14:40

4.1 브라우저 이벤트 모델 이해하기

4.1.1 DOM 레벨 0 이벤트 모델

  • 어트리뷰트 방식으로 DOMM 레벨 0 이벤트 헨들러를 선언하는 방법은 1.2 절에서 설명한 튀지않는 자바스크립트 원칙을 위반한다.
  • Event 인스턴스의 프로퍼티는 발생한 이벤트에 관한 많은 정보를 제공한다. 엘리먼트 마우스이벤트 좌표, 키보드 이벤트의 키 정보 등
  • 이벤트 버블링. 먼저 대상이 되는 엘리먼트에게 이를 전달한 뒤, 조상 엘리먼트에게 순서대로 이벤트를 전달하는 과정. 이걸 멈출 수 있나?
  • 표준 호환 브라우져에서는 stopPropagation()메서드, IE에서는 cancleBubble프로퍼티

4.1.2. DOM 레벨 2 이벤트 모델

  • 프로퍼티에 저장하는 레벨 0 방식은 두가지 동작 처리 안됨
  • 레벨 2에서는 하나이상 할당하도록 설계
  • addEventListener(eventType, listener, useCapture) 메서드를 사용
  • 이벤트 버블링. 루트에서 대상 엘리먼트로 전파(캡쳐단계), 다시 대상엘리먼트에서 루트로 전파(버블단계)
  • useCapture 매개변수를 false로 설정하면 버블 헨들러, true로 하면 캡쳐 헨들러
  • ie는 캡쳐단계 지원 안함

4.1.3 인터넷 익스플로러 이벤트 모델

  • ie 7에서도 DOM 레벨 2를 지원하지 않음
  • ie는 attachEvent(eventName, handler)라는 비슷한 것을 지원
  • jQuery를 통해 이런 브라우저간 차이를 해결

4.2 jQuery 이벤트 모델

  • 이벤트 핸들러를 할당할 수 있는 통합 메서드 제공
  • 엘리먼트 이벤트 타입마다 여러 헨들러 할당 가능
  • click, mouseover 같은 표준 이벤트 타입 사용
  • 핸들러 매개변수를 써서 Event 인스턴스를 사용
  • 자주 사용하는 Event 인스턴스의 프로퍼티들에 일관된 이름을 사용
  • 이벤트 해제와 기본행동을 막는 통합메서드 제공
  • 캡쳐단계는 지원하지 않음

4.2.1 jQuery를 사용해 이벤트 핸들러 바인딩하기

  • $('img').bind('click', function(event){alert('안녕!');});
  • eventTypeName - blur, change, click, dblclick, error, focus, keydown, keypress, keyup, load, mousedown, mousemove, mouseout, mouseover, mouseup, resize, scroll, select, submit, unload
  • .one() - 한번 실행 뒤 자동 삭제되는 핸들러

4.2.2 이벤트 핸들러 제거하기

  • .unbind(eventType, listenner)
  • .unbind(event)

4.2.3 Event 인스턴스

4.2.4 이벤트 전파 제어하기

4.2.5 이벤트 핸들러 호출하기

  • .trigger(eventType) - 일치된 엘리먼트에 대하여 전달된 이벤트 타입에 해당하는 이벤트 핸들러를 모두 실행한다. 단, 이벤트를 발생 시키지 않으며 전파 안됨
  • .blur(), .click(), .focus(), .select(), .submit() 등을 지원

4.2.6 그 외 이벤트 관련 커맨드

  • 리스너 토글하기 - toggle(listenerOdd, listenerEven) 번갈아 가면서 실행될 클릭 이벤트 핸들러 한쌍을 할당
  • 엘리먼트 위에서 맴돌기 - hover(overListener, outListener) 자식 엘리먼트로 이동은 무시됨
  • $('#outer2').hover(report, report);

4.3 이벤트 사용하기

  • HTML에는 화면을 꾸미는 정보는 담지 않는다. CSS로 정의
  • HTML에는 스크리브로 포함하지 않는다 (튀지않는 자바스크립트원칙)

     


3.1 엘리먼트 프로퍼티와 어트리뷰트 조작하기

3.1.1 엘리먼트 프로퍼티 조작하기

  • $('img').each(function(n){ this.alert='아이디가 '+this.id+'인 image['+n+']이다.'; }); - 0 부터 시작하는 index n을 매개변수로 받는다.
  • var allAlts = new Array();

$('img').each(function(){ allAlts.push(this.alt); });  - 모든 alt 배열을 얻음

3.1.2 어트리뷰트 값 가져오기

  • $("#myImage").attr("custom") - costom 어트리뷰트의 값
  • 브라져에 따라 다른 프로퍼티명 때문에 발생하는 귀찮은 문제를 해결해 준다. (ex className 등)

3.1.3 어트리뷰트 값 설정하기

  • $('*').attr('title', function(index) {

return '나는 ' + index + '번 엘리먼트이고 내 이름은 ' + (this.id ? this.id : 'unset') + '이다';

});

  • $('input').attr(

{ value: '', title: '값을 입력하세요.' }

); - value title등 설정

3.1.4 어트리뷰트 제거하기

  • removeAttr(name) - 자바스크립트 DOM 엘리먼트에서 대응하는 프로퍼티가 제거되는 것이 아니 값이 변경될 뿐이다.

3.1.5 어트리뷰트 가지고 놀기

  • $("form").submit(function() {

$(":submit", this).attr("disabled", "disabled");

}); - form의 submit 버튼을 비 활성화

 

3.2 엘리먼트 스타일 변경하기

3.2.1 클래스 추가하고 제거하기

  • addClass
  • removeClass
  • toggleClass
  • $('tr').toggleClass('striped'); - 번갈아 가며 클래스를 적용

3.2.2 스타일 얻고 설정하기

  • $("div.expandable").css("width", function() {

return $(this).width() + 20 + "px";

});

  • $("div.myElements").width(500); - $("div.myElements").css("width", "500px")와 같은 코드
  • $("div.myElements").height(500);
  • var val = $("div.myElements").width(); - 가져오기

3.2.3 스타일과 과련된 유용한 커맨드

  • $("p:first").hasClass("surpriseMe") - 클래스를 갖는지 true false 반환
  • $("p:first").is(".surpriseMe") - 위와 같은 코드
  • $("p:first").attr("class").split(" "); - 앨리먼트에 정의된 클래스 목록을 공백으로 구분된 문자열대신 배열로 얻음(undefined 발생 할 수 있다. 아래로 해결 )
  • $.fn.getClassNames = function() {

if(name == this.attr("className")) {

return name.split(" ");

}

else {

return [];

}

};

3.3 엘리먼트 콘텐츠 설정하기

3.3.1 HTML과 텍스트 콘텐츠 대체하기

  • html(text)
  • var text = $('#theList').text();

3.3.2 엘리먼트 복사하기와 이동하기

  • $('p').append('<b>테스트<b>');
  • $("p.appendToMe").append($("a.appendMe"))
  • $('#flower').appendTo('#targets p:first') - 확장집합의 모든 엘리먼트를 target의 끝으로 이동
  • prepend(), prependTo() - append(), appendTo()와 유사하게 동작하지만 대상 엘리먼트 앞에 삽입
  • before(), insertBefore() - 엘리먼트를 대상의 첫번째 자식으로 삽입하는 대신 대상의 바로앞 형제로 삽입
  • after(), insertAfter() - 엘리먼트를 대상의 마지막 자식으로 삽입하는 대신에 대상의 바로뒤 형제로 삽입

3.3.3 엘리먼트 감싸기

  • $("a.surprise").wrap("<div class='hello'></div>") - surprise 클래스가 있는 링크를 hello클래스를 지닌 div로 감싼다.
  • $("a.surprise").wrap($("div:first")[0]); - 첫번째 <div>엘리먼트를 복사하여 감싼다.
  • .wrapAll() - 일치하는 모든 엘리먼트를 감싼다.
  • .wrapInner() - 일치하는 엘리먼트의 텍스트 노드를 포함한 콘텐츠를 감싼다.

3.3.4 엘리먼트 제거하기

  • $("div.elementToReplace").after("<p>div를 대체한다.</p>").remove(); - 뒤에 추가하고(after 원본 반환) 앞을 제거함 (대체되는 것 같음)
  • $.fn.replaceWith = function(html) {

return this.after(html).remove();

}; - 이렇게 만들어서 확장 사용 가능

  • $("div.elementToReplace").replaceWith("<p> div를 대체한다.</p>"); - 위에서 확장해 사용

3.3.5 엘리먼트 복사하기

  • $('img').clone().appendTo('fieldset.photo'); - 모든 이미지 엘리먼트를 복사해서 photo클래스 fieldset에 붙인다.
  • $('ul').clone().insertBefore('#here').end().hide(); - 복사본 삽입후 원본 감추기

3.4 폼 엘리먼트 값 다루기

  • .val() - 첫번째 엘리먼트의 value 프로퍼티 반환
  • $('[name=radioGroup]:checked]').val(); - 첫 엘리먼트만 처리하므로 체크박스 그룹 사용 어려움. serialize()커맨드나 공식 Form 플러그인을 사용하는 것이 좋다.
  • .val(value) - 값을 설정
  • $('input, select').val(['하나', '둘', '셋']); - input과 select 엘리먼트를 찾아 발견된 체크박스, 라디오버튼, 옵션을 선택 (알아서 선택하니 편리)
     

+ Recent posts