Category Archives: .NET

PGP Decryption using C#

Sorry if the PGP meme is getting old, I had to write some new code yesterday that decrypted a file full of ciphertext and I didn’t see any other examples on the net, so it gets posted here for posterity. Just to frame the issue, the ciphertext is actually stored in the database, so I first extract the ciphertext from a text column, write the ciphertext to a file, decrypt the file, read the results and then delete the file:

// get ciphertext from DB
// and write to a file
// ...
string passphrase = "my_passphrase";
string filename = "myapp\encrypted.asc";
ProcessStartInfo psi = new ProcessStartInfo("pgp");
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.Arguments = filename + " -m -z " + passphrase;
Process process = Process.Start(psi);
string line = null;
string message = null;
while((line = process.StandardOutput.ReadLine()) != null) {
message = line;
}
Console.WriteLine("message = " + message);

If you’re scoring at home, I used the ProcessStartInfo and Process classes from the .NET Framework to invoke pgp.exe from the command line passing the -m flag so that the decrypted message is printed out to the screen (instead of pgp.exe decrypting the message to a new file) and passing the -z flag so that I can send the passphrase as an argument as well. In my project the message is only one line so I iterate over the lines of output until I get to the last line… where the message is then saved in the message string instance.

Peeling away the code, you end up with this:

C:\pgp6.5.8>pgp c:\myapp\encrypted.asc -m -z my_passphrase
Pretty Good Privacy(tm) Version 6.5.8
(c) 1999 Network Associates Inc.
Uses the RSAREF(tm) Toolkit, which is copyright RSA Data Security, Inc.
Export of this software may be restricted by the U.S. government.
moreflagFile is encrypted. Secret key is required to read it.
Key for user ID: Aaron Johnson
1024-bit DSS key, Key ID ******, created 2004/09/02
Key can sign.
Just a moment...
this is the message

A caveat: if you run the above code from an ASP.NET web application make sure that ASPNET user has access to the private key.

By the way, the folks over at Bouncy Castle have a C# port of the their excellent Java encryption libraries, but it doesn’t appear that the org.bouncycastle.openpgp package has been ported just yet, otherwise I would have used that.

ASP.NET: The View State is invalid for this page and might be corrupted

I fixed a tricky bug yesterday on one of our sites that runs ASP.NET. Like all good webmasters, anytime a 500 error occurs on the site, an email is sent to me that contains all the juicy details: the URL the user was visiting, the date/time, what browser they were using, which server in the cluster it occured on, the stack trace, any form variables, the querystring, session variables, and cookies. This particular error would occur on any page with a form and the stack trace would look like this:

Exception of type System.Web.HttpUnhandledException was thrown.
source = System.Web
target site = Boolean HandleError(System.Exception)
stack trace = at System.Web.UI.Page.HandleError(Exception e) at
System.Web.UI.Page.ProcessRequestMain() at
System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequest(HttpContext context) at System.Web.CallHandlerExecutionStep.System.Web.HttpApplication+IExecutio
nStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)

which isn’t very helpful at all. So my first problem was that I wasn’t getting enough information; I couldn’t tell what the problem really was. The HttpModule that I wrote that listens for Application_Error events was retrieving the exception using this code:

HttpApplication application = (HttpApplication)source;
Exception error = application.Server.GetLastError();

which technically does retrieve the error that caused the event, but I was missing one key step: the last line should have read:

Exception error = application.Server.GetLastError().InnerException;

and once I fixed that, I magically started receiving a much richer error description:

System.Web.HttpException: The viewstate is invalid for this page and might be corrupted. at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadPageViewState() at System.Web.UI.Page.ProcessRequestMain()

That description leads to a couple different knowledge base articles on support.microsoft.com; Q323744 and Q312906 were the ones that fixed the problem I was experiencing. Turns out that when you a) run an ASP.NET application in a cluster (in my case it’s an ASP.NET application load balanced behind with an F5), b) don’t use sticky sessions, and c) utilize view state, you must setup your web servers to use the exact same machine key, which is a setting in machine.config. Microsoft supplies a C# script that will generate the appropriate machineKey element for you machine.config in Q312906.

ebay web services talk by Jeffrey McManus

A couple weeks ago I attended the Boston .NET User Group to hear Jeffrey McManus give a talk on how ebay is using web services. I took a bunch of notes during his presentation, which I’m putting up here semi-edited. The first part of the talk was mainly about ebay the company; how much business they do per quarter, how many users they have,etc.. The second part was about the ebay API, which I was interested in because the company I’m working for now is exploring a similar program, so you’ll see more detailed notes there:

