Sunday, December 27, 2009

Sharepoint Articles links

How to optimize a sharepoint server 2007 with Web content management
1) http://msdn.microsoft.com/en-us/library/bb727371.aspx
2) http://msdn.microsoft.com/en-us/library/bb727372.aspx

10 steps to building XHTML compliant and performing MOSS publishing sites

http://blogs.code-counsel.net/Wouter/Lists/Posts/Post.aspx?ID=103

Best Coding practice while working with object model
http://msdn.microsoft.com/en-us/library/bb687949.aspx

Fire fox css issue
http://www.webmasterworld.com/forum83/7738.htm

Friday, December 18, 2009

Feature Stappling

Suppose when the site definition is already in use (and sites have been created) modifying a site definition once it has been deployed, since the site definition files on the filesystem are used for pages which are ghosted (not modified).
At this time we can go with feature stappling.
Some times it is also knows as site template association.
So finally feature-stapling Feature provides the mappings between the Feature and site definition.

Thursday, December 17, 2009

How to check the List Template Id in sharepoint site

Its difficult to find the list template Id of the page library in publishig site.
So in order to check list template Id of Page library or Image library follow the steps.
1) Open http://site/pages/forms/allitems.aspx
Check for view source of the page.Search for the keyword ctx.listtemplate, there you will find the list template id for the pages library.
Same thing do it for Image library also.
Some of the important template id are as follows.
Value
Description
100 Generic list
101 Document library
102 Survey
103 Links list
104 Announcements list
105 Contacts list
106 Events list
107 Tasks list
108 Discussion board
109 Picture library
110 Data sources
111 Site template gallery
112 User Information list
113 Web Part gallery
114 List template gallery
115 XML Form library
116 Master pages gallery
117 No-Code Workflows
118 Custom Workflow Process
119 Wiki Page library
120 Custom grid for a list
130 Data Connection library
140 Workflow History
150 Gantt Tasks list
200 Meeting Series list
201 Meeting Agenda list
202 Meeting Attendees list
204 Meeting Decisions list
207 Meeting Objectives list
210 Meeting text box
211 Meeting Things To Bring list
212 Meeting Workspace Pages list
300 Portal Sites list
301 Blog Posts list
302 Blog Comments list
303 Blog Categories list
1100 Issue tracking
1200 Administrator tasks list
2002 Personal document library
2003 Private document library

Deploying event receivers

There are 3 ways we can deploy the event receivers.
1) Deploying Programatically
2) Via Feature
3) With Content type

Programatically
This can be done only when an event receiver need to be associated with a single instance of a list rather than with all list of with template ID.

With Feature
Programmatic deploying will install the receiver againest a specific instance of a list and much reuse benefit is not possible in this.
To overcome this we can use this method.


Before creating any event handlers developers should think following points.

1. Security:

The assembly you deploy to the Global Assembly Cache(GAC) is running with full trust. Watch out for the following:



· Denial of Service attack: If a user uploads 10000 items to a list, what is the effect it will have to the systems your assembly uses.

· SQL Injection attack: If a user attempts to insert SQL statements into a column of a list that your assembly uses to update a database, what mechanisms are you using to make sure the input is valid.

· Cross Site scripting attack: What is the effect of adding script to a column that your assembly uses to update another area in SharePoint?



2. Performance:

Watch out for the following:



· Load: What burden are you placing on your web front end servers to run the assembly each time an event occurs? Use performance counters to determine this.

· Long Running Operations: Consider creating a custom SharePoint timer job. Kick off/ Schedule the Timer Job from the event rather than running all the logic inside the event. This will allow you to use the features of SharePoint to view whether the Timer Job ran successfully.

· Sync vs Async Events: Synchronous events have to wait until your code completes before returning the page, whereas Asynchronous events show the page immediately.



3. Error Handling:

When using synchronous events and you decide to cancel an event, let the user know why the event was cancelled. For example, update a Task List with a message why it failed.



