Wednesday, December 23, 2009

Free Microsoft Office 2010 Book

 

Download the free e-book “First Look: Microsoft Office 2010” from here

http://blogs.msdn.com/microsoft_press/archive/2009/12/09/free-e-book-first-look-microsoft-office-2010.aspx

Wednesday, December 02, 2009

The current farm uses database from the following SQL server(s) whose versions are not supported.

 

While upgrading from MOSS 2007 to SharePoint 2010, you might get the following error-

 

The current farm uses database from the follwoing SQL server(s) whose versions are not supported.


SharePoint requires these SQL server(s) to be upgraded to minimum supported version before you can continue. Refer to the log file of this configuration wizard for more information about the minimum supported SQL versions and download instructions.

 

To fix this you need to install cumulative updates for SQL Server 2008 SP1
http://support.microsoft.com/kb/970315

Steps to change Virtual Directory Local Path for a MOSS WebAppications and Central Admin site

 

One of easiest way to move Web Application virtual path is to delete the Web application(only IIS site) from Central Administration and recreate them again using new path. But you cannot move Central Admin site using this approach.

After goggling for sometime, I found this nice article which describes the steps to move SharePoint sites including Central Admin

The link is http://www.mattjimison.com/blog/2009/02/26/how-to-change-the-iis-path-for-a-sharepoint-web-application/\

Monday, November 30, 2009

Install SharePoint 2010 on Windows 7(64-bit):

 

SharePoint 2010 provide functionality to install SharePoint 2010 on Windows7. Follow these steps to install on Windows7(64-bit):

1.      Install SQL Express 2008 from "http://www.microsoft.com/express/sql/download/”

2.     Download SharePoint 2010 Beta from http://technet.microsoft.com/en-us/evalcenter/ee388573.aspx. Copy the exe to the folder C:\SharePointFiles

3.      Open Command prompt and run

c:\SharePointFiles\ en_sharepoint_server_2010_beta_x64_x16-19249.exe /extract:c:\SharePointFiles

4.      Open the file using notepad “c:\SharePointFiles\files\Setup\config.xml”

5.      Add <Setting Id="AllowWindowsClientInstall" Value="True"/> to the Configuration section

6.      Install the Filter Pack from C:\SharePointFiles\PrerequisiteInstallerFiles\FilterPack\ FilterPack.msi

7.      Install the following softwares:

 

8.      Run following command to Install Windows Features(IIS and other related)

 

start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;

IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;

IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;

IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;

IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;

IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;

IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;

IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;

IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;

WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;

WCF-NonHTTP-Activation

 

 

9.      Run “c:\SharePointFiles\Setup.exe” to install SharePoint

10.   On “Choose the installation you want page”, click Standalone

11.   Choose default settings and complete the installation

12.   Now, run RegEdit and browse to “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\WSS”

13.   Change “ServerRole” value from SINGLESERVER to WFE

14.   Start the “the SharePoint Products and Technologies Configuration Wizard” and follow the steps to install SharePoint 2010

Thursday, November 26, 2009

Sandboxed Solution in SharePoint 2010

 

SharePoint 2010 comes with a great feature – Sandboxed Solution. This is type of solution which could be deployed to a site by a site administrator. A site administrator don’t need to be a farm administrator to deploy the solution. The solution have full access to the site where it is deployed but limited to other sites and resources for security reason.

This would be ideal for SharePoint Online services where you could create multiple sites and give user permission to manage and upload custom code to their site without needing assistance from farm administrator

To create a sandboxed solutions:

  1. Create a new SharePoint project in VS 2010
  2. On SharePoint Customisation Wizard, enter your Site URL. Select “Deploy as a sandboxed solution” as trust level
  3. Click Finish and start adding your artifacts to the project
  4. Build the solution and create WSP package
  5. Browse to your site
  6. Open Site Actions – Site Settings
  7. Under the Galleries section, select solutions
  8. On the Solution page, upload the solution