developer.ebay.com

45000 product categories
collectibles was the first product category on ebay, it is category id = 1
ebay did approximately $5.6 billion in cars last year

105 million registered users as of 3/1/2004
rate of growth is accelerating quarter over quarter
28 countries with a physical presence and localized website
20 million items for sale at any one time…
1 billion items were listed last year
7 gigabits per second outgoing traffic
10 billion api hits in 2004

in december 2003, 1 of every 3 people on the internet came to ebay

1 in 3 used golf clubs bought in the US are purchased on ebay
valueguide.pga.com uses ebay data to help determine the price of used golf equipment

Ebay isn’t just for knick knacks: more than 125,000 keyword searches for Louis Vuitton, Coach and Prada on ebay every day

superpawn.com
— they build a proprietary POS with ebay and significantly reduced costs
— used to cost $23 per item to list & describe each item on ebay (person costs), now approx $.25

highline auctions
— custom system integrator with a business around ebay integration, specifically in cars
— reduced the time it takes to create a professional listing from 30 minutes to under 3 minutes

auctionworks
— solution provider on ebay

use cases
— integration w/ business tools (quickbooks, excel, sap, etc..) (ie: a donation can be estimated for taxes using a data licensing application)
— integration w/ back ends for medium & large retailers, manufacturers

‘we make inefficient markets efficient’
scarce –> in-season reatail –> end of life–> used/vintage
— end of life scenario for retailers
— products at the end of life can be put on ebay programmatically saving companies the most of having to get rid of excess product

top level meta categories
— sports, tickets, etc…
— ‘browseability’ is a one of the challenges
— most likely use cases are sellers listing items programatically

data licensing services
— you can purchase data feeds from ebay so that you can find out what the given price for a given car in a given location is
andale.com: provides ebay pricing and selling recommendations

API

ASP.NET: Data-binding array of hashtables

Spent this morning in ASP.NET land working on a small modification in which I needed to data bind an array of hashtables to an <asp:repeater>. Looks like some other ASP.NETers had the same problem, but the ‘solutions’ they offered didn’t seem to solve the errors I was getting. First, in the code behind, I had something like this in the code behind:

public Repeater events = new Repeater();
private ArrayList aEvents = new ArrayList();
public void Page_Load(Object sender, EventArgs e) {
  Hashtable event1 = new Hashtable();
  event1.Add("name", "name of event 1");
  event1.Add("date", "5/31/2004");
  Hashtable event2 = new Hashtable();
  event2.Add("name", "name of event 2");
  event2.Add("date", "06/20/2004");
  aEvents.Add(event1);
  aEvents.Add(event2);
  events.DataSource = aEvents;
  events.DataBind();
}

and then a standard repeater tag in my ASP.NET code:

<asp:repeater id="events" runat="server">
  <ItemTemplate>
  Name:<%# DataBinder.Eval(Container.DataItem,"name") %>
  Date:<%# DataBinder.Eval(Container.DataItem,"date") %>
  </ItemTemplate>
</asp:repeater>

The first error I got was DataBinder.Eval: 'System.Collections.Hashtable' does not contain a property with the name name., which means that the DataBinder uses reflection to find a property called ‘name’ on the current object in the iteration. This is a problem because obviously a hashtable doesn’t have a public property for ‘name’, it only has an associate array of values. The workaround, although I don’t know why this works, is to wrap the keys in a brackets:

Name:<%# DataBinder.Eval(Container.DataItem,"[name]") %>
Date:<%# DataBinder.Eval(Container.DataItem,"[date]") %>

Using brackets lets you use an array of hashtables as a datasource. Since this works, it might be helpful to add it to the Data Binding Expression Syntax guide on MSDN.

C# Public Properties vs. Java getX() and setX()

Martin Fowler blogged about C# properties a couple weeks back saying that he “.. liked the notion of properties right from the start..” because it’s “.. much more natural to write obj.X = other.X.” Further, ” … from a language point of view, properties and fields look the same. So if I have a field x which I can just read and write to, I can just declare it as a field. I don’t worry about this violating encapsulation, because should I wish to do something more fancy I can just replace it with a property later. It all saves a lot of typing of stupid accessor functions.” For those of you who have never used C#, instead of writing this in Java:

// Java getter & setter
private String foo;
public String getFoo() {
  return this.foo;
}
public void setFoo(String foo) {
  this.foo = foo;
}
// access the private variable foo like this:
bar = obj.getFoo();

