Mental Jetsam

By Peter Finch

Archive for the ‘C#.NET’ Category

Accessing DataSource values from within a DataList ItemTemplate

Posted by pcfinch on June 29, 2011

The following C# (ASP.NET) code example shows a couple of ways to access the values returned by a asp:SqlDataSource from within a asp:DataList asp:ItemTemplate. The difficult part was accessing the data sources values and passing them to nested ASP controls like asp:Buttons and asp:ImageButtons.

<asp:SqlDataSource ID="ds" runat="server"
  ConnectionString="<%$ ConnectionStrings:portal %>"
  SelectCommand="select did, title, did from documents">
</asp:SqlDataSource>
<asp:DataList ID="dl" runat="server" DataSourceID="ds">
  <ItemTemplate>
    <div class="result">
      <a href='details.aspx?id=<%#Eval("did")%>>
      <div class="title"><%#Eval("title")%></div>
      <asp:ImageButton ID="butDelete" runat="server"
        ToolTip="Delete"
        ImageUrl="images/delete.png"
        OnClick="butDelete_Click"
        OnClientClick="javascript:confirm('Block comment thread?')"
        CommandName="delete"
        CommandArgument='<%# DataBinder.Eval(Container, "DataItem.did") %>' />
    </div>
  </ItemTemplate>
</asp:DataList>

In order to response to a click on one of the dynamically generated delete buttons use the following code.

protected void butDelete_Click (object sender, ImageClickEventArgs e)
{
  String command = ((ImageButton)sender).CommandName;
  if ("delete" == command) {
    int dId = Int16.Parse(((ImageButton)sender).CommandArgument);
    using(portalConnection portal = new PortalConnection())
    {
      portal.Delete(dId);
    }
    dl.DataBind();
  }
}

Posted in C#.NET | Leave a Comment »

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.

 

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 »