Untitled

Now, you could add your artifacts(web parts, activate features) specific to your site

Safe List object from SPWeb in SharePoint 2010

 

If MOSS 2007, the code to read the list object use to be

SPWeb web;
SPList list = null;
try
{
list = web.Lists[“Pages”] }
catch(Exception ex)
{
// List not found
}

The reason to have a try-catch was because SharePoint would throw an exception if the list does not exist

Glad to see that in SharePoint 2010, this issue is fixed. The code in SharePoint 2010, would be

SPWeb web;
SPList list = web.Lists.TryGetList(“Pages”)

TryGetList returns the list with the specified title from the list collection, but returns null if its not found. No more more error handling is required

Monday, November 23, 2009

Using Linq To SharePoint in 2010

 

SharePoint 2010 comes with SpMetal tool that auto-generate entity types based on a list definition. It uses the SharePoint Lists web service to get the schema of a list.

This tool is located at c:\program files\common files\microsoft shared\web server extensions\14\bin

The syntax is

spmetal.exe /web:SITE-URL /namespace:YOUR_NAMESPACE /code:CLassName.cs

Microsoft.Sharepoint.Linq Assembly

 

This is not installed in GAC and hence would not be visible in .NET assembly tab when adding a new reference to project. This is located under at “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI”

Data View Web Part in SharePoint 2010

 

This web part have been replaced by XSLT List View Web part in SharePoint 2010. The old Data View Web part is still supported in SharePoint 2010 but not recommended to use.

Developer Dashboard in SharePoint 2010

 

SharePoint 2010 comes up with great tool to check the performance and process steps(same like ASP.NET trace). This would enable the following information to be displayed:

· The SQL queries they have and their timings.
· Web Part Events Offsets for testing performance against custom web parts.
· Trace information, usually only found in the ULS logs, now available on the page.
· A tree view of all controls on the page.
· Session and Cookie information

To enable it, follow these steps:

  • Enable Developer Dashboard- Run this command “stsadm.exe" -o setproperty -pn developer-dashboard -pv OnDemand”
  • Do IISReset
  • Activate Developer dashboard by clicking on the icon in the top right corner of the browser window of your site
  • This will refresh the browser and display the tool bar at the bottom of the page. Click on the Show or hide additional tracing information link at the bottom for detail trace information

Friday, November 20, 2009

Update Parent Content Type

 

When you update a parent content type, the following consideration need to be taken account:

  1. Settings of child content type column would be overridden by setting of parent content type column
  2. If you make some changes in parent content type and don’t push them down to child content type, these changes would not be pushed to child content type on later stage.
  3. If you delete any column in child content type, they are not created again when you push changes from Parent content type
  4. Read-only and Sealed child content type will not be updated and an error would raise

Error “Attempting to load a 64-bit application, however this CPU is not compatible with 64-bit mode"

 

This error occurs when you are trying to create a 64 Bit operating system VMware.

To fix this, restart your machine and enter your system BIOS. Look for Virtualization property and enable it. This is disabled by default.

Installing SharePoint 2010 on Microsoft Virtual PC

 

You can't install SharePoint 2010 on Microsoft Virtual PC as it needs 64 bit Platform. As of now, Microsoft Virtual PC don’t support 64 bit operating system guest.

To overcome, you need to use VMWARE as Windows 2008 64 Bit could be installed on VMware Client.

Upgrade Vista 32 Bit to 64 Bit Windows 7

 

If you try to install Windows 7 64-bit on 32-bit Vista, the following error would occur:

The Version of this file is not compatible with the version of Windows you're running.

