Apply masterpage to multiple site collections - c#

I need to apply a masterpage to multiple site collections in SharePoint 2010. The masterpage is part of a feature of a VS 2010 solution. The problem is, I can only use site and web scope, not web application. When I use the following code, I get an error that an .aspx website could not be found. Does anybody have a hint why?
SPWeb CurrentWeb = properties.Feature.Parent as SPWeb;
string masterUrl = CurrentWeb.MasterUrl = CurrentWeb.Site.RootWeb.ServerRelativeUrl + customMasterpage;
string customUrl = CurrentWeb.CustomMasterUrl = CurrentWeb.Site.RootWeb.ServerRelativeUrl + customMasterpage;
CurrentWeb.Update();
SPWebApplication webApp = CurrentWeb.Site.WebApplication;
System.Diagnostics.Debugger.Break();
foreach (SPSite site in webApp.Sites)
{
foreach (SPWeb web in site.AllWebs)
{
ChangeMasterPage(web, masterUrl, customUrl);
}
}

Related

Token failed : 401 Forbidden Error connecting to Sharepoint using pnpframework

I am writing a web app that I would like to have access to Sharepoint Document Libraries from a particular site using the currently logged on user credentials. I have looked at a number of articles that suggest using the PnP Framework and using a certificate instead of the client/secret ids.
I have tried both, the code of which is below:
string siteCollectionURL = "https://mycompanyname.sharepoint.com/sites/staffportal";
var authManager = new AuthenticationManager(ApplicationId, "C:\\pathtopfxfile\certifcatefx.pfx", "certificatepassword", "https://mycompany.sharepoint.com/sites/staffportal");
using (var clientContext = authManager.GetACSAppOnlyContext(siteCollectionURL,ApplicationId,ClientSecretId))
{
clientContext.Load(clientContext.Web, p => p.Title);
clientContext.ExecuteQuery();
return Ok(clientContext.Web.Title);
}
Unfortunately on the ExecuteQuery line I am consistently getting the 401 error, indicating that I am not authorized.
I registered the app in Azure -> Enterprise applications:
I have checked the following articles:
How to use the PnP Framework in a c# application
Secure Authentication of SharePoint with PnP Framework with C#(Code)
And tried the code snippets, but I cannot seem to find anything that suggests using the currently logged in user to the Web app.(see screen shot) - the user is a global administrator
Below is the error:
Any suggestions would be much appreciated.
Regards,
Darren
UPDATE TO ARTICLE
jimas13's link is what pointed me in the right direction. The tweaks I mentioned in the comment I have posted below for anyone wanting to write an MVC C# web app. This does require that the app needs to be registered and needs a self-signed certificate setup.
The two Async lines need to be written as follows:
public static async Task<AuthenticationResult> GetToken(IConfidentialClientApplication app, string[] scopes)
{
return await app.AcquireTokenForClient(scopes).ExecuteAsync();
}
public static async Task<Web> GetClientContext(string Uri,AuthenticationResult authResult)
{
using (var clientContext = ContextHelper.GetClientContext(Uri, authResult.AccessToken))
{
Web web = clientContext.Web;
clientContext.Load(web);
await clientContext.ExecuteQueryAsync();
return web;
}
}
The rest of the code is here:
public IActionResult Index()
{
AuthenticationConfiguration.AuthenticationConfiguration config = AuthenticationConfiguration.AuthenticationConfiguration.ReadFromJsonFile("appsettings.json");
string siteURL = config.SiteUrl;
string[] scopes = new string[] { config.Scope };
CertificateDescription certificate = config.Certificate;
ICertificateLoader certificateLoader = new DefaultCertificateLoader();
certificateLoader.LoadIfNeeded(certificate);
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithCertificate(certificate.Certificate)
.WithTenantId(config.Tenant)
.WithAuthority(config.Authority)
.Build();
AuthenticationResult result = GetToken(app, scopes).Result;
Web WebSite = GetClientContext(siteURL, result).Result;
return Ok(WebSite.Title);
}
The .SiteUrl and .Scope were added to the AuthenticationConfiguration.cs file as a property and then also added to the appsettings.json file.

Why does SPContext.Current return a null value?

