Tuesday, May 31, 2011

Sample–Using ECMAScript Client Object Model

 

Below is a sample application page which uses ECMAScript client object model to retrieve a List instance and show its Title property.

<%@ 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#" AutoEventWireup="true" CodeBehind="ECMAScriptDemoPage.aspx.cs" Inherits="ECMAScriptDemo.Layouts.ECMAScriptDemoPage" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<SharePoint:ScriptLink ID="SPScriptLink" runat="server" LoadAfterUI="true" Localizable="false" Name="SP.js" />

<script language="javascript" type="text/javascript">
var clientContext;
var web;
var oContactsList;
function onQuerySucceeded(sender, args) {
alert('Title of the List: ' + this.oContactsList.get_title());
}

function onQueryFailed(sender, args) {
alert('Request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

function retrieveContacts() {


this.clientContext = new SP.ClientContext.get_current();
this.web = this.clientContext.get_web();
this.oContactsList = this.web.get_lists().getByTitle("News");
this.clientContext.load(this.oContactsList);
this.clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));


}

</script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<input type="button" onclick="retrieveContacts()"
value="Click me to get the list!" />
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
ECMAScript Object Model Demo Page
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
ECMAScript Object Model Demo Page
</asp:Content>

Saturday, May 07, 2011

Retrieving SharePoint List data in blocks

 

To reduce the impact on the sever, you could use SPQuery object’s RowLimit property to get data from SharePoint list in blocks.

The below code shows how one could get data in block of 10s-

SPList list = web.Lists["News"];
SPQuery query = new SPQuery();
// Define the query
query.Query = "<Where><Contains><FieldRef Name=\"Title\" />
<Value Type=\"Text\">San</Value></Contains></Where>";


// Define the maximum number of results for each page (like a SELECT TOP)
query.RowLimit = 5;


do {
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items) {
}
// Set current position to make SPQuery able to set the start item of the next page
query.ListItemCollectionPosition = items.ListItemCollectionPosition;
} while (query.ListItemCollectionPosition != null);

The ListItemCollectionPosition property is of type SPListItemCollectionPosition. It offers a PagingInfo property of type String, which contains the following data:
Paged=TRUE&p_ID=10


The _ID is the unique identifier of the last item retrieved so that SharePoint can know the starting position of the next page.

Friday, April 29, 2011

Unexpected Behavior of LINQ to SharePoint

 

When using LINQ to SharePoint to query items in list folder and the folder path is invalid, the query seems to return item from all the folders recursively Sad smile

When using LINQ to SharePoint inside PageMethods, the code need to be run under elevated permissions Sad smile

Thursday, March 24, 2011

LINQ to SharePoint code under elevated permission

 

Use the following code to run your code under elevated permission…

string url = SPContext.Current.Site.Url;
HttpContext backupCtxt = HttpContext.Current;
try
{
    if (SPContext.Current != null) HttpContext.Current = null;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite sc = new SPSite(url))
        {
            using (SPWeb web = sc.OpenWeb())
            {
                HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
                using (MyDataContext dc = new MyDataContext(web.Url))
                {

                          // YOUR CODE
 
                }
            }
        }
    });
}
catch
{
    throw;
}
finally
{
    if (SPContext.Current == null)
        HttpContext.Current = backupCtxt;
}

The one thing to note is that as SPContext is recreated, you will not be able to refer this in YOUR CODE. Also, any function which is called from YOUR CODE should also not use SPContext object.

Tuesday, October 12, 2010

7 free .net books for Programmers and Architects.

Foundations Of Programming

The Foundation Of Programming Series Free e-book By Karl Seguin is one of my favorites. It is simple, short and sweet. Especially for ‘casual’ programmers, this will give a better thought process – that’ll definitely enable them to code better and think better. This book covers the ALT.NET Philosophy, Domain Driven Development concepts, DI, TDD etc in a nice way. This book is close to my heart.

Microsoft Application Architecture Guide, 2nd Edition

Published by Microsoft, this is an essential read for any Microsoft.NET developer or Architect to understand the underlying architecture and design principles and patterns for developing successful solutions on the Microsoft platform and the .NET Framework. This guide neatly covers popular architecture patterns, best practices and common challenges you need to understand for developing .NET applications. Get a good grip on developing enterprise applications in .NET.

