Archive for October, 2011

CSS Menus and Unordered Lists

 

Why use CSS Menus?

The short answer … because they are awesome. If you do much web programming, especially if you are more of a programmer than a designer, you have probably had the opportunity to sit in front of the computer and come up with some type of menu schema that will look nice and work properly across all browsers. This can often be a very frustrating experience, but help has arrived … I give you CSS and an unordered list. This concept is certainly not new, but it is powerful and worth reviewing.

The truth is that you can find many different controls that will produce a menu for you. Among them are:

There is even the Microsoft provided menu control, which you can find here:

Microsoft Menu Control

Now, it is not my intention to bash any of these controls. I actually think that they are all very beautiful and quite impressive. Here at TLS, I have used several Telerik controls with excellent results. Nevertheless, building a great looking menu is not anywhere near as difficult as it used to be and it can now be done using nothing but an unordered list and some CSS tags. If you want to spruce your menu up a little bit more, you can also include an image or two but that is not necessary.

Making a menu like this has several advantages.

  • Cross Browser Compatibility – Any browser that supports CSS (which by now should be all of them) will render your menu correctly. If you feel compelled to do so, you could add in some CSS for older IE versions, but I say …. If you are still using IE5 or IE6, that is your problem, not mine.
  • Code Simplicity – By this I mean that the amount of code on the page necessary to actually render the menu using an unordered list is much smaller than any other kind of menu you could use.
  • Graceful Failability – In other words, if for whatever reason, your styles are not working or javascript is turned off or the user has some ancient browser that doesn’t support modern CSS or Javascript, then the menu will still render as a normal Unordered List, which works perfectly fine as a menu, even if it is not the flashy affair that you envisioned.
  • Mobile Device Scalability – Lets face it, gone are the days in which you could plan on a user having either an IE or a Mozilla browser. Now a user could be on any number of browsers as well as an iPhone, an iPad, an Android Phone (all 2,394 models each with a different resolution), a Kindle Fire, a Windows Phone (I hope) and even an old non-smart phone with internet access. A menu done this way is far more likely to work correctly and look good on the lot of them.
 

Creating a CSS Menu

So … lets see some examples. First of all, we need to create our menu. This is very simple, just create an unordered list of some values. Mine will look like this:

<ul>
    <li><a href="#">Michael Westen</a></li>
    <li><a href="#">Sam Axe</a></li>
    <li><a href="#">Fiona Glenanne</a></li>
    <li><a href="#">Madeline Westen</a></li>
    <li><a href="#">Jesse Porter</a></li>
</ul>

When actually rendered on a page, it will look like so (Bullets and all):

 

As I mentioned, while not pretty, this is certainly serviceable as a menu if the CSS wasn’t working for some reason. By contrast, go look at a website using a complex menu control and then disable javascript and css … the result will be ugly and generally not even recognizable as a menu. But to make ours into a pretty menu, we are first going to add some styles to our unordered list which can then be used to make the list look more like a classic webpage menu. The first thing that we have to do, is set up a style identifying this list as a menu so that it will behave differently than other unordered lists that we might have on our webpage. The first thing that we need to do is to encase the unordered list in a containing tag. I will use a “div” tag. This gives us a couple of advantages, such as making sure that it extends to 100% of the element that it is inside of and allowing us to set a background color for the menu as a whole. Then we will give the container a class name … I’ll call it CssMenu. Like so:

<ul id="Menu">
    <li><a href="#">Michael Westen</a></li>
    <li><a href="#">Sam Axe</a></li>
    <li><a href="#">Fiona Glenanne</a></li>
    <li><a href="#">Madeline Westen</a></li>
    <li><a href="#">Jesse Porter</a></li>
</ul>
 

Now, this will not do anything to make the menu display different because we haven’t defined a CSS Style for “CssMenu” yet. So the next step is to style the unordered list so that it is starting to appear the way we want it to appear. To begin with, we will set the margins and paddings to 0 and then also set the height. Most importantly, we will set the “list-style-type” attribute to “None” so that it does not actually look like a list. The style tag would look like this:

        #Menu
        {
            margin: 0px;
            padding: 0px;
            list-style-type: none;
            height: 25px;
        }
 

Doing that gives us the following result:

If you wanted a vertical menu, then what we have right here would work pretty well, but I want our menu to be horizontal, so I will add additional style tags to make the “li” items in the list line up next to one another as opposed to on top of one another. The style for that looks like this:

        #Menu li
        {
            float: left;
        }
 

At this point, our list items are lining up one after the other like this:

 

