The Statingleton

Currently, I’m working for a company that creates software for a health care company. We support their processes with our software. Some of this software was written before things like O/R mapping and ORM became big and widely utilized, so this project has some custom classes which does just that. Quite nice, actually. What’s less nice, is this one particular class I found somewhere in the custom ORM. I dubbed it ‘The Statingleton’. It’s a beauty and I wonder why the Gang Of Four didn’t think of this pattern.

In short, it has (almost) everything you could ask from a Singleton:

  • Protected constructor
  • An instance of itself
  • A static method to access the single instance (which will create it if it doesn’t exist)

Strangely, all other methods in this class, were static. Every single one of them. And almost every single method executes some hard coded SQL in the underlying MSSQL database.

What do you get, then? Well, this (sorry about the VB.NET, didn’t feel like porting it):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Public Class Statingleton
    Private Shared _instance As Statingleton

    Protected Sub New()
    End Sub 'New

    Public Shared Function Instance() As Statingleton
        If _instance Is Nothing Then
            _instance = New Statingleton
        End If
        Return _instance
    End Function

    Public Shared Function Foo(ByVal s As String) As Integer
        Dim iSom As Integer
        Dim iTeller As Integer
        Dim f As Integer = 0

        If Len(s) = 0 Then
            f = 0
        ElseIf Len(s) <> 9 Then
            f = 1
        Else
            For iTeller = 1 To 8
                iSom = iSom + ((10 - iTeller) * Val(Mid$(s, iTeller, 1)))
            Next iTeller
            iSom = iSom - Val(Mid$(s, 9, 1))
            If iSom Mod 11 = 0 Then
                f = 3
            Else
                f = 2
            End If
        End If
        Return f
    End Function
    'Insert more methods
End Class

Yes, I don’t know, either.

No Comments

Using unbound CheckBox to update a row in ASP.NET using LINQ.

Background

The idea for this post comes from a simple problem: you have a form with a GridView with two, maybe three columns. One of these contains a CheckBox which indicates a status of the object which you’re viewing and it is the only thing you need to update in that form. Because of this, you don’t want to press the ‘Edit’ button at the left of the row just to update the status of the object, but you rather you could just click on the CheckBox and that the status updates automatically. But to do that, you need to create an unbound CheckBox, meaning you can’t get that row’s unique identifier. To solve that problem, we’ll be using the OnRowDataBound and OnCheckChanged events.

Enough of the abstract stuff, time for a concrete example to see what I mean.

Example

The example will be a User table with a boolean flag which indicates if the user is active or not, and a single ASPX page which can flip the flag using an unbound ASP CheckBox.

The database

For our example, we’re going to create a simple table in MSSQL. Three columns are required, the rest is arbitrary. The table will be called ‘User’, with the following three columns: UserID (datetype: integer. int, identity specification = yes), UserName (nvarchar) and Active (bit). Any other columns can be added, but will not be used.

