#me { float: left; }

May 21, 2014

Auto hyphenate text as typed in jQuery

Filed under: jQuery, Programming — Simon Rigby @ 10:49 am

I had a requirement to proved a hyphenated version of a documents title to use as the default url. The idea was for the user to type in the title and a hyphenated version would be used as the url with the ability to manually change it if required.

My solution was to create two text boxes with ids #Title and #Url. The user would type in “This is the name of my page” into #Title and as they were typing “This-is-the-name-of-my-page” would appear in the #Url text box.

In jquery this is pretty straight forward.

$(“#Title”).keyup(function () {
$(“#Url”).val($(this).val().split(” “).join(“-”));
});

Hope that’s helpful.

June 23, 2010

WCF doesn’t work on Windows Server 2008 out of the box

Filed under: Uncategorized — Simon Rigby @ 9:41 am

A quick post for those who can’t get their WCF service to work on Windows 2008/IIS7. See this link for an excellent article and solution.

http://blah.winsmarts.com/2008-4-Host_a_WCF_Service_in_IIS_7_-and-amp;_Windows_2008_-_The_right_way.aspx?postID=416

I’ll follow this up later when I have time.

May 18, 2010

Consuming a WCF service in ASPX

Filed under: ASP.NET — Simon Rigby @ 6:10 pm

I’m developing a WCF web service to support an application that is being developed by my current employer. In essence the web service will be taking requests from a Java client and this has gone smoothly by simply using the NetBeans IDE to discover the service and create the appropriate proxy. All good and it all works.

However, during our closed beta phases there are elements of the application that are not yet implemented in the client, namely a registration process. The short answer appeared to be to create a little website that purely acts as a front end for the web service (in particular allowing the user to register their instance of the software with the web service – the details are of no significance). As I say this was only scoped at a small scale public beta so was acceptable in our situation.