There is nothing earth shattering here, I know, but I’m trying to go step by step. Believe it or not, we are almost there. From here, we just need to style the links on each list items so that they look pretty. Anyone with CSS experience should be able to do this with relative ease. In my case, I added things like a border, a background color, font family, font size etc. By adding padding also, you can add some space between the end of the word and the end of the link. By adding a right margin, you can separate each link into its own space. Also, by setting the display to “block” you can set the height or the width and have that value stick. Since block elements take up 100% of whatever they are inside of unless told otherwise, this means that the link will take the entire width of the list item. By adding in the following styles:

        #Menu a
        {
            border: solid 1px #000066;
            border-bottom: solid 1px #99000;
            background-color: #EDECD1;
            padding-right: 20px;
            padding-left: 20px;
            margin-right: 4px;
            display: block;
            line-height: 25px;
            font-family: Verdana, Tahoma, Arial;
            font-size: 10pt;
            color: #333333;
            text-decoration: none;
        }
 

My unordered list now looks like this:

 

To add some pizzazz, now, I am also going to add a style to the link so that it changes color when the mouse pointer hovers over it. Once again, this is very simple css code …. like this:

        #Menu a:hover
        {
            background-color: #990000;
            color: #ffffff;   
            border-bottom: solid 1px #990000;
        }
 

Now when the mouse hovers over a menu item, it will change color.

 

At this point, it is quite easy to put a content div tag right below the menu and make the colors match so that the menu appears to work in conjunction with the are below it … like this:

 

Conclusion

From here, the possibilities are endless. You could do all kinds of things using a few more simple css concepts like adding images or wrapping the menu in other tags. I’m not going to go into that, but I will say that in just a few lines of code here (with no images or javascript) we have made a nice little menu. If you are interested in more ideas as to how you could use these concepts, click here … but prepare to have your mind blown when you see all that can be accomplished just using CSS.

Tags: , ,


Denali New T-SQL features.

SQL Server Denali comes with a number of new features that will help to make our life easier or more complicated depending on your point of view. However, I think it will make our life a lot easier.

A few of the new features that I will talk about today are the Try/Catch block, execute a store procedure With Result Sets and the IIF function.

TRY/CATCH

It was originally introduced in SQL 2005. However it lacked flexibility and we were not able to re-throw the error like we do it in C# or VB.net. However, now we can using “THROW”. Here is an example of how it works:

DECLARE @REG VARCHAR(50);
DECLARE @MORE INT;

	BEGIN TRY
		SELECT @REG= RegionDescription FROM DBO.Region R
		INNER JOIN Territories T ON T.RegionID = R.RegionID	 

		SELECT @MORE= @REG

	END TRY

	BEGIN CATCH
		PRINT 'You need to cast the varchar before assign it to a int';
		THROW;

	END CATCH

This is just a simple example of how it works, however there are many different ways to format the message so you can display or return the right message for your code or UI. You can find additional information at Microsoft

WITH RESULT SETS

Another new feature that was called to my attention is the execution of stored procedures “WITH RESULT SETS”. With this new feature you won’t need the high cost efficient functions. Something else that is nice with this feature is that you can rename the columns returned by the stored procedure. Also if you were using a temp table in order to see the data you will not need it any more with the new “WITH RESULT SETS.” Here is an example:

-- Create the store procedure in the Northwind database
CREATE PROCEDURE [dbo].[spTerritories] (@Region int)
as
BEGIN
	SELECT TerritoryID, TerritoryDescription, RegionID FROM Territories
	WHERE RegionID = @Region
END
GO

EXEC spTerritories @Region = 1
WITH RESULT SETS
(
	(
		PlaceID varchar(100), 
		PlaceDescription text,
		Region float
	) 
) 	

Now, regarding cost, the new approach is a lot more efficient than the previous versions. In fact if you run something like this:

DECLARE @TestTable TABLE (TerritoryID varchar(MAX), TerritoryDescription text,
    RegionID float )

INSERT INTO @TestTable 
EXEC spTerritories @Region = 1

SELECT * FROM @TestTable

It will cost you around 5 times more than just executing the store procedure With Result Sets. Take a look at the image below.

The blue square is the execution of the store procedure with the result sets that was 14% of the batch. The red squares make a total of 14 + 57 + 14 = 85% of the whole batch, so there is no doubt that using WITH RESULT SETS is more efficient that the old way.

IIF Function

Another new feature in SQL Denali are the built in functions. I will not write about all of them but you can find great examples of them at Pinal Dave’s blog. You can find a reference to his blog at the end of this post.

The one that caught my attention was the new IIF function. It basically replaces the Case statement for simple scenarios. Obviously if you have a long nested IIF function the CASE may be your best option. However the new IIF improves the code a lot.