Rob Miles C# Yellow Book 2010

A nice action packed book that takes you through C# and .NET concepts. This book explains C# language and .NET library in general – with a clear focus on implementation thought process and best practices.

Threading in C#

A short, neatly written book from Joe Albahari about Threading in C#. This is a must read for any .NET programmer to understand more about threading in general, thread pooling, synchronization, Non blocking synchronization, etc. In this book, Joe even covers the Parallel Framework Extensions and Parallel programming in .NET

Improving .NET Application Performance and Scalability

This guide is again from Microsoft, and focuses on designing your applications with Performance and scalability in mind. It has sections relevant to architects, developers, testers, and administrators. Following the checklists and guidance in this book will ensure that there won’t be any unpleasant surprises in the end. Read this guide if you develop Enterprise applications in .NET

Applying Design Patterns

This is a quick introduction towards the thought process of applying design patterns. The objective of the book is to introduce design patterns in a simple way, so that developers can understand some common patterns and how to apply them. I wrote that some time back ;)

RefCardz from DZone

DZone has a number of awesome Ref Cardz (Quick reference sheets) on multiple technologies. You can go to DZone –> RefCardz to browse and download them (after getting a free DZone Id). Here are some of my recent favorites

 

Happy learning

Thursday, July 15, 2010

Understanding and Positioning of SharePoint Server 2010 for Technical Pre-Sales Professionals Course Completed

 

Finally managed to complete this pre-sales course and got certificate of completion from Microsoft Partner Academy…

Sunday, April 18, 2010

Fix for error Sql server 2005 reporting service add-in setup interrupted

 

To use Report Viewer web part in SharePoint 2007 64-bit environment, you need to install SQL Server 2005 Add-in. I downloaded the setup from Microsoft site and ran the MSI - “SharePointRSx64”.msi. The setup failed with the error as “sql server 2005 reporting service add-in setup interrupted”.  If you are having this issue, follow these steps:

  1. Open the command window (Start>Run type cmd and press enter)
  2. Navigate to the path where the installer (SharePointRSx64.msi) is stored
  3. Execute SharePointRSx64.msi SKIPCA=1 
  4. CD to %temp%. Look for rsCustomAction.exe. If not found, browse to the parent directory
  5. Execute rsCustomAction.exe /i  to auto-configure the installed files.

Once the installation will finish, you will be able to see the Reporting Integration section in Central Administration.

Wednesday, April 07, 2010

Presentation on Service Applications in SharePoint 2010

 

Check the slide show presented by me to Melbourne SharePoint user group on Service applications in SharePoint 2010

Presentation Link

 

Thursday, March 11, 2010

Running Hyper-V Disk Images on Windows 7

 

On Windows 7 you could install Virtual PC 64 bit but unable to run a 64 Bit guest operating systems. This is quite frustrating as you could not use Hyper-V VHD provided by Microsoft on Windows 7. The lack of Microsoft virtualization application lead us to use Sun VirtualBox.

VirtualBox includes support for 64-bit guest operating systems and applications. VirtualBox supports Windows 7 as a host OS. It also has no licensing costs as it is freely available as Open Source Software under the terms of the GNU General Public License. Another important feature is that VirtualBox natively supports Microsoft Hyper-V virtual disk image files (.VHD). This feature allows us to take a virtual machine built with Hyper-V and use it on a portable machine such as a laptop or desktop computer.

 

Download VirtualBox Binaries

Sun VirtualBox is available via download from the site http://www.virtualbox.org

Create a VirtualBox Virtual Machine

Creating a new virtual machine (VM) is performed by launching the New Virtual Machine Wizard.

  • Name the VM and select the OS Type as appropriate. The OS Version selected must indicate (64 bit). If you are unable to select a version with (64 bit), this likely means the CPU in your host is not 64 bit. You will not be able to run a 64 bit guest if the host CPU is not 64 bit. If you are running Windows 2008 R2 guest, select Windows 2008 (64 bit).

  • Select an appropriate memory allocation. The recommendation for a SharePoint 2010 server is 4096. Be sure to leave adequate memory for the host OS.

  • When configuring the disk, you need to specify the existing .VHD file. Click the icon to launch the Virtual Media Manager and add the existing .VHD.

  • After completing the wizard, click Settings to make a few adjustments:

    • Select the appropriate Network setting – see the VM Guest Network Configuration section below for guidance

    • It is suggested to disable Audio

