Wednesday, April 24, 2013

Sharepoint : LINQ Examples

In this post I am going to show some of the LINQ to SharePoint examples which will be useful in performing CRUD operations.

Before that lets think about SQL, CAML and LINQ

In SharePoint all the data will be stored in SQL databases. SharePoint List will be an front end for doing CRUD operation. Since the users does not have DB access List will be used as an interface to perform CRUD operation.

Suppose if we want to get few records from SharePoint list based on some condition then we need to write CAML query to get the records.

Writing CAML query is little bit tedious even though we have excellent CAML Query builder. To overcome this problem we have LINQ for SharePoint which will internally run CAML to perform CRUD operations.

So LINQ is a front end for CAML, internally CAML is front end to SQL.

Here I am showing how to use LINQ to SharePoint using SPMetal.exe

Lets create a SharePoint List called EmployeeDetails with following fields.

EmployeeID - Integer FirstName - Single Line Text LastName - Single Line Text DOB - Date field Phone - Number Email - Single Line Text

Create some dummy records in the employee list.

Requirement:

Lets assume we have one timer job which will send an EMail to the employee whose birthday is today :).

1) Open SPMetal.exe from CommondPrompt

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN



Run the following command from window.

c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN>SPMETAL.exe /web:http://sharepoint2010 /namespace:SharePointConsoleApplication1 /code:ListEntities.cs (This will create the entity class with the namespace.



or

c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN>SPMETAL.exe /web:http://sharepoint2010 /code:ListEntities.cs (This will create Entity class without namespace)



Add ListEntities.cs file from 14 hive folder to the project and verify the namespace(make sure Microsoft.Sharepoint.Linq dll reference has been added in the project)

The structure of the Project should be as below after adding the entity class into the project.



Read Operation:

I have pasted below code which will display Employee Name whose birthday is today. (Its like an Select statement in SQL)

using System;
using System.Linq;
using Microsoft.SharePoint;
namespace SharePointConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Open the List Entities Data context file and pass the Site url as parameter
using (ListEntitiesDataContext list = new ListEntitiesDataContext("http://sharepoint2010"))
{
//Once data context is ready its simple Linq statement to fetch the records based on the condition
var spItems = from a in list.EmployeeDetails where a.DOB == System.DateTime.Now select a;
//Loop through all the items
foreach (var item in spItems)
{
//Here we can write our business logic just displaying the employess first name
Console.WriteLine(item.FirstName);
}
}
}
}
}

Will continue :)

Friday, April 19, 2013

List of Sharepoint 2010 Developer Tools

Below are some of the Tools/application which will be handy during development/debugging phase of the projects.

1) WSP builder
http://wspbuilder.codeplex.com/releases/view/30858
The WSP builder will create .wsp file extension for the sharepoint, event though Visual Studio provide OOB package builder still this tool will be handy.

2) Caml
http://www.u2u.be/res/Tools/files/CamlBuilderSetupv4.0.0.0.zip Using this tool we can easily build complex query to fetch data from SharePoint list.

3) TFS power tool
http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f It's a plugin for Visual Studio and provides great flexibility to work with TFS.

4) Powershell
http://www.powergui.org/downloads.jspa Provides GUI for writing Powershell scripts to perform all sharepoint related administrative/developer task.

5) SPManger
http://spm.codeplex.com/releases/view/51438 The SharePoint Manager is UI based SharePoint object model explorer.

6) UlsViewer
http://archive.msdn.microsoft.com/ULSViewer This tool provides the sharepoint ULS log information where we can search or filtering the data based on category etc.

7) IE/Firefox developer tool bar
Out of the box tool where we can do style changes or debugging javascript code.

8) SPMetal
http://linqtosharepoint.codeplex.com/wikipage?title=SPMetal

9) CCleaner
http://download.cnet.com/CCleaner/3000-18512_4-10315544.html To clear cookies/browser history and this will be helpful when we use cookies related operation for storing data.

10) ILSpy
http://sourceforge.net/projects/sharpdevelop/files/ILSpy/2.0/ILSpy_Master_2.1.0.1603_RTW_Binaries.zip/download
This tool allows to decompile and browse the content of any .NET assembly

11) Fiddler
http://fiddler2.com/
Fiddler is a free web debugging tool which logs all HTTP(S) traffic between your computer and the Internet

