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

Add Web Parts to DispForm, EditForm or NewForm.aspx

When I browsed to the “View Item” page and clicked the “Site Actions” I noticed that there wasn’t an “Edit Page” option available. Strange, but after some -Googling- I found the following sollution:
  • Open IExplorer and navigate to your “View Item” page (DispForm.aspx)
  • Replace everything in the URL after “?ID=#“ with “&PageView=Shared&ToolPaneView=2″ (without the quotes of course) and press
After adding a Web Part to the page and saving it, the “Edit Page” option will be available the next time you click “Site Actions” on that Page.

Adding Quick Launch to custom webpart Pages

Where did that trusty Quick Launch Bar disappear to? Last time I remember, left it right here -

Has this happened to you? Have you searched high and low looking for some mystery setting in the Web Part Pages to display it? I know I have. Well let me tell you how to get it back, then how you can fix it so it appears for all newly created Web Part Pages in the future.
How to fix existing Web Part Pages to display the Quick Launch Bar
  1. Open SharePoint Designer 2007 and open your SharePoint site.
  2. Locate and open the existing Web Part Page and switch to Code view.
  3. Search for, and delete the following lines of code -

    < asp:Content ContentPlaceHolderId="PlaceHolderNavSpacer" runat="server">
    < asp:Content ContentPlaceHolderId="PlaceHolderLeftNavBar" runat="server">


    Notice that they are all next to each other, so if you find one, you can find the other 2 easily.
  4. Save the file. Now you will see the Quick Launch Bar on that particular Web Part Page.
  5. Repeat steps 1 through 4 for each existing Web Part Page you want to display the quick launch bar on.

How to Add a Web Part Zone for SharePoint

Every SharePoint site template (both MOSS 2007 and WSS3) has its own default layout of Web Part Zones. I would like to customize the layout of these zones for flexibility of design in a particular site

Solution

To customize the Web Part Zone layout, you need SharePoint Designer

Let's create a new document library for some practice Web Part Pages. (See this tip if you need instructions.) Later, you can use the procedure in this article to edit your main site pages.
In your Web Part Page library, create a new Web Part Page. Choose the "Header, RIght Column, Body" to follow my design (or choose another if you like to be creative).

Once you get your page, there is no need to add web parts now. Just stop editing it and return to the library where it exits. I use the breadcrumbs pictured below.



Editing Web Part Pages with SharePoint Designer

Now open the web page by clicking on it.

Here's a view of the blank page.

Assuming you have SharePoint Designer 2007 installed, go to the "File" menu of Internet Explorer and select "Edit with Microsoft Office SharePoint Designer".

You will now see your page, in edit mode, from inside the SharePoint Designer. Note that the Web Part Zones exist within a standard HTML table. (You may need to open the "Design" tab in SharePoint Designer.)

Select the lower row of the table.

Then, from the "Table" menu in SharePoint Designer, select "Insert" and then "Row Below".

Click into the row you just created. For illustration purposes, I am going to add a table with 3 rows and 3 columns. From the "Table" menu, select "Insert Table". Use the parameters I have below (or anything you like).

In the top left cell of the table, I now add a Web Part Zone:
Insert --> SharePoint Controls --> Web Part Zone.
(The graphic below looks like I am in the HTML menu, I am really not.)

Repeat the procedure for each cell in the table.


View the Results

Save the page in SharePoint Designer and exit the application. Then open the page in your library, click "Site Actions" and then "Edit Page".

Here you should see the new Web Part Zones added.

Script to hide Edit, delete item properties of sharepoint list

hideFormMenuItems("New Item", "Delete Item");





function hideFormMenuItems()

{





var titleToHide="";

var anchorTag;

var allAnchorTags = document.getElementsByTagName

('a');

for(var i = 0; i <

hideFormMenuItems.arguments.length; i++ )

{

titleToHide =

hideFormMenuItems.arguments[i];

if(titleToHide!='Alert Me')

{



for (var j = 0; j

< allAnchorTags.length; j++)

{



anchorTag= allAnchorTags[j];





if (anchorTag.title.indexOf(titleToHide)!=-1)



{













anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="no

ne";





anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.style

.display="none";



break;



}



}

}

else

{

for (var k=0; k <

allAnchorTags.length;k++)

{



anchorTag= allAnchorTags[k];







if (anchorTag.id.indexOf("SubscribeButton")!=-1)



{





anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="no

ne";



break;





//anchorTag.parentNode.parentNode.parentNode.parentNode.parentNode.previousSibling

.style.display="none";





}

}



}





}



var allSpanTags = document.getElementsByTagName

("span");

var spanTag;

var toolbarRow;

var lastCell;

for(var m=0; m < allSpanTags.length;m++)

{

spanTag = allSpanTags[m];



if

(spanTag.id=='part1')

{



toolbarRow = spanTag.childNodes[2].firstChild.firstChild;



lastCell = toolbarRow.lastChild.previousSibling





while(lastCell.style.display=='none')

{











lastCell = lastCell.previousSibling;





}





if(lastCell.innerText == '|')

{







lastCell.style.display='none';



}

















break;

}

}





}



Script to keep the group  by items in collapsed mode

<script type="text/javascript">
var rows = document.getElementsByTagName('tr');
var numRows = rows.length;
for (var i = 0; i < numRows; ++i)
{
    if (rows[i].getAttribute("isexp") != null && rows[i].getAttribute("isexp").toLowerCase() == "true")
    {
          if(rows[i].firstChild.firstChild != null && rows[i].firstChild.firstChild.tagName.toLowerCase() == "a")
          {   
              if (rows[i].firstChild.firstChild.title.toLowerCase() == "expand/collapse")
                  {
                    rows[i].firstChild.firstChild.fireEvent("onclick");
            }
          }
    }

}
</script>

