Sunday, November 22, 2009

SharePoint 2010 Beta 2 and Silverlight 4 Beta available

Microsoft announced the availability for SharePoint 2010 Beta 2

http://blogs.msdn.com/sharepoint/archive/2009/11/18/sharepoint-2010-public-beta-is-now-available-for-download.aspx

At the PDC in n Los Angeles, Scott Guthrie announced the availability of Silverlight 4 beta:

http://team.silverlight.net/announcement/silverlight-4-beta-is-now-available/
http://www.silverlight.net/getstarted/silverlight-4-beta/

Saturday, November 7, 2009

What are Sharepoint Querystring Parameters?

Here are some Query String parameters that I think every SharePoint Developer\Implementer must know about it
 
To open the Web Part Maintenance Page

"?Contents=1"


To Open the Page in Web Part Design Mode

"?ToolPaneView=2"


To Open the Search Web Part Zone

"?ToolPaneView=3"


To open the Design Bar - Useful for pages in the Pages Library

"?DisplayMode=Design"


To turn on Web Part Zone Editing

"?ControlMode=Edit"


To Show the Shared version of a page

"?PageView=Shared"


To Show the Personal version of a page

"?PageView=Personal"

Sunday, October 11, 2009

How to Insert Item in Sharepoint List using WebService with Javascript

Without using Sharepoint API we can achieve by OOB. In following code I have inserting items in MyList and ID and Title.

You can call the from a button with the following code

<input type="button" value="Save List Item" onclick="javascript:SaveListItem();">

function SaveListItem()
{
var soapRequest = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">' +
' <soap12:Body>'+
' <UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">'+
' <listName>TestList</listName>'+
' <updates>'+
'<Batch OnError="Continue">'+
' <Method ID="1" Cmd="New">'+
' <Field Name="ID">New</Field>'+
' <Field Name="Title">TestData</Field>'+
' </Method>'+
'</Batch>'+
' </updates>'+
' </UpdateListItems>'+
' </soap12:Body>'+
'</soap12:Envelope>';
xmlHttp=new XMLHttpRequest();
xmlHttp.open('post', 'http://ServerName/SiteCollection/_vti_bin/Lists.asmx', true);
xmlHttp.setRequestHeader('Content-Type','application/soap+xml; charset=utf-8');
xmlHttp.send(soapRequest);
}

Saturday, October 3, 2009

How to Delete attachment from an Item in Sharepoint List

public static void DeleteAttachements(int id)

{
using (SPSite site = new SPSite("http://portal"))
{
using (SPWeb web = site.OpenWeb())
{
SPListItem listItem = web.Lists["mylist"].GetItemById(id);
List<string> fileNames = new List<string>();
foreach (string fileName in listItem.Attachments)
{
fileNames.Add(fileName);
}
foreach(string fileName in fileNames)
{
listItem.Attachments.Delete(fileName);
}
listItem.update();
}
}
}

Thursday, September 24, 2009

How to Update User Profile using C#