12) CKS Visual Studio Extension
SPServer
http://visualstudiogallery.msdn.microsoft.com/en-us/ee876627-962c-4c35-a4a6-a4d89bfb61dc
Foundation
http://visualstudiogallery.msdn.microsoft.com/a346880f-2d29-47a6-84a2-f2d568dd6997/
This tool extends the Visual Studio 2010 SharePoint project system with advanced templates

13) Sharepoint Installer
http://autospinstaller.codeplex.com/downloads/get/100843

14) SPDisposecheck
http://archive.msdn.microsoft.com/SPDisposeCheck
SPDisposeCheck is a tool that helps developers and administrators check custom SharePoint solutions that use the SharePoint Object Model helping measure against known Microsoft dispose best practices

Thursday, April 18, 2013

Sharepoint Delegate control - Notification bar in sharepoint

In this post I am going to show how to add a notification bar in the sharepoint site(Notification bar is used to display notification to the users about the site maintenance activity)
Step 1: Override the delegate control in the master page
Step 2: Associate this delegate control as sharepoint feature(This will be usefull for the site admin, whenever its required they will be activate and deactivate this feature)
Open Visual Studio and create new project called NotificationFeature
Add new sharepoint Feature Called NotificationFeature and set the scope to Site level.
Add new user control called NotificationControl(Map to sharepoint control template folder at the 14 hive)
Open NotificationControl.ascx file and add the below code to display notification bar.
Here I have added jQuery reference and javascript function which set the div background color and div tag to display the message. (Adding jQuery reference and validate method is optional we can set the background color for the div tag directly)
Add New Empty element to the project and name it as NotificationControl.
Open Element.xml file and add below code.
<Control Id="AdditionalPageHead" ControlSrc="~/_CONTROLTEMPLATES/NotificationFeature/NotificationControl.ascx" Sequence="15100" /> Finally our Element.xml file looks like below.

Add jQuery file to the layouts folder. This step is optional since I am applying style for the div element through jQuery I am using this else we can skip this step.
Final structure of our project:
Build, Package and deploy the solution. And activate the Notification Feature at the site level.
Now our notification bar will be displayed when the user open the site.

Tuesday, December 27, 2011

Way to wait for jQuery's JSON method retruning from server

There are some scenarios where we may need to set the value for the text box or some html control based up on the value returned from the JSON.

I had scenario where two method.

1) JSON call
2) Normal Jquery/javascript function call

My thought was that till JSON call got executed my second method wont execute, since JSON is ASYNC call it wont till it get response from JSON, it will start executing our Jquery method.

The problem starts here, i was setting few variable(global) in 1st method and using them in the 2nd method.

Since it takes time to execute the 1st method, so the values will be loaded properly.

So we need to use $(document).ready(function () {
$.ajaxSetup({'async': false});
//Method1()
//Method2()
});

This will work like synchronous and this fixed my issue.

Tuesday, October 11, 2011

Anti XSS

Today I came across one of the more weird issue in the production environment.

The site is developed in sharepoint 2010, and we have a search box in the page.

When user try to enter some of the javascript code ex: <script>alert('hi')</script> in the search text box, our site was broking(in the sence styles) all the times.

By default sharepoint will take care of Anti cross side scripting for the all the out of the box the control(specially with search).

But in our case it was breaking. After doing an investigation I came to know some where we are writing the text query in the page(As a title we are using this).

There we are not doing AntiXss for the that. After fixing this our page rendered as expected.

To get more information about AntiXss please follow this post.

http://ha.ckers.org/xss.html

Saturday, July 23, 2011

Application Pages Vs Site Pages

Application Pages:


1.These are the normal .aspx pages deployed within SharePoint. Most common of them are the admin pages found in _layouts folder.

2.These are deployed either at the farm level or at application level. If they are deployed within _layouts folder or global SharePoint Virtual Directory, then they can be used by any SharePoint application (available at farm level), otherwise they can be deployed at application level only by creating a virtual directory.

3.These are typical ASP.Net aspx pages and can utilize all of the functionalities available within ASP.Net including code-behind, code-beside, inline coding etc.

4.These are compiled by .Net runtime like normal pages.

5.They can only use master pages available on file-system not within SharePoint Content Databases and for the same reason, you will notice that _layouts pages can only use Application master page deployed within _layouts folder and cannot use any of your custom master page deployed within SharePoint masterpage library.

6.If you deploy your custom ASPX pages within _layouts folder or within SharePoint application using a virtual directory, you will not be able to use SharePoint master pages and have to deploy your master page within the virtual directory or _layouts folder.

7.Application Pages cannot use contents as this concept is associated with SharePoint Page Layouts not with ASP.Net.