The issue is you can’t do a direct in-pace upgrade from 32-bit to 64-bit Windows 7. The only way to do a clean install. Follow the below steps:

  1. Backup manual data from your machine
  2. Backup the application settings and user documents\pictures etc using Windows Easy Transfer(http://www.microsoft.com/windows/windows-vista/features/easy-transfer.aspx)
  3. Create a bootable DVD or USB using Windows 7 USB/DVD Download tool(http://download.cnet.com/Windows-7-USB-DVD-Download-Tool/3000-18513_4-10972600.html)
  4. Restart the machine and access BIOS(using F12 or other key as per your machine). Change the Boot sequence to use DVD\USB as the first option
  5. Restart the machine, Windows7 setup should start now
  6. Select “Custom” installation option and follow the instructions
  7. Install and activate Windows 7

Enjoy the wonderful experience of Windows 7

Tuesday, November 17, 2009

Update SharePoint List LookUp field

To update a lookup field in SharePoint, you need to use SPFieldLookupValue constructor

The format is

Item[“LookupField”] = new SPFieldLookupValue(ITEM_ID, ITEM_TITLE);

Create a blank page in Pages Library

You need to perform these steps:

Get a blank page from file system or using the below function

StringBuilder sb = new StringBuilder();
sb.Append("<%@ Page Inherits=\"Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,");
sb.Append("Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c\" %> <%@ Reference VirtualPath=\"~TemplatePageUrl\" ");
sb.Append("%> <%@ Reference VirtualPath=\"~masterurl/custom.master\" %><html xmlns:mso=\"urn:schemas-microsoft-com:office:office\" ");
sb.Append("xmlns:msdt=\"uuid:C2F41010-65B3-11d1-A29F-00AA00C14882\"><head>&nbsp;<!--[if gte mso 9]><xml>");
sb.Append("<mso:CustomDocumentProperties><mso:PublishingContact msdt:dt=\"string\">1218</mso:PublishingContact>");
sb.Append("<mso:display_urn_x003a_schemas-microsoft-com_x003a_office_x003a_office_x0023_PublishingContact ");
sb.Append("msdt:dt=\"string\">avanade</mso:display_urn_x003a_schemas-microsoft-com_x003a_office_x003a_office_x0023_PublishingContact>");
sb.Append("<mso:PublishingContactPicture msdt:dt=\"string\"></mso:PublishingContactPicture>");
sb.Append("<mso:PublishingContactName msdt:dt=\"string\"></mso:PublishingContactName>");
sb.Append("<mso:ContentTypeId msdt:dt=\"string\">0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390064");
sb.Append("DEA0F50FC8C147B0B6EA0636C4A7D40073BD3FF4186E874380ADB2C06F742F8E</mso:ContentTypeId>");
sb.Append("<mso:Comments msdt:dt=\"string\"></mso:Comments>");
sb.Append("<mso:PublishingContactEmail msdt:dt=\"string\"></mso:PublishingContactEmail>");
sb.Append("<mso:PublishingPageLayout msdt:dt=\"string\">/_catalogs/masterpage/BlankWebPartPage.aspx, ");
sb.Append("Blank Web Part Page</mso:PublishingPageLayout>");
sb.Append("</mso:CustomDocumentProperties>");
sb.Append("</xml><![endif]--><title></title></head>");
Byte[] blankPage = ASCIIEncoding().GetBytes(sb.ToString());

 

Now, add this blank page to the Pages Library

SPList list = web.Lists["Pages"];

SPFile file= list.RootFolder.Files.Add(“blankpage.aspx”, blankPage);

Monday, November 16, 2009

SharePoint Online

This comes in two offerings:

Standard Offering

Dedicated Offering

Multiple customers share a common infrastructure

Each customer has its own infrastructure

Customer priority: rapid deployment

Customer priority: heavy customization

No lower seat limit

For customers with more than 5000 seats

Cost efficiency optimized for customers with up to 20,000 users

Optimized for customers with 20,000+ users

The dedicated offering support custom code including SharePoint Packages

For developing on SharePoint Online Services, check this white paper which describes the customization (or extensibility) capabilities that are supported with the Standard offering of SharePoint Online-

Microsoft SharePoint Online Standard Developer Guide (http://www.microsoft.com/downloads/details.aspx?familyid=d007f35e-375c-4b11-bc40-bc9082bb224a&displaylang=en&tm)

Microsoft Online Services

Seeing the prospect and future in cloud computing, Microsoft have moved rapidly in BPOS(Business Productivity Online Suite). This Suite contains of:

  • SharePoint Online
  • Exchange Online
  • Office Communicator Online
  • Office Live meeting

The next product to add to this suite would be Dynamics CRM. Having SharePoint online using Microsoft Live services is a great initiate as this would help to target small to medium customer. These customer who wants to have a presence on web would vastly benefit from this cost effective, secure and reliable server.

For more details check http://www.microsoft.com/online/default.mspx and try 30 days trial

Follow the Microsoft Online Service team on their blog at http://blogs.technet.com/msonline/default.aspx

Friday, August 28, 2009

Get WorkFlow Task Item from List Item Id

 

        public static SPListItem WorkflowTaskItemBasedOnListItem(SPWeb web, string listName, string workflowTaskListName, int itemId)
        {
            SPListItem workflowItem = null;
            SPList workflowTasks = web.Lists[workflowTaskListName];
            SPList mainList = web.Lists[listName];
            SPListItem listItem = mainList.GetItemById(Convert.ToInt32(itemId));
            SPWorkflowFilter filter = new SPWorkflowFilter();
            filter.InclusiveFilterStates = SPWorkflowState.Running;
            // Get a list of workflow tasks associated with current Item
            SPWorkflowTaskCollection workTaskColl = web.Site.WorkflowManager.GetItemTasks(listItem, filter);
            foreach (SPWorkflowTask task in workTaskColl)
            {
                if (task != null)
                {
                    workflowItem = workflowTasks.GetItemById(task.ID);
                    break;
                }
            }

            return workflowItem;
        }

 

This function returns a workflow item based on Parent List item Id. It reads the List Item and finds the associated workflow which are still running against this list item.

Type 'Microsoft.SharePoint.SPUser' in Assembly 'Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' is not marked as serializable. Type 'Microsoft.SharePoint.SPUser' in Assembly

Make sure you are not storing any object of SPUser type in Session on ViewState. I was getting this error SPUser was persist in ViewState. We changed the logic to store LoginName and everything worked fine

The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again

Recently, I was getting this error when non-admin were trying to alter a workflow task. My code was running under elevated permission using the option first as described in my last post(using SharePoint\System) user

To fix, I need to run the code under elevated permission using second option as described in my last post(RunWithElevatedPrivileges)


    string siteURL = SPContext.Current.Site.Url;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        SPSite objSite = new SPSite(siteURL);
        SPWeb web= objSite.OpenWeb();

        web.AllowUnsafeUpdates = true;

        Hashtable taskHash = new Hashtable();
        SPListItem item = null;
        item["Status"] = "Completed";
        SPWorkflowTask.AlterTask(item, taskHash, false);
        web.AllowUnsafeUpdates = false;
    });

Running Code with Elevated Permissions

 

There are 2 ways to run code under elevated permissions. The first one is using the token created from SharePoint\System(internal user) user

public static SPWeb GetElevatedWeb
        {
            get
            {
                var superUser = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
                var superToken = superUser.UserToken;
                using (var site = new SPSite(SPContext.Current.Web.Url, superToken))
                {
                    return site.RootWeb;
                }
            }
        }

This function returns a SPWeb object which is created using elevated permissions

The second method is using SPSecurity.RunWithElevatedPrivileges

public static SPWeb GetSPElevatedWeb
        {
            get
            {
                SPWeb web = null;
                string siteURL = SPContext.Current.Site.Url;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite objSite = new SPSite(siteURL);
                    web = objSite.OpenWeb();
                });
                return web;
            }
        }