Log your errors so that you can determine what issue is occurring when your system is in production environment.



4. Connections: Cater for external systems being down when you are trying to connect to them. Don’t let your code / solution go belly up because you cannot connect to a database.



5. Bulk Operations:

The MSDN documentation mentions that event handlers will not fire when bulk operation is occurring. For example, when a new list is created, the FieldAdding event will not fire.

Limitations of Event Handler in SharePoint

Strangely there is no “SiteAdding”, “SiteAdded” event. However, if you really need this event you could create a “feature” to accomplish this. Features in SharePoint have a “FeatureActivated” event, where you could perform an action on creation of a site.

Very Good site about sharepoint

http://www.sharepointkings.com/2009/07/accessing-content-type-via-object-model.html
http://www.sharepointkings.com

Wednesday, December 16, 2009

To check page is in edit mode or not for publishing page

This field can be used to check whether page is in edit mode or not



By checking value of this hidden field we will come to know about page is in edit mode or not.

Friday, December 11, 2009

Caml Query

Substracting 5 days from the current date in the caml query.

SPSite site = new SPSite("http://url");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["ListName"];
string querystring = ""
+ "
";
SPQuery query = new SPQuery();
query.Query = querystring;
DataTable table = list.GetItems(query).GetDataTable();

Running code with elevated previliges

Often it is useful to write code which has the ability to perform tasks that the user executing the code cannot do. For example, you may want to capture feedback from a user through a custom web part and add that feedback to a SharePoint list that the user does not have access to directly. Since server-side code executes in the context of the current user, the attempt to write the list item would fail.

The way around this is to use a method on SPSecurity called RunWithElevatedPrivileges. This method accepts an anonymous delegate which will contain all of the code you want to execute. Any code within this delegate will execute as the system account.

// this code runs in the context of the user
SPWeb web = SPContext.Current.Site.RootWeb;
SPList list = web.Lists["My List"];

// this code will run in the context of the system account
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite rootSite = new SPSite("http://myserver");
SPWeb rootWeb = rootSite.RootWeb;
SPList myList = rootWeb.Lists["My List"];
});

// now we're back to the user context
int itemCount = list.ItemCount;

One important thing to note is that only objects instantiated within the RunWithElevatedPrivileges code block will have the context of the system account. So objects created outside of that will still have the context of the current user - even if they are used within the RunWithElevatedPrivileges block.

// create an object in the context of the user
SPWeb web = SPContext.Current.Web;

// run as system account
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// this will execute as the current user, not the
// system account because it is accessing the web
// object which was instantiated outside of the
// RunWithElevatedPrivileges block
SPList myList = web.Lists["My List"];
});

Event Receivers
RunWithElevatedPrivileges is often used in Event Receivers to perform some sort of automation. Event receiver methods are passed SPItemEventProperties objects which provide easy access to the current list, current list item, current web, etc. However, you cannot use these objects directly within a RunWithElevatedPrivileges block because they were instantiated outside in the context of the user. As a workaround, you can re-create these objects within the context of the system account.

public override void ItemAdded(SPItemEventProperties properties)
{
// start sys account context
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// accessing the list item directly from the properties
// will execute as the end user - not the system account
properties.ListItem["Title"] = "Hello";

// instead, re-instantiate these objects using data from the
// properties, but not the actual objects themselves
SPSite site = new SPSite(properties.SiteId);
SPWeb web = site.OpenWeb(properties.RelativeWebUrl);
SPList list = web.Lists[properties.ListId];
SPListItem item = list.Items.GetItemById(properties.ListItemId);
item["Title"] = "Hello";

item.Update();
}
}

Tuesday, November 3, 2009

Activating the feature at sub site level

Avoiding manual activation of feature at the sub-site (web) levels


Add the ID (GUID) of the feature in Onet.xml file

Feature activation for timer jobs

