Preventing the duplication of CSS files? - c#

I got a user control which implements a reference to a css file, now I want to use this user control many times on page, and this will lead to duplication of inclusion of the css file.
With javascript files it is simple by using the ScriptManager.
So what is your suggestion for a solution or similar approach to the ScriptManager?

Here's a technique I've used before, although it may not be the best one:
Dim cssLink As String = String.Format("<link rel='stylesheet' type='text/css' href='{0}/css/cssLink.css' />", Request.ApplicationPath)
If (From c As LiteralControl In Page.Header.Controls.OfType(Of LiteralControl)() Where c.Text = cssLink).Count = 0 Then
Page.Header.Controls.Add(New LiteralControl(cssLink))
End If

As q is tagged c# thought I may as well paste in c# version from helper class:
public static void AddStyleLink(string href)
{
Page page = (Page)HttpContext.Current.CurrentHandler;
var existing =
(from c
in page.Header.Controls.OfType<HtmlGenericControl>()
where c.Attributes["href"] == href
select c).FirstOrDefault();
if (existing == null)
{
HtmlGenericControl link = new HtmlGenericControl("link");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", href);
page.Header.Controls.Add(link);
}
}

There is no easy way to check if the styles are registered to the page like ClientScript utility.
If you register your styles as an external css file to page like that :
HtmlLink link = new HtmlLink();
link.Href = relativePath;
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
Page.Header.Controls.Add(link);
You can then check if it exists by looping the page header's Controls collection and looking for the path of the CSS file.

Related

How to scrape a variable data from a source code?

