Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Tuesday, August 25, 2009

Installing Web Profile Generator on ASP.NET 3.5

I finally figure out how to do this. Unfortunately the technical writers were out to lunch when the tried to explain this. Here is my explanation on how to accomplish this in ASP.NET 3.5:

Install the MSI.
Add (under the other Imports), the <Import Project="$(MSBuildExtensionsPath)\WebProfileBuilder\WebProfileBuilder.targets" />](without []) line to the "MyProject.csproj" file (NOT the user project file, but the one without an extension on Vista) where MyProject is your Web Application Project name.
Add an App_Code folder to your project.
Add the WebProfile.cs file (rt. clicking folder and add existing item)
Rt. click the WebProfile.cs file and click properties.
Change its Build Action from Content to Compile.

Add the profile tags to the web.config file: e.g.

Now you are set. Just make a call to your Profile by setting up this method:

public static WebProfile Profile
//get { return new WebProfile(HttpContext.Current.Profile); }
get { return WebProfile.Current; }

It should be noted that when you change the Profile, you will need to remove the class from the App_Code and add the newly generated WebProfile.cs class as before.

Sunday, August 23, 2009

How to disable Internet Explorer 8 From Installing With Automatic Updates

To disable Internet Explorer 8 From Installing With Automatic Updates follow these directions:
Download the file from the link below and run.


Saturday, August 15, 2009

Use log4net to Log Errors or Visitors

log4net is a free utility that can be used for logging data about errors or visitors. It is available here:

Here is an introductory article:

I think a useful way to track users is to log users by their IP Address. Once your log4net is installed correctly, the following code in the Page_Load event can be used to write IP Addresses to a file placed in the App_Code folder (where it is not public):

if (!Page.IsPostBack)
string nowip;
nowip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (nowip == null)
nowip = Request.ServerVariables["REMOTE_ADDR"];
log.Info("Visitor IP: " + nowip);

I'll include the BasePage for a reference to the log variable above (which the System.Web.Page inherits from):

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using log4net;

public class BasePage : System.Web.UI.Page
public static readonly ILog log = LogManager.GetLogger("Logger");
public BasePage()
/// <summary>
/// initializes Log4Net
/// Described at
/// configured in web.config
/// </summary>
private void initLog4Net()
/// <summary>
/// test log4net
/// </summary>
protected void logAllTest()
bool isDebugEnabled = log.IsDebugEnabled;
bool isErrorEnabled = log.IsErrorEnabled;
bool isFatalEnabled = log.IsFatalEnabled;
bool isInfoEnabled = log.IsInfoEnabled;
bool isWarnEnabled = log.IsWarnEnabled;
log.Debug("Debug msg");
log.Error("Error msg");
log.Fatal("Fatal msg");
log.Info("Info msg");
log.Warn("Warn msg");


Sample SQLServer Databases

2005 and 2008 Sample SQLServer Databases are available here: MSFTDBProdSamples
Northwind and pubs databases are available here: Northwind and pubs

These are useful for testing .NET Data objects by using SQLDatasource as the DataSource.

Highlight Rows in a GridView

To highlight rows in a GridView you will want to use the GridView DataBound event to add the onmouseover and onmouseout attributes. While CSS methods may work in FireFox browsers, they do not work in Internet Explorer. For the associated javascript method, you can directly set it with, but this is inflexible. Instead, change the CSS class.

Here is the CSS for the highlighted and normal row (see reference for source of the simple CSS):

<style type="text/css">

background-color:white;/* You can update the background Color to normal Gridview Back Color */
cursor:pointer;/* You can change cursor pointer to default, Pointer etc */

background-color:Gray;/* You can change the background Color of the row to whatever color you want. You can also give Hexadecimal color code also */
cursor:pointer;/* You can change cursor pointer to default, Pointer etc */


Here is the CodeBehind for the GridView DataBound event:

protected void GridView1_DataBound(object sender, EventArgs e)
foreach (GridViewRow row in GridView1.Rows)
if (row.RowType == DataControlRowType.DataRow)
row.Attributes.Add("onmouseout", "this.className='normalRow'");
row.Attributes.Add("onmouseover", "this.className='highlightRow'");

Further modifications for multiple class rows can be made by checking the original CssClass (or checking implicitly by rowCount%currentRow for alternating rows) in the CodeBehind and setting the onmouseout event to switch back to that original class. Another example where this may be necessary is with check box rows that can be selected.


Rid Grid Lines or Borders in a GridView

Here is how to get rid of Grid lines or borders in a GridView:

<asp:GridView ID="GridView1" GridLines=None runat="server">


What are VB Me and MyBase Equivalents in C#?