For a full MSSQL script for this table, look below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
SET ANSI_NULLS ON
GOSET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[User](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NOT NULL,
[Active] [bit] NOT NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

The website

Now, create a new ASP.NET Website. The code behind language is irrelevant, but I’ll be doing my examples in C# since I’m more fluent in that. It’s pretty basic code, so translating it to VB.NET should not be hard.

Add a new Linq to Sql class (a DBML file), add a connection to the database your table is in and drag the table onto the design surface and save the file.

Drag a GridView (in the Toolbox, under Data) on the Default.aspx page. Go to the design view, open the smart tag and select in the ‘Choose Datasource’ drop to add a new Data source. Click on ‘LINQ’, specify an ID, click OK. On the next page, select the DataContext you just created in the DBML. Click next, select the table you want to see in the datagrid, add Where clauses if applicable. Do not enable ‘Allow update’ under Advanced. Finish the wizard.

You’ll now have a GridView and all its fiels are bound to a column specified in the database.

Using the TemplateField

The current CheckBox can not update the status when it’s being (un)checked, so let’s take care of that.

First, remove the CheckBoxField that was automatically added and which corresponds to the boolean field you want to edit without the ‘Edit’ button and replace it with the following:

<asp:TemplateField HeaderText=”[insert your text]“>
<itemtemplate>
<asp:CheckBox EnableViewState=”true” ID=”Active” runat=”server” Checked=’<%#Bind(“Active”) %>’ AutoPostBack=”true” />
</itemtemplate>
</asp:TemplateField>

This way, you get an unbound CheckBox and its Checked property will be set to the value stored in the database.

Updating the column in the database

Now there is only one single problem: when you (un)check the CheckBox, nothing happens. We’ll have to catch the event and handle it. Add the following attribute to the CheckBox you just added: OnCheckedChanged=”ChangeActiveStatus”.

In the code behind, add the following:

1
2
3
protected void ChangeActiveStatus( object sender, EventArgs e ) {
  //Handle the OnCheckChanged event
}

Once you start writing the method, you’ll encounter your last problem: because the CheckBox is unbound, you have no clue which row to update once the event is raised. We’ll solve that problem using the GridView’s OnRowDataBound event and the Attributes array of the CheckBox.

Adding the OnRowDataBound event handler

The OnRowDataBound is raised every single time a row in a GridView is being bound to a dataset. Since we’re binding the content of our LINQ datasource to our previously created GridView, this event will be raised for every row in the datasource.

Add the following Attribute to the GridView: OnDataRowBound=”onRowBound”
Lastly, add the following code to your code behind:

1
2
3
4
5
6
    protected void onRowBound( object sender, GridViewRowEventArgs e ) {
        if( e.Row.RowType == DataControlRowType.DataRow ) {
            CheckBox c = (CheckBox) e.Row.FindControl("Active");
            c.Attributes.Add("UserID", DataBinder.Eval(e.Row.DataItem, "UserID").ToString());
        }
    }

Whenever the OnRowDataBound event is raised, the event handler will add a custom attribute called UserID to the Attributes array and will set the value to UserID using the DataBinder.Eval method. The first argument of Eval is an object identifier, in this case the underlying data object to which the row is being bound and the second argument is a String expression which, in our case, indicates the column we’re reading from.

Now we can fill in the ChangeActiveStatus method (or whatever you called the event handler for OnCheckChanged) to update properly.
Use Convert.ToInt32(( (CheckBox) sender ).Attributes["UserID"]) to get the value stored in the attribute and to convert it to an Int. Since you’re using an unbound CheckBox, you’ll have to use a Stored Procedure or some direct SQL to update the column. For instance, your code could look like this:

1
2
DataContext c = new DataContext();
c.UpdateActiveStatus(Convert.ToInt32(( (CheckBox) sender ).Attributes["UserID"]), ((CheckBox) sender).Checked);

Preventing the PostBack

If you absolutely hate PostBacks, then you can use some AJAX to update the field instead.

, , , , , , , , , , ,

No Comments

Lexmark X1195 and Ubuntu 9.04.

Lexmark and Ubuntu (or Linux, for that matter), do not mix or blend. They work so horrible together, that not even the BlendTec blender will make these two blend until Lexmark does something about its driver development for Linux. Enough about that. This is more about how to get the Lexmark X1195 working under Ubuntu and since most other Lexmark printers are the same, it just might work for your printer as well! If you do use this guide to get your Lexmark printer up and running, please drop a comment with the model of your printer.
Everything you’re about to read is for the Lexmark X1195 and it currently runs sweetly on Jaunty. I read this on some Ubuntu forums and decided to compile the information for future usage, should I ever have to wipe my OS.

If none of the commands work, check the file names!

Getting some specific drivers and setting everything up

First, go here. Select Linux and download CJLZ600LE_CUPS_1_0_1.TAR.gz.

Yup, that’s a Redhat package. We’re gonna change that in a bit.

Transforming the package to DEB and installing them

I’m not entirely sure if the next set of commands are needed. If you know, let me know.

Run the following commands in a terminal:

1
2
3
4
5
sudo apt-get install tcl8.3-dev
sudo apt-get install tk8.3-dev cupsys
sudo apt-get install tclx8.3-dev
sudo apt-get install libstdc++5
sudo apt-get install alien #installs alien. You WILL need this

Navigate to the folder where you downloaded the TAR.GZ file to and unzip it:

1
tar -xvzf CJLZ600LE_CUPS_1_0_1.TAR.gz

Now, run the following commands:

1
2
tail -n +143 z600cups-1.0-1.gz.sh > install.tar.gz
tar -xvzf install.tar.gz

These commands pick grabs the last 143 lines of the install script and puts them in a tar.gz file, then unzips it using tar.

After unzipping, you’ll have several files starting with the string z600. Awesome. Run the next few commands:

1
2
sudo alien -k z600llpddk-2.0-1.i386.rpm
sudo alien -k z600cups-1.0-1.i386.rpm

If you see any message about scripts not being converted, don’t bother with those. Now enter the following commands to install the packages:

1
2
sudo dpkg -i z600cups_1.0-1_i386.deb
sudo dpkg -i z600llpddk_2.0-1_i386.deb

Hooking up the printer

Easiest part. I simply plugged my printer into the USB port. Ubuntu will complain that there are no suitable drivers. Tell Ubuntu that you want to select the drivers yourself. The drivers will be listed under Lexmark > Z600 or something similar. Your printer configuration will show your printer as a Lexmark Z600 color printer. Try and print a test page to see if things worked out alright. I had it working without any errors this way myself.

But wait, what about my scanner?

Install SANE and the SANE GUI to make things easier for you to use.
Once done, you’ll find XSane Image Scanning Program under Applications > Graphics. It should automatically detect the scanner in the printer, thus allowing you to scan once you press the ‘Scan’ button.

Happy Lexmarking!

, , ,

2 Comments

Sending SOAP in Java, without frameworks.

Just a quick little snippet on how I occasionally send SOAP messages in Java without frameworks such as SAAJ. The main reason I sometimes don’t use such frameworks is because I already know exactly what I have to send and because I don’t need all the wrapper methods and classes that the library provides.

The basic idea behind sending SOAP over the internet is using an HttpURLConnection object and manually setting the headers to match the data you’re going to send and sending the SOAP message itself as a byte array, all using a POST request.

Here is a quick sample on how to send SOAP messages over HttpURLConnection objects, with some things parametrized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * Sends a SOAP message to the remote server as an array of bytes and prints its response.
 * @param SOAPMessage - The SOAP message to send, including envelope, header and body
 * @param serviceLocation - The full location name of the remote service, such as http://orly-yarly.net/Service.asmx
 * @param remoteMethod - The name of the method that will be consumed on the server
 * @param nameSpace - The namespace of the SOAP message. Such as http://www.opengis.net/sos/1.0/
 * @param characterEncoding - The encoding of the message, such as UTF-8
 */

public void sendSOAPMessage(String SOAPmessage, String serviceLocation, String remoteMethod, String nameSpace, String characterEncoding) {
  //Create new URL object and HttpURLConnection object
  URL url = new URL(serviceLocation);
  HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

  //Convert the message to a byte array
  byte[] messageBytes = SOAPmessage.getBytes();

  //Set headers
  httpConnection.setRequestProperty("Content-Length", String.valueOf(messageBytes.length));
  httpConnection.setRequestProperty("Content-Type","text/xml; charset=" + characterEncoding + "\"");
  httpConnection.setRequestProperty("SOAPAction", nameSpace + remoteMethod);
  httpConnection.setRequestMethod("POST");
  httpConnection.setDoInput(true);
  httpConnection.setDoOutput(true);

  //Write and send the SOAP message
  OutputStream out = httpConnection.getOutputStream();
  out.write(messageBytes);
  out.close();

  //Read server response
  BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

  String inputLine;
  while((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
  }
}

This is very bare bones, but it works. However, when you use this, you’ll have to parse the SOAP response yourself, as well.

, , ,

No Comments

Multiple repositories on a single SVN server on Windows.

I spent quite some time figuring this one out today, so I figured I’d share my experiences with it. It’s not too hard to do, but you just have to know how to go about it. This install will not make use of Apache based access!
This guide was written while playing around on Windows Vista, but it should work just as well with Windows XP.

Get and install Subversion

Get the latest version of Subversion from here. I used version 1.4.6 for this (because I used an old install for this), but I would not be surprised if this works for newer versions, as well.
The concepts remain the same, after all.

Download the installer. Look for the one saying “Windows MSI installer with the basic win32 binaries – includes bindings for Apache 2.0x and 2.2x”.
Let it install naturally. For easiness sake, I’m assuming you installed it under C:\SVN.

Setting up multiple repositories

If you’re anything like me, then you dislike having a single, global revision number. Of course you can put all your projects in a single repository, but then that single revision number for the repository goes for all projects in that repository. That’s not what you want when all of your projects are under a separate version control.
Instead, I create one repository per project. svnserve will make it possible to serve all these repositories in one go using only a single service under Windows.

Go to whatever folder in which you want to store your repositories. For the sake of keeping things simple, I’ll assume you’re storing repositories in D:\projects.

Open a command line, and navigate to the D:\projects folder.

Due to me being unimaginative, I give my projects really lame names, such as project1, project2, project3, etc.. Let’s create the SVN repositories using svnadmin.

1
2
3
4
5
D:\projects&gt; svnadmin create "D:\projects\project1"

D:\projects&gt; svnadmin create "D:\projects\project2"

D:\projects&gt; svnadmin create "D:\projects\project3"

If the svnadmin command is not working, then your PATH variable does not have the path to the subversion BIN folder in it. Add that folder and try again.
This will create the new directories and place all required folders and files in the directory you specified.

If you ask for the directory listing using dir, you should see the following:

1
2
3
4
5
6
7
8
17/05/2008  13:35    <dir>          conf
17/05/2008  13:35    </dir><dir>          dav
17/05/2008  13:35    </dir><dir>          db
17/05/2008  13:35                 2 format
17/05/2008  13:35    </dir><dir>          hooks
17/05/2008  13:35    </dir><dir>          locks
17/05/2008  13:35               234 README.txt
</dir>

Easy enough, right?

Setting up SVN as a service

The most interesting part is setting up SVN as a service. Of course you could just svnserve it, but this is more fun.
What happens now is dependent on your OS: Anything earlier than XP will have to look for the sc.exe executable, Windows XP and Vista will have it available.

If the sc command is not available to you even though you’re using XP or Vista (i.e.: you get the following error: ‘‘SC’ is not recognized as an internal or external command, operable program or batch file‘), then you must run the command line as Administrator and try again.

Type the following command and replace everything where needed:

1
sc create svn binpath= "C:\SVN\bin\svnserve.exe --service -r d:\projects" displayname= "Subversion" depend= Tcpip start= auto

Run the command and the service will be created and started up whenever Windows starts. All that remains is getting it to run for the first time.
Simply type the following command to start it up for the first time:

1
net start svn

Setting up authorisation

The last thing to do is to set up authorisation for your SVN repositories. You have to do this on a per repository basis.

Each repository you create will have a conf folder. In that conf folder you will find a file called svnserve.conf. Open that file in a simple editor such as notepad or wordpad.
Remove the pound symbol (#) the following lines:

# anon-access = none
# auth-access = write
[...]
# password-db = passwd

Change the authorisation control access to whatever you prefer. I prefer “none” for anyone not authorised and “write” for anyone who is authorised, but I’ll leave that up to you.
Uncommenting the last line tells SVN to use the passwd file in the same folder in order to determine if someone is authorised to use the repository. This file contains username and password combinations.

Save and close the file.

Now, open passwd in the same folder. It will look like this:

1
2
3
4
5
6
7
8
### This file is an example password file for svnserve.
### Its format is similar to that of svnserve.conf. As shown in the
### example below it contains one section labelled [users].
### The name and password for each user follow, one account per line.

[users]
# harry = harryssecret
# sally = sallyssecret

Remove the harry and sally users and replace them with your own. The syntax is: [username] = [password].

Once you’ve created all of the users, you’re good to go! You won’t need to change anything if you add new repositories, so you’re free to add as many as you want.

Accessing repositories

I use Tortoise SVN to do this. When attempting to access repositories, don’t forget to open your firewall(s) and to allow TCP/IP access on port 3690, or else you’ll get connection errors.

You can now access the repositories on the following URL:
svn://localhost/project1 for the project1 repository (if you’re accessing it locally)
OR
svn://IP/project1 for the project1 repository (for networks, where you replace IP with the computers IP or some valid domain name).

, , , , , ,

2 Comments

Remembering the difference between Big Oh, Big Omega and Big Theta.

I’ve never been really good in remembering the difference between these three complexity classes. There is a simple mnemonic for it, though. It helped me through my course on complexity so it’s probably useful to someone, I hope.

This article is written not from the mathematical point of view, but the information technology point of view, so there won’t be any mathematical things in this article. I also will not handle complexity in greater detail than necessary.

A quick recap

Algorithm complexity studies the limiting behaviour of algorithms as the input n approaches infinity. There are three main complexity classes in which algorithms can be placed: Oh, Omega and Theta. Two of them, Oh and Omega can be divided in subclasses: Big-Oh and Little-Oh and Big-Omega and Little-Omega.

This article describes an easy but useful mnemonic that can be used to differentiate between the three main classes.

Big-Oh and Little-Oh

This one helps if you know that the letter is not actually a capital ‘o’, but the Greek capital Omicron. The Omicron looks deceptively much like the capital ‘o’: Ο. The mnenomic lies in the name of the Greek letter.
To access the mnemonic, Omicron should be read as O-micron. Extended to a sentence, you get: ‘… is micro compared to … as n approaches infinity’.

Let’s take, for example, the following notation:

f(n) ∈ Ο(g(n))

Using the mnenomic, the following can be read: “The function f is micro compared to g as n approaches infinity.” This means that, as n approaches infinity, f is asymptotically bounded above by g (up to a constant factor).
Or: f(n) ≤ g(n) ⋅ k as n approaches infinity.

Be mindful that this means that f(n) could very well equal g(n) for some constant factor as n approaches infinity.

If the two should not be equal, use the tighter ο (Little-Oh). I use the same mnemonic for this one as for the Big-Oh, but as the hole in the letter is tighter, it reminds me that ο describes a tighter bound which is strictly smaller than its Ο bound.
This corresponds with the definition of f(n) ∈ ο(g(n)): g(n) asymptotically dominates f(n), or, more mathematically: f(n) < g(n) ⋅ k.

Big-Omega and Little-Omega

This mnemonic is a bit easier since the Greek letter is already used. To access it, read the Omega as O-mega. Extended to a sentence form, you can read ‘… is mega compared to … as n approaches infinity.’

Let’s take, for example, the following notation:

f(n) ∈ Ω(g(n))

Using the mnemonic, the following can be read: “The function f is mega compared to g as n approaches infinity.” This means that, as n approaches infinity, f is asymptotically bounded below by g (up to a constant factor).
Or: f(n) ≥ g(n) ⋅ k as n approaches infinity.

Be mindful that this means that f(n) could very well equal g(n) for some constant factor as n approaches infinity.

If the two should not be equal, use the tighter ω (Little-Omega). I use the same mnemonic for this one as for the Big-Omega, but as the hole in the letter is smaller, it reminds me that ω describes a tighter bound which is strictly smaller than its Ω bound.
This corresponds with the definition of f(n) ∈ ω(g(n)): f(n) asymptotically dominates g(n), or, more mathematically: f(n) > g(n) ⋅ k.

Big-Theta

There’s no real mnemonic for this one, but when f(n) grows just as fast as g(n) asymptotically, then f(n) ∈ Θ(g(n)). Should the other two mnemonics fail, then the function you’re trying to evaluate is most likely in this class.
Informally, use this when the asymptotic growth of two functions is equal.

As there’s no such thing as Little-Theta, there’s no confusion possible on which to use.

Conclusion

I hope this was useful for you. It certainly was to me when I took a course in it.

, , , , , , ,

No Comments