Edit source css with C# - c#

I was just wondering is it possible to edit a websites source clientside using C#. Like say I wanted to change webkit-user-select from none to inherited.
body {
background: #000;
color: #333;
margin: 0;
padding: 0;
-webkit-user-select: none;
}
I was wanting to add the option to the pageloadcomplete section, Just don't know where to begin. Never done that.

It sounds like you want to temporarily modify the CSS file of (I assume the same project as your C# web site?) so it renders differently, but you want to do it from C# some how?
If so, the answer is you can, but I don't recommend it. But you can't do it in the ASPX WebForms page request, because the link in the CSS file that the ASPX request links to is a separate HTTP request completely.
Instead, you would have to write an HTTP handler and run all your CSS requests through it, manually load the CSS file, parse it, and somehow determining how and when to modify the response. Way too much work; I don't recommend it.
I think the simpler solution would be to have an extra CSS class in the file that doesn't normally apply to the element you want it to, then render client-side JavaScript in your ASPX page so that when the page loads (in the client) the JavaScript can add the CSS class to the element you need it to so different CSS applies.
There are lots of ways to write JavaScript to add/remove classes, both with libraries or in direct code. Google search for how to do that, there are a lot of basic tutorials on altering CSS classes on DOM elements via JavaScript.
IF the assumptions above are wrong, and you want to modify the CSS of another site you don't control, the answer is again, technically yes, but an even more emphatic "it's not worth it." You'd have to write a whole C# application to load the web site and all its resources, intercept the CSS file before being loaded into whatever renderer you're using, write code to parse the CSS and adjust it, etc. There's no reason to go to all that effort.
It would be a little more reasonable to write a browser plugin to do it, but again, that's a ton of work too.

Related

What is the best way to filter bad HTML Content from Posts using AntiXSS Library?

I want to create an Asp.net Website and I want to prevent Cross Site Scripting. I have a page with Summernote (a WYSIWYG HTML Editor), which, when submittet, posts HTML Code to MVC ActionResult via form or Ajax Post.
This Method saves this Code in my Database as content/body of a message. On another Site, you can display the content, which shows formating things like Lists etc.
Because of security reasons i want to filter the content i recieve from client. I am using the AntiXSS Library from Microsoft.
A part of my MVC Code:
[ValidateInput(false), HttpPost, ValidateAntiForgeryToken]
public ActionResult CreateMessage(string subject, string body)
{
var cleanBody = Sanitizer.GetSafeHtmlFragment(body);
//do the Database thing here
}
The major problem is, that it kills my HTML Elements with tag, because it removes the src=""
should be:
<p><img src="data:image/png;base64,some/ultra/long/picture/code/here" data-filename="grafik.png"></p>
remaining:
<p><img src="" alt=""><img src=""></p>
What can i do to prevent this?
Is there a way to add an exception rule?
Is there an another better way?
How does it work?
Thanks for help!
There is no such thing anymore as the "AntiXSS Library". It used to be a separate library, but Microsoft moved it into .Net, so it's now under System.Web.Security.AntiXss.
The reason this is important is that you need a sanitizer. The way you are using AntiXss currently will take a list of html tags and a list of attributes to those tags, and will remove everything else from your html code. That's not very good for you, because you only want to remove javascript, regardless of tags or attributes. Let's take for example <a>, with its href attribute. You most probably want to allow your users to insert links, but you don't want them to be able to insert javascript via <a href="javascript: ...">. So you cannot filter out href for <a>, but if you leave it, your page will be vulnerable to XSS.
So you want a sanitizer that only removes javascript. In the original AntiXSS library there was a sanitizer, but when Microsoft moved it to .Net, the sanitizer was left out.
So in short, AntiXss will not help you with your current usecase.
You can find proper html sanitizers like for example Google Caja (client-side sanitizer here), or many others. The point is, even if this sanitizer is in javascript (on the client), if you carefully don't insert your data into the page DOM before sanitizing it, it will all be fine.
So in short, you could just save any data from the HTML editor to your database as is without any transformation (mind sql injection of course, but current data access technologies should have that covered), and then when such data is displayed, send it to the client without adding it to the page dom (like as json data for example, but properly encoded for json then of course!), then run your sanitizer that will remove any javascript, and then add it to the page.
The reason this is very good is because your wysiwyg html editor will likely have a preview screen. Don't forget to add sanitization to previews as well, otherwise the preview will be vulnerable to XSS. If sanitization was on the server, you would have to send the editor contents to the server, sanitize it and send it back to your user for preview - not very user-friendly.
Also note that many wysiwyg editors support hooking into their rendering and adding such a sanitizer. If an editor does not support this and does not have its own sanitizer, that cannot be made secure with regard to XSS.

Include pre-compiled content in MVC View

I have some pre-compiled html content which I want to include in my View like:
#*View Start*#
Some precompiled html
Some view content
Some precompiled html
Some view content
Some precompiled html
#*View End*#
I have already thought of some ways but each of them has some GREAT downsides that I don't want to use it. these are the ways I have thought of:
Although these html codes are pre-compiled with fixed content they may change time to time (let say weekly) so can not be included in view itself
They're rather big in size so I don't think having them in database would be wise (would increase database size and data-bandwith)
Having them in html files and writing them into view using C# functions something like #File.ReadAllText("page-customized-head.html") and this would be slow and would make hard disk busier than it should.
I want to know if anybody can suggest a better solution or a way to improve the above solutions.
Edit:
I had put aside solutions like ajax, as in this situation was not suitable for my design. After #Hadee's comment I noticed that my description is not complete, so I'm adding some more description.
These content files can be unique for different pages of different users as user can customize css, js. add - edit remove html elements. So each user may have several pages that each page may have several different "Pre-Compiled" section.
As these content may be the head section of the page, may contain css, js (that following content may rely on it), ... ajax is not suitable in here.
And as for partial views, I don't see any different between them and having the content written into html file. Actually I think html file and #File.ReadAllText("page-customized-head.html") would be faster, as unlike .cshtml it does not need compiling.

C# best solution for Print invoice

I would like to design a invoice and print using asp.net C#. I has tried create a aspx page and using window.print to print it through browser. But it was no good results since every computer difference setting/margin/resolution.
I searched the web and tried many way like tbody tbody, css page break, media print, ReportGridView. But still same no good results too.
The template I want to print is consists of a table above every printed page to display information about the invoice. Below consists of a gridview. Since every records got difference length and also difference amount of record inside an invoice.
The invoice should fulfill those condition:
print a table a header on every printed page
display page numeber like 1/n page in every printed page
auto split gridview if exceed page length
Anyone met this issue before can share your tech/coding/skill/comment/experience? Thanks. Some people suggest me save as PDF. What tools would be suitable for this?
I have been using plain HTML document extensively to display invoice in real world production environment. What you need to do is well-defined the document size. Below is an example:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Invoice
</title>
<style type="text/css">
.page{
width: 630px;
height: 900px;
margin: auto;
border: 1px solid black;
padding: 10px;
}
.middleblock{
height: 600px;
border: 1px solid black;
}
.bottomblock{
height: 100px;
padding: 20px;
}
</style>
</head>
<body>
<div class="page">
<h1>Invoice</h2>
<div class="middleblock">
</div>
<div class="bottomblock">
Issued by,
</div>
</div>
</body>
</html>
Well, I think you did a good job of describing the page. I have faced this issue many times. You have left a lot of freedom as to how to do it, so I will propose a few.
[Rebuttal to browser attempt]
I have tried the whole, print in browser thing. It is good for the end user, but not internal docs. I think you were good to stay clear of that. This is a problem I to would like to simplify.
Another person might extract the browser measurements using some javascript. I think the only detractor is possible maintenance there, so it is not bad approach. Not sure the measurements are your only cross-browser concern though. I think the .print function has been limited(unsupported in many browsers, so I had my client use chrome, and it was acceptable).
[Real Concerns]
IMO, the hard part is the page breaks. That can be hard to calculate and greatly complicate the issue. So, a good go is to try to use a familiar app like Excel or Open Office. I avoid the interop libraries that can handle Excel files natively. It is very low level. If your going to go that far, maybe use a pdf gen library like PhantomJS below.
[Bad, but maybe?]
One solution that has been recently made harder, would be to design your layout as an HTML table, and write it into the response as a .xls file. For a long time, Excel would throw a warning when opening the file, but it worked just fine and could be crudely styled.
However, recently Excel has a 'feature' where when these (.xls, xlsx)files that come from the web require the user to right-click on them, select properties, and then click the 'UnBlock' button. Not a deal breaker, but a nuisance for sure if the use case is legitimate.
[Better, but doesn't answer the question]
In most cases where budget is a concern, we are replacing that system with an even easier solution of just writing a csv file (delimited file). If done properly, we can get the data into a spread sheet. From there, their people are ok with a copy and paste into their actual formatted sheets. CSV cannot provide any formatting.
[Maybe?]
Another possible solution might be to use an approach like http://wkhtmltopdf.org/. This has worked in a lot of situations. We have found that it has a hard time rendering style in nested tables though. Frankly, that is easily disputed (could have been my fault at some level) and this is probably worth a look in your case.
[Possibly?]
Another possible method would be to send some html to PhantomJS. (See 9/2016 update below for more info) They have an .exe that will read your JavaScript code file to do some cool stuff, including rendering it and taking a screenshot. I use that to make images from html generated by a text editor. The nice thing there is that it always uses webkit, so the 'output' is the same across browsers. I may not render what the user intended, but I render the final and they work around, for now.
They also offer an API and a cloud service. I get images generated on their server faster than ours. There is a pay 'wall' you can hit though. I get like only 10,000 renders a month for free, or some absurdly favorable thing. (cause I do html text snips, as I said, where they base price on avg page render time of their current users. (process time and output))
[Our Friends said...]
If you are .Net savvy and the projects allow, I cannot discount the other poster who referred to the controls that allow for this within the .Net Asp frame work. My boss has a terrible problem with using .Net web controls. However, I have used the very tool you would be in a desktop app. Done simply because it had so many export options. The design process is a lot like Access, if you are familiar. And Crystal Reporting is like Access on steroids, but again, like interop or native pdf gen, requires learning a whole new thing.
[Done]
:p
So, that is what I had to say. I hate this issue badly and hope this helped.

Using C# variables in CSS

I'm working on a website using ASP.NET C# code, the website will be used for a variety of websites and only serve as a 'placeholder'. We would love to have CSS code which can have different markup depending on which website you are visiting. We're pulling information about the website someone is visiting from our database, which has some methods attached to return these values.
The problem is that we want to be able to use these values in CSS code, and currently the only way I can think of doing this is by using inline CSS code instead of .css files. Which would make our code look something like:
<style>
.navbar {
background-color: #Website.Models.WebsiteConfiguration.NavbarColor;
}
</style>
Which isn't ideal. Is there another way of using C# variables in CSS code, without using inline code? I've found a website which describes using a custom handler to modify the css files, however we couldn't get this to work because our parser was never called. We also found the .LESS library, but we would rather not use this library, and instead work on a solution that only uses a couple lines of code.
You could use some sort of templating language to render the css files. On it's own variables in css won't be populated but you could write a utility class to read the template file, populate variables, save new file to appropriate location and output the correct style element on the page, pointing to new css file.
That way you could have something like the following that would render the appropriate css:
<% CssHelper.Load("myFile.template", "websitex/style.css")%>
Would that be a viable option?

C# Insert block of code to every aspx page

I'm having a web application project which is running .NET 4.0. I've plenty of .aspx page and now I would like to add in a block of script code to all the .aspx page header, for example Google Analytics.
I know there is a solution to do is add in every single page, but I would like to know is there any other's way to do this instead modify every single .aspx page?
*My header is not runat server
I got an idea to do but not sure it's work or not.
Get the page class in Global.asax
Get the output stream from the page class.
Insert the Google Analytics code in the HTML header.
I couldn't get the Page.Response in the Global.asax as I tried in the Application_PostRequestHandlerExecute & also Application_EndRequest. Does anyone know is this work and how it's work?
Thanks.
Use master pages. This is the ASP.NET way of putting the same content on multiple pages without repeating yourself.
All of our aspx pages code-behind classes inherit from the same base class, which allows us to inject standard client side elements (controls, script, etc) into every page using a single point of control.
Our design was implemented before the advent of master pages, but while it could possibly be converted to a master-page design, we have found this implementation to be extremely flexible and responsive to changing needs.
For example, we have two completely separate application designs (different skin, some different behavior) that is based off of the same code base and page sets. We were able to dynamically swap out banners and other UI and script elements by simple modifications to the base class in order to support this without having to duplicate every page.
Unfortunately, if you want the script to be in the head element, you will need to ensure that they are all marked as runat=server.
Our base class itself inherits from Page, so it can intercept all of the page's events and act on them either instead of or in addition to the inheriting classes (we actually have internal overrideable methods that inheritors should use instead of the page events in order to ensure order of execution).
This is our (VB) code for adding script to the header (in the Page's LoadComplete method):
' sbscript is a stringbuilder that contains all of the javascript we want to place in the header
Me.Page.Header.Controls.Add(New LiteralControl(sbScript.ToString))
If it is not possible to change the heads to runat server, you could look into ClientScriptManager method RegisterClientScriptBlock which places the script at the top of the page.
You can create a basic page with the header with the custom code such as Google analytics and have the other pages inherit from that. It will facilitate two things:
1) In case you ever want to change the custom code you will only have to do it in one place
2) No repetitive code hence more maintainable
I am trying to do the same thing on a legacy app that we're trying to decommission. I need to display a popup on all the old pages to nag users to update their bookmarks to use the new sites, without forcing them to stop using the legacy site (yet). It is not worth the time to convert the site to run on a master page when I can just plop in a popup script, since this whole thing is getting retired soon. The main new site uses a master page, which obviously simplifies things there.
I have this line in a file that has some various constants in it.
Public Shared ReadOnly RetirementNagScript As String = "<Script Language='javascript'> alert('[app name] is being retired and will be shut down [in the near future]. Please update your bookmarks and references to the following URL: [some URL]'); </script>"
Then I am inserting it in Global.asax, in Application_PostAcquireRequestState:
Response.Write(Globals.RetirementNagScript)
Hopefully this is useful to you; I still need to be able to present a clickable URL to the user that way, on each page of the legacy site, and JS alert doesn't do that for me.

Categories