Sunday, November 14, 2010

Writing Server-side ( C# ) code in SharePoint custom pages

There are basically two approaches to write server side code:
A) Inline coding ( C# and HTML code in same ASPX page)
B) Code-Behind (C# and HTML code in seperate files)

A) Inline coding

1) In this approach, first you have to modify application's web.cofig file.
Locate PageParserPaths node in config file and then change it as per your requirement.

If you doesn't know page(s) name which is(are) using server side code, then write /* in VirtualParth attribute,
else write page name as /pagename.aspx in VirtualParth attribute.
[For each page add a seperate PageParserPath node,
for example you want to allow server side code in 5 pages then you have to add PageParserPath nodes.]




<PageParserPaths>
        <PageParserPaths>
        <PageParserPath VirtualPath="/Custom Webpart Pages/*" CompilationMode="Always"   AllowServerSideScript="true" />
      </PageParserPaths>
</PageParserPaths>




2) Write server side code as


<script runat="server">

protected void Page_Load(Object sender, EventArgs e)
{
    Response.Write("Server code in Sharepoint");
}

</script>

The above script
I placed  inside the PlaceHolderMain place holder.

B) Code-Behind approach

1) Create a C# file (or VB file) for your server code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNameSPace
{
    public class MyClass : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        //Server control declarations
        protected Label lblMessage;

        protected void Page_Load(Object sender, EventArgs e)
        {
            lblMessage.Text = "Server Code";
        }
    }
}



Points to remember:
- Inherits the class with LayoutsPageBase (there are other options also available for choosing base class)
- Declare ASP.Net server control with protected modifier.



2) Register the DLL (that contains above class) in GAC.

3) safecontrol entry in application's web.config file.

4) Create ASPX file for HTML code


<%@ Assembly Name="MyNameSPace, Version=1.0.0.0, Culture=neutral, 
       PublicKeyToken=bf118dafb4e11f4b" %>
<%@ Page Language="C#" MasterPageFile="~masterurl/default.master" 
       Inherits="MyNameSPace.MyClass" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Label runat="server" ID="lblMessage" ForeColor="Red" 
        Visible="false"></asp:Label>
</asp:Content>


Merits & Demerits

Inline coding
-
In case of any change(s) in code (HTML + C#), replace the existing ASPX file with modified one in SharePoint Designer.
- It is unsafe, to allow server side code by modifying PageParserPaths node in web.cofig
- Can't debug the page [Major disadvantage while development].
-
Easy to deploy, no need to do DLL registration in GAC, IISRESET and safecontrol entry in web.config


Code-Behind
- Can debug server side code ( Debug -> Attach to Process -> w3wp.exe process )
- Need to do DLL registration in GAC, IISRESET and safecontrol entry in web.config
-  In case of any change(s) in HTML code, replace the existing ASPX file with modified one in SharePoint Designer.
- In case of any change(s) in server-side ( C# ) code, re-register the DLL in GAC (drag-n-drop dll in assembly folder) and do IISRESET [ Must ] to see the change(s).

Login pop-up in SharePoint

If you gets login pop-up whenever you opens any SharePoint page in Internet Explorer (IE), then solve this issue we need to change following IE settings...Add the SharePoint site to the list of Local Intranet (IE7/8).
1) In Internet Explorer, on the Tools menu, click Internet Options. 
2) On the Security tab, in the Select a Web content zone to specify its security settings box, click Local Intranet, and then click Sites. 
3) Clear the Require server verification (https:) for all sites in this zone check box. 
4) In the Add this Web site to the zone box, type the URL to your site, and then click Add. 
5) Click Close to close the Local Intranet dialog box. 
6) Click OK to close the Internet Options dialog box. 

Code to download document from SharePoint Document Library