The SPSite object is created by reading the SPContext object before calling RunWithElevatedPrivileges as the context will change in the code block

Monday, August 03, 2009

Create custom groups in SharePoint

To create custom groups in SharePoint, use the SPWeb SiteGroups collection.

web.SiteGroups.Add(groupName, owner, member, description)

Groups created using code will not automatically appear in left navigation. For them to appear there, the groups need to be associated with web. The code to this is

web.Properties["vti_associategroups"] = web.Properties["vti_associategroups"] + “;” +  web.SiteGroups[groupName].ID.ToString();

web.Properties.Update();

Function to read List Item Id based on task

taskListItemId = id of task item

web = Web object

SPListItem taskItem = taskList.GetItemById(taskListItemId);
Guid workflowInstanceId = new Guid((string)taskItem["WorkflowInstanceID"]);
SPWorkflow workflowInstance = new SPWorkflow(web, workflowInstanceId);
SPList itemList = workflowInstance.ParentList;
SPListItem parentListItemId = itemList.GetItemById(workflowInstance.ItemId);

Other way of getting Elevated Web

SPUser superUser = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
string superToken = superUser.UserToken;
using (var site = new SPSite(SPContext.Current.Web.Url, superToken))

      return site.RootWeb; 
}

This function would return a web object running under the super user “SharePoint\System” (inbuilt) account

