Take Screenshots Programatically in iOS with Category on UIViewController

By: Brian Dobberteen

Thought I’d share this almost-trivial technique for taking screenshots of an iOS device. This will essentially replicate the user pressing the home & power buttons simultaneously, but will return a UIImage for you to use as you please.

Without further ado:

UIViewController+Screenshot.h

UIViewController+Screenshot.m

To make use of this, create these two files (or download them here) and add them to your project. Import the UIViewController+Screenshot.h file as needed.

Here’s a quick usage example:

Pretty self-explanatory, I think. Adjust to suit your needs, such as a different path for the images or a different ‘quality’ level for the resultant JPEG file (we’re using 0.5 here).

Hope somebody finds this useful!

UPDATE: NEVER MIND!!!

Enhancing the TypeSafe Enum Pattern

By: Brian Dobberteen

As I mentioned in my last post about the Typesafe Enum Pattern in C#/VB.NET, I left out a few features that I had originally wanted to include in that post.

Namely, these features were nothing more than implementing the IComparable<T> and IEquatable<T> interfaces.

Upon further investigation, I’ve found that there is no need to implement IEquatable<T> here, as we’ll see in an example in just a moment.

Also, I’m not sure how often we’d find ourselves needing to sort collections of our enum-esque class.

Here’s the original class from the previous post:

The ‘Enum’ Class

This will be our baseline to begin implementing the interface(s):

Again, if you’d like to re-familiarize yourself with the above code and its features, check out the original post: Typesafe Enum Pattern in C#/VB.NET.

Do We Need IEquatable<T>?

See for yourself:

This behaves just as a normal Enum would. Clearly, there is no need to implement IEquatable<T> in this case.

Do We Need IComparable<T>

IComparable<T>, on the other hand, might prove useful if we ever find ourselves wanting to sort an Array, etc, of UselessItem pseudo-Enums.

Without implementing IComparable<T>, we are not able to do:

Implementing IComparable<T>

IComparable<T> is definitely one of the easier interfaces to implement – it only requires the implementation of a single method:

int CompareTo(T other);

CompareTo returns:

If this object is less than the other argument, the method returns a negative integer.If this object is equal to the other argument, the method returns zero.

If this object is greater than the other argument, the method returns a positive integer.

See MSDN’s Entry on IComparable<T> for more information.

This mechanism is what allows, for example, Array.Sort() to work easily with a simple lambda expression.

So let’s implement it!

In line 18, you can see that we want to be able to sort by our ItemName property. Sorting the GUID ItemIDs is probably something of little interest, but it certainly can be done as well. In fact, this pattern can be used to make our enum-esque Class sortable by whatever property/datatype we might need for our purposes.

Let’s try a sample sort:

Not too shabby!

Conclusion

Well, we haven’t added a ton of real-world useful functionality to our enum-esque Class, though it was an easy way to demonstrate the implementation and usefulness of IComparable<T>. Initially, I had thought that implementing IEquatable<T> was also necessary to do simple operations such as:

But, as it turns out, the nature of our enum-esque class gives us the above capability out-of-the-box.

And free stuff, that works as expected? A rarity these days!

Setting up VisualSVN for Local Projects

By: Brian Dobberteen

This one is pretty straightforward, but potentially useful to those of you not yet familiar with source control.

In a nutshell, source control allows us to keep a historical record of any changes we’ve made to files over the course of time. This is beneficial because if multiple people are working on the same project, it can be very easy to accidentally overwrite someone else’s changes that you may not have been aware of. It also gives some peace of mind to know that copies of your teams’ work are safe from accidental local deletion, corruption, and other such maladies.

The source control system that we will be using today is known as Subversion.

Subversion (SVN) is an open-source, widely used, and in my experience, very solid choice for a version control system (VCS). To be sure, there are many others out there, such as Git, Mercurial, Team Foundation Server, CVS… the list goes on.

We’re going to quickly learn how to get an SVN server up and running on your Windows box with the aid of two software packages: VisualSVN Server and TortoiseSVN (which will serve as our client).

First, let’s grab these two packages – try and be sure to grab the latest stable release offered at each site.

VisualSVN Server: http://www.visualsvn.com/server/download/

TortoiseSVN: http://tortoisesvn.net/downloads.html

Installing VisualSVN Server