Here are a couple of examples using tables from the Northwind database.

SELECT IIF(RegionID >= 2, 'Good Region', 'The best') as RegionScore, 
		TerritoryID, TerritoryDescription, RegionID 
FROM  dbo.Territories 

Another example would be something like this. In this case I’m nesting the IIF function.

SELECT IIF(RegionID >=2,
		IIF(
			(SELECT e.FirstName
			FROM  Employees  e
			LEFT JOIN EmployeeTerritories et 
                            on e.EmployeeID = et.EmployeeID
			WHERE et.TerritoryID =ttr.TerritoryID) is null, 'No Data',
			(
			        SELECT  e.FirstName 
				FROM Employees  e
				LEFT JOIN EmployeeTerritories et 
                                    on e.EmployeeID = et.EmployeeID
				WHERE et.TerritoryID =ttr.TerritoryID
		       )
			),'No Employee Assigned') as RegionScore, 
		TerritoryID, TerritoryDescription, RegionID 
FROM  dbo.Territories  ttr

Some of the other built-in functions are specified on Pinal’s website. You can take a look at them Clicking Here. Microsoft is another reference for any information I wrote on this post.

Tags: , , , , , , , ,


C# Regex Multiple ReplacementsC# Regex reemplazos múltiples

As I was testing the XML request for web service, I would periodically get a response back: [400]: Error parsing xml. After some troubleshooting, I discovered that the error was caused by a few of the Predefined XML Entities included in the actual data. The most common issue was the ampersand “&” being embedded in the Address and Account data.

I needed a way to replace those xml entity characters, but didn’t want to replace each one separately, so I thought, great I’ll just use a Regular Expression.

The Regex.Replace method has 4 overloads, but the basic syntax in .NET is Regex.Replace(string input, string pattern, string replacement). That didn’t work for me because I needed the replacement value to vary, based on the pattern.

For example, this simple replacement…Regex.Replace(input, "&", "&")…wasn’t what I wanted as that would mean repeating it for the other replacements. Now the pattern can include multiple items, for example Regex.Replace(input, "&|”|<|>|’", replacement), but the replacement would be the same for each one, so I needed to use the overload that accepts a MatchEvaluator delegate that is called each time a regular expression match is found during a Replace operation.

Regex.Replace(string input, string pattern, MatchEvaluator evaluator)

Given that my search and replace values were simple, I decided to use a generic Dictionary and store the entity and its replacement as name value pairs.

var xmlEntityReplacements = new Dictionary<string, string> {
    { "&", "&amp;" },
    { "'", "&apos;" },
    { "<", "&lt;" },
    { ">", "&gt;" },
    { """, "&quot;" }
};

Great, now I can revised the Regex like this:

Regex.Replace(input, "&|"|<|>|'", delegate(Match m) { 
    return xmlEntityReplacements[m.Value]; 
})

Not bad, but I am duplicating the items in the pattern (they are already in the dictionary) and why use the anonymous method approach when I’m using .NET 3.5 and have access to LINQ? So a little refactoring was in order.

Ok, but I need to get the dictionary Keys and return then as a pipe-delimited string. There is a CopyTo() method on the collection to convert the Keys or Values to an array, and from the array I can get the string I needed. That’s good, but I don’t want to have to declared and array to house the values and then use CopyTo, that’s an extra step. Hmmm, another great use for LINQ and its extension methods:

Regex.Replace(source, string.Join("|", xmlEntityReplacements.Keys
    .Select(k => k.ToString()).ToArray()), m => xmlEntityReplacements[m.Value])

Here’s the code converted to a method.

/// <summary>
/// Replaces the 5 predefined entities in XML with the appropriate
/// name/escape character.
/// </summary>
/// <param name="source">string to search</param>
/// <returns>source string with replaced value or original string</returns>
public static string ReplaceXmlEntity(string source)
{
      if(string.IsNullOrEmpty(source)) return source;

      // The XML specification defines five "predefined entities" representing
      // special characters, and requires that all XML processors honor them. 
      var xmlEntityReplacements = new Dictionary<string, string> { 
            { "&", "&amp;" },
            { "'", "&apos;" },
            { "<", "&lt;" },
            { ">", "&gt;" },
            { """, "&quot;" }
      };

      // Create an array and populate from the dictionary keys, then
      // convert the array to a pipe-delimited string to serve as the 
      // regex search values and replace
      return Regex.Replace(source, string.Join("|", xmlEntityReplacements.Keys
          .Select(k => k.ToString()).ToArray()), 
              m => xmlEntityReplacements[m.Value]);
}

