How to insert a header on SharePoint page - c#

I have a very simple requirement but of course as is the case with CSOM it seems really difficult to achieve anything. I did have a solution for this, but now that the site template has changed (outside of my control) nothing works any more, and I have no idea how to debug this.
Requirement
Add a simple header to an existing SharePoint page.
Old solution
This used to work great. I pass in the page name, the web part xml and the details of the zone (I have no idea how I found those it seems ridiculously complicated just to insert a web part with code... why?...)
When i try it now I get
the object specified does not belong to a list
On the 2nd ExecuteQuery()
private void InsertWebPart(ClientContext clientContext, string webPartXml, string markerTemplate,
string pagePath, string zoneId, int zoneIndex, string description, string content, string fieldName)
{
var relUrl = new Uri(baseUrl).AbsolutePath;
clientContext.Credentials = credentials;
var web = clientContext.Web;
var page = clientContext.Web.GetFileByServerRelativeUrl($"{relUrl}/{pagePath}");
var webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
var importedWebPart = webPartManager.ImportWebPart(webPartXml);
var webPart = webPartManager.AddWebPart(importedWebPart.WebPart, zoneId, zoneIndex);
clientContext.Load(webPart);
clientContext.ExecuteQuery();
var marker = string.Format(markerTemplate, webPart.Id);
var item = page.ListItemAllFields;
clientContext.Load(item);
clientContext.ExecuteQuery();
item[fieldName] = marker + item[fieldName];
item.Update();
clientContext.ExecuteQuery();
}
I tried this solution but all I get is
the object specified does not belong to a list
Again... Please can someone advise?
How hard can it be to just simply add 1 header?

Check the solution below:
1.You can add "?contents=1" in the current site page, and remove the custom web part which add it using the CSOM code.
2.Open the site page using SharePoint designer, and edit in Advanced Mode.
3.Add the Header HTML code and JavaScript code under the "PlaceHolderMain" control.
Example code:
<div id="customHeader" style="height:20px;width:auto;background-color:green">Test</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#ms-designer-ribbon").before($("#customHeader"));
});
</script>
4.Save the page.
If you can't use the SharePoint designer, we can also use script editor web part/content editor web part with some HTML code to achieve it.
If you want to make all the page have the custom header, we can add some code into the master page to make it works.

Related

c# HtmlAgilityPack class inside many classes, need to check if class exist

I am working on this for days without a solution.
For example, I have this link: https://www.aliexpress.com/item/32682673712.html
I am trying to check if the Buy now button disable
if I have this line inside the DOM : Buy Now
the problem is that this line inside a class that inside a class and so on...
I know there is an option to get a specific node with HtmlAgilityPack But I didn't succeed
var nodes = doc.DocumentNode.SelectNodes("//div[(#class='next-btn next-large next-btn-primary buynow disable')]/p");
but I don't get anything
I tried to get the entire dom and then search with inside but didn't succeed
var getHtmlWeb = new HtmlWeb();
var document = getHtmlWeb.Load(url);
I just got the html and not the DOM
another thing I tried to do is:
var Driver = new FirefoxDriver();
Driver.Navigate().GoToUrl(url);
string pagesource = Driver.PageSource;
and it did works! but this solution open the browser and I don't want that (I am running over many links)
Please help a frustrated guy :)
thanks.
This is happening because the buynow button is being loaded via JavaScript.
If you open network tab in chrome dev tools, you will notice that the page is making a call to some api to load the product information.
The url with json data for the product looks like this:
https://www.aliexpress.com/aeglodetailweb/api/store/header?itemId=32682673712&categoryId=100007324&sellerAdminSeq=202460364&storeNum=720855&minPrice=4.99&maxPrice=4.99&priceCurrency=USD
You will most probably have to send same headers as chrome is sending for the request in order to load the api endpoint in your app.

Getting session variables from c# to a different aspx page?

I am trying to get strings that I have put in my session variables to another aspx webform. I am getting it inside my JS script and I would like to know how to go about it. I have tried the following but it doesnt seem to work. Please anyone guide me a bit.
Home.aspx.cs
HttpContext.Current.Session["InstitutionID"] = BankID;
HttpContext.Current.Session["InstitutionName"] = txtBankName.Text.Trim();
Index.aspx
$(document).ready(function () {
var param1var ='<%= Session["InstitutionID"]%>';
var param2var = '<%= Session["InstitutionName"]%>';
console.log('param1', param1var);
console.log('param1', param2var);
........
})
Are you using System.Web.SessionState.HttpSessionState.Session object to get the session object data in the Javascript? That is how I use it in one of my WebForms projects. Hope it helps.
HttpContext.Current.Session[Constants.SessionStateVariables.LoginFailed] = false;
var loginIsFailed = '<%=Session[XYZProcet.Common.Constants.SessionStateVariables.LoginFailed]%>';

