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

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
}

Related

Unable to rename subsite URL via CSOM in SharePoint Online

I have set up a SharePoint Online site and I have created a provider hosted app. One of the features of the app is to create subsites and there are times when a subsite needs to be renamed, including renaming the subsite URL. I can use the CSOM to create the subsite without any problems but when I try to rename the URL I get an access denied error. If I only change the title and description of the subsite there is no problem. If I log into SharePoint Online via the browser (using the same user account!) and I use the UI to rename the URL then it works without any problem. The page in SharePoint I use to rename the URL is https://tenant.sharepoint.com/testproject/_layouts/15/prjsetng.aspx
I have tried this on both a Microsoft 365 Developer subscription (where I am doing most of my development and testing) and the main SharePoint Online site where the solution will eventually be deployed to. I don't know much of the details for the main SPO site, other people set it up and I was provided an account to test renaming the subsite. To be clear, I am able to rename the subsite URL via the UI in both the developer and main SharePoint Online sites.
Is there something I'm doing wrong? Is there a limitation to renaming a subsite URL via code in SharePoint Online? Is there a bug in SharePoint Online that prevents renaming a subsite URL using code?
The exception thrown includes ServerErrorTypeName = "Microsoft.SharePoint.SPException". I can get the correlation id but from what I understand that's of no use in SharePoint Online. The exception Message is literally "Access denied." There is no inner exception.
Here is the code I'm using to rename the subsite:
SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
ClientContext clientContext = new ClientContext(spContext.SPHostUrl)
{
Credentials = new SharePointOnlineCredentials("SPUserName", "SPPassword".ToSecureString())
};
var webUrl = request.OldProjectUrl;
var subweb = clientContext.Site.OpenWeb(webUrl);
clientContext.Load(subweb);
clientContext.ExecuteQuery();
subweb.Title = request.ProjectName;
subweb.Description = request.ProjectName;
subweb.ServerRelativeUrl = "/HardcodedForTesting"; // <-- if I skip this line there is no error
subweb.Update();
clientContext.ExecuteQuery();
I was trying to achieve the same result but encountered the same error.
I was able to solve this by disabling the NoScriptSite setting of the site collection.
Using the PnP.PowerShell module:
Set-PnPSite -NoScriptSite:$false
Also the value you give to the ServerRelativeUrl property must be correctly constructed. I found two allowed format:
/sites/site-collection-path/new-subsite-path
new-subsite-path
Just did a test on my environment, I could rename the subsite URL via CSOM code normally. I use the same code as yours.
For your issue, you'd better create a service request with Microsoft.

Getting error message in Sharepoint when I publish a webpart

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!

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.

Getting the GUID for any given path to sharepoint

I'm trying to get the GUID of a given sharepoint URL. I don't mind using the API or the webservices or Sharepoint's database.
if i were to write a function, it's signature would be:
//get a GUID from path.
string GetGuidFromPath(string path){}
I had a lead: SPContentMapProvider but it doesn't seem to get the right info.
Thank you!
Depends - what's the context of the current request? Is your code running in the context of a SharePoint request? If so you can just use SPContext.Current.Web.ID
Otherwise, is your code at least running on one of the SharePoint servers? If so you'll need to use:
// Given the URL http://mysharepointsite.com/sites/somesite/somesubsite
using(SPSite site = new SPSite("http://mysharepointsite.com/sites/somesite"))
{
using(SPWeb web = site.OpenWeb("somesubsite"))
{
Guid webId = web.ID;
}
// Or
Guid rootWebId = site.RootWeb.ID;
}

How can I restrict what web parts show up in the Add Web Parts window?

I'd like to expose a web part to some users, but not all of them. How can I show or hide a web part in the Add Web Parts pop up window? I'd like to do this through code, and I'm hoping to use SharePoint Roles to make this happen.
I know you can manage which web parts show up in the Add Web Parts window in the Web Part Gallery.
While I haven't done it... since it's just another SharePoint List, you should be able to programmatically assign roles to Groups/Users?
More Info...
Update - Since you want to see some code. Nothing special, just a quick hack. You'll definitely want to do your standard error checking, etc. HTH :-)
using (SPSite site = new SPSite("YOUR SP URL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Web Part Gallery"];
// Your code for choosing which web part(s) to modify perms on
// will undoubtedly be more complex than this...
SPListItem listItem = list.GetItemById(19);
SPPrincipal groupToAdd = web.SiteGroups["YOUR GROUP NAME"] as SPPrincipal;
SPRoleAssignment newRoleAssignment = new SPRoleAssignment(groupToAdd);
SPRoleDefinition newRoleDefinition = web.RoleDefinitions["Read"];
newRoleAssignment.RoleDefinitionBindings.Add(newRoleDefinition);
listItem.RoleAssignments.Add(newRoleAssignment);
}
}
You can do this with SharePoint Groups.
Go to the Web Part Gallery, click "Edit" on the web part you wish to scope, then click Manage Permissions. Here you can specify which users or groups can use the web part.

Resources