How to Update properties of sharepoint 2010 feature - sharepoint

I have a problem with updating properties of sharepoint 2010 feature
this is my code :
using (SPSite site = new SPSite("http://vm-pc:2000"))
{
foreach (SPFeatureDefinition def in SPFarm.Local.FeatureDefinitions)
{
if (def.Scope == SPFeatureScope.WebApplication)
{
if (def.GetTitle(System.Threading.Thread.CurrentThread.CurrentCulture) == "Configure Site Settings")
{
((SPFeatureProperty)def.Properties[0]).Value = "5";
def.Properties.Update();
def.Update();
}
}
}
}
The problem with def.Properties.Update();
It throws an exception :
Updating the properties of a feature definition is not supported.

Why dont you use the Property bag?
SPSite site = new SPSite("URL");
SPWeb web = site.RootWeb;
web.Properties.Add("Key", "Value");
web.Properties.Update();
and get value:
web.AllProperties["Key"]

Related

[SharePoint 2010]Value from a User Profile custom field returns Null

In an EventReceiver I call this method GetPernNr on Item Added:
public override void ItemAdded(SPItemEventProperties properties)
{
SPSite site = properties.Web.Site;
using (SPWeb currentWeb = site.OpenWeb(properties.Web.ID))
{
.....
perNr = UserProfileUtils.GetPernNr(currentWeb, assignedTo.ToString());
.....
}
}
where assignedTo is a SPUser.
public static string GetPernNr(SPWeb web, string accountName)
{
string perNr = string.Empty;
UserProfile upUser = null;
try
{
PermissionSet ps = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ps.Assert();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteColl = new SPSite(web.Site.ID))
{
SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);
UserProfileManager upm = new UserProfileManager(serviceContext);
if (upm.UserExists(accountName))
{
upUser = upm.GetUserProfile(accountName);
if (upUser["PersonNumber"] != null)
{
perNr = upUser["PersonNumber"].Value.ToString();
}
}
}
});
}
catch (Exception ex)
{
..
}
finally { System.Security.CodeAccessPermission.RevertAssert(); }
return perNr;
}
It's strange, this code works when I try to get value from a default field in UserProfile (Office, Manager, etc). And also works when I call this method outside EventReceiver, but in my case, upUser["PersonNumber"].Value returns null.
Any help will be much appreciated
Did you check the custom property permission in the central admin.
Central Administration -> Edit User Profile Property -> Policy Settings
Make default privacy policy to everyone and then try.
Here is the steps for SharePoint Server 2013:
Central Admin > Application Management > Manage service applications > Your User Profile Application > Manage User
Properties
Select Edit option from property menu.
Now Under "Policy Settings":
Set Default Privacy Setting: Everyone

EventReceiver to Create folder sharepoint 2010

I have this event receiver c# class that I am trying to implement on a Sharepoint site. It did not work. I have deployed it from visual studio 2010 after it was build ok. Does anyone see what is the problem? Is the code ok? or is the problem on the SP? Thank you.
- here is the new code
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace EventReceiverCFolder.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
if (properties.ListTitle == "CF") // list where the item was added
{ // if item was added to this list then create a folder on - Dlib - list
UpdateFolder(properties);
}
}
catch (Exception ex)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
}
}
private void UpdateFolder(SPItemEventProperties properties)
{
string foldername = properties.ListItem["Title"].ToString();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//inside RunWithElevatedPriviliges I need to open a new site (an elevated site)
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("DLib"); // this is doc Library where the new folder will be created
//note that we are creating a list item, not a folder - a folder IS a list item
SPListItem createdFolder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
if (createdFolder != null)
{
createdFolder["Name"] = foldername;
createdFolder.Update();
}
list.Update();
}
}
});
}
finally { }
}
}
}
Don't do this: SPUser privilegedAccount = properties.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
Read up on using SPSecurity.RunWithElevatedPrivileges. See the MSDN documentation here.
Also don't do a using (SPSite... and inside the using block you try to get the web via SPContext.Current - that web won't be elevated anymore.
The correct way is something along these lines (I didn't try this, so it' just to give you an idea where you are headed):
private void UpdateFolder(SPItemEventProperties properties)
{
string foldername = properties.ListItem["Title"].ToString();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//inside RunWithElevatedPriviliges I need to open a new site (an elevated site)
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("ListTitle"); //is that really the list title?
//note that we are creating a list item, not a folder - a folder IS a list item
SSPListItem createdFolder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
if (newFolder != null)
{
createdFolder["Name"] = foldername;
createdFolder.Update();
}
list.Update();
}
}
});
}
Also try to debug your code, set breakpoints etc.
I had to get folder name like this:
string foldername = Convert.ToString(properties.AfterProperties["Title"]);
Did you try to debug it? try to debug and tell us what error you are getting.
BUT before you debug first use sharepoint manager to see if your event receiver is attached properly.
If you dont know how to debug sharepoint event receiver then please see this

