Getting error message in Sharepoint when I publish a webpart - sharepoint

I have this in a webpart inserted into a page from Sharepoint Admin Site (http://sharepointserver:port) and I want to read some info from mysite:
SPUserToken objSPUserToken = SPContext.Current.Site.SystemAccount.UserToken;
//SPUserToken objSPUserToken = SPContext.Current.Web.CurrentUser.UserToken;
using (SPSite mainSite = new SPSite("http://sharepointserver/sites/mysite", objSPUserToken))
{
SPWeb mainWebSite = mainSite.OpenWeb();
SPListItemCollection listItemsP = mainWebSite.Lists["Pages"].Items;
}
When I run it from Visual Studio, asks for user/password and executes normally, but when I publish the wsp and run it from browser, I have the message:
Sorry, this site hasn't been shared with you
I've tried with the CurrentUser (commented line) and it gaves me the same message even from Visual Studio.
I'm sure that the user has rights into mysite, Do you have any idea of what´s happening?
Thanks!

Modify the code as below.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//New SPSite object.
using (SPSite mainSite = new SPSite("http://sharepointserver/sites/mysite"))
{
using (SPWeb mainWebSite = mainSite.OpenWeb())
{
SPListItemCollection listItemsP = mainWebSite.Lists["Pages"].Items;
}
}
});
Reference: SPSecurity.RunWithElevatedPrivileges method

I finally got it, the reason behind the message "Sorry, this site hasn't been shared with you" is because sharepoint log into the site not as the current user but the pool's account, so the message indicates that the site has not been shared for the sp_applicationpool or sp_farm accounts. I solved adding thats accounts into mysite.
Thanks for your help!

Related

UserCustomAction does not fire for non-tenant admin in SharePoint online

I have written a fairly straight-forward JavaScript for SharePoint Online that I am deploying as a user custom action into the root site collection using CSOM.
The following code is the block I am using for provisioning the script to the site collection:
public static void ProvisionScriptLinkCustomAction(ClientContext ctx, string name, string url)
{
Site site = ctx.Site;
ctx.Load(site.UserCustomActions);
ctx.ExecuteQuery();
foreach (UserCustomAction action in site.UserCustomActions)
{
if (action.Name == name)
{
action.DeleteObject();
break;
}
}
ctx.ExecuteQuery();
UserCustomAction customAction = site.UserCustomActions.Add();
customAction.Location = "ScriptLink";
customAction.Name = name;
customAction.ScriptSrc = url + "?" + Guid.NewGuid().ToString();
customAction.Update();
ctx.ExecuteQuery();
}
I am logged in as the tenant administrator when deploying and initially testing the custom action. Everything works as expected until I log in as a user that is not the tenant admin. When logged in as any other user that is only a site collection administrator or lower, the custom action does not fire and all of my efforts are for naught.
This feels like a configuration or permissions issue to me but I am at a loss to begin to know where to look to rectify this issue.
Any helpful thoughts would be greatly appreciated!
Turns out I had console.log calls in my JavaScript. Some versions of IE apparently do not know how to log to the console when in browser mode without debug tools which presumably throws an uncaught and unlogged exception. Removing the console.log statements made the issue go away.

How can i access the current url in a sharepoint custom webpart?