Retrieve the attachments of List Item

To retrieve the attachment, access the folder object of the item and then read the files

SPFolder folder = Web.Folders["Lists"].SubFolders[listName];

folder = folder.SubFolders["Attachments"].SubFolders[itemNo];
foreach (SPFile file in folder.Files)
{
}

Read AD SPUser in SharePoint

Web object’s AllUsers property returns user which have accessed the site. To validate a user which has never existed on the site use

Web.EnsureUser(strUserLogin);

Add\remove Quick launch link

       Add a quick launch link group

     public static void AddQuickLaunchGroup(SPWeb web, string groupName)
        {
            SPNavigationNodeCollection quickLaunchNodes = web.Navigation.QuickLaunch;
            SPNavigationNode groupMenu = new SPNavigationNode(groupName, "", false);
            quickLaunchNodes.AddAsFirst(groupMenu);
            web.Update();
        }

        Remove quick link group-

        public static void RemoveQuickLaunchGroup(SPWeb web, string groupName)
        {
            SPNavigationNodeCollection quickLaunchNodes = web.Navigation.QuickLaunch;
            foreach (SPNavigationNode node in quickLaunchNodes)
            {
                if (string.Compare(node.Title, groupName) == 0)
                {
                    quickLaunchNodes.Delete(node);
                    web.Update();
                    break;
                }
            }
        }

        Add Quick launch link to a group-


        public static void AddQuickLaunchLink(SPWeb web, string groupName, string linkName, string linkUrl)
        {
            SPNavigationNodeCollection quickLaunchNodes = web.Navigation.QuickLaunch;
            foreach (SPNavigationNode node in quickLaunchNodes)
            {
                if (string.Compare(node.Title, groupName) == 0)
                {
                    SPNavigationNode linkNode = new SPNavigationNode(linkName, linkUrl, true);
                    node.Children.AddAsFirst(linkNode);
                    web.Update();
                    break;
                }
            }
        }

        Remove quick launch link from a group-


        public static void RemoveQuickLaunchLink(SPWeb web, string groupName, string linkName)
        {
            SPNavigationNodeCollection quickLaunchNodes = web.Navigation.QuickLaunch;
            foreach (SPNavigationNode node in quickLaunchNodes)
            {
                if (string.Compare(node.Title, groupName) == 0)
                {
                    foreach (SPNavigationNode nodeChild in quickLaunchNodes)
                    {
                        if (string.Compare(nodeChild.Title, linkName) == 0)
                        {
                            node.Children.Delete(nodeChild);
                            web.Update();
                            break;
                        }
                    }
                }
            }
        }

Add field to default view in SharePoint List