Note, for more complex patterns/searches, the dictionary approach won’t work as the MatchEvaluator would expect to find the match as a Key in the Dictionary and it wouldn’t be there. For example, let’s say your match pattern was “T.p” (T followed by any character then a lowercase p), the replacement value was “Top” and the input string was “Just Tap and Tip.” The dictionary would have a Key of “T.p” and a Value of “Top” Now, the pattern “T.p” is going to match both “Tap” and “Tip” but those words aren’t Keys in the dictionary and you’d get the error “The given key was not present in the dictionary.”

I’ll leave that as an exercise for you to do if you so choose.

As I was testing the XML request for a web service I would periodically get a response back: [400]: Error parsing xml.   After some troubleshooting, I discovered that the error was caused by a few of the Predefined XML Entities included in the actual data.  The most common issue was the ampersand “&” being embedded in the Address and Account data.

I needed a way to replace those xml entity characters, but didn’t want to replace each one separately, so I thought, great I’ll just use a Regular Expression.

The
Regex.Replace method has 4 overloads, but the basic syntax in .NET is Regex.Replace(string input, string pattern, string replacement).  That didn’t work for me because I needed the replacement value to vary, based on the pattern.

For example, this simple replacement…
Regex.Replace(input, “&”, “&amp;”)…wasn’t what I wanted as that would mean repeating it for the other replacements.  Now the pattern can include multiple items, for example Regex.Replace(input, “&|”|<|>|'”, replacement), but the replacement would be the same for each one, so I needed to use the overload that accepts a MatchEvaluator delegate that is called each time a regular expression match is found during a Replace operation.

Regex.Replace(string input, string pattern, MatchEvaluator evaluator)

Given that my search and replace values were simple, I decided to use a generic Dictionary and store the entity and its replacement as name value pairs.

var xmlEntityReplacements = new Dictionary<string, string> {
    { “&”, “&amp;” },
    { “‘”, “&apos;” },
    { “<“, “&lt;” },
    { “>”, “&gt;” },
    { “””, “&quot;” }
};

Great, now I can revised the Regex like this:

Regex.Replace(input, “&|”|<|>|'”, delegate(Match m) { return xmlEntityReplacements[m.Value]; })

Not bad, but I am duplicating the items in the pattern (they are already in the dictionary) and why use a the anonymous method approach when I’m using .NET 3.5 and have access to LINQ?  So a little refactoring was in order.

Ok, but I need to get the dictionary Keys and return then as a pipe-delimited string.  There is a
CopyTo() method on the collection to convert the Keys or Values to an array, and from the array I can get the string I needed.  That’s good, but I don’t want to have to declared and array to house the values and then use CopyTo, that’s an extra step.  Hmmm, another great use for LINQ and its extension methods:
Regex.Replace(source, string.Join(“|”, xmlEntityReplacements.Keys
.Select(k => k.ToString()).ToArray()), m => xmlEntityReplacements[m.Value])

Here’s the code converted to a method.

///
<summary>
/// Replaces the 5 predefined entities in XML with the appropriate name/escape character.
///
</summary>
///
<param name=”source”>string to search</param>
///
<returns>source string with replaced value or original string</returns>
public
static
string ReplaceXmlEntity(string source)
{
if(string.IsNullOrEmpty(source)) return source;

// The XML specification defines five “predefined entities” representing special
    // characters, and requires that all XML processors honor them.
    var xmlEntityReplacements = new Dictionary<string, string> {
    { “&”, “&amp;” },
        { “‘”, “&apos;” },
        { “<“, “&lt;” },
        { “>”, “&gt;” },
        { “””, “&quot;” }
    };

    // Create an array and populate from the dictionary keys, then convert the array
    // to a pipe-delimited string to serve as the regex search values and replace
    return Regex.Replace(source, string.Join(“|”, xmlEntityReplacements.Keys
.Select(k => k.ToString()).ToArray()), m => xmlEntityReplacements[m.Value]);
}

Note
, for more complex patterns/searches, the dictionary approach won’t work as the MatchEvaluator would expect to find the match as a Key in the Dictionary and it wouldn’t be there.  For example, let’s say your match pattern was
“T.p” (T
followed by any character then a lowercase
p), the replacement value was “Top” and the input string was “Just Tap and Tip.” The dictionary would have a Key of “T.p” and a Value of “Top”  Now, the pattern “T.p” is going to match both “Tap” and “Tip” but those words aren’t Keys in the dictionary and you’d get the error “The given key was not present in the dictionary.”

I’ll leave that as an exercise for you to do if you so choose.

Tags: , , , ,