Fire up the VisualSVN Server installer that you downloaded from the above link. Follow the on-screen prompts – the default settings should be fine. Once that’s done, it should offer to take you right to the VisualSVN Server Manager Console – click OK and we’ll find ourselves at a screen that should look similar to:

VisualSVN Server Management Console

The next step is to create at least one user and one repository:

Adding Users and Repositories

Creating a new user couldn’t be simpler – just decide on a username and enter/confirm a password.

Setting up a new repository is equally simple – all you need to do at this point is give it a name, preferably something meaningful to you and your team. For now, don’t worry about the ‘Create default structure’ checkbox and make sure that it’s not checked.

And that’s it! Told you it was simple!

Installing and Using TortoiseSVN

Again, first step will be to run the TortoiseSVN installer that you downloaded earlier. Just accept any default settings. Once the installer is done, it will prompt you to reboot – go ahead and do so.

Once back in Windows, we find that our right-click context menu has some new additions:

Next, we’ll want to create a folder to create what is known as our ‘working copy’ of the project that will now be under source control.

In whatever location you deem appropriate, create a new folder, preferably with a name that matches the name of the repository you created earlier in VisualSVN Server.

Once that’s done, right click the new folder, and then click on ‘SVN Checkout…’ in the context menu, which brings us to:

All that’s needed for this screen is to type the URL of the repository you’ve created. I’m using localhost here, and this may or may not work. If it does not, replace localhost with the name of your machine.

Finally, replace where I show ‘Site1’ with the name of the repository you created earlier.

Leave all other settings as they are, then click OK.

Because we’re connecting over SSL, TortoiseSVN will prompt you about whether or not you want to accept the security certificate. Choose ‘Accept Permanently’ and you’ll be good to go for now and in the future.

Now, you have an active ‘working copy’ that is under version control by SVN!

Adding Project Files to SVN

If you already have an existing project, made up of files and directories, the first step will be to copy those items to the folder you just did the SVN Checkout to.

Note that it is easy to tell at a glance what folders/files are under source control, and what their current status is:

So, let’s add some files to our working copy folder and place them in to the repository.

The first step is to select the files that you want to place in the repository by first selecting those files/folders, right clicking your selection, and choosing TortoiseSVN -> Add…

Which brings us to:

Leave everything checked, then click OK.

TortoiseSVN will show the progress of the Add – if everything went ok, it should say so. Click OK to close the window.

Note that now each file/folder icon will be overlaid with a blue plus sign, indicating that it has been added but not committed.

The final step is to Commit these added files/folders by again, first selecting the ones you’ve just added, right-clicking that selection, and choosing ‘SVN Commit…’:

Which brings us to:

The area circled in red above is a text area to enter a log message detailing what you are committing. Personally, I think it best to always try to include some meaningful comment about what you’ve included/changed in the commit.

Messages like: ‘Pulled the javascript out of index.html and placed it in scripts/myscript.js” can definitely be of help.

Though the log message is optional for us, some shops may require a log message on each commit.

Don’t be lazy – always enter a commit log message!

Once you’re done entering your message, click OK. TortoiseSVN will show the progress of the commit, ending with a display of what revision you are now on. Since this was the very first commit, it makes sense that you should see that you are now at Revision 1.

Day to Day Usage of SVN

Frequently Updating and Commiting your project files is an excellent habit to get into. We already know what a Commit does, and I bet you can guess what an Update does.

To try it, select any files you’d like to have the latest copy of so that you can be sure that you’ve picked up any changes by other members of your team. Right click these selected files and click SVN Update…

Since you are the only one who has committed anything to this point, you’ll see that nothing has changed and that you are still on Revision 1.

Next Steps

Add more users, one for each member of your team.

Add more repositories, one for each of your projects.

Individually make and commit changes, being sure to update after each one to ensure you have the latest code.

Experiment with features such as ‘Locking’ which will prevent other team members from modifying the locked file until you release that lock.

Hopefully this has been of some use to you CVS n00bs out there – next time, we’ll go over conflict resolution, an important tenet of version control.

Typesafe Enum Pattern in C#/VB.NET

By: Brian Dobberteen

Been doing some thinking about Enum and a couple of its shortcomings.

First, let’s create a simple Enum:

From here on out, we’ll stick to C# in these examples (VB.NET source available for download soon!).

A recent project prompted me to create a number of Enums, as I have done in the past in many other projects.

For this project, however, I had a desire to have tighter control over the usage of the Enum type, as it dawned on me that:

Ok, well that’s kinda disconcerting, but I’m sure .NET has a library function to check if an Enum value is defined. Not surprisingly, they do, and even less suprisingly, it is:

Enum.IsDefined(Type enumType, Object value)

Works great:

No surprises here, right? Well… maybe not so fast.

Hit up Google for some research and immediately found widespread concern over the performance of Enum.IsDefined().

It turns out that Enum.IsDefined() uses Reflection and must access metadata in order to do its magic. Neither of these operations are real speed demons, to be sure, and when using IsDefined in a loop with a ton of iterations, these performance problems may manifest themselves in an attention-getting way.

No, I never bothered to test this.

An alternative method for checking if an in-range UsefulItem variable was given:

This works, but what about when you add another UsefulItem to your Enum definition? The code above suddenly goes stale, maintenance nighmare ensues, company goes under, and you begin your unlimited unemployment benefit checks!

And the above was for a simple enum that had integer values in the Enum definition that matched the integer values in the DB lookup table. (The use of Enums to represent DB lookup table values can be discussed at another time).

The next Enum I needed to create didn’t have any integer values to line up with. The next lookup table that I wanted to represent used GUIDs as its primary key (PK) and this doesn’t work:

I get that last snippet was a bit gratuitous – we all know by now that Enums use integers as their underlying datatype.

And not only did I want to have a GUID represent each of my quasi-Enums, but I also wanted string representation beyond the camelcase names in the Enum. I won’t bother with another silly example – clearly a string is not an int, and can in no way be tied to the members of an Enum.

During my earlier research that revealed .NET’s willingness to allow any integer to be assigned to an Enum, I stumbled across something called the Typesafe Enum Pattern.

For reasons unknown to me, Java apparently doesn’t do Enums. That may not be entirely true, but for the sake of argument, let’s just over-simplify things here and agree that Java doesn’t do Enums.

I ended up finding Replace Enums with Classes [sun.java.com] and was inspired by what I read.

It led me to develop:

Note that the version above has been somewhat stripped down for clarity – originally I had implemented both IComparable and IEquatable as well as overridden the ‘==’ and ‘!=’ operators and the ToString() and GetHashCode() methods. These changes are left as an exercise for the reader 😉

Using this newly created struct, let’s check out some of its characteristics:

Could a disgruntled fanboi do this?

Definitely not! Note lines 3 and 4 of our UselessItem Class definition – they only allow setting of these two properties from within the class itself. This is caught at compile time and simply not allowed.

Other things that the compiler will keep us safe from:

In line one above, we cannot create new UselessItem objects, thanks to our private explicit default contructor:

Lines 3 and 5 will fail to compile as nothing but UselessItem objects can be cast to UselessItem.

Though this, as contrived as it is, will only be caught at runtime:

Try the above code and get an InvalidCastException at runtime, killing the application if not caught.

And we even get the same behavior out of our class as we would a traditional Enum:

For some reason, this surprised me. At first, I thought that using a struct rather than a class would be prudent here, seeing as how structs are value types and classes are reference types.

After giving it a bit of thought, I believe it is because we cannot actually even instantiate a UselessItem object, we don’t have to worry about usual reference type behavior.

There is some tradeoff, I suppose.

Because a class can contain an explicit parameterless constructor, and a struct cannot, we end up the following difference between the two approaches:

Assume for a moment that UselessItem is indeed a struct:

Because structs are value types, they can never be set to null. This is partly the reason why they cannot have explicit parameterless constructors. Calling new on a struct is no different than declaring a new struct variable without assigning a value:

Though you aren’t able to use the ui2 variable here (compile-time error – Use of unassigned local variable ‘ui2’) it is plain to see during debugging that after line 2 above has run, both ui1 and ui2 contain the same values, which for structs, are all the default values for each type contained within (in this case, null for the ItemName and {00000000-0000-0000-0000-000000000000} for the ItemId.

On the other hand, using a class, we end up with:

Obviously, the code in line 1 above is not an issue, since it fails at compile time. ui2, though, is actually equal to null following this initial declaration. Again, this is contrast to a struct, who ends up with default values for all of its members.

I, for one, think the use of a class here is a bit cleaner, as we can just check the whole object against null rather than checking some/all of the struct members against default values to determine if our object represents an unknown, or null, UselessItem.

Pretty cool!

Would love to hear comments on this approach – go ahead, tear me a new one, I can take it.

Using PHP and MySQL to Create a Simple Contact Form and Results Browser

By: Brian Dobberteen

By request, let’s build a simple Contact Form with a PHP/MySQL backend!

(Disclaimer: I don’t pretend to be an expert in PHP [nor .NET for that matter!], so please understand that the way I go about this might be sub-optimal. Whatever, sue me.)

Building the HTML Contact Form

This part is as straightforward as can be. We’re going to create a ‘Contact Form’ with a grand total of THREE fields – extending this model is left as an exercise for the reader (lol, always wanted to write that!)

For brevity, we’re going to use the HTML5 doctype and a table-based (gasp!) layout. Feel free to change it to whatever you want.

Here goes:

Which, in IE9 renders as:

I’ve highlighted line 10 above to bring attention to the ‘action’ attribute of our opening form element. Whatever the form’s action is set to is where, on submission, the form ‘posts’ its values to. To read more about HTTP POST, please visit google.

And that completes the form!

Creating a MySQL Table to Store Form Values

Again, as a Microsoft fanboy ©, I rarely spend much time with MySQL in any real capacity. You have been warned.

We are going to assume that you have a MySQL instance installed and available to you. And that you know how to login and arrive at the MySQL ‘command line.’

Once logged in, we’ll first need to create a new database to store our new table which in turn will store our contact form values:

Not surprisingly, this creates a new database with the name MyRadContactForm. The ALL CAPS is not required, but SQL is typically written in this fashion.

Next, we must let MySQL know what database we want to use:

Now our new DB is the active one, and we can create our table in it:

Quickly, ContactID is what we call a Primary Key – it is used to uniquely identify each record in the table.

It is an INT (Integer) type, meaning it can store whole numbers.

It is a NOT NULL column, meaning that it must contain a value for each row in the table.

And finally, it is an AUTO_INCREMENT column – this means that each time we add a new record to this table, MySQL will ensure that each ID is unique by essentially adding one to the highest existing ID at the time of a new insert.

VARCHAR(100) means that we can store a string (sequence of letters, numbers, etc) up to 100 characters in length.

DATETIME… well, that should be obvious.

Our new table should now be in place, though to quickly check, we can try:

Creating PHP Server-Side Code to Store New Values

Well, now we have something the client sees (the HTML form) and something buried deep within the bowels of a database to store values input by the client.

How, then, do we manage to bridge the gap between these two pieces?

In this case, we’ll use PHP.

We assume that you have a functioning PHP installation. Check out xampp for a relatively painless way to get up and running with PHP/MySQL/Apache on various platforms.

Right, without further delay:

This example is lacking in a number of areas, but we aren’t going to care about SQL Injection or error-checking at this point.

Brief rundown of the above code:

Lines 4-6: We are creating three variables to store the values of our incoming form. Note that each item matches the ‘name’ attributes of our form inputs.

Line 11: This is the equivalent of the USE MyRadContactForm command that we issued earlier to our MySQL server prior to creating our table.
Line 13: This is the beginning of an SQL INSERT statement. Not surprisingly, this command inserts new records into our table. In the first set of parentheses, we specify which table columns that we want to store our data in. The second set of parentheses represent the actual values to store in the table.

Lines 20-22: PHP makes life a bit easier for us here, as it will automatically detect our variable names and replace them with the values they contain. NB: The $sql string we’ve created is surrounded with aka double quotes. This is crucial to get this behavior. The variable names are themselves surrounded by aka single quotes, as this is standard SQL for indicating that you are working with string values (aka VARCHAR).

Line 23: We call the MySQL built-in function NOW() to store the current date/time in ContactDateCreated at the time our insert is performed. There are other ways of handling this (such as declaring a variable in PHP), but this is easy.

Line 26: mysql_query does the actual work of sending our INSERT statement to our DB via the $sql_connection we created earlier.

Remember, this is just a primer (and not much of one at that!). Writing code like this will likely draw ire from your peers and pink slips from your employers.

Creating an HTML Contact Form Submission Viewer

So, we’ve got our form, database, table, and server-side PHP script. If all is well, we should now be adding new records to the table with each form submission.

But what good does this data do anyone if it is tucked safely away in the bowels of our MySQL server?

Let’s make a quick-and-dirty PHP page to display the input values:

Line 26: Finally, we use echo one last time to close our <table> tag.

UPDATE

Line 12: This time, since we want to display data already in our DB, rather than insert new records, we issue a SELECT statement. The * (asterisk) tells SQL that we want every column for each row we get back. We store the data we receive in a variable named $result.

Line 14: Using PHP’s echo command, we begin the definition of our HTML table. PHP echoes its argument to the HTML page seen by the end user.

Line 17: The keyword while indicates to PHP that we want to start a loop, in which we will output the values stored in each row of our DB. When we reach the last row, the while statement is no longer true, and the loop exits.

Line 19: Again, we use echo to get our stuff out on to the HTML page. Here, we are building a table cell (<td>) that contains whatever is stored in the ContactName field for this record. Note that PHP uses a single . (dot) character to stitch strings together. This is often referred to as ‘string concatenation.’

By request, I’ve put together a zip file containing the PHP/HTML source seen above. I haven’t actually run it to verify its accuracy, so please keep that in mind.

ContactFormDemoSource

Using Nullable Types to Handle Possible NULL Values From Database

By: Brian Dobberteen

I’d like to describe a techinque that I’ve come up with to handle the ever-present issue of the easiest (best?) way to handle building an object from a database query that may or may not contain NULL values. I feel compelled to post this because I haven’t seen this approach detailed elsewhere online.

First, let’s create a simple class to demonstrate our needs:

Note the use of nullable value types on lines 5 and 7 above. For those not familiar with the concept of nullable types, have a look at: Using Nullable Types – MSDN.

In our class, we are anticipating that there may be NULL values stored for a Person’s Age and Last Modified Date.

Simple enough. But how to best build a Person object from a SqlDataReader? I’ve seen tons of different approaches, such as:

This approach certainly isn’t that bad, and seems to be a very common method for handling NULLs via nullable types.

But we’re not content with something that’s only ‘not bad,’ are we? Of course not.

Let’s try another way:

Check out lines 9 and 11 – we are using the ‘as’ operator rather than the clunky ternary, resulting in code that, IMHO, is more concise, clear, and therefore easier to read and maintain.

I’m surprised that I haven’t seen others doing this… I know I’m not the only one to have stumbled across this approach!

[smartads]

Getting Value of NEWSEQUENTIALID() on Insert

By: Brian Dobberteen

Recently, I was writing a stored procedure that, at one point, performs an insert into a table that has a GUID (uniqueidentifier) primary key. The default value for this column is set to NEWSEQUENTIALID().

Further along in the stored procedure, I needed the value of this newly-inserted GUID to use in another INSERT statement. Fortunately, T-SQL provides us with precisely what we need – the OUTPUT clause.

A quick demo:

The table DDL:

Example portion of sproc:

Thanks to the bit highlighted above on lines 7 and 15, we now have a reference to the newly inserted GUID and can use it as needed.

Additionally, the use of newsequentialid() here lessens the impact of using a GUID clustered index.

[smartads]

Check Existing Values with ASP.NET CustomValidator + jQuery $.ajax()

By: Brian Dobberteen

 

This was selected as an ASP.NET Article of the Day for June 18, 2010

‘SjAJ’ ASP.NET CustomValidator

SjAJ?! Sorry, I couldn’t resist. I had started with AJAX, but thinking now… hmmm, the method being described here is Synchronous jQuery And JSON.

Something tells me that SjAJ is not going to make it to buzzword status. Oh well, I tried.

We will try to quickly outline a method for using the ASP.NET CustomValidator control in conjunction with jQuery and the AJAX Control Toolkit.

Initially, I had tried to use other APIs to call my web services and/or page methods. Problem was, at least that I could tell, was that the asynchronous nature of these operations cause an issue inside the ClientValidationFunction specified in the CustomValidator control.  Eventually, I revisted the code in my earlier posts, and once again, jQuery came to the rescue! Details follow.

ASP.NET CustomValidator Control

For those not familiar with the CustomValidator control, let me give a brief explanation.

The bit we’re most concerned with here is the ClientValidationFunction. This will fire during client-side page validation, receiving two arguments.

source contains the <span> element rendered for the validation control. Since we are going to use the ASP.NET Ajax Control Toolkit’s ValidatorCalloutExtender we will ignore the argument source.

arguments is much more interesting here, as it contains two properties: IsValid and Value

As you might expect, Value contains the value contained in the ControlToValidate that we’ve specified in our validator control. IsValid is what we’ll use to indicate whether or not the value we’re checking exists or not.

Here’s a simple, albeit very contrived, example of how the ClientValidationFunction works:

Again, very contrived, and quite silly, actually – we would be much better off using a RegularExpressionValidator for this particular case… but I digress.

Briefly, this CustomValidator uses client-side code to test the value entered in a text box (ZipCodeTextBox in this case) against the regex /^\d{5}(-\d{4})?$/ which will allow values such as 95060 or 95060-1234 but not 950-0000 nor 95064-0.

Checking for An Existing Value

As mentioned earlier, I was having trouble getting things to work using a few asynchronous techniques. It seemed that if arguments.IsValid is set inside a callback function, it doesn’t register properly, and the control always appears valid.

Luckily, jQuery’s $.ajax() function has a handy option: async, which when set to false does what we need – it waits for the response from the server before continuing to our success function.  Without further ado…

In line 6, we specify the name of our PageMethod contained inside our Default.aspx page. This is only one of many ways to accomplish this, of course. See http://brian.dobberteen.com/code/responding-to-jquery-ajax-request-with-php/ for my treatment of using PHP as a ‘web service’ of sorts.

Line 9 is the all-important async: false that seems to provide the needed magic to get this all working.

Finally, on line 14, we set our CustomValidator’s IsValid property to true only if the value we are checking for did not exist.

To make things easy, let’s use the ASP.NET membership system to check for an existing username. This has the benefit of providing the method for both server and client side validation. Here goes:

The logic here is very simple. On line 13, we use the ASP.NET Membership system to check for an existing username. This logic also serves us well for our OnServerValidate event handler, starting on line 16.

The .aspx page:

And finally, a screenshot of what the validator looks like when I enter ‘bdobberteen’ for the username – an account I created minutes earlier:

I am not sure if this degrades gracefully in the face of a non-javascript browser. Namely, the ValidatorCalloutExtender won’t display. A possible solution would be to add a ValidationSummary control, initially set its visibility to false, and, upon postback, if the server-side validation fails (!Page.IsValid), set that same ValidationSummary to visible, allowing downstream browsers to view the various error message(s).

Hope this helps someone!

– brian –

Sample Code for Article

[smartads]

Calling a Web Service with ASP.NET AJAX Client Script

By: Brian Dobberteen

Wow! It’s been waaaaay too long since my last installment – been busy with latest programming contract, not that you care.

Since beating the proverbial dead horse is my specialty, this brief post is going to cover making a call to the Yahoo! Maps API via an ASP.NET web service (.asmx) which we then call from client script with the aid of the Microsoft ASP.NET AJAX library(ies).

In order to access the necessary JavaScript script libraries, we must first include the customary ScriptManager object in our page:

As you may have already guessed, this declaration creates a ScriptManager for our page and includes a reference to the web service (which we will create momentarily) used for fetching the City and State upon user input of a US Zip Code.

Without further ado, here’s the complete web service code:

After our ScriptManager registers this service, we now have access to proxy(ies) that can be called from the client side. To do so, we can create a wrapper to the service call:

It’s not as simple as just including the above call – we need to provide the methods named in the second and third parameters (the two lines highlighted in green above). Which would look something like:

Though we aren’t making any use of the context and methodName parameters being passed to our callback functions, I’ll just point out that the context is whatever was set when calling the webservice – in this case, the date and time were used. The context can be very useful to track asynchronous calls in a stateless environment.

The methodName, cleverly enough, returns the name of the web service method that we’ve called – in this case, methodName contains GetCityStateByZip which, as we all know, is the name of the only method exposed by our YahooMapsZipCodeLookup.ZipCodeService.

There is another option to writing explicit callback methods, and one that I prefer (probably due to my experience with jQuery). If we don’t want to write explicit methods, we can use anonymous functions as parameters in the call to our web service:

The two highlighted lines indicate where we’ve replace the names of functions with anonymous functions. NB: the line numbers in the above snippet are supposed to correspond with the actual aspx page.

To hook everything up on our actual page, we need to add an event handler to, in this case, a textbox:

I also snuck in the CityStateResult div that is the target of our DOM manipulation upon receipt of a response from the web service. I also added a do-nothing submit button to demonstrate that a button press will fire the textbox’s onchange event.

The entire aspx page:

In a nutshell, when the user triggers the onchange event of our textbox, the event is handled by our wrapper function getCityStateByZip(zip), to which we pass this.value, which contains the changed value of the textbox. This value is then passed to the web service, which returns a CityState object – ASP.NET AJAX handles all of the serialization and other such details for us in a nearly transparent way. We can refer to the CityState object returned by our web service as if the object was a normal .NET object, i.e. result.City or result.State.

And I think that covers it! No more posts on zip code lookups, I promise!

Before I forget, here is the source to the samples seen above: Calling a Web Service with ASP.NET AJAX Client Script Source Code
[smartads]

Using LINQ to XML instead of XmlReader

By: Brian Dobberteen

Previously, I mentioned that I wasn’t sure if using an XmlReader was the best way to fetch the City and State values from the XML response from the Yahoo Maps API:

We were using the above to basically read the XML response line-by-line, checking for the two elements we are interested in, and storing their values in our simple CityState object ‘ret.’ Again, the XML we are processing looks like:

Though our XmlReader method works fine, it seemed a bit clunky to me, so I set out to check out LINQ to XML to see if we can clean the code up a little bit.

LINQ is still somewhat of a new concept for me, as I haven’t had much chance to work with it given the nature of much of the work I do. Its potential usefulness, however, seems pretty clear to me, and definitely look forward to working with it as much as possible – at least until the next latest, greatest thing comes along! I’ve always felt the LINQ syntax to be a bit unusual, and – unlike I’d first hoped – not that close to SQL. Of course, LINQ isn’t SQL, so I suppose I shouldn’t be surprised that LINQ doesn’t look more like:

Of course, this is an incredibly trivial example, and the only difference between a similar LINQ query is the arrangement of the three components of the query (SELECT, FROM, and WHERE). But in reading that I’ve done, LINQ can get pretty cryptic at times… though I used to feel the same way about complex SQL, which now is very easy for me to comprehend.

At any rate, we’ll be dropping our use of the XmlReader class and instead opt for a LINQ-to-XML XDocument object. We need to change our Imports declaration slightly, removing System.Xml and replacing it with System.Xml.Linq. Much the same as we did with the XmlReader, we use XDocument’s static function Load to grab our XML from the Yahoo Maps API (more about accessing the Yahoo Maps API).

Just like our earlier examples, this is contained within a PageMethod that accepts ‘zip’ as its only parameter and returns a simple CityState object. After the XDocument is loaded, we can now perform a LINQ query on it, allowing for us to easily specify what elements (City and State, in this case) we’d like the value of.

Because we’re interested in the City and State elements, which are descendants of the root ‘ResultSet’, we’re using the cleverly named property Descendants of our XDocument object. Descendants is an IEnumerable collection of XElement objects which is what makes our LINQ operations possible. As you can see, the LINQ query first specifies where to look for something (akin to the FROM clause in an SQL SELECT statement), then we set the criteria to be sure we find the ‘City’ element. I discovered that el.Name won’t work for us, as the Name property of an XElement object is an XName object. The LocalName property of an XElement refers to the elements unqualified name, without any namespace info included. The LINQ statement next ‘Selects’ the element matching our criteria. Finally, since we are only expecting a single city to exist in our XML response, we wrap the whole LINQ query in parentheses and use .Single to return the one-and-only value we’re after. .Single will throw an exception if more than one element was found by our query. To get the value of the State element, just replace Where el.Name.LocalName = “City” to Where el.Name.LocalName = “State”.

I’ve experimented with polling both the City and State elements in one pass, i.e.

But this just seemse to necessitate another query to be sure that we’re getting the right values from our new, albeit smaller, collection of XElements. So, for now, we’ll just perform two seperate LINQ operations… please let me know if there are better ways of going about this (and I’m sure that there are!)

Finally, let’s take a quick look at using a Lambda expression to streamline this whole thing a bit more. The following gives us the same result as the first LINQ query above:

The call to .Where from our xdoc.Descendants is a call to an ‘extension method.’ These extension methods are central to the functionality of LINQ. In this case, we’re passing an ‘anonymous function’ to the Where extension method that we will be using to apply our criteria. The anonymous function is passed el which is an XElement object. And again, we want an element with a LocalName of City, so the body of our anonymous function does just this, compares the LocalName to ‘City’, and if it matches, the expression continues by fetching the Single city element’s Value.

Clearly, we’ve only just scratched the surface of LINQ and LINQ to XML, but we gotta start somewhere, no?
[smartads]