A SharePoint feature receiver based on timer job is created as a site collection feature and you try to activate the feature

May throw the error message “EXECUTE permission denied on object 'proc_putObject'.

This is because adding the timer job is done by the account that runs the application pool of your web application. This account normally does not have write / execute permissions in the configuration database.

The best way to get around this is to change the scope of your feature to WebApplication. In a few examples on the internet, the feature is Site scoped. If you change it to WebApplication scope, you have to activate the feature in the Central Administration. The application pool that runs that web application has enough permission to do this. Of course you need to slightly modify the code of your feature receiver. Instead of casting the properties.Feature.Parent to a SPSite, you cast it to a SPWebApplication.

http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5-28d9-464f-b1c9-91e07c8f7e47&ID=82

Sharepoint Tips and tricks

1) We can Use single Content Type for multiple Page Layouts.
2) Always Use using(SPWeb/SPSite obj = new SPWeb()/SPSite() ) object. These two SharePoint object won't
get release from memory by GC and need to deallocate those explicitly

3) To Lock the block/method/event across the thread,
Create global object of object class and lock it.
private static readonly object objCentralLock = new object();

public override void Execute()
{
lock(objCentralLock)
{
......
}
}


4) SPJobDefinition(Timer job) Feature Development.
If the scope of feature is WebApplication then it will work fine. Otherwise it will throw database permission exception.
If you change it to WebApplication scope, you have to activate the feature in the Central Administration.
The application pool that runs that web application has enough permission to do this.
Of course you need to slightly modify the code of your feature receiver.
Instead of casting the properties.Feature.Parent to a SPSite, you cast it to a SPWebApplication.


100) Default page limit of sharepoint web for Navigation is 50. OOTB

to change this limit,Need to update web.config of perticular application.

Add DynamicChildLimt="XXXX" as attribute for all providers
1) GlobalNavSiteMapProvider
2) CombineNavSiteMapProvider
3) CurrentNavSiteMapProvider
4) CurrentNavSiteMapProviderNoEncode

XXXX is an integer number.

Tips and tricks(ASP .Net)

ASP.NET 1) To access requested page url
Page.Request.UrlReferrer.AbsoluteUri
2) Not to save page in browser's Cache
call Page.Response.Cache.SetNoStore(); Page.Response.Cache.SetAllowResponseInBrowserHistory(false);
in Base Master file's OnLoad() event or Page_Load() of page load event
3) To post any data as a Form's POST method use following class
3.1) First need to call Add() method to set fields name and values
Note: If it is asp.net target site and not handled Remote form posting request in Page_Load() then need to pass __ViewState value as parameter and also submit button type and ID should match to remote site page submit button. In this case remote site's button click event will get triggered automatically.
3.2) Post() method to post requset
public class RemotePost { string url; private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection(); public string Url { get { return url; } set { url = value; } } public string Method = "post"; public string FormName = "TestForm"; public void Add(string name, string value) { Inputs.Add(name, value); }
public void Post() { try { //Clear old respose System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Write(""); System.Web.HttpContext.Current.Response.Write(string.Format("")); System.Web.HttpContext.Current.Response.Write(string.Format("
", FormName, Method, Url)); //Add all parameters as html input hidden controls with id,name and value for (int i = 0; i < name="\" id="\" type="\" value="\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]])); } //Hide submit button System.Web.HttpContext.Current.Response.Write(string.Format("
")); System.Web.HttpContext.Current.Response.Write("
"); //trigger submit button click event using javascript click() method System.Web.HttpContext.Current.Response.Write(""); System.Web.HttpContext.Current.Response.Write(""); //Complete request HttpContext.Current.ApplicationInstance.CompleteRequest();
} catch (Exception ex) {
throw ex; }
} }
4) Force browser to download file(image filem .js or .css etc) from server then need to add querystring parameter where we have referening perticular filee.g. Here we are passing ?Version=1 value as a query string parameter and if file name from browser's temp folder and this mismatch thenbrower will download file from server and will refer latest one.If you modify CustomValidation.js file then you can add Version=2 value as query string parameter
This problem is mostly with IE 7.0 brower.
5) To determine who caused postback, use Request.Form["__EVENTTARGET"]. It holds the UniqueID of the control that caused postback.If the control is a button, its UseSubmitBehavior must be set to false. So in case you are getting nulls, you probably have UseSubmitBehavior=true.
6) Not to ask Remember Password or any field by any browser Add Autocomplete=off Attribute(like ControlID.Attribute.Add("Autocomplete","off");) to the User ID Textbox control.
7) Allow User to Read/Write/Delete disk file even if another user is using, Use FileShare mode with FileStream object as shown below.
using (FileStream fs = new FileStream("C:\\dat.txt", FileMode.Create, FileAccess.Write, FileShare.Write FileShare.Read FileShare.Delete)) { while (true) { fs.WriteByte(84); fs.Flush(); Console.Write("."); Thread.Sleep(1000); } }

