Friday, August 17, 2012

Configure Forms Based Authentication (FBA) with SharePoint 2010


Implementing FBA in SharePoint is simple, if you follow all the steps correctly. there are lot of FBA pack in market which allows you to just install the WSP and start working with it.

FBA is concept already present in .Net. we need to create Membership provider and Role provider. Lets set up FBA on our own.

Step 1: Create Web Application using Claims Authentication

  1. Open Browser by choosing “Run as Administration” option.
  2. Browse to Central Administration.
  3. Select Application Management > Managed Web Application.
  4. Click on “New” button ribbon to create new web application.
  5. Select Authentication as “Claims Authentication”
    ClaimsAuthentication
  6. Select “Claims Authentication Types” as “FBA“
    - Provide the Membership Provider Name as “MyCustom_MemberShipProvider”
    - Provide the Role Manager Name as “MyCustom_RoleManager”

    ClaimsAuthentication_Type
  7. Click “Ok” button to create Web Application
  8. Create Root Site Collection as soon as Web Application is created.

Step 2: Create ASP.NET Membership Database

  1. 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
  2. Select “Configure SQL Server for application services”, then click Next
  3. Write Database Name in Dropdown Box. we will named the database as ”Custom_FBA_DB”.
  4. Click on next and finish the activity.

Step 3: Providing the access to the Membership Database

  1. In SharePoint most of Service Account that runs the Application Pool. we need to identity the Service account and ensure that this service account has the DB_Owner permission on the ASP.Net Membership database created in Step 1
  2. If not then we can open database and in security tab grant permission “DB_Owner”

Step 4: Modify the Application web.config file

Modify the Application web.config to add the details of the Membership Provider and Role manager details

  1. Open web.config present under “C:\inetpub\wwwroot\wss\VirtualDirectories\” followed by your web application port number.
  2. Add following connection string in Connection string section, if section is not present then add exactly above <system.web>

    <connectionStrings>

        <add name="Custom_FBA_SQLConnectionString" connectionString="data source=.;Integrated Security=SSPI;Initial Catalog=Custom_FBA_DB" />

      </connectionStrings>

    Data Source       :     Database Server Instance Name (. or .\InstanseName)
    Intital Catalog     :     Database Name (Custom_FBA_DB)

  3. Add/Replace following lines to add/Replace Role Manager and Membership Provider details

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

          <providers>

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

            <add connectionStringName="Custom_FBA_SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="MyCustom_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="Custom_FBA_SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="MyCustom_MemberShipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

          </providers>

        </membership>

  4. Ensure the Provider names are exactly same as defined at time of creating the Web Application in Step 1
  5. Save Web.Config file

Step 5: Modify the Central Administration web.config file

Modify the Central Administration web.config to add the details of the Membership Provider and Role manager details

  1. Open web.config present under “C:\inetpub\wwwroot\wss\VirtualDirectories\” followed by your Central Administration port number.
  2. Add following connection string in Connection string section, if section is not present then add exactly above <system.web>

    <connectionStrings>

        <add name="Custom_FBA_SQLConnectionString" connectionString="data source=.;Integrated Security=SSPI;Initial Catalog=Custom_FBA_DB" />

      </connectionStrings>

    Data Source       :     Database Server Instance Name (. or .\InstanseName)
    Intital Catalog     :     Database Name (Custom_FBA_DB)

  3. Add/Replace following lines to add/Replace Role Manager and Membership Provider details

    <membership defaultProvider="ASPNetSqlMembershipProvider">

          <providers>

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

          </providers>

        </membership>

       

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

          <providers>

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

          </providers>

        </roleManager>

  4. Ensure the Provider names are exactly same as defined at time of creating the Web Application in Step 1
  5. Save Web.Config file

Step 6: Modify the Security Token web.config file