PhantomJs save webpage containing dynamic data as webpage

I have used jQuery plugin to generate charts on screen along with dynamic data and notes.
I need to generate PDF of this webpage on button click.
I have tried to search good option but not able to find any proper one.
Right now I am trying to use phantomjs for this. It works for internet sites but not working for intranet sites.
I am continuously getting Unable to load address.
Can anyone suggest me the way to achieve this? Or any alternative way to generate PDF from html content (My html contains SVG, Javascript generated dynamic data too).
Code:
string serverPath = "C:\\Phantomjs\\bin\\phantomjs";
var phantomJS = new PhantomJS();
var outFile = Path.Combine(serverPath, "google2.pdf");
if (File.Exists(outFile))
File.Delete(outFile);
try {
phantomJS.Run(Path.Combine(serverPath, "rasterize.js"),
new[] { "http://localhost:61362/HT.aspx?FNo=D1&PrNo=Dummy1&HtId=1033", outFile });
} finally {
phantomJS.Abort();
}
The url is not working in this case. But if I take any internet hosted site, it works.

SharePoint Foundation 2013 - Master Page 404 NOT FOUND

I hope this is right place to ask question. I tried use sosial msdn, but it seems that msdn forum is dead. I have small problem with Master Page. I have created Web Template and Master Page. When I create new site collection and I try access to it (http://win2008r2/sites/Test), it throws me error that: "404 NOT FOUND".
However, when I check MasterPage gallery: http://win2008r2/sites/Test/_catalogs/masterpage/Forms/AllItems.aspx
I can find my Demo.master . When I check Site Collection Features, I can see that my Master Page feature is active. I checked the logs and this was only thing what I found: Failure when fetching document. 0x80070002
I have set Web Template scope to farm and I have set Master Page scope to site.
I try to solve problem using google and I tried different guides but no I cannot get it work. Can anyone please help me?
Here is Element.xml:
<Module Name="MyMasterPage" List="116" Url="_catalogs/masterpage">
<File Path="MyMasterPage\Demo.master" Url="Demo.master" Type="GhostableInLibrary">
</File>
</Module>
Here is event receiver:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPWeb _web = ((SPSite)properties.Feature.Parent).RootWeb)
{
Uri _siteMaster = new Uri(string.Format("{0}/_catalogs/masterpage/Demo.master", _web.Url));
_web.MasterUrl = _siteMaster.AbsolutePath;
_web.CustomMasterUrl = _siteMaster.AbsolutePath;
_web.Update();
}
});
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite curSite = (SPSite)properties.Feature.Parent;
SPWeb curWeb = curSite.RootWeb;
Uri masterUri = new Uri(curWeb.Url + "/_catalogs/masterpage/v4.master");
curWeb.MasterUrl = masterUri.AbsolutePath;
curWeb.CustomMasterUrl = masterUri.AbsolutePath;
curWeb.Update();
}
If you want to see more of my code to solve this problem, please feel free to ask, so I put more code up. ;)
Thank you Yevgeniy.Chernobrivets! Problem was that I had named my default.aspx to MySite.aspx and it didn't work. When I created it again and I keep default.aspx name it worked! Well now I have to find way to change that default.aspx name =)

Modify the content of the home page programmatically in SharePoint 2010

First of all, I'm pretty new to SharePoint so don't shoot me if this is a noobish question or if I don't provide all the right information at once... :)
I have a team-site in SharePoint with following URL: "http://myServer/Opdracht_Ben/". By going to this URL I'm redirected to following page: "http://myServer/sites/Opdracht_Ben/SitePages/Home.aspx".
In Visual Studio I have a project for this site with a feature. When this site-feature is activated it should change the content of the home-page to some custom tekst and layout (i.e.: HTML). The content is not contained within a web part or the page is not a WikiPage, just text on a page.
I've been looking on MSDN and on several tech-sites and blogs but I have not found anything that could help me further. Does anyone know how I can 'reach' the content of the page and modify/update it?
PS:
Here on SO I have found a related question (Click for the question), but the provided solution is for when the web is a "Publishing Web", which is not the case here, so that solution won't do me any good.
Thanks in advance!
I have found out that the page IS a WikiPage after all. So I managed to change the content with following code:
using (var site = new SPSite(ApplicationResources.Url.SiteRoot))
{
using (var web = site.OpenWeb())
{
var page = web.GetFile(ApplicationResources.Url.FullDefaultPageName);
var item = page.Item;
item["Wiki Content"] = NewContent(title, text);
item.Update();
}
}
Maybe this is not the best method, so if anyone has a better and more reliable solution: feel free to correct me! ;)

Categories