you can write this:

// C# public property
private String _foo;
public String Foo {
  get {  return _foo; }
  set {  _foo = value; }
}
// access the private variable _foo like this:
bar = obj.Foo;

I initially liked this feature of C# as well, it definitely seems more natural to use properties. Also, like Martin mentions, it saves you from having to make decisions about encapsulation.. do you use a getX()/setX() method or do I just mark it as public? With C#, you can change the implementation without changing your published API.

Martin points out that in this case beauty is only skin deep. If you use reflection to access the public properties or fields of a C# class, you might be surprised to see that the implementation does in fact change. In the example above, the property ‘Foo’ gets turned into 2 methods: get_Foo() and set_Foo(), which you can see using reflection:

Type type = (typeof(YourClassName));
MemberInfo [] members;
members = type.GetMembers(BindingFlags.Public|BindingFlags.Instance);
Console.WriteLine( "\nThe public instance members of class '{0}' are : \n", type);
for (int i =0 ; i
Martin ends by noting "... now I have to write stupid accessor functions for accessible data values." which is something that your IDE can do for you. In Eclipse, declare your private instance variables and then right click --> Source --> Generate Getter & Setter...

.NET, Reflection and multiple assemblies

As part of a project I worked on at Mindseye, I wrote a couple utilities using C# that used reflection to query a given type for the existence of a method and if the method existed, to then invoke the method. In short, the utility allowed me to do this (pseudo-code):

AbstractType type = AbstractTypeFactory.Find("com.company.SomeClass");
string result = type.InvokeMethod("delete");

The AbstractTypeFactory type has a single static method ‘Find()’ that looks for the given type by name. If successful, it returns an instance of AbstractType, which you can use to invoke a given method on the type you looked up using the InvokeMethod() method. The InvokeMethod() method checks to see if the given method is a static or instance method, creates an instance if necessary, and then calls the method.

These utilities worked fine until I need to call the Find() method against a type that wasn’t in the same assembly as the assembly that my utility was in. Inside the AbStractTypeFactory (which is a pseudo-name by the way), I used the .NET Type class:

// Gets the Type with the specified name, performing a case-sensitive search.
Type type = Type.GetType("com.company.SomeClass");

I didn’t have time to look into why the GetType() method wouldn’t find types outside of the currently assembly… until today when I really needed to be use the utilities against a different assembly. It turns out that it’s relatively simple to do. Instead of using the type name (ie: “com.company.SomeClass”), you can use the AssemblyQualifiedName, which looks likes this:

com.company.SomeClass, assemblyname, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

where assemblyname is the name of the DLL that com.company.SomeClass exists in. It’s relatively easy to retrieve the AssemblyQualifiedName using the AssemblyQualifiedName property of the Type type. For example, the .NET documentation gives this example:

Type objType = typeof(System.Array);
Console.WriteLine ("Qualified assembly name: {0}.", objType.AssemblyQualifiedName.ToString());

There are alot of good reasons why Microsoft designed the GetType() method the way they did, the majority of them related to how the runtime locates assemblies, which you should read about when you have a alot of time.

NAnt build file tips

I found the documentation for NAnt to be lacking in build file examples, especially examples that deal with more than one task or include. If you’re completely new to NAnt, I’d suggest reading the article that Jeffrey McManus wrote for ondotnet. If not, read on.

One of the first things you’ll notice when reading examples on any site is that most of them are explicit in regard to the fileset to be compiled. You’ll see this:

<csc target="library" output="company.dll">
 <sources>
  <includes name="src\com\company\packagea\ClassA.cs"/>
  <includes name="src\com\company\packagea\ClassB.cs"/>
  <includes name="src\com\company\packageb\ClassC.cs"/>
....

instead of something like this:

<csc target="library" output="company.dll">
 <sources>
  <includes name="src\com\company\packagea\*.cs"/>
  <includes name="src\com\company\packageb\*.cs"/>
....

Of course, this means that you have to manually add in each namespace, which can be tedious and error prone. NAnt provides a shorthand: **, which means we can reduce the above to this:

<csc target="library" output="company.dll">
 <sources>
  <includes name="src\com\company\**\*.cs"/>
....

If you don’t want a particular file included in the list (say for instance all the files in ‘packageb’), you can use the <excludes> tag like so:

<csc target="library" output="company.dll">
 <sources>
  <includes name="src\com\company\**\*.cs"/>
  <excludes name="src\com\company\packageb\*.cs"/>

That’s all I had off the top of my head. There are a couple new features in release .84 that might be worth taking a look at: xmlpeek (which allows you to extract text from an xml file like say for instance the web.config), xmlpoke (which allows you to replace text in an xml file…) and servicecontroller (which allows you to stop/start/restart Windows Services).

Using Eclipse & NAnt

I’ve been using the Eclipse and NAnt together to write C#/ASP.NET apps for the last couple months, they’re relatively easy to get working together, but I thought I’d write it up for those who aren’t having such an easy time.

1) DownloadEclipse and NAnt from their respective download sites and install/unzip (you have to build nant). I’m also using the C# Improv plugin, which you can download here.