Start the VM and Install the Guest Additions

After first starting the VM guest, it is strongly recommended to install the VirtualBox Guest Additions to improve performance and enable mouse/keyboard transitions between host and guest.

  • Click Start to launch the VM guest

  • Login to the VM (the CTRL + ALT + DELETE key sequence is RIGHT CTRL + DELETE)

  • If you need to release the mouse, press RIGHT + CTRL

  • At this time, ignore error messages indicating failure to load device drivers (installing the Guest Additions will take resolve these failures)

  • When prompted to restart the computer to apply changes, click Restart Now

  • Login again

  • Install the Guest Additions by clicking Devices, Install Guest Additions… (or pressing RIGHT + CTRL + D). When prompted, select Run VBoxWindowsAdditions.exe. Accept all defaults and accept prompts to install Sun Microsystems device drivers.

  • Restart when prompted

  • Login again

  • If desired, adjust the display resolution

  • If you have Internet connectivity, run Windows Update and install the latest security updates

  • Adjust the time zone as appropriate

Wednesday, March 10, 2010

Office 2010 and SharePoint 2010 planned for launched on 12th May

Watch Stephen Elop, President of the Microsoft Business Division, announce the launch of Office 2010 and SharePoint 2010 on May 12, 2010 at 11 a.m. EST. The live keynote focuses on the next wave of productivity that delivers:

End user productivity across the PC, phone and browser
IT choice and flexibility
A platform for developers to build innovative solutions
Join the virtual launch event with Microsoft executives, product developers, partners and customers to:

Find out how peers and partners are already seeing benefits to their business by leveraging the next wave of productivity.
Submit your questions through live Q&A.
Participate via blogs, tweets, social media networks, commenting, and more.
View on-demand breakout sessions showing how Office 2010 and SharePoint 2010 meet the unique challenges people and businesses are faced with today, and provide the solutions they need for tomorrow.

http://sharepoint.microsoft.com/businessproductivity/proof/pages/2010-launch-events.aspx#fbid=DI4gkPybuyL

Friday, February 26, 2010

Application variables empty in classic ASP when deployed on IIS 7.0

 

Last week, I went back in time when one of my friend asked me to help on his site developed in classic ASP. He wanted to deploy this on IIS 7.0 and was getting all his Application variables empty. First, I thought there will be one more global.asa in one of parent directory. But there was no other global.asa file and the worst part was all session variables were working. Finally, I was able to fix this by converting the site from Virtual directory to an Application in IIS 7.0.

So, to make your classic ASP site which is using Application variables work with IIS 7.0, deploy it as an application and not virtual directory. Glad ASP.NET came :-)

Friday, February 05, 2010

Microsoft SharePoint 2010 Products Preparation Tool

 

This tool assist you in the installation of the software prerequisites for SharePoint Server 2010. Ensure that you have an Internet connection, because some of these prerequisites are installed from the Internet.

To Run this tool:

This tool checks if following prerequisites exists:

  • Web Server (IIS) role
  • Application Server role
  • Microsoft .NET Framework version 3.5 SP1
  • Microsoft "Geneva" Framework
  • Microsoft Sync Framework Runtime v1.0 (x64)
  • Microsoft Filter Pack 2.0
  • Microsoft Chart Controls for the Microsoft .NET Framework 3.5
  • Windows PowerShell 2.0 CTP3
  • Microsoft SQL Server 2008 Analysis Services ADOMD.NET
  • ADO.NET Data Services v1.5 CTP2

Tuesday, February 02, 2010

Feature Activation Error : Office SharePoint Server Publishing Infrastructure

 

If you get error denied while activating this feature, you have not activated the dependent feature called “PublishingResources”.

Fix:

Activate the “PublishingResources” feature using stsadm command

stsadm -o activatefeature -name PublishingResources -url http://YOUR_WEBSITE
(change the URL)

Now, Activate the Office SharePoint Server Publishing Infrastructure feature.

Friday, January 29, 2010

Error: “The search service is currently offline. Visit the Services on Server page in SharePoint Central Administration to verify whether the service is enabled. This might also be because an indexer move is in progress”

 

Check you don’t have duplicate XML tag in the machine.config file on the server reporting error. It was Index server for me.

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