I am new in SharePoint development and I am developing a custom SharePoint Farm Solution. I am currently having an issue with code which runs properly on the production and test environments but gives an error on the development and I don't know why. The source code looks identical in all environments. I was able to locate the error through debugging and I found that it gives an error on the following line:
SPWeb web = SPContext.Current.Web;
The code is about sending an email upon the completion of course evaluation function in my application. Here's the code:
MailConfiguration config = new MailConfiguration();
MailNotification content = config.GetMailNotification(userId, courseId);
SPWeb web = SPContext.Current.Web;
string subject = content.Subject;
string msgBody = content.Body;
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, content.To, subject, msgBody);
message = "Email sent successfully";
});
Could you please explain to me why this is happening? The SendEmail function is not working now due to this error.
Check the follows:
1.Check the alternate mapping access(AAMs). If not, configure it.
2.Check if have Site Collection at the root of the SharePoint website.
3.Use the method below to create a fake SPContext in a non-SharePoint context.
public static SPContext FakeSPContext(SPWeb web)
{
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(TextWriter.Null));
}
if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
{
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
}
return SPContext.Current;
}

Getting Access Denied on sharepoint list

I'm making an ASMX web method call that contains the following code...It ultimately adds a new item to a sharepoint list
string spsite = "http://site/subsite";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite objSite = new SPSite(spsite))
{
using (SPWeb oweb = objSite.OpenWeb())
{
oweb.AllowUnsafeUpdates = true;
SPList list = oweb.Lists["List"];
SPListItem item = list.Items.Add();
item["col1"] = "test";
item["col2"] = "test";
item.Update();
}
}
});
However, I get the following error messages...
You do not have permission to view this directory or page using the credentials that you supplied
Why is this? I thought RunWithElevatedPrivileges does away with this?
Where is this web service hosted? Using RunWithElevtatedPrivileges will use the account that the app pool runs on. If the app pool does not have permission, then you will get access denied.

Accessing list from Sharepoint Webservice with Sharepoint Online 2013

I am trying to access a list from sharepoint via the web services.
I have tried lots of different web reference URLS for my web service.
The list is found at :
example.com/sites/dms/_layouts/15/start.aspx#/Lists/Documents/AllItems.aspx
the Web service URL I am using now is
https://example.com/sites/dms/_vti_bin/lists.asmx
Obviously example.com is not the real URL.
when I run the code
service.GetList("Documents");
I get the error:
List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
0x82000006
My full code (many things are just for testing purposes):
public void UpdateList()
{
MKLists.Lists service = GetService();
string targetSite = "https://mywebpage.com/sites/dms";
using (ClientContext ctx = ClaimClientContext.GetAuthenticatedContext(targetSite))
{
if (ctx != null)
{
ctx.Load(ctx.Web); // Query for Web
ctx.ExecuteQuery(); // Execute
string test = (ctx.Web.Title);
}
}
CookieCollection authCookie = ClaimClientContext.GetAuthenticatedCookies(targetSite, 925, 525);
service.CookieContainer = new CookieContainer();
service.CookieContainer.Add(authCookie);
XmlNode tester = service.GetList("Documents");
}
private MKLists.Lists GetService()
{
MKLists.Lists myService = new MKLists.Lists();
myService.Credentials = System.Net.CredentialCache.DefaultCredentials;
return myService;
}
change this line:
MKLists.Lists service = GetService();
with
MKLists.Lists service = new MKLists.Lists();
i hope this helps.
Edit
according to your comment in the answer here is the update #Michael
try changing your targetsite url to
string targetSite = "https://mywebpage.com/sites/dms/_vti_bin/Lists.asmx";
hope this time it helps
IT turns out it was to do with the subsites.. and this line solved it:
service.Url = "https://mywebpage.com/sites/dms/_vti_bin/lists.asmx";
I've found some users with the same issue.
They said that these links below solved that issue. Could you try it?
http://blogs.msdn.com/b/sharepointdev/archive/2011/05/12/connecting-to-sharepoint-online-web-services.aspx
http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx

TopNavigation Bar is shown Null for Report Centre site in Sharepoint 2007

I have create a Publishing site collection and when i try to get the TopNavigation Bar for 'Report Centre' site I get it null. Why ? However for Document Centre,News etc it is not null. Can someone explain me ?
string siteUrl = "http://sp07:9988/sites/testpubsite/Reports";
using (SPSite site = new SPSite(siteUrl))
{
SPWeb web = site.OpenWeb();
var topBar = web.Navigation.TopNavigationBar;
}

Categories