Modify the Security Token web.config to add the details of the Membership Provider and Role manager details

  1. Open web.config present under 14-ive “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebServices\SecurityToken”.
  2. Add following connection string in Connection string section, if section is not present then add exactly above <system.web>. If <System.Web> is not present add at the end of file before closing tag of </configuration>.

    <connectionStrings>

        <add name="Custom_FBA_SQLConnectionString" connectionString="data source=.;Integrated Security=SSPI;Initial Catalog=Custom_FBA_DB" />

      </connectionStrings>

    Data Source       :     Database Server Instance Name (. or .\InstanseName)
    Intital Catalog     :     Database Name (Custom_FBA_DB)
  3. Add/Replace following lines to add/Replace Role Manager and Membership Provider details
    <roleManager cacheRolesInCookie="false" defaultProvider="c" enabled="true">

          <providers>

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

            <add connectionStringName="Custom_FBA_SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="MyCustom_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="Custom_FBA_SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="MyCustom_MemberShipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

          </providers>

        </membership>

  4. Ensure the Provider names are exactly same as defined at time of creating the Web Application in Step 1
  5. Save Web.Config file

Step 7: Reset IIS using IISReset command.

Step 8: Browse to your web Application.

  1. Open Browser and browse to you SharePoint Web Application.
  2. This will represent you the form with two option “FBA” and “Windows Authentication”.
    DefaultSignin-1
  3. Select FBA.
  4. A form will appear to enter the credential.
    DefaultSignin-2
  5. Enter your credential and click on sing in button to get into the site (Provided site collection administrator has given you the permission)

Note:

  • This uses the default sign in Page provided by SharePoint 2010 (Shown in Step 8). You can customize the Sign in Page and enforce your web application to use it for Sign in.
  • If you do not wish to add FBA users and roles through the UI programmatically. You can add users through the IIS. (inetmgr.exe). Ensure that after adding user using IIS verify the Steps 4,5 and 6. and reset IIS. (Its always better to give user UI to enter users and Roles to avoid modification and verification web.config files)
    User_Roles_IIS

Next Article will explain the How to customize the Login page.

Monday, July 16, 2012

Activate Features on Site creation


Most of the times we need to activate certain features as soon as site gets created using site template. These features can be custom or OOB. also we have to manage the feature sequence in which we want to turn them on.

Following are 2 ways to implement:

  1. Using ONET.XML
  2. Using Feature stapling concept

1. Using ONET.XML: The global Onet.xml file defines list templates for hidden lists, list base types, a default definition configuration, and modules that apply globally to the deployment. Each Onet.xml file in a subdirectory of the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates directory can define navigational areas, list templates, document templates, configurations, modules, components, and server email footers that are used in the site definition to which it corresponds.

In an Onet.xml file, the Feature element is used within a site definition configuration to contain a reference to a Feature instance and default property values. The Configuration element specifies lists and modules to use when creating SharePoint sites. For information about the format and elements used in site definitions, see Site Schema.

SharePoint Foundation activates Features specified within the Onet.xml file in the order that they are listed. even you can specify Features that are depended upon before Features that depend upon them.

Following is the Key Elements which can be set to activate features:

<SiteFeatures>: Can be used to activate Site Scope features as soon as Site Created using the Site Template.
<WebFeatures>: Can be used to activate Web Scope features as soon as Site Created using the Site Template.
<Lists>: Can be used to create instance of List as soon as Site Created using the Site Template.

<Configurations>
  ...
  <Configuration
    ID="0"
    Name="Default">
    <Lists>
      <List
        FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101"
        Type="101"
        Title="$Resources:core,shareddocuments_Title;"
        Url="$Resources:core,shareddocuments_Folder;"
        QuickLaunchUrl="$Resources:core,shareddocuments_Folder;/Forms/AllItems.aspx" />
      ...
    </Lists>
    <Modules>
      <Module
        Name="Default" />
    </Modules>
    <SiteFeatures>
      <Feature
        ID="00BFEA71-1C5E-4A24-B310-BA51C3EB7A57" />
      <Feature
        ID="FDE5D850-671E-4143-950A-87B473922DC7" />
    </SiteFeatures>
    <WebFeatures>
      <Feature
        ID="00BFEA71-4EA5-48D4-A4AD-7EA5C011ABE5" />
      <Feature
        ID="F41CC668-37E5-4743-B4A8-74D1DB3FD8A4" />
    </WebFeatures>
  </Configuration>
  ...
</Configurations>

=================================================================================

2. Using Feature Stapling
: This is also knows as “Feature Site Template Association”. This is used to attach Feature(s) to all new instances of sites for a given given site definition without modifying the site definition or creating code routines to activate the Feature on each site.