string siteURL = "http://mysite:80/"; //Write valid site URL 
//Get SPSite and SPWeb instance
using (SPSite spSite = new SPSite(sireURL))
{
 using (SPWeb spWeb = spSite.OpenWeb())
 {
        //Get time stamp to download file with unique name
     string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");

        //Get folder path
     string directoryPath = 
       Path.Combine(Environment.GetFolderPath
                          (Environment.SpecialFolder.LocalApplicationData),
                        "MyFolder");

        //Create directory if it not exist
        if (!(Directory.Exists(directoryPath)))
        {
            Directory.CreateDirectory(directoryPath);
        }

        //Get template url
        string documentUrl; //Write valid document URL

        //Download file in file system
        SPFile myFile = spWeb.GetFile(documentUrl);
        byte[] binFile = myFile.OpenBinary();

        //Generate file name
        filename = Path.Combine(directoryPath, strFileName + ".doc");

        //Do file write operation
    FileStream fs = 
     new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(binFile);
        bw.Close();
    }
}

Saturday, November 13, 2010

Configure SharePoint Forms Based Authentication to use LDAP

Problem

This article outlines how to configure SharePoint Forms Based Authentication (FBA) to use Lightweight Directory Access Protocol (LDAP), typically used on a SharePoint Extranet.

Solution

Prepare the Authentication Provider

First we need to configure the Authentication Provider to use Forms Based Authentication. This is done via SharePoint Central Administration.

  1. Browse to SharePoint Central Administration
  2. Select the Application Management tab
  3. Under the Application Security section select Authentication Providers
  4. Select the appropriate Web Application which you want to allow FBA for.
  5. Click the appropriate Zone you would like to change, only Default is shown below.
  6. Scroll down to the Authentication Type section and change the Authentication Type to Forms
  7. Scroll down to Membership Provide Name and enter the name of your Membership provider, this must match the name in your web.config (see below).
Note the Enable Anonymous access check box. This is one of two settings you need to change to allow anonymous access to part of your site. You might want to do this to present a custom logon form.

pdate SharePoint Central Admin web.config

Please note that updating the web.config incorrectly can damage your SharePoint installation. Extreme care should be taken, please do not edit the web.config if you are not familiar with web.config or XML structures.

  1. Make a backup of the web.config file (always a best practice).
  2. Locate your web.config file for the SharePoint Central Administration website. Normally located in C:\Inetpub\wwwroot\wss\VirtualDirectories
  3. Take special care to select the right Virtual Directory, mine is named SharePointCA80 yours will be different
  4. Locate the web.config file and open it with notepad
  5. Scroll down to the configuration node, find





  6. Replace the ??? with your domain name
  7. Scroll down to the system web node and the following membership







  8. Replace the connectionstring to the one matching your environment and replace "xxx" with domainname\username and "yyy" with password
  9. Save and close the web.config for SharePoint Central Administration
  10. Update the web.config of SharePoint Web application
  11. Repeat steps 1 to 8 for the web.config of the SharePoint web application you configured the Authentication Provider for Forms Based Authentication above
  12. Check the authentication in this web.config is set to the following.




Note you can specify a custom login page here, shown as loginUrl="" above. I strongly recommend you use an LDAP query tool to discover your path before setting up SharePoint.

Sharepoint Calculated columns

Calculated columns – An example

By adding a calculated column to a list or library, you can create a formula that includes data from other columns and performs functions to calculate dates and times, to perform mathematical equations, or to manipulate text. For example, on a tasks list, you can use a column to calculate the number of days it takes to complete each task, based on the Start Date and Date Completed columns.
(Excerpt from the Microsoft Web site)

Let me use this Microsoft example to walk you through the setup of calculated columns.

We first need to create our SharePoint tasks list (Site Actions > Create > Tasks).

It already includes a [Start Date] column, let’s add the [Date Completed] one:
- Select: Settings > Create Column
- Create a column called “Date Completed”, with type set as ”Date and Time”.
- Click OK

  • We are now ready to create our first calculated column:
    - Select: Settings > Create Column
    - Create a column called “Duration”, with type set as ”Calculated (calculation based on other columns)”
    - Enter the formula:
    = [Date Completed]-[Start Date]
  • - Click OK

Let’s take a look at the result:

As you can see, the result is incorrect when the [Date Completed] field is empty. To fix this, we’ll add a condition to our formula:
=IF([Date Completed]=0,”",[Date Completed]-[Start Date])

Now, the duration will only be displayed after the user enters a value for “Date Completed”:


A sales engineer is someone who promise you a bridge, even when there's no river.