Is there an enum for the ContentType property on a HttpWebResponse ("text/plain", "application/octet-stream" etc.)? - content-type

The closest thing I could find was System.Net.Mime.MediaTypeNames but that doesn't seem to have everything (like json) since it seems to be more focused around email attachments.

An enum doesn't make much sense. MIME types are open-ended. That is, the list is not finite: new types are added from time to time.
See RFC4288: Media Type Specifications and Registration Procedures

In 2022, with .NET Core and .NET5+, this is now available via MediaTypeNames. For example:
MediaTypeNames.Application.Json
MediaTypeNames.Image.Png
MediaTypeNames.Text.Html
Microsoft documentation around MediaTypeNames, and each of Application, Image, Text.
https://learn.microsoft.com/en-us/dotnet/api/system.net.mime.mediatypenames?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.net.mime.mediatypenames.application?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.net.mime.mediatypenames.image?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.net.mime.mediatypenames?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.net.mime.mediatypenames.text?view=net-6.0

IANA's database is most likely to be complete. Currently, they have the list available in CSV format at https://www.iana.org/assignments/media-types/application.csv. I am assuming this is a stable URL whose content changes as updates are made. If you want to stay up to date, you'd need to put together a mechanism that is appropriate for your needs.
There is also the mime.types file that comes with Apache which seems to have been derived from the said list.

If like me you wanted to have no hard-coded string in your code you can use something like below
httpHeaders.add(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);
which is essentially
httpHeaders.add("Content-Type","application/json");

Related

Does Kentico allow query strings with question mark?

I'm trying to migrate my ASPX site to Kentico, and as part of my task I'm migrating URLs. I need to preserve my URL structure, so I need to keep URLs which look like : "foo.com/bar.aspx?pageid=1".
I checked page's "URLs" property tried to use wildcards, some patterns like /bar/{pageid}- /bar/{?pageid?}-, etc but Kentico always replaces question marks.
Is there a way to achieve that via the admin interface?
You don't need to do anything in order to use "foo.com/bar.aspx?pageid=1" url.
Create a page under the root and call it bar, so you'll get a page # foo.com/bar.aspx. Kentico and/or .net does not care what you add to a url after question mark, so foo.com/bar.aspx?pageid=1 will work as well as foo.com/bar.aspx?someparam=sdf, or foo.com/bar.aspx?id=1&p=3&t=3.
You may (or may not) implement some functionality based on query string (e.g. paging), so it will parse query string and act in appropriate way.
By default Kentico UI does not handle adding URL aliases with URL parameters like you show. There is an article on the DevNet for a URL Redirection module which has code you can import into your site to allow you to perform these redirects within the Kentico UI. I'd suggest using this approach.
Unfortunately, I can't share a code sample since it's an article but it also has a link to download the code too. This appears to only be coded for Kentico 8.2 right now but I'm guessing you could do some work to make it work for other versions if you needed.
I think there are few concepts that you are clubbing here. I will start with your line code here
/bar/{pageid} - {pageid} is a positional parameter in Kentico's language if you choose to use dynamic URLS based on patterns. SO if you have a code that relies on pageid parameter to fetch some data then Kentico will pass that value. E.g in case of /bar/420, it will pass pageid as 420 different web parts on your template
/bar/{?pageid?} - This will search for query string parameter "pageid" on the request URL and replace its value here. So if you passed foo.com/bar.aspx?pageid=366, the resulting URL will be /bar/366
The #1 is positional parameter and #2 is the way in which Kentico resolves query string macros.
I hope this clarifies.

Explanation for url() function Drupal 8