SPView view = list.DefaultView;
view.ViewFields.Add(fieldName);
view.Update();

Create a Lookup field in SharePoint list

/// <summary>
/// Adds the lookup field to list.
/// </summary>
/// <param name="web">The web.</param>
/// <param name="list">The list.</param>
/// <param name="fieldName">Name of the field.</param>
/// <param name="lookupListName">Name of the lookup list.</param>
/// <param name="lookupFieldName">Name of the lookup field.</param>

SPField AddLookupFieldToList(SPWeb web, SPList list, string fieldName, string lookupListName, string lookupFieldName)
        {
            SPList destList = web.Lists[lookupListName];
            list.Fields.AddLookup(fieldName, destList.ID, required);
            SPFieldLookup field = list.Fields[fieldName] as SPFieldLookup;
            field.LookupField = destList.Fields[lookupFieldName].InternalName;
            field.Update(true);
            return field;
        }

Create a User field in SharePoint List

SPList list;

list.Fields.Add(fieldName, SPFieldType.User, required);
SPFieldUser field = list.Fields[fieldName] as SPFieldUser;
field.SelectionMode = SPFieldUserSelectionMode.PeopleOnly;
field.AllowMultipleValues = false;
field.Presence = true;
field.Update(true);

Tuesday, June 23, 2009

The selection of directory service properties is disabled because the portal is in an untrusted domain

In User Profile, I was unable to modify any user property mapping due to missing Data Source field dropdown. There was no question of untrusted domain as I am using only one active directory and SharePoint was able to import from that. I finally managed to fix these by following these steps:

  • Goto to Profile and Import Settings
  • Click View Import Connections
  • Click on Existing Import Connection and select edit
  • In Authentication Information section, make sure the account is SharePoint Admin Domain account and not the default account
  • Click Ok and you should now able to see mapping data source drop down

Tuesday, April 07, 2009

Delete a Web Part in SharePoint

If you are planning to remove a web part from a page, ALWAYS click on Delete menu rather than pressing the X button. Clicking on X button would close the web part and you will receive a warning in your servers event log. The web part is not actually deleted from the page, it is removed from the Visible area of the page and placed in the Web Part Page Gallery.

You can delete a CLOSED web part  by using the Web Part Maintenance page. Browse to http://www.yourserver.com/yoursite/yourpage.aspx?contents=1

You could see the web part that has been closed. Now, delete it by selecting the checkbox and pressing Delete

Accessing Current User in MOSS

You could get the current user in SharePoint by calling the following code:

SPUser user = SPContext.Current.Web.CurrentUser;

But to access the current user inside the code running under Elevated Privileges, open new reference to SPSite.

SPSecurity.RunWithElevatedPrivileges(delegate()

{
    using (SPSite site = new SPSite(“http:\\MOSS_SITE”))

{
      using (SPWeb web = site.OpenWeb())

          SPUser user =SPContext.Current.Web.CurrentUser;

    }

}
);

The above code will switch the user context and now, you would get the user under which application pool is running

Mystery of SharePoint\System Account

When you run your code with Elevated Privileges, the code runs under the identity of the hosting application pool. SharePoint\System account exists ONLY within content of SharePoint runtime(not recognised by Windows Security subsystem) and map internally to the account under which application pool is running.

If you are running application pool under DOMAIN\SSUSER account, the code is still audited as running under SharePoint\System account. So, if you get access error on SharePoint site stating that SharePoint\System account don’t have access to the resource, this is because the application pool identity account don’t have access to the resource. Don’t spend time looking for SharePoint\System account :-)

Friday, April 03, 2009

Set Manager Profile property value

To assign manager from one profile to another, you could not set it directly. You need to convert the Source Manager profile to a UserProfile object and then assign the account name to the destination profile manager’s property.

UserProfileManager upManager;
UserProfile sourceProfile,
destProfile;

string managerId = sourceProfile["manager"].Value.ToString();