Feature stapling is a concept that allows you to attach (or staple) a SharePoint Feature to a SharePoint site definition without modifying the original site definition files in any way

Following is an example of feature stapling that associates the Feature with only the “MySite” site definition templates:

Add Module:
StapleeHolder Feature

  • SharePoint Server Publishing Infrastructure (f6924d36-2fa8-4f0b-b16d-06b7250180fa) (Site Feature)
  • Team Collaboration Lists (00bfea71-4ea5-48d4-a4ad-7ea5c011abe5) (Web Feature)

Add/Update Elements.xml of StaplerHolder Module:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <FeatureSiteTemplateAssociation Id="f6924d36-2fa8-4f0b-b16d-06b7250180fa" TemplateName="MySite#0" />
   <FeatureSiteTemplateAssociation Id="00bfea71-4ea5-48d4-a4ad-7ea5c011abe5" TemplateName="MySite#0" />
   <FeatureSiteTemplateAssociation Id="f6924d36-2fa8-4f0b-b16d-06b7250180fa" TemplateName="MySite#1" />
   <FeatureSiteTemplateAssociation Id="00bfea71-4ea5-48d4-a4ad-7ea5c011abe5" TemplateName="MySite#1" />
</Elements>

So In above example we have 2 Site Template of “MySite” Site Definition. As soon as the site is created from any of above template the “SharePoint Server Publishing Infrastructure” and “Team Collaboration List” feature will be activated.

Add Feature at WebApplication Level: This will activate staple feature at WebApplication level. Add above created module in it.

StapleeHolder Feature Web

Wednesday, June 27, 2012

Create Custom Web Part Page Template


Hello friends,

Most of us created new Web Part Page using Web Part Page Layouts provided by SharePoint 2010. SharePoint comes with the “Web Part Page” option to create pages from web part page layouts. SharePoint 2010 provides total of 8 Web Part Page Layouts. Following are the styles provided by SharePoint 2010 by default.


  1. Header, Footer, 3 Columns
  2. Full Page, Vertical
  3. Header, Left Column, Body
  4. Header, Right Column, Body
  5. Header, Footer, 2 Columns, 4 Rows
  6. Header, Footer, 4 Columns, Top Row
  7. Left Column, Header, Footer, Top Row, 3 Columns
  8. Right Column, Header, Footer, Top Row, 3 Columns

These all Web Part Templates are stored at location \Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS\.

You can have your own custom Web part Page Layouts created and stored in same directory. But as per my research and R&D Microsoft displays all these option when you click on Site Actions > View All Site Contents > Create > Web Part Page which calls spcf.aspx page. This page internally gives call to "/_vti_bin/owssvr.dll?CS=65001" to generate the page for each templates and this dll only support 8 Web Part Page Layout Templates only. So we need to develop our own spcf.aspx page which will generate the Page using our Custom Web Part Page Layout Template.

While doing so we will not touch the Web Part Page option provided by the SharePoint 2010 in Site Actions > View All Site Contents > Create

Let’s follow following steps to create our own custom Web Part Page option under Create action in Site Actions > View All Site Contents

Step1: Download the Customspcf.aspx page from here.

Step2: Once customspcf.aspx page is download/created copy into Mapped the directory [Layouts].

Step2

Step3: Create new Web Part Page Templates with the help of stspd1.aspx present under the \Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS\.

Create4-originalfiles

Step4: Make a copy of it and rename as per your naming convention (for e.g. CustomPage1.aspx). Modify the content of the page as per your Web Part Page Layout/Template. You can keep all these new templates in _Layouts/CustomWebPartTemplates Folder.

 Create5-Newfiles


Note: there is no need to keep your new templates in the same directory used by Microsoft SharePoint 2010.

Step5: Create new images for each templates you are adding, in our case five templates so we need five images. we can keep these images in the _Layouts/Images/MyWebPartLayoutImages directory.

Create6-NewImagesfiles

Step6: Modify content of customspfc.aspx as per your application such as the directory in which all Web Part Page layouts are kept, Naming convention followed for pages (step4), Images etc.


    1. Search for string “sourceFilePath” and replace the path with the path wherever you have kept for your custom page layouts
      (i.e. defined in Step4: _Layouts/CustomWebPartTemplates).
    2. Search for id “onetidWebPartPageTemplate” add number of options depending on your number of page Layouts (in our case five templates).
    3. Each option value must correspond to the page Layout Name (which is Name and followed by option value).