I'm very new to drupal and have to do some real quick small work. While going through the documentation at https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates, I saw string parameter to url() function.
{{ 'View all content'|t }}
what is the value that url() is taking?
Infact, i'm trying to get relative path. I used
Solutions
But, it didn't work for me because {{directory}} changed each time and led to url append. Is there any best practices? Thank you for suggestions.
When adding a URL into a string, for instance in a text description, core recommends we use the \Drupal\Core\Url class. This has a few handy methods:
Internal URL based on a route - Url::fromRoute(), Example: Url::fromRoute('acquia_connector.settings')
Internal URL based on a path - Url::fromInternalUri(), Example: Url::fromInternalUri('node/add')
External URL - Url::fromUri, Example: Url::fromUri('https://www.acquia.com')
The last two methods are very similar, the main difference is, that fromInternalUri() already assumes an 'internal:' prefix, which tells Drupal to build an internal path. It's worth reading up on what prefixes are supported, for instance the ':entity' prefix can help in building dynamic URIs.
When you need to constrict and display the link as text you can use the toString() method: Url::fromRoute('acquia_connector.settings')->toString().
If you need additional information please ask.

Are there any anti-XSS libraries for ASP.Net?

I was reading some questions trying to find a good solution to preventing XSS in user provided URLs(which get turned into a link). I've found one for PHP but I can't seem to find anything for .Net.
To be clear, all I want is a library which will make user-provided text safe(including unicode gotchas?) and make user-provided URLs safe(used in a or img tags)
I noticed that StackOverflow has very good XSS protection, but sadly that part of their Markdown implementation seems to be missing from MarkdownSharp. (and I use MarkdownSharp for a lot of my content)
Microsoft has the Anti-Cross Site Scripting Library; you could start by taking a look at it and determining if it fits your needs. They also have some guidance on how to avoid XSS attacks that you could follow if you determine the tool they offer is not really what you need.
There's a few things to consider here. Firstly, you've got ASP.NET Request Validation which will catch many of the common XSS patterns. Don't rely exclusively on this, but it's a nice little value add.
Next up you want to validate the input against a white-list and in this case, your white-list is all about conforming to the expected structure of a URL. Try using Uri.IsWellFormedUriString for compliance against RFC 2396 and RFC 273:
var sourceUri = UriTextBox.Text;
if (!Uri.IsWellFormedUriString(sourceUri, UriKind.Absolute))
{
// Not a valid URI - bail out here
}
AntiXSS has Encoder.UrlEncode which is great for encoding string to be appended to a URL, i.e. in a query string. Problem is that you want to take the original string and not escape characters such as the forward slashes otherwise http://troyhunt.com ends up as http%3a%2f%2ftroyhunt.com and you've got a problem.
As the context you're encoding for is an HTML attribute (it's the "href" attribute you're setting), you want to use Encoder.HtmlAttributeEncode:
MyHyperlink.NavigateUrl = Encoder.HtmlAttributeEncode(sourceUri);
What this means is that a string like http://troyhunt.com/<script> will get escaped to http://troyhunt.com/<script> - but of course Request Validation would catch that one first anyway.
Also take a look at the OWASP Top 10 Unvalidated Redirects and Forwards.
i think you can do it yourself by creating an array of the charecters and another array with the code,
if you found characters from the array replace it with the code, this will help you ! [but definitely not 100%]
character array
<
>
...
Code Array
& lt;
& gt;
...
I rely on HtmlSanitizer. It is a .NET library for cleaning HTML fragments and documents from constructs that can lead to XSS attacks.
It uses AngleSharp to parse, manipulate, and render HTML and CSS.
Because HtmlSanitizer is based on a robust HTML parser it can also shield you from deliberate or accidental
"tag poisoning" where invalid HTML in one fragment can corrupt the whole document leading to broken layout or style.
Usage:
var sanitizer = new HtmlSanitizer();
var html = #"<script>alert('xss')</script><div onload=""alert('xss')"""
+ #"style=""background-color: test"">Test<img src=""test.gif"""
+ #"style=""background-image: url(javascript:alert('xss')); margin: 10px""></div>";
var sanitized = sanitizer.Sanitize(html, "http://www.example.com");
Assert.That(sanitized, Is.EqualTo(#"<div style=""background-color: test"">"
+ #"Test<img style=""margin: 10px"" src=""http://www.example.com/test.gif""></div>"));
There's an online demo, plus there's also a .NET Fiddle you can play with.
(copy/paste from their readme)

stupid caching in asp.net

i use such code
string.Format("<img src='{0}'><br>", u.Avatar);
u.Avatar-it's like '/img/path/pic.jpg'
but in this site i can upload new image instead old pic.jpg. so picture new, but name is old. and browser show OLD picture (cache). if i put random number like /img/path/pic.jpg?123 then works fine, but i need it only ufter upload, not always. how can i solve this?
string imgUrl = _
string.Format("<img src='{0}?{1}'><br>", _
u.Avatar, _
FunctionThatLookupFileSystemForItsLastModified(u.Avatar).Ticks.ToString());
Instead of linking to the images directly, consider setting up a generic HTTP handler to serve the images.
MSDN: HTTP Handlers and HTTP Modules Overview
Stack Overflow: How to use output caching on .ashx handler
Append DateTime.Now.Ticks to the image url:
string imgUrl =
string.Format("<img src='{0}?{1}'><br>", u.Avatar,DateTime.Now.Ticks);
EDIT: I don' think this best practice are even a practice I would use. This is just a suggestion given the limited information given in case the Random implementation isn't truly Random.
Read your post again,,, sorry for general answer.
To workaround it do following
On Application_Start create a Dictionary with uploaded images save it on Application object, set it to null. Once you upload an image add it to this Dictionary. Wrap every place avatars appear on your website with function that evaluates image in Dictionary if found return imagename.jpg?randomnumber and then delete it from a Dictionary else return just an imagename.jpg.
This is going to be heavy because you will need to check each image in Dictionary but this will do exactly what you need.
You can set cache dependancy using the System.Web.Caching.CacheDependency namespace.
This can set the dependancy on the file uploaded, and will release the cache for that file automatically when the file changes.
There are lots of articles and stuff on MSDN and other places so I will not go into details on all that level of detail.
You can do inserts, deletes and other management of cache using the tools available.
(and this does not require you to change the file names or tack on stuff - it knows by the file system that the file changed)

Removing header from a flat file in BizTalk

What is the simplest way to remove the header row from a flat file in BizTalk? I have implemented this by creating a separate schema for the header row (and one for the body) and then set the HeaderSpecName property in the 'Configure Pipeline' dialog to the header schema I've just created and then the PreserveHeader property to false. My problem, however, is that with this solution I need to create a schema that does nothing other than it needs to exist so I can remove the header row.
I believe what you stated is the recommended way to do what you are asking. I just had to do this on a project i am working on and chose to have the extra schema.
Another option would be to write your own custom pipeline component for the Disassemble stage that executes before the flat file dissassembler. The Decode stage would work too, but it seems that the disassemble stage is made for this type of work.
This second option would make the removing of the header row more generic and could be used across many different schemas so you wouldn't have to create a separate header schema for each flat file schema.
i recommend doing this through the flat file schema wizard; define your first record as a singular record and then your other records as repeating records. then in whatever map or transformations you're working with you can just ignore the header record. you could also ignore the header record when going through the FF wizard by ignoring it altogether, but i prefer to have everything defined in my schemas...
check out the help and microsoft tutorials, also there's a decent article on the code project that incorporates identifying header records. note that if you know the absolute position of the header record (like: "always the first line") you don't need to mess with record tagging.
http://www.codeproject.com/Articles/13706/Creating-Flat-File-schemas-using-the-BizTalk-Serve
You could always just parse the header row and not map it.
The schema exists for many reasons. One such reason is to capture the structure of the message generated by a party which effectively means the agreement. So it is good to capture the schema as it is even though you may not use the fields.
I don't think PreserveHeader acts as you may expect. This property simply determines whether or not values from the header are promoted into the context of the XML message that comes out of the disassembler.

Resources