if (upManager.UserExists(managerId))

{

UserProfile managerProfile = upManager.GetUserProfile(managerId);

destProfile["manager"].Value = managerProfile["Accountname"].Value;

}

Tuesday, March 31, 2009

Change the Regional Setting of Site

You could change the regional setting of the site by browsing to Site Actions > Site Settings > Regional Settingsimage

You could also change the Locale using the following code:

using (SPSite site = new SPSite("http://SITE"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPRegionalSettings newRegionalSettings = new SPRegionalSettings(web);

        // Change to Australia
        newRegionalSettings.LocaleId = 3081; 
        web.RegionalSettings = newRegionalSettings;
        web.Update();
    }
}

Friday, March 27, 2009

In-Line Script in SharePoint Page

You could add in-line script to a SharePoint page or Page template.

<asp:Content ID="main" runat="server"  ContentPlaceHolderID="PlaceHolderMain">
<% Response.Write("Hello Sanjay Sansanwal"); %>
</asp:Content>

You would able to access this page without error provided this page is ghosted(uncustomised) as WSS complies a ghosted page into an assembly DLL for processing.

But if you customise this page or open in SharePoint,  SharePoint safe mode don’t allow this and you would get error “Code blocks are not allowed in this file”.

You could force SharePoint to allow in-line scripts in customised pages by adding following to the web.config

<SharePoint>
  <SafeMode ... >
    <PageParserPaths>
      <PageParserPath
          VirtualPath="/Study/CustomPages/*"
          IncludeSubFolders="true"
          CompilationMode="Always"
          AllowServerSideScript="true" />
    </PageParserPaths>
  </SafeMode>
</SharePoint>

Note: You should avoid doing this as it compromise SharePoint security. In-Line scripts are not allowed in customised pages so that unwanted user could not write malicious code to hack the system.

Add a custom menu to the list

Change the elements.xml described in last blog posting to add a menu item to the menu which appears when you edit a document item


<CustomAction Id="ListMenuForMyPage"
  RegistrationType="List"
  RegistrationId="101"
  ImageUrl="/_layouts/images/GORTL.GIF"
  Location="EditControlBlock"
  Sequence="105"
  Title="My Page" >

  <UrlAction Url="~site/_layouts/CustomPages/MyPage.aspx?ItemId={ItemId}&amp;ListId={ListId}"
    />
</CustomAction>

This CustomAction element is different than what you have seen before because it has a RegistrationType attribute that is assigned a value of List. It also is configured with a RegstrationID attribute that is assigned a value of 101. Note that 101 is a list type identifier that applies to all document libraries. You should also notice that the Location attribute has a value of EditControlBlock, which creates the effect of adding the menu item to the ECB menu of documents within a document library.

Note the {ListId} token and the {ItemId} token within the UrlAction Url’s QueryString. MOSS dynamically replaces them  with list GUID and itemId

Add Custom Action to SharePoint Site

Create a new feature which copy custom page(My Page) to the layout\CustomPages folder. Add the following in the elements.xml to create a custom action item.

<!-- Add Command to Site Actions Dropdown -->
<CustomAction Id="SiteActionsToolbar"
  GroupId="SiteActions"
  Location="Microsoft.SharePoint.StandardMenu"
  Sequence="2001"
  Title="My Page"
  Description="Browse to my custom page"
  ImageUrl="/_layouts/images/DECISION.GIF">
   <UrlAction Url="~site/_layouts/CustomPages/MyPage.aspx"/>
</CustomAction>

This would add a new menu called “My Page” to the Site Actions menu.

When creating a CustomAction element, you can configure the URL attribute of the inner UrlAction element by using the ~site token, as you have just seen. You could also use ~sitecollection token in cases in which custom page should always be executed within a URL associated with the current site collection and its top-level site.

To restrict this page to only viewable to administrator, add RequireSiteAdministrator attribute to CustomAction and set it to “True”. For more security, add the following code in the “My page” custom page -