2) Create your project in Eclipse (not a Java project, use a Simple Project) and then create your XML build file and name it {your_project}.build. You can see a sample build file here.

3) With Eclipse open, click ‘Run –> External Tools –> External Tools’. You should see something like this:

Eclipse NAnt Integration

4) Give this instance of the external tool a name, I use something like ‘NAnt — My Project’. Enter the location of the NAnt executable (which should exist wherever you unzipped it too, something like C:\nant-0.8.3\nant-0.8.3.50105\bin\NAnt.exe). Finally, enter the working directory by clicking the ‘Browse Workspace’ button and selecting the appropriate project from the list of projects. Click the Run button at the bottom of the page and you should see the results of NAnt being displayed in the Eclipse Console.

To run the build process now, you simply click Run –> External Tools –> NAnt — My Project (where NAnt — My Project is the name you gave to this instance in step 4).

Accessing ASP.NET DropDownList Items from Code behind

Couple days ago I was writing an ASP.NET webform and I wanted to programmatically inspect the items in the drop down. The drop down list in the ASP.NET page looks something like this:

<asp:dropdownlist id="mydropdown" class="dropbox" runat="server">
  <asp:listitem text=" -- select -- " value="" />
  <asp:listitem text="Text 1" value="1" />
  <asp:listitem text="Text 2" value="2" />
  <asp:listitem text="Text 3" value="3" />
</asp:dropdownlist>

and then in the code behind (like I mentioned before) you can do a bunch of useful things. First, if I wanted to set the default selected item in the form, I’d write this:

public void Page_Load(Object sender, EventArgs e) {
  // initialize form
  if (!IsPostBack) {
   mydropdown.SelectedValue = "1";
  }
}

That’s relatively trivial, it gets more interesting when you consider that you can access the DropDownList items programatically:

foreach (ListItem l in mydropdown.Items) {
  if (l.Value == 1) {
   l.Selected = true;
  }
}

In the above example I use the foreach statement to iterate through the collection of ListItems in the Items property. If the Value property of the ListItem is 1, then I set that to be selected. You can also access the Text property of the List Item.

The C# foreach construct jogged my memory about Java 1.5 (Tiger) which is supposed to have enhanced ‘for’ loops (also read this); for example this:

for (Iterator i = c.iterator(); i.hasNext(); ) {
  // do stuff with 'i'
}

becomes this:

for (Object o : c) {
  // do stuff w/ 'o'
}

When is 1.5 gonna arrive?

ASP.NET TextBox MultiLine Incorrect Documentation

[Update: The link to the TextBox class from the ASP.NET TextBox Web Server Control points to the Windows Forms TextBox, not the Web Controls TextBox. Balls!]

If you’re running into trouble when using the TextBox class in ASP.NET, the MultiLine property and the Microsoft .NET Framework SDK Documentation, it’s probably because the documentation is wrong. The documentation that ships with v1.1 says that you can use the ‘Multiline’ property of the TextBox class (which is actually a property of the TextBoxBase class) to toggle the TextMode property like this:

private void CreateMyMultilineTextBox() {
  // Create an instance of a TextBox control.
  TextBox textBox1 = new TextBox();

  // Set the Multiline property to true.
  textBox1.Multiline = true;
  ....
}

If you do what the documentation says, you’ll get a compiler error that says this:

error CS0117: 'System.Web.UI.WebControls.TextBox' does not contain a definition for 'Multiline'

So instead, use the the TextBoxMode enumeration and the TextMode property:

private void CreateMyMultilineTextBox() {
  // Create an instance of a TextBox control
  TextBox textBox1 = new TextBox();

  // use the TextMode property and the TextBoxMode enumeration
  textBox1.TextMode = TextBoxMode.MultiLine;
  ....
}

All of this is documented correctly online.