I have created a custom webpart and deployed it in sharepoint. Now i want to modify the webpart and use the url of the site page where the web part is embedded. How can i access the url progmatically?
If you mean in the Webpart codebehind you can reference it like this:
string currentWebUrl = SPContext.Current.Web.Url;
NOTE: SPContext.Current.Site\Web (unlike new SPWeb\SPSite) does NOT need to be disposed.
Hope this helps.
Resource:
SPContext MSDN (http://msdn.microsoft.com/en-us/library/ms475883.aspx)
Something like this will give you access to the url and then you can do whatever your trying to do:
using (var spSite = new SPSite(SPContext.Current.Web.Url))
using (var spWeb = spSite.OpenWeb())
{
// code here
}

SharePoint 2010 event handler (receiver) not working on personal sites of the MySites site collection

I have a SharePoint 2010 MySites set up on its own web application. There is the standard site collection at the base level, http://site:80/.
The personal sites for each user is at the managed URL /personal/.
I have a working event handler which add items to the Newsfeed when a user adds something to a picture library.
THE PROBLEM:
The problem is, this only works if they add to a picture library at the base site collection, http://site:80/, and does NOT work if they add to http://site:80/personal/last first/.
Does anyone know why? The event handler feature is site scoped and my understanding is that it should work on all subsites.
The problem is that personal sites are not subsites of My Site host. In fact each user's personal site is a site collection on its own. So basically you need to register your event receiver not only for My SIte host, but also for each user's personal site.
Ok. Because you can only 'staple' features to site definitions which will be provisioned in the future, you need a way to activate new features on existing sites.
So, the fix I discovered and used follows:
The default page for the newsfeed is http://site:80/default.aspx. If you create an event receiver and scope it for 'site' and deploy it globally or to that web application, then it will work on the base site collection. Each personal site is a site collection and has the feature but it needs to be activated on each personal site collection.
So, in the default.aspx page, you place the following which will activate the feature if it has not yet been activated.
<script runat="server" type="text/c#">
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
String sAccount = (((SPWeb)((SPSite)SPContext.Current.Site).OpenWeb()).CurrentUser.LoginName).Split('\\')[1];
String basePersonalURL = "http://site:80/personal/";
String eventReceiverFeatureId = "12345678-1234-1234-1234-1234567890ab";
using(SPSite site = new SPSite(basePersonalURL + sAccount)) {
site.AllowUnsafeUpdates = true;
using(SPWeb web = site.RootWeb) {
web.AllowUnsafeUpdates = true;
try { site.Features.Add(new Guid(eventReceiverFeatureId)); } catch {}
web.AllowUnsafeUpdates = false;
}
site.AllowUnsafeUpdates = false;
}
}
</script>
You also need to edit the web.config file in order to allow inline code to run for this page. Hope this helps.

Strange behavoir of RunWithElevatedPrivileges in Console Aplication with FBA

I have a named site collection where FBA is on und i use ActiveDirectoryMembershipProvider.
We have a farm administrator domain\administrator. He is not explicitly sitecollection administrator.
I created a sample console application that I run under the domain\administrator account.
In the code is something like that:
using (SPSite site = new SPSite(serverUrl))
{
using (SPWeb web = site.OpenWeb())
{
Console.WriteLine(web.CurrentUser.LoginName);
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
string userName = "domain\\testuser";
SPUser spUser = web.EnsureUser(userName);
SPGroup group = web.SiteGroups["GroupName"];
group.AddUser(spUser);
group.Update();
}
}
The console output is domain\administrator however I become an AccessDenied exception when I try to add user to the group.
However when I run this with RunWithElevetadPrivileges (which according to all posts I read should have no influence in console app) and set AllowUnsafeUpdates = true (the same story) the code goes smoothly through, no exception thrown and the user is added to the group. The interesting thing is that the user that is written to the console output is still domain\administrator.
So my question is: WTF? Is there a better way? Why is this happenning? Has anyone already had this problem? Should I use another membershipprovider?
Small hint: When the FBA is off I become no exceptions.
RunWithElevatedPrivileges runs code with permissions of user that the application pool runs. It can be other than Administrator. Are you sure you get the same result with RunWithElevatedPrivileges?
Anyway, a better, more reliable way of elevating privileges is to pass system users User token in SPSite constructor. Try it.

Reset page library permission for anonymouse user in SharePoint

In the Site Collection level there is a Page library, which has been created along with the whole site. I didn't touch it for long time until recently I added new content types, modified some page layouts and master pages using a solution file. When accessing the home page using the site configured for anonymouse user it failed with "401 UNAUTHORIZED" error on the web page. I noticed the URL was /_layouts/AccessDenied.aspx?Source=...&Type=list&name={...} Then I copy this string to the site for authenticated user, it appears as "Error: Access Denied". I also checked the guid of name={...}. It's the page library list ID.
It seemed the page library permission is not correctly set. However the other page libraries of sub sites are all working well under anonymous user, using the same new content type, master page and page layouts. Their permission are identical on the settings page (all inherit from parent) and all have "allow anonymous" enabled.
I also tried create pages with other page layouts in that page library, clean up content types, all didn't help.
It's not the permission issue of the page library, rather it is related to the code I modified. SPContext.Current.Site.RootWeb is the the refernce by anonymous user. That user do not have privilege to access root folder. I assumed that SPContext.Current.Site.RootWeb.RootFolder.WelcomePage would work with elevated privilege, but after some reading I realized it's not elevate the privilege as I thought. Here's an explanation.
bool rtn = false;
SPWeb rootWeb = SPContext.Current.Site.RootWeb;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(rootWeb.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
rtn = web.Url + "/" + web.RootFolder.WelcomePage
== this.Page.Request.Url.AbsoluteUri;
}
}
});
return rtn;

Resources