protected override bool RequireSiteAdministrator {
    get { return true; }
  }

Find PublicKeyToken of signed assembly

To find the publickeytoken of an assembly, I use to drag and drop the assembly to C:\Windows\Assembly folder and then view the properties.

The better way is to use SN.EXE located under “C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin” folder.

You could integrate this tool into VS IDE using external tool features.

  1. In Visual Studio 2005, click Tools -> External Tools...
  2. Click Add and enter the following into the different fields as displayed in the following screenshot:
    • Title: Get Public Key
    • Command: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe
    • Arguments: -Tp "$(TargetPath)"
    • Uncheck all options, except Use Output window\

Now, you have a new entry listed in the Tools menu titled Get Public Key as shown in the following screenshot:

image

 

 

 

 

Assuming you have a project open that has been configured to be signed when built, and you've built it at least one time, selecting the new Get Public Key menu item from the Tools window to get the public key token and blob in the Output window.

image 

 

 

 

Here you have assembly publictokenkey in second entry

Missing Create GUID Tool from Visual Studio 2005

I created a new VM and installed Visual studio 2005. To my horror, I could not found the Create GUID tool in Visual Studio.The Create GUID tool is often found under the Tools menu.

To fix this, I performed the following steps:

  • Reset my IDE settings.
    Select "Tools --> Import and Export Settings --> Reset All Settings" to restore the defaults. Woh, I could see the Create Guid in tool. But, it was disabled :-(

The actual file for generating GUID is guidgen.exe which would be located at “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools”.

I realised that this file is missing as I didn’t installed Visual C++. I was trying to be smart :-)

Wednesday, March 25, 2009

MOSS Filter web parts Not found

To add filter web part to your web part list:

1. Click on the new button in the web-part gallery and select the correct classes from web part gallery

2. If you can’t find them in web part gallery, upload the Web Part definition files from %CommonProgramFiles%\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\BizAppsSiteTemplates\dwp.

For more information about Filter web part Click here

Filter MOSS custom list view based on User Profile properties

MOSS 2007 comes with a number of filter web parts that makes it really easy to filter your SharePoint lists by connecting filter web parts with list view web parts.

Note: These are only available in MOSS enterprise edition and could only be applied to “All Items” view or to view configured as “Standard View” type

I would walkthrough in this tutorial to filter a list items based on User Location (mapped to Office profile property in the User Profile repository).

Background

There are list of courses stored in a custom list called “Courses”. The requirement is to display courses only available in current logged user’s location.  The easiest way would be to create a view on the list and set the filters. Ironically, there is not inbuilt [Location] attribute like [Me] or [Today]. You could filter the view on [Me.Office] as shown below

clip_image002

The other way is to use the Current User Filter. With the Current User Filter you can filter the contents of web parts by using any property of the current user.

Steps

1.      Create a List called Courses

12

Column

Description

Type

Name of Course

Description

Detail about the course

Instructor

Name of instructor

Location

City where course would be held

2.      Add couple of items to this list with different location. Make sure one record have location same as your location. In this example, current user’s Office profile property has value as “Melbourne”.

  3

3.      As the list page is a web part page, you could easily add web parts to this using User Interface.

4.      Click Site Actions -> Edit Page

5.      On the top of the list, click “Add a new Web part” and select web part “Current User Filter”

 5

6.      Edit the newly added web part “Current User Filter” by clicking Edit -> Modify Shared Web part

7.      Click “SharePoint profile value for current user” and select “Office” from dropdown

 6

8.      Press OK.

9.      Now, we need to make a connection between this web part and courses list. On “Current User Filter” web part, click Edit -> Connections and Select Courses

 7

10.   You would be prompt with a dialog box, select the List field which need to be mapped to the User’s Office attribute.

 8

11.   Click Finish and Exit the edit mode. You would now only see the items in list which have location same as your Office.

 9