How to add a People Picker SPField to a SPList in SharePoint? - sharepoint

Looking for a snippet of code.

The "People picker" control is used by SP when a column is of type User
so, the following snippet will add one such column:
using (SPWeb oWebsite = SPContext.Current.Site.AllWebs["MySite"])
{
SPFieldCollection collFields = oWebsite.Lists["MyList"].Fields;
collFields.Add("MyField", Microsoft.SharePoint.SPFieldType.User, false);
}

Related

Additional code required when developing custom visual web part for anonymous access?

I have a simple custom web part with three drop downs that reads from three different list. When the user tries to access this page they get prompted for password, if they don't enter any credentials they get a 401 error.
I have enabled anonymous access both in central admin and on the site itself, users can browse to the site and view it without getting prompted for password. I have made sure that anonymous user have "view" access to the lists in questions but they still can't view any page with a custom web part.
So is it a SharePoint setting or do I have to add something in my web part projects?
Thanks in advance.
Edit:
I call this method in page load and still get the same error
private void LoadImageGallery()
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite oSiteCollection = SPContext.Current.Site;
SPWebCollection collWebsites = oSiteCollection.AllWebs;
DataTable dt = new DataTable();
for (int i = 0; i < collWebsites.Count; i++)
{
using (SPWeb oWebsite = collWebsites[i])
{
if (oWebsite.Title == "People")
{
SPList peopleList = oWebsite.Lists["Pages"];
if (peopleList != null)
{
SPListItemCollection collListItems = peopleList.Items;
dt = collListItems.GetDataTable();
// Include Surname to omit default/search page
dt = collListItems.GetDataTable();
rptImageGallery.DataSource = dt;
rptImageGallery.DataBind();
}
}
}
}
});
}
I also tried with
SPSite oSiteCollection = SPContext.Current.Site;
SPWebCollection collWebsites = oSiteCollection.AllWebs;
above runwithelevated..
I set system\sharepoint to have full control in the entire site
The custom page needs to meet two requirements so that the anonymous users can access it:
it needs to inherit from the class UnsecuredLayoutsPageBase,
the property AllowAnonymousAccess needs to be overridden to return true.
For anonymous access, you have to modified your code for access List to bind drop down list as below. Add you code in SPSecurity.RunWithElevatedPrivileges Delegate method.
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPSite site = new SPSite(web.Site.ID))
{
//ADD YOUR WEB PART Code HERE
}
});
Important: You must create SharePoint Objects in this Delegate otherwise code will not run with Admin access.

SPListItem not added to SPList

I'm using the following code to add an item to a list on the top level of my application but it is not adding anything, does anyone know why? Is there anything missing?
It doesn't return me any error, just doesn't add the item and the list remains empty.
The code is in the FeatureActivated method of the feature where the list instance is being deployed.
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList icons = web.GetList(path)
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPListItem icon = icons.Items.Add();
icon[SPBuiltInFieldId.Title] = "title";
icon[new Guid("d3429cc9-adc4-439b-84a8-5679070f84cb")] = "class1";
icons.Update();
}
you have to call the Update() method of the icon object, not icons.
I found out there are 2 ways of successfully add an item to a list:
Like Andreas Scharf said:
SPListItem item = list.Items.Add();
item["Title"] = "some title";
item.Update();
Some other way using the AddItem() instead of the Add() from the items collection
SPListItem item = list.AddItem();
item["Title"] = "some title"; // Add item's field values
item.Update(); //also the item is updated, not the list

how to update infopath form library item field programatically?

I was successfully able to update one of the fields (which was of type boolean) from infopath for library item using sharepoint object Model as if it was a list item.
But for another field which is of type text, the same code just gets executed but does not change the field value !!!!
I am using following code, which works for that boolean field but for another field of type string , not sure why it is not working. Any idea ?
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb web;
SPSite site = new SPSite("http://sharepointsite");
web = site.OpenWeb();
SPList formLibList = web.Lists["FormLibraryName"];
SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + titleName + "</Value></Eq></Where>";
web.Site.WebApplication.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;
SPListItemCollection col = formLibList.GetItems(query);
if (col.Count > 0)
{
col[0]["CustomerName"] = "test customer name";
col[0].Update();
}
web.Site.WebApplication.FormDigestSettings.Enabled = true; web.AllowUnsafeUpdates = false;
});
Thanks,
Nikhil
I had to declare SPListItem and set it instead of directly modifying list item collection.
It's not an answer to your question (you already found the solution yourself), but you may want to put your SPSite and SPWeb objects in a using block. In your example code you are not disposing them, which results in a memory leak. The correct way would be like this:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://sharepointsite"))
{
using (SPWeb web = site.OpenWeb())
{
// the rest of your code
}
}
});

Retrieve all Master Pages for a SharePoint Site?

How can I determine programmatically what master pages (custom and OOTB) that are available for to use for a web site in SharePoint?
Thanks, MagicAndi
I came up with this solution, making use of a SPQuery object to query the team site collection's Master Page Gallery list:
try
{
using (SPSite site = new SPSite(this.ParentSiteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists["Master Page Gallery"];
SPQuery oQuery = new SPQuery();
oQuery.Query = string.Format("<Where><Contains><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">.master</Value></Contains></Where><OrderBy><FieldRef Name=\"FileLeafRef\" /></OrderBy>");
SPListItemCollection colListItems = myList.GetItems(oQuery);
foreach (SPListItem currentItem in colListItems)
{
// Process master pages
}
}
}
}
catch (Exception ex)
{
}
Use reflection and check whether the type's base type equals System.Web.UI.MasterPage.
So something along the lines of:
foreach(Type t in Assembly.GetExecutingAssembly().GetTypes())
{
if (t.BaseType==typeof(MasterPage))
{
// do something, add to collection - whatever
}
}
But, depending on in what assembly your MasterPages are defined, and the fact it iterates over all the types in a specific assembly, it may definitely not be the best solution.
I am blissfully ignorant about SharePoint, but this solution is somewhat more generic I guess.

update DateTime field with webservice UpdateListItems

is it possible to set a DateTime filed to be null/empty when calling UpdateListItems?
I can set the field to a date value, but not set it to be empty.
Yes, it's possible.
I have tested with both a required and non-required datefield and setting the field to null works.
using (SPSite site = new SPSite("http://intranet"))
{
using (SPWeb web = site.OpenWeb("site"))
{
SPList list = web.Lists["MyCustomList"];
SPListItem item = list.Items.Add();
item["Title"] = "My Item";
item["UpdateDate"] = null;
item.Update();
list.Update();
}
}

Resources