I'm trying to scrape a link from the source code of a website that varies with every source code.
Form example:
<div align="center">
<a href="http://www10.site.com/d/the rest of the link">
<span class="button_upload green">
The next time I get the source code the http://www10 changes to any http://www + number like http://www65.
How can I scrape the exact link with the new changed number?
Edit :
Here's how i use RE MatchCollection m1 = Regex.Matches(textBox6.Text, "(href=\"http://www10)(?<td_inner>.*?)(\">)", RegexOptions.Singleline);
You mentioned in the comments that you use Regulars expressions for parsing the HTML Document. That is a the hardest way you can do this (also, generally not recommended!). Try using a HTML Parser like http://html-agility-pack.net
For HTML Agility Pack: You install it via NuGet Packeges and here is an example (posted on their website):
HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm");
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[#href]")
{
HtmlAttribute att = link["href"];
att.Value = FixLink(att);
}
doc.Save("file.htm");
It can also load string contents, not just files. You use xPath or CSS Selectors to navigate inside the document and select what you want.
How about a JS function like this, run when the page loads:
// jQuery is required!
var updateLinkUrl = function (num) {
$.each($('.button_upload.green'), function (pos, el) {
var orig = $(el).parent().prop("href");
var newurl = orig.replace("www10", "www" + num);
$(el).parent().prop("href", newurl);
});
};
$(document).ready(function () { updateLinkUrl(65); });

How to use html tag in code behind?

I need to use html tags such as <sup></sup> in code behind without declaring anything in aspx page.
So far I've tried below:
string s = HtmlTextWriterTag.Sup.ToString("1");
Try this one:
var strVariable = "This is a string object";
strVariable = strVariable.sup();
From MSDN
you may use html gerneric contorls
HtmlGenericControl sub= new HtmlGenericControl("sub");
sub.Attributes.Add("class", "your-class");
sub.ID = "subId";
sub.ClientIDMode = ClientIDMode.Static;

Add CSS File in DLL (Class Library)

I have a Class Library project named "AddJsFunction" which contains a class where I am including all related JS, CSS and Image files. Below is the IncludeJsFile method inside the above mentioned class where I am adding all the Javascript files which works as expected.
public void IncludeJsFile(Page pg)
{
pg.ClientScript.RegisterClientScriptInclude(this.GetType(), "Test2", pg.ClientScript.GetWebResourceUrl(this.GetType(), "AddJsFunction.queue.js"));
string csslink2 = "<script type='text/javascript' language='javascript' src='" + pg.ClientScript.GetWebResourceUrl(this.GetType(), "AddJsFunction.queue.js") + "' />";
LiteralControl include2 = new LiteralControl(csslink2);
pg.Header.Controls.Add(include2);
}
Same way I want to embed the CSS files which i tried to include like shown above but that is not working and I need some help to do the same.
Thanks,
VY.
From Is there a ClientScriptManager.RegisterClientScriptInclude equivalent for CSS:
HtmlLink link = new HtmlLink();
link.Href = "Cases/EditStyles.css";
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
//check if it exsists on the page header control first
foreach (Control control in pg.Header.Controls)
{
if ((control is HtmlLink) &&
(control as HtmlLink).Href == href)
{
return true;
}
}
pg.Header.Controls.Add(link);

Create a page programatically with C# in SharePoint 2007

Not sure if this is asked, but searching hasn't quite yielded what I'm looking for. I have a page layout already, what I need to do is programmatically create a page in the Pages library.
I'm fuzzy on the details, but somehow I think I will need to open the Layout, then stream it to a page and then save the page. I'm unsure how to go about this.
The page is context sensitive so I think I'll begin with using SPSite and SPWeb to get access to the lists.
What I'm unclear on is, how can I get the Layouts? I think I should be able to add a page somewhat like this:
SPWeb web = SPContext.Current.Site.OpenWeb();
SPList Pages = web.Lists["Pages"];
SPListItemCollection splc = Pages.Items;
foreach (SPListItem spli in splc)
{
if (spli.Name == "lmIntraTopicsArticle")
{
}
}
SPListItem sli = splc.Add();
Pages.Update();
SPFolder PagesFolder = Pages.RootFolder;
byte[] layoutContents = new byte[20];
SPFile myNewPage = PagesFolder.Files.Add(PagesFolder.Url + "/TopicWindowArchive.aspx", layoutContents);
web.Update();
Now I need to figure out how to add content from a layout. Update in a few if I figure it out.
Thank you,
The trick is to get a PublishingWeb object. That contains the layouts.
See here for an example
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
string pageName = “MyCustomPage.aspx”;
PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();
PageLayout currPageLayout = pageLayouts[0];
PublishingPageCollection pages = publishingWeb.GetPublishingPages();
PublishingPage newPage = pages.Add(pageName,currPageLayout);
newPage.ListItem[FieldId.PublishingPageContent] = “This is my content”;
newPage.ListItem.Update();
newPage.Update();
newPage.CheckIn(“This is just a comment”);
Also check this answer

Adding StyleSheets Programmatically in Asp.Net

I want to add StyleSheets programmatically in the head section but one of the examples I saw seemed to need to many lines of code to add just one style sheet even though I may need a lot:
Example Code:
HtmlLink css = new HtmlLink();
css.Href = "css/fancyforms.css";
css.Attributes["rel"] = "stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["media"] = "all";
Page.Header.Controls.Add(css);
I also use Page.Header.RenderControl() method but it didn't work either. Object null something error was thrown.
I also used Page.Header.InnerHtml and InnerText += "<link .... "/> things but they threw the Literal error which is I think common error.
I used this code :
List<Literal> cssFiles = new List<Literal>();
cssFiles.Add(new Literal() { Text = #"<link href=""" + ResolveUrl("~/Resources/Styles/MainMaster/MainDesign.css") + #""" type=""text/css"" rel=""stylesheet"" />" });
cssFiles.Add(new Literal() { Text = #"<link href=""" + ResolveUrl("~/Resources/Styles/MainMaster/MainLayout.css") + #""" type=""text/css"" rel=""stylesheet"" />" });
AddStyleRange(cssFiles);
private void AddStyleRange(List<Literal> cssFiles)
{
foreach (Literal item in cssFiles)
{
this.Header.Controls.Add(item);
}
}
It worked at first but when I change the pages it stopped working.
I am using Master Page and I am writing these codes on Master.cs file and also some people recommended to use this.Header instead of Page.Header but when I built it throws an error which says I cannot declare that like this.
It shouldn't be that hard to add many styles.
It is getting complicated.
Okay, here is the solution I am currently using :
I created a helper class :
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BusinessLogic.Helper
{
public class CssAdder
{
public static void AddCss(string path, Page page)
{
Literal cssFile = new Literal() { Text = #"<link href=""" + page.ResolveUrl(path) + #""" type=""text/css"" rel=""stylesheet"" />" };
page.Header.Controls.Add(cssFile);
}
}
}
and then through this helper class, all I have to do is :
CssAdder.AddCss("~/Resources/Styles/MainMaster/MainDesign.css", this.Page);
CssAdder.AddCss("~/Resources/Styles/MainMaster/MainLayout.css", this.Page);
CssAdder.AddCss("~/Resources/Styles/Controls/RightMainMenu.css", this.Page);
//...
So I can add as much as I want with one line of simple code.
It also works with Masterpage and content page relationships.
Hope it helps.
P.S: I don't know the performance difference between this and other solutions but it looks more elegant and easy to consume.
I'll paste the thing which worked for me:
HtmlLink link = new HtmlLink();
//Add appropriate attributes
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");
link.Href = "/Resources/CSS/NewStyles.css";
link.Attributes.Add("media", "screen, projection");
//add it to page head section
this.Page.Header.Controls.Add(link);
Even I searched a lot on this, I'd to add a overriding style sheet when a button is clicked. I used the above code and it worked perfectly to me.
I define a generic HTML <link> and set the href attribute programmatically.
For example, in the page <head> I have:
<link id="cssStyle" runat="server" rel="stylesheet" type="text/css" />.
Then in Page_Load set the Href property of cssStyle:
cssStyle.Href = "path/to/Styles.css";
Seems a bit cleaner with the upside of having the design control over placing the <link> in the desired order.
I went a step over, I wanted a method that makes me impossible to add include duplicates, something like ClientScriptManager.RegisterClientScriptInclude().
The solution is to give an ID to the control added in the Header section.
if (!String.IsNullOrEmpty(Key))
if (Page.Header.FindControl(Key) != null) return;
HtmlLink link = new HtmlLink();
if (!String.IsNullOrEmpty(Key)) link.ID = Key;
link.Href = StyleUrl;
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(link);
For the complete article I wrote: http://www.idea-r.it/Blog.aspx?Article=49

Categories