Create Sharepoint 2010 Webpart page in C#

I want to programmatically create a Webpart page (.aspx file) for Sharepoint 2010. I already found this code snippet:
public static PublishingPage CreatePage(string fileName, string title)
{
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(Web);
PageLayout[] layouts = pWeb.GetAvailablePageLayouts();
PageLayout layout = layouts[0];
foreach (PageLayout p in layouts)
{
if (p.Name.Equals("BlankWebPartPage.aspx"))
{
layout = p;
break;
}
}
try
{
PublishingPage newPage = pWeb.GetPublishingPages().Add(fileName, layout);
newPage.Title = title;
newPage.Update();
return newPage;
}
catch (Exception)
{
return null;
}
}
But my problem is SharePoint Foundation Server does not have the Publishing part but I have to run it on a SharePoint Foundation Server.
Is it possible to create a Webpart Page without PublishingWeb?
greets
Publishing Infrastructure is one of the features that is only avaialble in SharePoint Server Standard or Enterprise. It is not included in SharePoint Foundation 2010. It wasn't included in Windows SharePoint Servives (WSS) either. Publishing has always required the purchased version of the product.

webpart is working on local server but not working on production when "SPSite" class is uesd in the webpart

webpart is working on local server but not working on production server when "SPSite" class is uesd in the web part. On the production server it throws error. If I do not use that class in the webpart the web part also works on live machine.
Any idea what might be causing the error?
the code in the webpart is this:
namespace CompanyNews
{
[Guid("40de3c60-9e30-4050-b9f3-01e71868f522")]
public class CompanyNews : System.Web.UI.WebControls.WebParts.WebPart
{
private HtmlTextWriter writer;
public CompanyNews()
{
}
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
string listName = "News Display";
writer.Write(listName);
SPList list = null;
foreach (SPList currentList in web.Lists)
{
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase))
{
list = currentList;
break;
}
}
writer.WriteBeginTag("ul");
foreach (SPListItem item in list.Items)
{
writer.Write("<li style=\"font-size:12px;padding:1px\">");
writer.Write(item["Title"].ToString() + "... ");
writer.Write("<a class=\"smallerred\" href=\"#\">Read More</a>");
writer.Write("</li>");
}
writer.WriteEndTag("ul");
}
}
}
}
}
The dll of the webpart is in the bin folder and in the web.config file there is an entry for the web par as a safe control.
Other webpart which displays a "hellow world" message is also uploaded to production the same way.
I i guess its the code that is causing the problem.
The error message is: "An error occurred while previewing the web part"
just something I noticed, you shouldn't wrap objects from the Current Context in a using statement. Good article here Clicky
Better practice would be to use the following
using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
{
...
}
Also you should look at packaging up your solution in a WSP, allowing stsadm to deploy it. Dragging into the GAC isn't very good practice.
Shane
The SPSite object isn't getting reference anywhere that I can see. Why don't you remove it anyway as it's superflous to your needs?
SPWeb web = SPContext.Current.Web;
string listName = "News Display";
writer.Write(listName);
SPList list = null;
foreach (SPList currentList in web.Lists)
{
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase))
{
list = currentList;
break;
}
}
writer.WriteBeginTag("ul");
foreach (SPListItem item in list.Items)
{
writer.Write("<li style=\"font-size:12px;padding:1px\">");
writer.Write(item["Title"].ToString() + "... ");
writer.Write("<a class=\"smallerred\" href=\"#\">Read More</a>");
writer.Write("</li>");
}
writer.WriteEndTag("ul");

Retrieve a list of web parts on a page

I am trying to get a list of webparts deployed on a web page in sharepoint 3.0. Is there way I can retrieve it from sharepoint content database or can I do it programmatically?
You can use the SPWebPartManager to iterate thru a list of web part in a page.
See this MSDN example.
EDIT:
This is maybe a better example:
private static void GetWebParts()
{
using (SPSite site = new SPSite("<YOUR SITE URL>"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("default.aspx"); // or what ever page you are interested in
using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
foreach (WebPart wp in wpm.WebParts)
{
Console.WriteLine("Web part: {0}", wp.Title);
}
}
}
}
}
Adding web parts programmatically is simple:
SPWeb site = SPContext.Current.Web;
SPFile page = web.GetFile("Pages/somepage.aspx");
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
// logic to get web parts here.
ContentEditorWebPart webPart = new ContentEditorWebPart();
webPart.Title = "Test Web Part";
webPartManager.AddWebPart(webPart, "Zone 1", 0);
}
finally
{
// SPLimitedWebPartManager has known memory leak where it does not dispose SPRequest object in its SPWeb, so dispose it
webPartManager.Web.Dispose();
}
}

Resources