Mental Jetsam

By Peter Finch

Archive for the ‘Programming’ Category

Programming Language topics

ASP.NET catch “A potentially dangerous Request”

Posted by pcfinch on April 7, 2011

ASP.NET has a handy little feature enabled that filters requests that may be dangerous from the application. One of these is a check for HTML code that may be in a response field in order to avoid the possibility of injecting malicious code onto websites. It’s a nice security feature, and easy to disable by just adding “ValidateRequest=’false'” to the Page directive.


<%@ Page Language="C#" MasterPageFile="~/site.master" AutoEventWireup="true" CodeFile="myWebPage.aspx.cs" Inherits="details" Title="Test" ValidateRequest="false"%>

However, if you want to leave it turn on but avoid the nasty C# exception, that gets thrown when it happens, you can either override the default error page in ASP.NET or the following code can catch (trap) the HttpRequestValidationException exception and render a custom message, or redirect to your own error page.

public partial class myWebPage: System.Web.UI.Page {
 virtual public void ProcessRequest(HttpContext context) {
   try {
     Page.ProcessRequest(context);
   } catch (HttpRequestValidationException) {
     context.Response.Write("Danger");
   }
 }
}

I’m not sure if this is the official way to do it, but it works.

 

Advertisements

Posted in C#.NET | Leave a Comment »

Simple ASP.NET User Control

Posted by pcfinch on March 1, 2011

This is a simple ASP.NET user control template that can be used with a data bound data source and has a persistent ViewState. The trick when using the control with something like a data bound DataList, etc,  is to initialize the value of the child controls (e.g. lblMessage) in the Page_Prerender() function not the Page_Load() function. The value of Message attribute will be initialized from the value in the HTML (aspx page), however, the value can be changed later on by simply using “myControl.Message = … ” if required and the state will be maintained.

public partial class SimpleUserControl : System.Web.UI.UserControl {
  public String Message {
    get { object o = ViewState["Message"]; return (o == null) ? (String.Empty) : ((String)o); }
    set { ViewState["Message"] = value; }
  }
  protected void Page_Prerender(object sender, EventArgs e) {
    lblMessage.Text = Message;
  }
}
<%@ Control Language="C#"
  AutoEventWireup="true"
  CodeFile="SimpleUserControl.ascx.cs"
  Inherits="SimpleUserControl" %>
<h1><asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></h1>

To use the control on a simple webpage just add the following.

<%@ Register TagPrefix="my" TagName="SimpleUserControl"  Src="~/controls/SimpleUserControl.ascx" %>
<my:SimpleUserControl ID="myControl" Runat="Server" Message="Hello World!" />

If you want to use it in a DataList (for example) just do this…

<asp:DataList ID="projectDataList" runat="server" DataSourceID="projectDataSource">
  <ItemTemplate>
   <my:SimpleUserControl ID="myControl" Runat="Server" Message='<% Eval("Title") %>' />
  </ItemTemplate>
</asp:DataList>

Posted in C#.NET | Leave a Comment »

Displaying XML data in .NET

Posted by pcfinch on February 14, 2011

The following is an example of displaying information from a XML document in .NET using an “xmlDataSource” and “DataList”. This is a very simple way to display record base information from an XML data source placed in the application directory like the file below (e.g. “~/data/news.xml”), and it is easy to convert to an “sqlDataSource”, in the future, by replacing the “XPath()” function with “Eval()”.

<?xml version="1.0" encoding="utf-8" ?>
<news>
 <item id='a1'>
 <title>New Website</title>
 <date>Monday, 7th Feb 2011</date>
 <image>news/website.jpg</image>
 <short>New Development Labs website.</short>
 </item>
 <item id='a2'>
 <title>New Taskbar</title>
 <date>Monday, 207th Dec 2010</date>
 <image>news/taskbar_1.jpg</image>
 <short>Released new taskbar functionality.</short>
 </item>
</news>

Just insert the following code into the C# webform and masterpage.

<asp:XmlDataSource ID="newsDataSource" runat="server" DataFile="~/data/news.xml">
</asp:XmlDataSource>
<asp:DataList ID="newsDataList" runat="server" DataSourceID="newsDataSource">
 <ItemTemplate>
 <img src='images/<%#XPath("image")%>' />
 <a href='details.aspx?id=<%#XPath("@id") %>'>
 <%#XPath("title") %>
 </a>
 <div><%#XPath("date") %></div>
 <div><%#XPath("short") %></div>
 </ItemTemplate>
</asp:DataList>

A subset of the XML document can be selected by adding an optional “XPath” attribute to the “xmlDataSource” tag…

<asp:XmlDataSource
  ID="newsDataSource" runat="server"
  DataFile="~/data/news.xml"
  XPath="/news/item[@id='a1']">
</asp:XmlDataSource>

or using the following C# code.

newsDataSource.XPath = String.Format("/news/item[@id='{0}']", id);

Posted in C#.NET, HTML | Leave a Comment »

Binary HTTP GET in C#

Posted by pcfinch on January 13, 2011

The following code returns binary data (an array of bytes) from a HTTP GET request, and returns the mime type as a output parameter of the function.

public byte[] httpGetBytes(String url, out String mimeType)
{
  byte[] response = null;
  byte[] buffer = new byte[4096];
  int read;

  HttpWebRequest fetchReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  fetchReq.Method = "GET";
  HttpWebResponse fetchResp = (HttpWebResponse)fetchReq.GetResponse();
  Stream responseStr = fetchResp.GetResponseStream();
  mimeType = fetchResp.ContentType;

  MemoryStream ms = new MemoryStream();
  while((read = responseStr.Read(buffer, 0, buffer.Length)) > 0)
    ms.Write(buffer, 0, read) ;
  response = ms.ToArray();

  fetchResp.Close();
  return (response);
}

Posted in C#.NET | Leave a Comment »