e.g. If option value is 1 then Page Layout should present in the page layout folder with “mywpptd1.apsx”.
If option value is 101 then Page Layout should present in the page layout folder with “mywpptd101.apsx”.

Create7-TemplatesNameDisplay

Step7: Create a new feature which will install new option “Custom Web Part Page” with similar functionality of “Web Part Page”. Make sure that this new option points to the new customspcf.aspx file when selected to create new Web Part Page using Template.

Create and empty element module and add following code into the element.xml file to change the highlighted part as per your settings.

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<CustomAction

Id="CustomWebPartPageSettings"

Title="Custom - Web Part Page"

Description="Create a Web Part Page with Custom Web Part Page Template"

Location="Microsoft.SharePoint.Create"

GroupId="WebPages">

<UrlAction Url="_layouts/customspcf.aspx" />

</CustomAction>

</Elements>

Step8: Add new feature with scope to FARM. Add the newly created module from Step5 to this feature.

Step9: deploy feature to the Server.

After deployment, when you click on Site Actions > All Site Content.

Click on Create Link, If you have Silverlight installed you will get icon “Custom – Web Part Page”

Create1

else you will get link as “Custom – Web Part Page” under Pages and Sites

Create2

custom.aspx page

===============================================

  1. Create a new file customspcf.txt
  2. Copy the below text into it.
  3. then save and rename the customspcf.txt to customspcf.aspx.

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" DynamicMasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase"       %>


<script runat="server">
string L_GeneralError_Text = "An error has occurred.";
private void Page_Load(Object sender, EventArgs e)
{
    try
    {
        SPWeb spWeb = SPControl.GetContextWeb(Context);
        SPSite spServer = SPControl.GetContextSite(Context);
         // Make sure that the user is authenticated
        SPUtility.EnsureSessionCredentials(SPSessionCredentialsFlags.RequireAuthentication);
        // Create the select drop down control for the available Document Libraries only when the page is first loaded
        if (!Page.IsPostBack)
        {
            SPListCollection spLists = spWeb.Lists;           
            spLists.IncludeRootFolder = true;
            int iIndex = 0;
            bool bDocLibAvailable = false;
            for (int i = 0; i < spLists.Count; i++)
            {
                SPList spList = spLists[i];
                SPDocumentLibrary spDocLib = spList as SPDocumentLibrary;
                if ((!spList.Hidden) && (spList.BaseType == SPBaseType.DocumentLibrary) && spDocLib != null && !spDocLib.IsCatalog && (spList.BaseTemplate != SPListTemplateType.PictureLibrary))
                {
                    bool bHasPermission = false;
                    bool oldState = spServer.CatchAccessDeniedException;
                    try
                    {
                        spServer.CatchAccessDeniedException = false;
                        bHasPermission = spList.DoesUserHavePermissions(SPBasePermissions.AddListItems);
                    }
                    catch (UnauthorizedAccessException)
                    {
                    }
                    finally
                    {
                        spServer.CatchAccessDeniedException = oldState;
                    }
                    if (bHasPermission)
                    {
                        bDocLibAvailable = true;           
                        string value = SPEncode.HtmlEncode(spList.ID.ToString("B").ToUpper());
                        // ListItem encodes the text already, so no HTML encode here is needed
                        string text = spList.Title;
                        ListItem li = new ListItem(text, value);
                        if(iIndex == 0)
                        {
                            li.Selected = true;
                        }
                        onetidDocLibIDSelect.Items.Add(li);
                        iIndex++;
                    }
                }
            }
            // If no document library is available, disable the select drop down, and renders a link to create a document library
            if (iIndex == 0)
            {
                string L_NoneAvailable_Text = "None Available";
                onetidDocLibIDSelect.Disabled = true;
                ListItem li = new ListItem(L_NoneAvailable_Text);
                onetidDocLibIDSelect.Items.Add(li);
                string L_CreateDocLib1_Text = "Create a new ";
                string L_CreateDocLib2_Text = "Document Library";
                onetidCreateDocLibLabel.Text = L_CreateDocLib1_Text;
                onetidCreateDocLibLink.HRef = "new.aspx?ListTemplate=101&ListBaseType=1";
                onetidCreateDocLibLink.InnerText = L_CreateDocLib2_Text;
                btnCreate.Enabled = false;
            }
        }
        else // If the form posts back then we assume users press to enter button to create Web Part Pages
        {
            CreateWebPartPage();
        }
    }
    catch
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
}