Sunday, October 25, 2009

Page Layouts

Yesterday i faced a problem related to the page layout. I created a page layout with SummaryLinkFieldControl and its works fine with users having admin permission but for user having less previliges its throwing access denied error.
After searching in the net i came to know that its a problem with summary link web part.
The reason behind this may be safe control entry may not be there in the web config file(Its a just guess)
Its better to have web part zone where we can add summary link web part.
In google try to search with the key
(SummaryLinkFieldControl)

Thursday, September 24, 2009

How to refresh application pool without resetting iis

This is the common scenario in sharepoint development. Suppose if you modify site definition file(xml) or you need to deploy the latest dll in GAC, then iisreset is must to get the changes.
But the thing is if the deployment is in production server then your customer may raise a issue. If server contains more than one application then its bad idea to give iisreset. Instead of that you can reset the application pool where your application is running.
For this we require the application pool id. How to get the application pool id?
Type the below line of text in command prompt.
C:\windows\System32\iisapp
This will display all the application pool id. Easily you will come to know about your app pool Id.
Next step is to refresh the application pools.
Type the following line in command prompt, that will refresh the app pool.
C:\windows\System32\iisapp.vbs /a “ApplicationName” /r
Another way is create one batch file and paste the following line of code.
C:\windows\System32\iisapp.vbs /a “ApplicationName” /r
pause

Wednesday, September 23, 2009

Deleting Items in a sharepoint list

How to delete items in sp list?
Whenever we are thinking about this scenario, suddenly the code comes in the mind is create foreach loop and loop through each items and delete the items.
But the problem is we cannot the the list items by this way. It will give the error like "Collection was modified; enumeration operation may not execute."
So to overcome this problem we need to write the code in differently.

int iCount = list.Items.Count;//Its allways better practice to assign the the count to some variable if we use list.Items.Count in for loop it will get the count record from database as many times as for loop will run.
int j ;
for(int i=iCount-1; i>=0;i--)
{
j = i;
list.Item[j].Delete()
}

Same logic will be applied to all share point collection.

Tuesday, September 22, 2009

Event Handlers

Difference between workflows and event handlers

1) Event handlers will trigger automatically where as workflows can be in either way.

2)User interaction is not there in event handlers where as opposite in workflows.

3) Event handler run for short duration where as workflows run for long duration

4) Workflows will be avalable after system down(maintainace,IISRESET etc) but this is not possible in event handler

There is no event for site created but site deleting and site deleted events are available.

To handle/run some custom code whenever a site is created.
Create a Feature that has an Event Receiver defined on it and call the Feature activation event.(There we can run code) Then, use a Feature Staple to staple your Feature to the GLOBAL site definition.

Friday, September 18, 2009

Sharepoint Development Links

In this blog i am providing only the links and good articles where it will be usefull for sharepoint developers and also some code snippets to do an workaround.