Monday, November 8, 2010

Creating a List Item

Site Administrator has the privilege to configure new list. For adding new list, one has to login as Administrator privilege. To perform this action, you have to go through below steps
Ø Navigate to Site Settingsà Modify all Settings found below the Site Actions menu. This will take to Settings page, where you can find list of Settings related to site.

Ø Click on “Site Libraries and List” link found under the Site Administration.
Ø Click on “Create new Content” for adding new content to the page.

Ø Under the Custom List tab, you can find the Custom List link; one has to click on the link to add a new List as shown below.

Ø Specify the name of the list that you wish to configure.

Ø If the list that is added has to be shown up in the Quick Launch navigation, then click the “yes” radio button. Then click “Create” button to create the list.

Ø Once the list is created, there are various options to customize the list.

Ø New Columns can be added to the list by selecting List Settings under Settings menu

Ø For adding any new item to the newly added list, click on New Item under “New” menu.

Creating Content Editor Web part

You can use the Content Editor Web Part to add formatted text, tables, hyperlinks, and images to a Web Part Page.

· The Content Editor Web Part is intended for adding HTML content to a Web Part Page, which may include hyperlinks. However, this Web Part is not designed to connect to a Web site. If you need to connect a Web Part to a Web site, consider using the Page Viewer Web Part.
· The Content Editor Web Part does not accept the HTML FORM element. If you need to add a Web Part that uses the FORM element, consider using the Page Viewer Web Part or the Form Web Part.



Ways you can use the Content Editor Web Part
You can use the Content Editor Web Part to add:
· An introductory, formatted paragraph to a page.
· A table of instructions to explain a chart on your page, the data that is used in the chart, and how the chart was created.
· A set of hyperlinks to more information.


Add content to the Content Editor Web Part

· Rich Text Editor You can use the Rich Text Editor to type formatted content automatically without prior knowledge of HTML syntax. Click the buttons on the Standard and Formatting toolbars at the top of the window to enter and format the content. Click Help on the Standard toolbar to display a summary of the tasks that you can perform and their corresponding buttons.
· Source Editor You can use the Source Editor to enter or modify HTML source code. The Source Editor is a plain text editor and is intended for users who are familiar with HTML syntax.
· Content Link Instead of editing content, you can link to existing content by entering a hyperlink to a text file that contains HTML source code. The two valid hyperlink protocols that you can use are:
Hypertext Transfer Protocol (http://)
Hypertext Transfer Protocol with privacy, which uses Secure Sockets Layer (SSL) encryption (https://)
You can use an absolute URL or a relative URL. However, you cannot use a file path.

If you enter a URL into the Content Editor Web Part as a relative link, the link converts to an absolute URL when the entry is saved. This automatic conversion can be an issue if you are deploying content from a staging environment to production, where absolute URLs reference the original server's name. To address this automatic conversion issue, you will need to edit the Content Editor Web Part on the production server and update the URLs manually

Common properties of Web Parts
All Web Parts share a common set of properties that control their appearance, layout, and advanced characteristics.
To see the advanced section in the tool pane, you must have appropriate permission.
· For a specific Web Part, a Web Part developer may have chosen not to display one or more of these common properties or may have chosen to create and display additional properties that are not listed below in the Appearance, Layout, and Advanced sections of the tool pane.
· Some permission and property settings may disable or hide Web Part properties.

Creating document libraries in sharepoint

Creating Document libraries
Document libraries are collections of files that you can share with team members on a Web based on Microsoft Windows SharePoint Services. For example, you can create a library of common documents for a project, and team members can use their Web browsers to find the files, read them, and make comments.
A document library is created to store a collection of documents or files that you want to share. Document libraries support features such as sub-folders, file versioning, and check-in/check-out. One of the neat new features of a SharePoint document library in SharePoint 2007 is the ability to send a document to another location. The first is that most teams have a collaborative area where they create content that will eventually be consumed and available for the remainder of the company.
In many cases, this collaborative area is restricted to only those that belong to the team responsible for creating the content. However once the document is complete, it should be published out to a location where everyone has access
Another great feature of this Send To option is the ability to create a custom location. This allows us to specify a common place that content may be published to. To do this you must go to the Advanced Settings of the document library, and specify the location of the document library you wish to publish to.
Once you have your specified custom location, it will show up in context menu of documents in that library.


Checking out a document
With document library files, you should always check out a file before opening it and making changes. This prevents other users from opening the file and making changes while you have it checked it. If a user views the file while you have it checked out, he or she will see the last version that was checked out, not the version that you're working. Once you check the file back in, users can see the changes that you made.
In the document library that’s being created, point to the file Sample.doc to display a down arrow.
Click the down arrow to reveal a menu, and then click Check Out.
Once you've checked out a file, the Check Out option on the menu changes to Check In. You can use this option to check the file back in after you're done making changes to the file. In this tutorial, however, you'll use the Check In option in Word.
Check in a file
With the properties set, you're ready to check the file in and close Word 2003.
Click File, and then click Check in.
Click File, and then click Exit.
If a file in a document library is missing required property settings, you'll be prompted to provide them. After you've done so, Word 2003 will close.
Delete a document library
On the page that displays the document library, under Actions, click Modify settings and columns.
Under General Settings, click Delete this document library.
Click OK.


Creating Views for Document library
To modify the views for document library, select the View drop arrow on the right side of the document library. Select the desired view. To modify the existing view, click on modify this view link and customize accordingly. To create a new custom view, below procedures are followed.
· Click Settings menu and select Create View
· Click Standard View
· Give the view a name (Example: Folder View)
· Pick the columns to display - Type (icon linked to document) - Name (linked to document with edit menu)
· Limit the number of items displayed by expanding "Item Limit" (Example: 10)
· Click OK to create the view

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