Wednesday, June 16, 2010

Creating site columns thorugh SQL query

Sometimes, you may feel pain while creating site columns and content types through CAML, because you need to know CAML syntax for each and every site column data type, but you can avoid this by simply running one sql query

Normally in SharePoint when we create any site column or content type through SharePoint user interface that will go and stored into content database in the form of CAML, so we can run simple sql query and get that data and build it into features and deploy the same in some other environment means production

Steps

1. create sitecoumns and content types using SP user interface

2. connect to sql server database

3. Execute below query

"Select definition from content types where definition is not null"

4. you can see all site columns and content types in form CAML

5. just extract that and build a features and deploy

Friday, June 11, 2010

Access denied error when code runs with SPsecurity.RunWithElevatedPriviliges

Today, while reviewing code ,I have found some thing, which will give access denied error if our code runs with SPSecurity.RunWithElevatedPriviliges and AllowUnsafeUpdates = true

Check the piece of code which I have written below that gives access denied error

using (SPSite site = new SPSite(SPContext.Current.Web))
{
SPList list = web.Lists[listUrl];
SPFieldCollection fieldCol = list.Fields;
SPListItem newItem = list.Items.Add();
foreach (SPField field in fieldCol)
{
if (!field.Hidden && !field.ReadOnlyField)
{
if (field.Title.Equals(question, StringComparison.OrdinalIgnoreCase))
{
newItem[field.Title] = answer;
web.AllowUnsafeUpdates = true;
newItem.Update();
web.AllowUnsafeUpdates = false;
break;
}
break;
}
}
}

The main problem here is that the current request will execute under the priviligies of anonymous user credentials because user is a anonymous user, so this code always gives access denied error

The web object is created using SPContext, so this web object is runs under credentials of spcontext, so this always gives problem

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[listUrl];
SPFieldCollection fieldCol = list.Fields;
SPListItem newItem = list.Items.Add();
foreach (SPField field in fieldCol)
{
if (!field.Hidden && !field.ReadOnlyField)
{
if (field.Title.Equals(question, StringComparison.OrdinalIgnoreCase))
{
newItem[field.Title] = answer;
web.AllowUnsafeUpdates = true;
newItem.Update();
web.AllowUnsafeUpdates = false;
break;
}
break;
}
}
}
}

The above code will run under credentials of system account that means with full permissons so this will execute fine here the difference is we are creting spsite object with url not from current context and the SPsecurity.RunWithElevatedPriviges will work fine here