I had already been testing the service via a windows client purely to allow me to send requests to the service and to see the responses in a reasonably friendly fashion. All I did in this case was publish the service to a local IIS7 virtual directory and then add a web reference in the usual way (ie pointing it to http://localhost/myvirtualdirectory/myservice.svc?wsdl). This worked fine but for some reason I was getting errors when using the same approach in the aspx web site. The really cool (add sarcasm symbol here) bit was that the service was performing the action but the web site was choking on the response. The service uses MTOM to carry large binary data (ie packets of up to 1 MB) to and from the service and the error tended to indicate that the client was getting  the ‘attachment’ style payload that MTOM uses but was expecting text/xml. Straight away I thought that this had to do with a bad configuration setting but that turns out to be only half the story.

It turns out that I really should have paid attention to the documentation as it is crucial in this case.

So here’s how you do it.

Fire up a Visual Studio Command Prompt and locate your self in the directory where you want the output of this process to go. In short this process is going to create two files, one that contains a client proxy for the service that you can then code against in the service and one that will contain a config section to be merged into web.config.

Using the above URL as an example you use the command:

svcutil.exe http://localhost/myvirtualurl/myservice.svc?wsdl

svcutil will then create a file of the same name as the service (ie myservice.cs) which will contain a class called MyServiceClient. Simply add this file to your web application and its ready to be used by creating instances of MyServiceClass and calling its methods. The contents of output.config are to be merged into the web.config file. I simply copied everything between <configuration></configuration> and pasted it before the closing </configuration> tag in my web.config file.

Not only does this provide you with the correct configuration for the web.config file but the proxy that is generated also features a set of constructors which at this stage I assume are allowing the correct endpoints and bindings to be used (I’ve only had a quick glance at this stage – It works – but I don’t exactly know why yet – however I think its got to do with correct binding and endpoint configurations).

It all works perfectly. Sorry this post is rushed, but its another one of my ‘get it down before you forget’ posts. I may return to this to flesh out the detail soon, but for now if you have any questions or think that this ‘smells’ a little familiar but need more detail, please feel free to comment and I will endeavour to help where I can.

April 22, 2010

Bogus file errors when using subversion with Windows 7

Filed under: Subversion, Windows 7 — Simon Rigby @ 7:44 am

I have a brand new laptop and you can imagine my distress when I started seeing a number of error reports (including log events) indicating that CHKDSK needed to confirm the health of my disk (not nice to see on new hardware). Turns out this is due to a known issue with revisions to the NTFS file system that ships with Windows 7. Whilst a fix is slated for SP1 this is annoying. By the way, its not just subversion that is potentially affected by this change to NTFS but that’ how its manifesting for me. See http://subversion.wandisco.com/blogs/windows-7-bogus-errorfilecorrupt-error-.html for further details.

February 8, 2010

Configuring publish in Visual Studio 2008

Filed under: Uncategorized, Visual Studio 2008 — Simon Rigby @ 5:04 pm

Just a quick one. I was working on an old site today where we have some legacy php code (ie the shop is still in php). As our brief was to create the new website but just to leave the old shop in php hanging off a /shop url, I simply imported that directory into Visual Studio to keep all the files that need publishing in one place. However, by default  Visual Studio 2008 will not publish .php files. When the project is published using the option to publish only the files needed to run this web application it skips the .php files as it doesn’t see them as ‘needed’. It will quite happily publish any jpgs though as it sees those as content and hence required.

But of course that is the solution. To Visual Studio 2008 a .php file is not required for the site to run nor is it seen as a ‘valid’ resource.

To solve this, select the files that aren’t being published, then select the properties tab and mark the Build Action as ‘Content’.

The next time you publish, all of the files that you have marked as content will be published to the output folder or ftp location.

Hope this helps.

(By the way look at what they have done in Visual Studio 2010 and you will see that the publish feature is a lot more flexible).

November 18, 2009

Copying tables between databases on SQL Server

Filed under: SQL Server — Simon Rigby @ 3:43 pm

Copying tables from one database to another is pretty straight foward. No need to create the destination table as the script will create it on the fly.

Assume a database called sourceDB and a database called destinationDB (all owned by dbo for this example). To duplicate the table called myTable the syntax would be.

USE destinationDB

SELECT * INTO destinationTable FROM sourceDB.dbo.myTable

That’s it .. a copy now exists in the destinationDB. One thing you will need to you is establish the primary key on the copy as it is not created as part of the copy.

May 19, 2009

Errors installing Apache web server on Windows XP alongside IIS 6.0

Filed under: Uncategorized — Simon Rigby @ 1:30 am

Ok this might have more relevance that just to Windows XP and/or IIS 6.0 but its how I found it.

I’m doing a piece of work at the moment (retrofitting something for a website) that takes advantage of some Apache modules. The site PHP/MySql (essentially WAMP) and in the past I have just worked with PHP in the WIMP environment. It was my first go at installing Apache and it didn’t go well. Firstly, the installer said consult install.txt for help installing (that will be the file that the installer creates – correct? f**king brilliant thinking that). I’m not having a go at the Apache web server, I don’t know enough about it to form an opinion, but put the install instructions somewhere they can be read BEFORE you install it.

Anyway, having eventually installed with a domain name of ‘localhost’, a server name of ‘bluebox’ (my machine name) and my email address for the admin email (makes sense), and choosing to install it as a service on port 80, off I went. Now I knew ahead of time that there was going to be a conflict with port 80 with IIS but having read a bit knew that I could resolve that later by some tweaking to httpd.conf file, I went ahead with port 80 (I’ll jsut change it 8080 later).

The install completes and it attempts to start the service for the first time; Two errors and the crux of the post:

httpd.exe: Could not reliably determine the server’s fully qualified domain name
, using 192.168.0.2 for ServerName

Eventually traced this down to the fact that installer seems to have just ignored that I’d chosen localhost for the server name and left the line commented out in httpd.conf.

# Look forServerName localapache:8080

… and remove the #. And its using a different server name to the one I specified in the installer (er why???). Ok localapache:8080 is fine by me. First problem solved.

(OS 10048)Only one usage of each socket address (protocol/network address/port)
is normally permitted.  : make_sock: could not bind to address 0.0.0.0:8080
no listening sockets available, shutting down
Unable to open logs

This is common with services that do anything with standard ports (80 for example). The solution is to find what is listening on the port that the service wants to listen on and kill it, or do some port reassingment. To find this open a command prompt and type:

netstat -a -o

For info the -a switch displays all connections and listening ports and the -o switch identifies the process id that is lisenting on that port. Now keep in mind that my httpd.conf is now set to use localapache on port 8080 so in my case I’m looking for anything listening on that port. Sure enough I find one. Take note of the process ID and open up Task Manager and click the Processes tab. Click the PID column to order on that column and scroll down to find your offending process. A common offender is Skype listening on port 80 (if you have Apache set to listen on port 80 instead of 8080 as in my example). In my case it was the Sql Server Reporting Service on port 8080. Stopped those two services in the services manager (don’t just kill them .. close them properly and while your there maybe set them to not start automatically). Started the Apache service and sure enough it started. Opened a browser and browsed to http://localapache:8080 and got the lovely “It Worked” message.

Hopefully this will be useful to others.

As an aside, it is a bit crap that Skype has a thunking mechanism to use port 80 or 443 if it can’t get through the firewall on its port of choice. But contrary to popular belief this can be turned off. In Skype goto Tools -> Options -> Advanced -> Connection … and uncheck the box marked Use port 80 and 443 as alternates for incoming connections.

April 1, 2009

ASP.NET AJAX Update Panels swallow detail – What’s the real error?

Filed under: Uncategorized — Simon Rigby @ 11:42 am

Here’s one that caught me out last night (and I’m ashamed to say I spent several hours on this).

Simple scenario, a DataList bound to LINQ2SQL Data Source. Each row has an edit button and the panel that allows detail editing was being displayed via a Modal Popup Extender. And the whole thing is inside an Update Panel (with EnablePartialRendering = true).

Initially, I was just displaying the panel to allow editing and everything worked fine. Then I wrote the code that responded to the "Edit" command from the DataList (basically populating the panel’s controls with data for that record). Then a test run and …

[Exception... "'Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException:
Cannot have multiple items selected in a DropDownList.' when calling method:
[nsIDOMEventListener::handleEvent]"  nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)"
location: "JS frame :: chrome://firebug/content/spy.js :: onHTTPSpyReadyStateChange :: line 497"  data: no]
http://localhost:1606/ScriptResource.axd? ……… etc

Now on reflection the error was clear (and yes I was doing something funky with a DropDownList), however Firebug was displaying the error as originating in a method to do with Date Abbreviations. This threw me and I started looking for data format errors and the like. Finally, I switched of EnablePartialRendering and lo and behold a stack trace.

Forget was actually happening, the lesson learned is, develop with EnablePartialRendering set to false or at very least remember to do that when you get one of these odd errors that is being eaten by AJAX/the UpdatePanel etc.

November 20, 2008

Writing LINQ to SQL select queries with optional where arguments

Filed under: C#, LINQ to SQL, SQL Server — Simon Rigby @ 3:12 am

Firstly, I should say that there are ‘probably’ more elegant ways to do this (i.e. expression trees – which I can’t get my head around) and System.Linq.Dynamic (which I have downloaded and compiled but due to being up against an impending deadline, I’ve not had a chance to research).

Ok, caveat over.

I have a scenario where I need to write a LINQ to SQL select query where I have many search parameters but I’m not sure which ones will be supplied. This is a derivation of an old SQL pattern which I used in vanilla SQL many times to solve a similar problem.

Let’s say we are searching for a list of customers and we can filter (where clause) these results based on City, Type and Rep (just as an exercise). So a user can have the following parameter combinations:

  • None supplied – returns all customers
  • City supplied – returns all customers in a given City
  • Type supplied – returns all customers of a certain Type
  • Rep supplied – returns all customers assigned to a certain Sales Representative
  • City and Type supplied – returns all customers in a given City of a certain Type
  • City and Rep supplied – returns all customers in a given City assigned to a certain Sales Representative
  • Type and Rep supplied – returns all customers of a certain Type assigned to a certain Sales Representative
  • City and Type and Rep – returns all customers in a given City of a certain Type assigned to a certain Sales Representative

Ok, a bit long winded, but I wanted to be sure we were all clear on the scenario.

In pseudo code we can define the solution as:

SELECT all the rows
WHERE City is in some state
AND Type is in some state
AND Rep is in some state 

... but we only want to define a WHERE argument if the parameter is of some use to us (i.e. defined). The secret it to substitute any parameter not being used with the expression true. So in pseudo code when only City is defined our code looks like ...

SELECT all the rows 
WHERE City equals some value 
AND true 
AND true

.. where the ‘AND true’ elements substitute for missing values. Ok let's see the code to make more sense of this. For the sake of the argument I am getting these values from three textboxes called txtCity, txtType and txtRep respectively.

MyDataContext db = new MyDataContext();
IQueryable<Customer> customers = from c in db.Customers
          where (txtCity.Text.Length != 0) ? c.City == txtCity.Text : true
          && (txtType.Text.Length != 0) ? c.Type == txtType.Text : true
          && (txtRep.Text.Length != 0) ? c.Rep == txtRep.Text : true
          select c;

We use the ternary operator in each line of the where clause to test for a useable value. If we find one we add a WHERE 'portion' for that parameter. If not we substitute 'true'.

So there you go. I've not looked at the code this spits out yet (SQL). But then as I said before I'm up against a deadline.

Enjoy.

November 19, 2008

A one way encryption approach to storing passwords in SQL Server

Filed under: C#, SQL Server, Uncategorized — Simon Rigby @ 1:08 am

Storing passwords in the database in clear text isn’t really a great idea for a number of reasons. Remember a password is used to establish identity. It’s not a hoop to jump through before you can access data, it says "I know the password for this account thus authenticating that I am the account’s owner." There are plenty of two encryption techniques (combination of public and private key) to encrypt and decrypt passwords on the fly. However, I am more much for of a fan of the one way approach.

In short a one way encryption algorithm is designed to encrypt data in such a way that it cannot be decrypted. So it’s not a good solution for data you need to retrieve.

So, a couple of caveats to this approach. If a user cannot remember their password, it cannot be retrieved from the database. The better approach in my humble opinion is to generate a new random password and send that to the user. Then once they have logged in successfully, allow them a facility to change it to something more memorable (and inherently more guessable .. but that’s another story .. grin).

OK enough waffle, onto the approach:

There are plenty of one way algorithms in existence but the one I’m going to use is SHA1. Yes there are stronger algorithms but the principal is the same in all cases so it’s fine for our example.

SHA1 (and many other one way algorithms) take a variable length string and convert it to a fixed length cipher. The cipher that SHA1 produces is 160bit (or 20 bytes) in length, regardless of the input string. So to generate and encrypt a password we do the following.

  1. Generate a random password of any length.
  2. Generate a cipher with SHA1.
  3. Store that byte array in a SQL Server field of type varbinary(20)

Let’s look at some code:

// GetRandomPassword() just creates a random password
// Code not included in this article
string username = "Fred";
string password = GetRandomPassword();
SHA1CryptoServiceProvider prov = new SHA1CryptoServiceProvider();
byte[] passwordCipher = prov.ComputeHash(Encoding.UTF8.GetBytes(password));

// And lets use LINQ to store the password
// targeting a table called SiteUser with a username and password field
myDataContext db = new myDataContext();
SiteUser user = new SiteUser();
user.Username = username;
user.Password = passwordCipher;
db.SiteUsers.InsertOnSubmit(user);
db.SubmitChanges();

Ok, so that's pretty straight forward. We're just creating a new SHA1CryptoServiceProvider and using it's ComputeHash function to generate a cipher. Finally we store it away.

So how do we check when a user logs in that they have entered the correct password. We can't retrieve the password from the database to compare it as that is the very nature of a one way encryption strategy .. it's one way!

What we need to do is encrypt the password that the user provides and then compare the ciphers. To make life a bit easier, we won't compare the byte arrays. We will convert each byte to a character and then compare the resulting 20 character string.

Onto the code. Please note I am omitting code like checking to see if the username exists before even bothering to compare the password etc .. it's just a demo.

string suppliedUsername = "Fred";
string suppliedPassword = "password":

// first we encrypt the supplied password in exactly the 
// same way as we did before, but we take an extra 
// step of converting the byte array to a string
SHA1CryptoServiceProvider prov = new SHA1CryptoServiceProvider();
byte[] suppliedPasswordCypher = 
    prov.ComputeHash(Encoding.UTF8.GetBytes(suppliedPassword));
string suppliedPasswordHash = Convert.ToBase64String(passwordPasswordCypher);

// next we retrieve the data from SQL Server
myDataContext db = new myDataContext();
SiteUser user = db.Users.Single(u => u.Username == suppliedUsername);

// and then convert that retrieved 160bit cipher to a 20 character string
string storedPasswordHash = Convert.ToBase64String(user.Password.ToArray());

// and finally compare
if (storedPasswordHash == suppliedPasswordHash) {
    // user is who they say they are
} else {
    // user is politely told to sod off
}

There you go. Not that hard and of course this could be wrapped up into helper methods to encapsulate this approach. Enjoy.

Older Posts »

The WordPress Classic Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.