private void SubmitBtn_Click(Object sender, EventArgs e)
{
    try
    {
        CreateWebPartPage();
    }
    catch
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
}
private void CreateWebPartPage()
{
    SPWeb spWeb = SPControl.GetContextWeb(Context);
    string templateName = Request.Form["WebPartPageTemplate"];
    // Validate the source file name
    if (templateName == null)
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    templateName = templateName.Trim();  // get rid of white spaces
    if (templateName.Length == 0)
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    templateName = templateName + ".aspx";
    if (templateName.Length > SPUtility.MaxLeafNameLength)
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    // Avoid characters like "..\..\" in the path
    if (templateName != System.IO.Path.GetFileName(templateName))
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    // Validate target file name
    string fileName = Request.Form["Title"];
    if (fileName == null)
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    fileName = fileName.Trim();  // get rid of white spaces
    if (fileName.Length == 0)
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    // Avoid characters like "..\..\" in the path
    if (fileName != System.IO.Path.GetFileName(fileName))
    {
        Context.Server.Transfer("error.aspx?ErrorText=" + SPEncode.UrlEncode(L_GeneralError_Text));
        return;
    }
    // Prepare the source file, assuming the Web Part Page templates live in
    // <Installation Path>\Template\Layouts\CustomWebPartTemplates
    string sourceFilePath = SPUtility.GetGenericSetupPath("Template\\") +
        "Layouts\\CustomWebPartTemplates\\";
   
    //string sourceFilePath = SPUtility.GetGenericSetupPath("Template\\") +
    //    spWeb.Language.ToString() + "\\" + spWeb.WebTemplate +
    //    "\\doctemp\\smartpgs\\";

    sourceFilePath = sourceFilePath + "mywpptd" + templateName;
    Response.Write(sourceFilePath);
    System.IO.StreamReader sr = new System.IO.StreamReader(sourceFilePath);
    //Response.Write("Ok");
    string content = sr.ReadToEnd();
    // Assuming the Web Part Page template has a Title Bar Web Part with the title place holder "_TitlePlaceHolder_"
    content = content.Replace("_TitlePlaceHolder_", fileName);
    // Save the target file into the database
    fileName += ".aspx";
   
    string doclibID = onetidDocLibIDSelect.Value;
    Guid guidDocLib = new Guid(doclibID);
    SPList doclib = spWeb.Lists[guidDocLib];
    string folderPath = doclib.RootFolder.Url;
    string targetFilePath = spWeb.Url + "/" + folderPath + "/" + fileName;
    // Convert the string into UTF8 encoded bytes
    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    System.Byte[] contentBytes = encoding.GetBytes(content);
    System.Byte[] bytes = new System.Byte[contentBytes.Length + 3];
    // Adding UTF8 byte order mark
    bytes[0] = 0xEF;
    bytes[1] = 0xBB;
    bytes[2] = 0xBF;
    contentBytes.CopyTo(bytes, 3);
    SPFileCollection fileCollection = spWeb.Files;
    if (OverwriteCheckBox.Checked)
    {
        SPFile spFile = spWeb.GetFile(targetFilePath);
        if (spFile != null && spFile.Exists)
        {
            SPFolder spFolder = spWeb.GetFolder(folderPath);
            spFolder.Files.Delete(targetFilePath);
        }
    }
    fileCollection.Add(targetFilePath, bytes);
    // Redirect to the newly created Web Part Page, with the toolpane opened in the Add Web Parts view
    Response.Redirect(targetFilePath + "?PageView=Shared&DisplayMode=Design&InitialTabId=Ribbon.WebPartPage&VisibilityContext=WSSWebPartPage");
}
</script>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<% SPSite spServer = SPControl.GetContextSite(Context); SPWeb spWeb = SPControl.GetContextWeb(Context); %>
<head>
    <meta name="GENERATOR" content="Microsoft SharePoint"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="Expires" content="0"/>
   
    <title id="onetidTitle"><SharePoint:EncodedLiteral ID="EncodedLiteral1" runat="server" text="<%$Resources:wss,pagetitle_sharepoint%>" EncodeMethod='HtmlEncode'/></title>