using (SPSite site = new SPSite(“http://portal”))

{
Microsoft.Office.Server.ServerContext Context = ServerContext.GetContext(site);
Microsoft.Office.Server.UserProfiles.UserProfileManager Mngr = new UserProfileManager(Context);
Microsoft.Office.Server.UserProfiles.UserProfile Profile = Mngr.GetUserProfile(“litwareinc\ashishk”);
System.Console.Write(Profile[“Title”].Value.ToString());
Profile[“Title”].Value = “New Title”;
Profile.Commit();
}


Bingo, here ashishk Title is updated with "New Title"

Tuesday, September 22, 2009

How to retrieve account names from UserProfile

It is quite difficult to get accountnames from userprofile database. Using SDK, you can get the account by following example

using (SPSite site = new SPSite(http://portal/))
{
        ServerContext context = ServerContext.GetContext(site);
        UserProfileManager profileManager = new UserProfileManager(context);

        foreach (UserProfile profile in profileManager)
       {
             Console.WriteLine(profile[PropertyConstants.AccountName]);
       }
}

Saturday, August 15, 2009

Data View conditional formatting using SharePoint Designer

Following article demonstrates how to use SharePoint Designer 2007 conditional formatting to format items in a SharePoint (MOSS 2007) list based on item metadata.

http://blog-sharepoint.blogspot.com/2009/05/data-view-conditional-formatting-using.html

Tuesday, July 28, 2009

How to send HTML email from Sharepoint with CC/BCC

public static void SendEmail(SPWeb web, string toEmail, string ccEmail,

string bccEmail,
string subject, string body)
{
   if (!string.IsNullOrEmpty(toEmail))
  {
     StringDictionary headers = new StringDictionary
     {
        {"to", toEmail},
        {"cc", ccEmail},
        {"bcc", bccEmail},
        {"subject", subject},
        {"content-type", "text/html"}
     };
     SPUtility.SendEmail(web, headers, body);
   }
}

Sunday, July 19, 2009

Interesting articles on various blogspot

I found various intereting articles on various blog as mentioned below

Wednesday, June 24, 2009

MOSS Expiration Issue after installing SP2 for MOSS 2007

Many people are facing problem MOSS expiration After installing SP2 for SharePoint Server 2007, because it incorrectly activates the product expiration date. This means after 180 days the SharePoint Server will become inaccessible to all end users.

As per Microsoft KB Article, follow the steps as mentioned below

  • Click Start, point to All Programs, point to Administrative Tools, and then click SharePoint 3.0 Central Administration.  
  • Click the Operations tab. 
  • Click Convert License Type.  
  • In the Enter the Product Key text box, type your product identification number, and then click OK.  
  • The License Synchronizer Job will run on all computers in the farm after a few moments. After all the computers have updated their license from the timer job, the Convert License Type page will reflect the correct license.
For more informatin, review following article
http://support.microsoft.com/kb/971620

http://blogs.msdn.com/sharepoint/archive/2009/05/21/attention-important-information-on-service-pack-2.aspx

Wednesday, June 3, 2009

How can I modify "Modified", "Modified By", "Created" and "Created By" Field Values Without Changing Version in Published Page List?

SPSite site = null;

SPWeb web = null;
site = new SPSite("http://portal/");
web = site.OpenWeb();
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
SPContentTypeId myContentType = new SPContentTypeId("MyContentTypeId");
PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts(myContentType );
PageLayout pageLayout = layouts[0];
string pageName = Guid.NewGuid().ToString() + ".aspx";
SPUser user = web.EnsureUser("DOMAIN\\ashishk");
string createdDate = "2009-06-03T22:35:10Z";
string modifiedDate = "2009-06-03T22:35:10Z";
web.AllowUnsafeUpdates = true;
PublishingPage newPage = publishingWeb.GetPublishingPages().Add(pageName, pageLayout);
newPage.ListItem["Author"] = user.ID;
newPage.ListItem["Editor"] = user.ID;
newPage.ListItem["Created"] = createdDate;
newPage.ListItem["Modified"] = modifiedDate;
newPage.ListItem.UpdateOverwriteVersion();
web.AllowUnsafeUpdates = false;
web.Dispose();
site.RootWeb.Dispose();
site.Dispose();

Friday, April 10, 2009

Download Document from SharePoint Library using WebService

In  following code, I am reading the contents from the documents and creating and storing documents in local system

//Copy WebService Settings
string webUrl = "http://portal/";
WSCopy.Copy copyService = new WSCopy.Copy();

copyService.Url = webUrl+"/_vti_bin/copy.asmx";

copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

//Source and Destination Document URLs
string sourceUrl = "http://localhost:1000/Shared%20Documents/Sample.doc";
string destinationUrl = "C:\\Documents\Sample.doc";


//Variables for Reading metadata’s of a document
WSCopy.FieldInformation fieldInfo = new WSCopy.FieldInformation();
WSCopy.FieldInformation[] fieldInfoArray = { fieldInfo };
WSCopy.CopyResult cResult1 = new WSCopy.CopyResult();
WSCopy.CopyResult cResult2 = new WSCopy.CopyResult();
WSCopy.CopyResult[] cResultArray = { cResult1, cResult2 };


//Receive a Document Contents into Byte array (filecontents)
byte[] fileContents = new Byte[4096];
copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);


//Create a new file and write contents to that document
FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
fStream.Write(fileContents, 0, fileContents.Length);
fStream.Close();

Thursday, April 9, 2009

SHAREPOINT DESIGNER 2007 IS NOW FREE!

SharePoint Designer 2007 provides the powerful tools you need to deliver compelling and attractive SharePoint sites and quickly build workflow-enabled applications and reporting tools on the SharePoint platform, all in an IT-managed environment.

You can download it at http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=baa3ad86-bfc1-4bd4-9812-d9e710d44f42.

Saturday, April 4, 2009

How to delete data from Sharepoint List using API?

Normally once you delete the data from the list it goes to Recycle Bin. During reading SDK I came to know about a method  'Delete' which deletes data permanently, does not send it recycle bin. So now we have two different approach for deleting list data.

Approach 1 - Delete Data Permanently

using (SPSite siteCollection = new SPSite("http://portal/"))
{
    using (SPWeb site = siteCollection.OpenWeb())
    {
       SPList list1 = site.Lists["MyList"];
       for (int i = list1.Items.Count - 1; i >= 0; i--)
      {
          list1.Items.Delete(i);
      }
    }
}

Approach 2 - Delete Data and it goes to recycle bin

using (SPSite siteCollection = new SPSite("http://portal/"))
{
   using (SPWeb site = siteCollection.OpenWeb())
   {
   SPList list1 = site.Lists["MyList"];
   for (int i = list11.Items.Count - 1; i >= 0; i--)
   {
      SPListItem olistitem = list11.Items[i];
      olistitem.Recycle();
   }
   }
}

Thursday, March 26, 2009

Common Date Time formulas for Sharepoint

Get Week of the year

=DATE(YEAR([Start Time]),MONTH([Start Time]),DAY([Start Time]))+0.5-WEEKDAY(DATE(YEAR([Start Time]),MONTH([Start Time]),DAY([Start Time])),2)+1

First day of the week for a given date:

=[Start Date]-WEEKDAY([Start Date])+1

Last day of the week for a given date:

=[End Date]+7-WEEKDAY([End Date])

If you want your week to start from Monday to Sunday, include an extra parameter value to your WEEKDAY() function

First day of the week for a given date:

=[Start Date]-WEEKDAY([Start Date],2)+1

Last day of the week for a given date:

=[End Date]+7-WEEKDAY([End Date],2)
First day of the month for a given date:

=DATEVALUE(“1/”&MONTH([Start Date])&”/”&YEAR([Start Date]))

TODAY + 1 hour formula
You can use formula like (1/24th of a day or 1 hour to the rest of us is 0.04167!)


=[Created]+0.04167

But we can’t use the Created/Modified field in the formula for a new record because it doesn’t exist yet.


OK, so what if we try and use this in the Default Value column as
=Today+0.04167

This will always be ‘Today at 1AM’ rather than ‘Today in exactly 1 hour’ as Today uses 12:00 AM as the time offset. Unfortunately there is no [Now] function in SharePoint.

Last day of the month for a given year (does not handle Feb 29). Result is in date format:

=DATEVALUE (CHOOSE(MONTH([End Date]),31,28,31,30,31,30,31,31,30,31,30,31) &”/” & MONTH([End Date])&”/”&YEAR([End Date]))

Day Name of the week : e.g Monday, Mon

=TEXT(WEEKDAY([Start Date]), “dddd”)

=TEXT(WEEKDAY([Start Date]), “ddd”)

The name of the month for a given date – numbered for sorting – e.g. 01. January:

=CHOOSE(MONTH([Date Created]),”01. January”, “02. February”, “03. March”, “04. April”, “05. May” , “06. June” , “07. July” , “08. August” , “09. September” , “10. October” , “11. November” , “12. December”)


Get Hours difference between two Date-Time :

=IF(NOT(ISBLANK([End Time])),([End Time]-[Start Time])*24,0)
Date Difference in days – Hours – Min format : e.g 4days 5hours 10min :

=YEAR(Today)-YEAR(Created)-IF(OR(MONTH(Today)<MONTH(Created),AND(MONTH(Today)=MONTH(Created),DAY(Today)<DAY(Created))),1,0)&” years, “&MONTH(Today)-MONTH(Created)+IF(AND(MONTH(Today)<=MONTH(Created),DAY(Today)<DAY(Created)),11,IF(AND(MONTH(Today)<MONTH(Created),DAY(Today)>=DAY(Created)),12,IF(AND(MONTH(Today)>MONTH(Created),DAY(Today)<DAY(Created)),-1)))&” months,“&Today-DATE(YEAR(Today),MONTH(Today)-IF(DAY(Today)<DAY(Created),1,0),DAY(Created))&” days”
You can get Get more formulas from

http://office.microsoft.com/en-us/sharepointtechnology/HA011609471033.aspx

Tuesday, March 17, 2009

RunWithElevatedPrivileges is not working - invalid/wrong security context

To fix this you need to get a news ite reference

SPSecurity.RunWithElevatedPrivileges(delegate()

{

//Gets a new security context using SHAREPOINT\system
//or by using (SPSite oSite = new SPSite(this.Page.Request.Url.ToString()))

using(SPSite oSite = new SPSite(SPContext.Current.Site.ID))
{
   using (SPWeb oWeb = oSite.OpenWeb())
   {
    oWeb.AllowUnsafeUpdates = true;
    // Add a record to the new list
    SPList oList = oWeb.Lists["myListName"];
    if (oList != null)
   {
    SPListItem item = oList.Items.Add();
    item["Title"] = "new item";

    // item.update to committ
    item.Update();
    }
 }
}
});

Thursday, March 12, 2009

How to integrate Google Map

To integrate Google Map with MOSS is very easy, you only need to add to content editor web part with some piece of HTML. For more information see following url

http://vspug.com/bobbyhabib/2007/12/05/create-a-google-map-web-part-for-free/

Monday, March 9, 2009

How to modify the values of "Created By", "Modified By" columns in SharePoint lists

SPSite oSite = new SPSite("http://portal");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["mylist"];
SPListItemCollection oListCollection = oList.Items;
foreach (SPListItem oListItem in oListCollection)
{
SPFieldUserValue oUser = new SPFieldUserValue(oWeb, oWeb.CurrentUser.ID, oWeb.CurrentUser.LoginName);

// or you can hard code the value like this,

SPFieldUserValue oUser = new SPFieldUserValue(oWeb, 14, "Ashish Kanoongo");
oListItem["Author"] = oUser;//created by - "14;#Ashish Kanoongo"
oListItem["Editor"] = oUser;//modified by - "14;#Ashish Kanoongo"
oListItem.Update();
}
oWeb.Update();

Sunday, March 1, 2009

How to create Custom Aspx Page in Sharepoint

For creating custom aspx page in Sharepoint follow the steps

  1. First, create a Class Library project in vs 2005/2008.
  2. Add Microsoft.SharePoint dll reference
  3. Create a file called HelloWorld.aspx or or you can create a sepeate code behind .cs file but add code into you
  4. Sign a strong key and build the project.
  5. Add the assembly into GAC
  6. Create a folder for example say 'test' and then Copy the HelloWorld.aspx to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\Test
  7. Now run the page as http://portal/_layouts/Test/HelloWorld.aspx
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
         Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase"  %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
  protected override void OnLoad(EventArgs e) {
    //SPWeb site = SPContext.Current.Web;
    SPWeb site = this.Web;
    lblSiteTitle.Text = site.Title;
    lblSiteID.Text = site.ID.ToString().ToUpper();
  }
</script>

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">
  <table border="1" cellpadding="4" cellspacing="0" style="font-size:12">
    <tr>
      <td>Site Title:</td>
      <td><asp:Label ID="lblSiteTitle" runat="server" /></td>
    </tr>
    <tr>
      <td>Site ID:</td>
      <td><asp:Label ID="lblSiteID" runat="server" /></td>
    </tr>
  </table>
</asp:Content>

<asp:Content ID="PageTitle" contentplaceholderid="PlaceHolderPageTitle" runat="server">
 Hello World
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
             contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
 Page Title 'Hello World' of Application Page
</asp:Content>

Friday, February 20, 2009

How to display custom context menu in SharePoint list or Document library?

Standard  context menu is the drop down menu displayed when a document library item or a list item is selected.














Whevever this menu is executes, it used JavaScript file which located in “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\OWS.js.

OWS.js also allows users to implement custom menu options that can be used to create a custom menu in the context menu.

Or you can use a content editor web part can be used to implement the same if the context menu is required only in a particular site collection.

Add a content editor web part for the library or the list for which the context menu needs to be implement. Then click on the link that says open the tool and pane which opens up the tool pane. In the Source Editor Web part add the following JavaScript code to add following custom menu for a Document Library

<script language="javascript">
function Custom_AddDocLibMenuItems(m, ctx)
{
var strDisplayText = "Navigate to Yahoo";
var strAction = "STSNavigate('http://www.Yahoo.com’)";
var strImagePath = "";
// Add our new menu item
CAMOpt(m, strDisplayText, strAction, strImagePath);

// add a separator to the menu
CAMSep(m);

// false means that the standard menu items should also be rendered
return false;
}
</script>

Save the script and check the Hidden option in the Layout section of the tool pane, now see te context menu















We have seen that how we can add custom context menu for a Document Library, with Custom_AddDocLibMenuItems function, if you want to add custom context menu for a list then use Custom_AddListMenuItems function in place of Custom_AddDocLibMenuItems function.

Wednesday, February 11, 2009

Access Denied during MOSS Crawling

I seen varius people facing a common proble during MOSS crawling and they got following problem

Access is denied. Verify that either the Default Content Access Account has access to this repository, or add a crawl rule to crawl this repository. If the repository being crawled is a SharePoint repository, verify that the account you are using has "Full Read" permissions on the SharePoint Web Application being crawled. (The item was deleted because it was either not found or the crawler was denied access to it.)

To fix this with Microsoft KB article, follow the steps

1. Click Start, click Run, type regedit, and then click OK.
2. In Registry Editor, locate and then click the following registry key:
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
3. Right-click Lsa, point to New, and then click DWORD Value.
4. Type DisableLoopbackCheck, and then press ENTER.
5. Right-click DisableLoopbackCheck, and then click Modify.
6. In the Value data box, type 1, and then click OK.
7. Quit Registry Editor, and then restart your computer.

Thursday, February 5, 2009

How to Download all files from SharePoint Library?

Using following code we can download all the documents including Subfolders.

SPList list = web.Lists["Shared Documents"];
SPView view = list.Views["All Documents"];
SPQuery squery = new SPQuery(view);
squery.ViewAttributes = “Scope=\”Recursive\”";
SPListItemCollection items = list.GetItems(squery);

//Read all documents and write those files to Local Machine
foreach (SPListItem item in items)
{
byte[] binfile = item.File.OpenBinary();
FileStream fstream = new FileStream(”F:\\” + item.File.Name, FileMode.Create, FileAccess.ReadWrite);
fstream.Write(binfile, 0, binfile.Length);
fstream.Close();
}

Monday, January 5, 2009

How Can I Show All Items with/without Folders in SharePoint?

To implement this we have 3 options

Option 1
Using SPQuery object and setting ViewAttributes property in it; You can retrieve only the folders from the SharePoint List, with a single condition.

SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["Shared Documents"];
SPQuery query = new SPQuery();
//Condition to check the item type is folder or not
query.Query = "<Where><Eq><FieldRef Name=’FSObjType’/><Value Type=’Lookup’>1</Value></Eq></Where>";

//Get all the items including subfolders from the list
query.ViewAttributes = “Scope=’RecursiveAll’";
//Retrieve the items based on Query SPListItemCollection items = list.GetItems(query);


string folderDetails="";
//Get the name and Url for the folder
foreach (SPListItem item in items)
{
folderDetails += "Folder Name:" + item.Name + "<br/>Folder URL:" + web.Url + "/" + item.Url + "<br/>";
}

In Query property of SPQuery object, You can set 0 for folder (if item type  = folder) or 1 for List Item/Documents(if ItemType=List Item).

We have set Scope=’RecursiveAll’, which allows to retrieve all the items and folders from the list or library.

Option 2
1. Open Data Source Details pane in Menu > Task Panes > Data Source Details.
2. Click the data source listed in Current Data Source.
3. In the opening Data Source Properties pane, change the item and folder scope from Files Only to Recursive
4. Save and exit.


Option 3
Other than dataview webpart you can also set options directly in views also. To implement this we can take example of "All Documents", follow the steps1. Select "All Documents" view
2. Select "Modify This View"
3. Scroll down whole page
4. Expand Folders
5. Then select "Show all items without folders"
6. Click OK button