What are VB Me and MyBase Equivalents in C#?







Creating a Pageable Gridview with Customized Pager Buttons

Matt Berseth put together a great post on creating a pageable GridView. It is basically a custom control that inherits from GridView and implements the DataPageable interface. The coolest part is how the GridView CSS is tailored to a specific looking type of Gridview.

I think it is worth going one step further and tailoring the DataPager with custom images to indicate both enabled and disabled. You will notice that there is a FirstPageImageUrl in the NextPreviousPagerField but no available FirstPage_DisabledImageUrl. To overcome this, we need to examine the DataPager controls dynamically and switch the images according to whether we are already at the start index or last index. This code is placed in the GridView's DataBound event:

protected void gvProducts_DataBound(object sender, EventArgs e)
ImageButton ibtn;
int pgEnd = gvProducts.PageCount;
int curPg = gvProducts.PageIndex;
foreach (Control ct in pager.Controls[0].Controls)
ibtn = ct as ImageButton;
if (0 == curPg)
ibtn.ImageUrl = "~/images/PageFirst_Disabled.jpg";
else { ibtn.ImageUrl = "~/images/PageFirst.jpg"; }
foreach (Control ct in pager.Controls[2].Controls)
if (ct.GetType().Equals(typeof(ImageButton)))
ibtn = ct as ImageButton;
if ((pgEnd-1) == curPg)
ibtn.ImageUrl = "~/images/PageLast_Disabled.jpg";
else { ibtn.ImageUrl = "~/images/PageLast.jpg"; }

I also changed the section in Matt's Default.aspx to:

<!-- Notice this is outside the GridView -->
<div class="pager">
<asp:DataPager ID="pager" runat="server" PageSize="8" PagedControlID="gvProducts">
ShowFirstPageButton="true" ShowPreviousPageButton="false"
ShowLastPageButton="false" ShowNextPageButton="false"
ButtonCount="7" NumericButtonCssClass="command"
CurrentPageLabelCssClass="current" NextPreviousButtonCssClass="command"

ShowFirstPageButton="false" ShowPreviousPageButton="false"
ShowLastPageButton="true" ShowNextPageButton="false"

The crude Microsoft Paint images are located here:

Now you know a technique to customize the DataPager. I further customized the buttons to display custom buttons (print, search, etc.) in the center and pager buttons on the right using JavaScript. That involves a lot of screen calculation details and JavaScript that is another topic. Note, the customization comes at a performance cost. This can be improved with direct reference to the control[x].FindControl("myImgControl"), but that requires inspecting how .NET names the ImageButton in the Debugger.

The result is customized ImageButtons for enabled and disabled buttons.

Download/view Matt's code to add in the customization I've written about.


Use a Class to Store ConnectionString

This appears the best way to store database ConnectionString objects in a given Class:

internal static string GetConnectionString(string specifiedConnectionString, bool lookupConnectionString, bool appLevel)
//Your Conn String goes here!!
return Factory.ConnectionString;

Notice that a static Class is used since we don't need to waste memory instantiating strings.

Specifically mentioned was to modify the SQLConnectionHelper.cs from:

Use Column Mapping with MappingType.Hidden to Hide Columns in a DataTable

It is possible to use Column mapping with MappingType.Hidden to hide columns in a DataTable of a Dataset before the Fill with the following:

myDS.Tables[0].Columns[i].ColumnMapping = MappingType.Hidden;

Of course, 0 may be substituted with the table name as a string. Unfortunately, this is not very useful if the Fill has already created the DataSet. In that case I would probable just want to use an item template in my data display control (such as a GridView) to output the specific fields. The other option is to run the delete columns on the DataTable, which is simply inefficient. Another losing option is to run a select command on the DataTable, which might have its uses for simply acquiring in memory data as opposed to viewing it.


Create a Column in Excel with Leading 0s

To create a column in Excel with leading 0s given a column A with values 0,1,..., and 12 character string to create, use this formula on the target column:

= RIGHT("000000000000" & A1,12)

The result will be 000000000000,000000000001,...
Then just use the copy, paste special as values technique mentioned earlier.


Concatenate two Excel Columns with a Character or String

To concatenate (or join) two columns A2 and B2 into C2 with a hypen (in this case), use this formula in C2:


Then copy the results down the column with click and drag downwards to duplicate the formula on the cell. Finally, copy column C and paste special into the target column as values only.


How to Create GUID from a String

This is an easy way, but esoteric task, to create a GUID from a string:

Guid g = new Guid(string);


Using Vista to Add a User Account to a Group

Here is a helpful description of how to add a user account to a group. Of course you probably need Vista Business or Ultimate.

Reference: Using Vista to Add a User Account to a Group