Thursday, July 1, 2010

Bind XML to DataGrid

Binding XML from a data table to a DataGrid

Code Behind
string xml = null;
while(reader.Read()){
  xml = reader["Responses"].ToString();
}

StringReader stream = new StringReader(xml);

using(DataSet ds = new DataSet()){
  ds.ReadXml(stream, XmlReadMode.InferSchema);

  ResultsDataGrid.DataSource = ds;
  ResultsDataGrid.DataBind();
}


aspx page
<asp:datagrid id="ResultsDataGrid" runat="server" AutoGenerateColumns="false">
  <Columns>
    <asp:BoundColumn DataField="LABEL" HeaderText="Question"></asp:BoundColumn>
    <asp:BoundColumn DataField="RESPONSE" HeaderText="Response"></asp:BoundColumn>
  </Columns>
</asp:datagrid>

Wednesday, June 30, 2010

Auto focus textbox

To auto focus the first textbox on each pageload:

1.) Copy the function below into the base page:
private void FocusFirstTextBox(){
  StringBuilder buildScript = new StringBuilder();
  buildScript.Append("var boxes = document.getElementsByTagName('input');");
  buildScript.Append("for(var i = 0; i < boxes.length; i++) {");
  buildScript.Append("if(boxes[i].type == 'text' && boxes[i].disabled == false && boxes[i].style.display != 'none'){");
  buildScript.Append("boxes[i].focus();");
  buildScript.Append("break;");
  buildScript.Append("}}");

  this.RegisterStartupScript(Guid.NewGuid().ToString(),
  "");
}


2.) Copy this function call into the base pages OnPreRender:
protected override void OnPreRender(EventArgs e) {
  base.OnPreRender (e);
  this.FocusFirstTextBox();
}

Thursday, December 10, 2009

Visual Studios debugger automatically stopping when IE comes up.

I installed IE8 and the debugger in Visual Studios stopped working. I found this solution on the interwebs and it worked for my system (Visual Studio 2003, WinXP):

IE 8 has a feature called Loosely-Coupled Internet Explorer (LCIE) which results in IE running across multiple processes.

http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie

Older versions of the Visual Studio Debugger get confused by this and cannot figure out how to attach to the correct process. You can work around this by disabling the process growth feature of LCIE. Here's how:

1.Open RegEdit
2.Browse to HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
3.Add a dword under this key called TabProcGrowth
4.Set TabProcGrowth to 0
Since you are running on Windows Server 2003, this is all you should need to do. If you run into the same problem on Vista or newer, you will also need to turn off protected mode.

Convert DataSet to Excel document

Below is a quick description on how to convert a DataSet to an Excel sheet. It applies XslTransform to a DataSet and writes the results to the Response.OutputStream of a web request. This will allow for a user to save or open the data as Excel.

Populate a DataSet:
using (DataSet ds = Service.GetSummary(UserId, Filter1, Filter2))
{
  ...
}

Configure Response object:
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";

Configure XslTransform:
XmlDataDocument xmlDoc = new XmlDataDocument(ds);
XslTransform xslTran = new XslTransform();
xslTran.Load(Server.MapPath("ExcelTransformFormat.xslt"));
Note: "ExcelTransformFormat.xslt" will need to be adjusted. Below is an example, but it will need to be modified to reflect the DataSet it is being used to transform.

Write results to Response:
xslTran.Transform(xmlDoc, null, Response.OutputStream, null);
Response.AppendHeader("Content-Disposition", "attachment; filename=Name.xls");
Response.End();

Example .xslt Transform File
<xsl:stylesheet version="1.0"
xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" >

<xsl:template match="NewDataSet">

<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">

<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="s21">
<Font ss:Bold="1"/>
<Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/>
</Style>
<Style ss:ID="s22">
<Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/>
<Font ss:Bold="1"/>
<Interior ss:Color="#99CCFF" ss:Pattern="Solid"/>
</Style>
</Styles>
<Worksheet>
<xsl:attribute name="ss:Name">
<xsl:value-of select='concat("RGN", Table/region, "DST", Table/district)'/>
</xsl:attribute>
<Table ss:ExpandedColumnCount="17">
<xsl:attribute name="ss:ExpandedRowCount" >
<xsl:value-of select="count(Table)+10"/>
</xsl:attribute>
<Column ss:AutoFitWidth="0" ss:Width="30"/>
<Column ss:AutoFitWidth="0" ss:Width="30"/>
<Column ss:AutoFitWidth="0" ss:Width="50"/>
<Row>
<Cell ss:StyleID="s21"><Data ss:Type="String">RGN</Data></Cell>
<Cell ss:StyleID="s21"><Data ss:Type="String">DST</Data></Cell>
<Cell ss:StyleID="s21"><Data ss:Type="String">Location</Data></Cell>
</Row>
<xsl:apply-templates select="Table"/>
</Table>
</Worksheet>
</Workbook>
</xsl:template>
<xsl:template match="Table">
<Row>
<Cell><Data ss:Type="String"><xsl:value-of select="region"/></Data></Cell>
<Cell><Data ss:Type="String"><xsl:value-of select="district"/></Data></Cell>
<Cell><Data ss:Type="String"><xsl:value-of select="location"/></Data></Cell>
</Row>
</xsl:template>
</xsl:stylesheet>

Saturday, October 24, 2009

Automatic webpage logout

Below is some javascript that can be added to any page in order to automatically log out a user after a given amount of time.

<script language="javascript">
  //function __logout(msg, loc ) {alert(msg); location.href = loc;}

  //function __startLogoutCountdown(){window.setTimeout("__logout('Login Expired: === \\nThis site uses a security feature that automatically logs you out from your session after 16 minutes. You may login again to continue your session.', '<%=Request.ApplicationPath%>/Logout.aspx');", 960000);};
</script>

Friday, September 25, 2009

Javascript ReplaceAll

In order to replace all occurrences of a particular string or char, you can use the format below:

replace(//g, "");

Lets say there is a variable: var tag = ctl0_Parent:Child:Item;
var itm = tag.replace(":", "_");
will result with itm being equal to: ctl0_Parent_Child:Item
var itm = tag.replace(/:/g, "_");
on the other hand, will result in itm being equal to: ctl0_Parent_Child_Item

Tuesday, September 15, 2009

Dynamically turn on/off Panel with Javascript

1.) Set client side OnChange event on a Button, CheckBox, etc...
  OnChanged="javascriptChangeHandler(this, 'Panel1');"

2.) Include the Panel named in the javascriptChangeHandler call in HTML
  <asp:Panel id="Panel1" Runat="server">
    Content...
  </asp:Panel>

3.) Add the Javascript function to the page or within included .js file
function javascriptChangeHandler (elem, panel) {
  var part = elem.id.substr(0, elem.id.lastIndexOf('_'));
  //Handle part logic to determine if panel should be turned off or on

  if ( part == null ) {
    elem.focus();
    return false;
  } else if ( part == "someIdentity" ) {
    document.getElementById(panel).style.display = "block";
    } else {
      document.getElementById(panel).style.display = "none";
    }
  }
}