<SharePoint:CssLink ID="CssLink1" runat="server"/>
    <SharePoint:Theme ID="Theme1" runat="server"/>
<SharePoint:ScriptLink ID="ScriptLink1" name="init.js" language="javascript" runat="server" />
<SharePoint:ScriptLink ID="ScriptLink2" name="core.js" language="javascript" runat="server" />
<SharePoint:CustomJSUrl ID="CustomJSUrl1" runat="server" />
<link type="text/xml" rel='alternate' href="_vti_bin/spdisco.aspx" />
</head>
<script type="text/javascript">
// <![CDATA[
var strImagePath = "../Images/MyWebPartLayoutImages/";
function DoValidateAndSubmit()
{
    var form = document.frmWebPage;
    form["Title"].value = TrimSpaces(form["Title"].value);
    if (form["Title"].value.length < 1)
    {
        var L_alert1_Text = "You must specify a non-blank value for Name.";
        window.alert(L_alert1_Text);
        form["Title"].focus();
        return false;
    }
    if (IndexOfIllegalCharInUrlLeafName(form["Title"].value) >= 0)
    {
        var L_IllegalChar_Text = "The file name contains invalid characters. Type another file name using valid characters.";
        window.alert(L_IllegalChar_Text);
        return false;
    }
    var index = document.frmWebPage.onetidDocLibIDSelect.selectedIndex;
    var ListValue = document.frmWebPage.onetidDocLibIDSelect.options[index].value;
    if (ListValue == "")
    {
    var L_NoDocumentLibary_Text = "No document library is selected for the save location.";
        alert(L_NoDocumentLibary_Text);
        return false;
    }
    return true;
}
function DoTemplateOptionChange()
{ULSEhF:;
    var frmWebPage = document.forms.<%SPHttpUtility.NoEncode(Form.ClientID,Response.Output);%>;
    var index = frmWebPage.WebPartPageTemplate.selectedIndex;
    frmWebPage.PreviewImage.src = strImagePath + "mywpptd" + frmWebPage.WebPartPageTemplate.options[index].value + ".png";
    frmWebPage.PreviewImage.alt = frmWebPage.WebPartPageTemplate.options[index].text;
}

// ]]>
</script>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
  <TABLE class="ms-main" cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
    <!-- Banner -->
<%
string alternateHeader = SPControl.GetContextWeb(Context).AlternateHeader;
if (alternateHeader == null || alternateHeader == "")
{
%>
<TR>
  <TD COLSPAN=3 WIDTH=100%>
  <!--Top bar-->
 
  </TD>
</TR>
<%
}
else
{
    Server.Execute(alternateHeader);
}
%>
   
<TR>
<TD valign=top height=100% > </TD>
    <!-- Page overview -->
    <td><IMG SRC="/_layouts/images/blank.gif" width=10 height=1 alt=""></td>
    <td style="padding-top: 2px" valign="top" width="100%"> <table cellpadding=2 cellspacing=0><tr><td><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></td></tr></table>
      <TABLE  border="0" cellpadding="0" cellspacing="0" width="100%" id="diidPageOverview">
        <TR>
          <TD valign="top" colspan="3" style="padding-bottom: 10px">
            <TABLE cellpadding="0" border="0" id="Table1">
              <TR>
                <TD class="ms-descriptiontext" id="align01">
                    A Web Part Page is a collection of Web Parts that combines list data, timely information, or useful graphics into a dynamic Web page. The layout and content of a Web Part Page can be set for all users and optionally personalized by each user.  <a href="javascript:HelpWindowKey('WPPTour')">Take the Web Part Page tour!</a>
                </TD>
              </TR>
            </TABLE>
          </TD>
        </TR>
    <!-- New form UI -->
        <TR>
          <TD>