8.Since application pages are compiled once, they are much faster

9.Normally application pages are not web part pages, hence can only contain server controls or user controls and cannot be personalized by users.

10.Easiest way to deploy your existing ASP.Net web site within SharePoint is to deploy its pages as Application Pages within SharePoint. In this way you can convert any ASP.Net web solution as SharePoint application with minimal efforts.

11.SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.

12.Application pages can be globalized using Resource files only.


Site Pages

1.Site Pages is a concept where complete or partial page is stored within content database and then actual page is parsed at runtime and delivered to end-users.

2.Pages stored in Pages libraries or document libraries or at root level within SharePoint (Wiki pages) are Site Pages

3.You must be thinking why we should use such pages? There are many reasons for this. One of the biggest catch of the SharePoint is the page layouts, where you can modify page once for a specific content type and then you can create multiple pages using the same page layout with different contents. In this case, contents are stored within database for better manageability of data with all the advantages of a data driven system like searching, indexing, compression, etc and page layouts are stored on file system and final page is created by merging both of them and then the outcome is pared by SharePoint not compiled.

4.Site Pages can contain web parts as well as contents placeholders, and all of them are stored per page-instance level within database and then retrieved at run time, parsed and rendered.

5.Another advantage is they are at user-level not at web-application or farm level and can be customized per site level.

6.Since their definition is retrieved from database, they can utilize master pages stored within SharePoint masterpages library and merged with them at run time for rendering.

7.They are slower as compared to Application pages as they are parsed everytime they are accessed.

8.SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.

9.Since they are rendered not compiled hence it is not easy to add any inline code, code behind or code beside. Best way of adding code to these pages is through web-parts, server controls in master pages, user controls stored in "Control Templates" folder or through smart parts. If you want to add any inline code to master page, first you need to add following configuration within web.config:

PageParserPaths
PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" /
PageParserPaths

10.To add code behind to SharePoint master pages or page layouts, refer to this MSDN article

11.Since Site pages are content pages, hence all SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages.

12.Variations can only be applied against Site pages for creating multilingual sites.

13."SPVirtualPathProvider" is the virtual path provider responsible for handling all site pages requests. It handles both ghosted and unghosted pages requests as shown below:



Friday, May 6, 2011

Creating Mysite host in moss 2007

1) Create a new web application (e.g. http://mossdev1:25000/)
2) Inspect Managed Paths for the new web application. You should already have:
(root) - Explicit inclusion
sites - Wildcard inclusion
3) Delete managed paths:
sites - Wildcard inclusion
4) Create managed paths:
personal - Wildcard inclusion
mysite - Explicit inclusion
5) End state for managed paths should be:
(root) - Explicit inclusion (thanks to imsaurabh for catching this!)
personal - Wildcard inclusion
mysite - Explicit inclusion
6) Create a site collection at /mysite/ managed path. This will use a My Site Host template:
Choose correct web application (e.g. http://mossdev1:25000/)
Title: My Site Host (doesn’t matter, really)
URL: http://mossdev1:25000/mysite (no fill-in because path is explicit in managed paths)
Template: Enterprise (tab) -> My Site Host
Specify primary and secondary administrators.
Click OK.
7) Create a blank site collection at the / managed path to enable self-service site creation:
Choose correct web application (e.g. http://mossdev1:25000/)
Title: Blank site (doesn’t matter, really)
URL: http://mossdev1:25000/ (no fill-in because path is explicit in managed paths)
Template: Collaboration (tab) -> Blank Site
Specify primary and secondary administrators.
Click OK.
8) Enable Self-Service Management. Choose from Application Management -> Application Security.

Now that you’ve created the host, here’s how to make sure it works properly in the SSP’s My Site Settings:

1) Navigate to My Site Settings (go to your SSP’s admin pages, it’s the 3rd link in the 1st section).
a) For form’s sake, inspect the Preferred Search Center entry. This URL should end in /SearchCenter/Pages/.
Set Personal Site Services to http://mossdev1:25000/mysite/. Note that this points to the URL for the explicit inclusion path and My Site Host Template site collection you created above.
b) Set Personal site Location into just personal. Note that this points to the URL (after SharePoint puts context to it) for the Wildcard inclusion managed path you created above.
c) Choose the 2nd Site Naming Format: User name (resolve conflicts by using domain_username).
d) Enable Allow user to choose the language of their personal site.
e) Disable My Site to support global deployments.
f) Default Reader Site Group: NT AUTHORITY\authenticated users.