<FORM id="frmWebPage" onsubmit="return DoValidateAndSubmit();">
    <!-- Name -->
             <TABLE  border="0" width="100%" cellspacing="0" cellpadding="0" id="Table2">
                   <TR><TD class="ms-sectionline" height="1" colspan="4"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   <TR>
                     <TD nowrap rowspan="3"></TD>
                     <TD class="ms-descriptiontext" rowspan="3" valign="top"  id="align02">
                       <TABLE border="0" cellpadding="1" cellspacing="0" id="Table3">
                         <TR><TD class="ms-sectionheader" height="28" valign="top" id="200">Name</TD></TR>
                         <TR>
                           <TD id="onetidNameDescription" class="ms-descriptiontext">
                                 Type a file name for your Web Part Page.  The file name appears in headings and links throughout the site.
                           </TD>
                         </TR>
                       </TABLE>
                       <IMG SRC="/_layouts/images/blank.gif" width=275 height=1 alt="">
                     </TD>
                     <TD height="3" colspan="2" class="ms-authoringcontrols"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   </TR>
                   <TR>
                     <TD class="ms-authoringcontrols" width="10">&nbsp;</TD>
                     <TD class="ms-authoringcontrols" id="400">
                       Name:<BR>
                       <TABLE border="0" cellspacing="1">
                         <TR>
                           <TD>&nbsp;</TD>
                           <TD>
                             <INPUT id="onetidListTitle" type="Text" title="Name" name="Title" maxLength="123"><SPAN class="ms-authoringcontrols">.aspx</SPAN>
                           </TD>
                         </TR>
                         <TR>
                           <TD>&nbsp;</TD>
                           <TD class="ms-authoringcontrols">
                             <asp:CheckBox id="OverwriteCheckBox" title="Overwrite" runat="server"/>
                             Overwrite if file already exists?
                           </TD>
                         </TR>
                       </TABLE>
                     </TD>
                   </TR>
                   <TR><TD class="ms-authoringcontrols" colspan="2" height="6"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   <TR><TD colspan="2">&nbsp;</TD><TD class="ms-authoringcontrols" colspan="2" height="21">&nbsp;</TD></TR>
    <!-- Layout -->
                   <TR><TD class="ms-sectionline" height="1" colspan="4"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   <TR>
                     <TD nowrap rowspan="3"></TD>
                     <TD class="ms-descriptiontext" rowspan="3" valign="top"  id="align03">
                       <TABLE border="0" cellpadding="1" cellspacing="0" id="Table5">
                         <TR><TD class="ms-sectionheader" height="28" valign="top" id="500">Layout</TD></TR>
                         <TR>
                           <TD id="onetidLayoutDescription" class="ms-descriptiontext">
                                 Select a layout template to arrange Web Parts in zones on the page. Multiple Web Parts can be added to each zone. Specific zones allow Web Parts to be stacked in a horizontal or vertical direction, which is illustrated by differently colored Web Parts. If you do not add a Web Part to a zone, the zone collapses (unless it has a fixed width) and the other zones expand to fill unused space when you browse the Web Part Page.
                           </TD>
                         </TR>
                        <TR><TD class="ms-descriptiontext" height="20"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                        <TR><TD align="center" class="ms-descriptiontext" height="6"><img src="/_layouts/MyApplication/Images/MyWebPartLayoutImages/mywpptd1.png" alt="Enterprise Layout – 33 / 66 Split" id="onetidPreviewImage" name="PreviewImage"/></TD></TR>
                        <TR><TD class="ms-descriptiontext" height="6"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                       </TABLE>
                     </TD>
                     <TD height="3" colspan="2" class="ms-authoringcontrols"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   </TR>
                   <TR>
                     <TD class="ms-authoringcontrols" width="10">&nbsp;</TD>
                     <TD class="ms-authoringcontrols" id="700" valign="top">Choose a Layout Template:<FONT size="3">&nbsp;</FONT><BR>
                       <TABLE border="0" cellspacing="1" id="Table6">
                         <TR>
                           <TD>&nbsp;</TD>
                           <TD>
                             <!-- Assuming the templates are named mywpptdN.aspx and the image files are named as mywpptdN.gif, where N is from 9 to 12 -->
                             <!-- 0 to 8 are used by the default web part page layouts provided by SharePoint 2010. So we start from 9 -->
                             <SELECT id="onetidWebPartPageTemplate" name="WebPartPageTemplate" size="5" onchange="DoTemplateOptionChange()">
                               <OPTION value="1" selected="true">Enterprise Layout – 33 / 66 Split</OPTION>
                               <OPTION value="2">Enterprise Layout – 66 / 33 Split</OPTION>
                               <OPTION value="3">Enterprise Layout – 100% Span</OPTION>
                               <OPTION value="4">Enterprise Layout – 33 / 66 / 33 / 33 Split</OPTION>
                               <OPTION value="5">Enterprise Layout – 33 / 33 / 33 Split</OPTION>
                             </SELECT>
                           </TD>
                           <TD>&nbsp;</TD>
                         </TR>
                       </TABLE>
                     </TD>
                   </TR>
                   <TR><TD class="ms-authoringcontrols" colspan="2" height="6"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                  <TR><TD colspan="2">&nbsp;</TD><TD class="ms-authoringcontrols" colspan="2" height="21">&nbsp;</TD></TR>
    <!-- Save Location -->
                   <TR><TD class="ms-sectionline" height="1" colspan="4"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   <TR>
                     <TD nowrap rowspan="3"></TD>
                     <TD class="ms-descriptiontext" rowspan="3" valign="top"  id="align04">
                       <TABLE border="0" cellpadding="1" cellspacing="0" id="Table7">
                         <TR><TD class="ms-sectionheader" height="28" valign="top" id="800">Save Location</TD></TR>
                         <TR>
                           <TD id="onetidSaveLocationDescription" class="ms-descriptiontext">
                                 Select the document library where you want the Web Part Page to be saved.
                           </TD>
                         </TR>
                       </TABLE>
                     </TD>
                     <TD height="3" colspan="2" class="ms-authoringcontrols"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   </TR>
                   <TR>
                     <TD class="ms-authoringcontrols" width="10">&nbsp;</TD>
                     <TD class="ms-authoringcontrols" id="900" valign="top"><label for="onetidDocLibIDSelect">Document Library</label>:<FONT size="3">&nbsp;</FONT><BR>
                       <TABLE border="0" cellspacing="1" id="Table8">
                         <TR>
                           <TD>&nbsp;</TD>
                           <TD>
                             <SELECT id="onetidDocLibIDSelect" runat="server"/>
                           </TD>
                           <TD>&nbsp;</TD>
                         </TR>
                         <TR>
                           <TD>&nbsp;</TD>
                           <TD class="ms-authoringcontrols">
                             <asp:Label id="onetidCreateDocLibLabel" runat="server"/><a id="onetidCreateDocLibLink"  runat="server"/>
                           </TD>
                           <TD>&nbsp;</TD>
                         </TR>
                       </TABLE>
                     </TD>
                   </TR>
                   <TR><TD class="ms-authoringcontrols" colspan="2" height="6"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD></TR>
                   <TR><TD colspan="2">&nbsp;</TD><TD class="ms-authoringcontrols" colspan="2" height="21">&nbsp;</TD></TR>
  <!--OK/Cancel-->
               <TR><TD colspan="4" valign="top" height="25"><hr size="1"></TD></TR>
               <TR><TD colspan=4> <TABLE cellpadding=0 cellspacing=0 width=100%> <COLGROUP> <COL width=99%> <COL width=1%> </COLGROUP> <TR> <TD>&nbsp;</TD> <TD nowrap id=align06>
                  <asp:button ID="btnCreate" text="   Create   " AccessKey="C" CssClass="ms-ButtonHeightWidth" OnClick="SubmitBtn_Click" runat="server"/>
                  <INPUT id="onetidClose" class="ms-ButtonHeightWidth" type="button" onclick="window.parent.history.back()" value="   Cancel   ">
                  <SharePoint:FormDigest ID="FormDigest1" runat=server/>
               </TD> </TR> </TABLE> </TD></TR>
               <TR><TD colspan="4" height="60">&nbsp;</td></TR>
             </TABLE>
             <TD width="10px">&nbsp;</TD>
            </FORM>
          </TD>
        </TR>
      </TABLE>
    </TD>
    </TR>
  </TABLE>

</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Create Custom Web Part Pages
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Create Custom Web Part Pages
</asp:Content>