Back to happy

I’ve always wanted to make a career in computers. It’s been 32 years since I got my first computer, a TI-99/4A, and taught myself BASIC and Extended BASIC.

I’ve done a number of other jobs between then and my web programming gig. This marks the end of my sixth season of going back to nature. Back to tending to lawns for the fine folks of my city. I’ve got to say, I’ve never been happier.

I can’t imagine going back to sitting behind this keyboard and staring at this screen all day for money. I may still work a few programming jobs during the off-season but I do believe that I’d actually enjoy delivering pizzas more.

The possibility of leaving .NET behind

I’ve been rather happy with ASP.NET and especially with ASP.NET MVC. I’ve got to say that C# and especially Linq is just a plain pleasure to use. I have no issues with the programming side. Ever since I’ve gone from running my own Windows Server to using shared hosting it’s been one headache after another. Getting permissions set on a folder is like pulling teeth. Getting the host to set trust levels is more teeth pulling. Have an issue with a web app? I’m running out of teeth!

Comparing PHP to C# is sort of laughable. I really don’t like the syntax. I’ve actually gone so far as to avoid PHP by trying Ruby on Rails because it was suggested because the MVC architecture is supposedly similar to ASP.NET MVC. I’ve got to say that Ruby on Rails is just one hot mess. I can’t stand using any of the editors and using the console to generate a simple controller takes so long that I lose interest by the time it’s ready. The “Ruby way” is just nuts, too. The ability or desirability of putting the condition at the end makes absolutely zero sense. What is the difference between “if this occurs, do this” and “do this if this occurs”? Asking for help about Ruby on Rails online is like shouting in the desert. All the forums are dead. No replies. It was once suggested that I get on IRC for Ruby on Rails help. Really? IRC? Maybe I should just hook up a CB Radio while I’m at it. Better brush up on my ten-code.

I currently pay for shared hosting on an Apache server through site5.com and I’ve had maybe 2 issues totaling half an hour, if that. My shared Windows server constantly gives up and shuts down AppPools refusing to spool them up in a timely fashion. Getting crawled by Google and Bing at the same time just brings the server to it’s knees and I get emailed error reports at least weekly.

Basically, I’ve traded my “WHAT IN BLAZES” moments in programming for “WHAT IN BLAZES” moments in hosting. I can control my confusing moments so I’m strongly considering getting back into PHP and leaving the issues behind. I’ve been fighting it because of all the time and money invested in learning .NET and purchasing Visual Studio but I think in the long run to cut the Windows Server service and go back to Apache will make more sense.

I’ve got to give Microsoft a whole lot of kudos for Visual Studio. It really is that good. They also deserve applause for LINQ, it’s wonderful. In the end though, if I can’t keep a site rolling properly, and I can’t easily add a site to the block list (.htaccess makes this so very simple) then I’m just going to say goodbye and take the other path and relax.

Dynamic Javascript using ASP.NET MVC

  1. Create a new MVC applictaion
  2. Open /Views/Shared/Site.Master
    1. <script src=”/Scripts/script.js” type=”text/javascript”></script>
    2. This doesn’t point to anything yet
  3. Open Global.asax
    1. Add a MapRoute
      1. routes.MapRoute(“Javascript”, “Scripts/{scriptFile}.js”, new { controller = “Scripts”, action = “Index”, scriptFile = “script” });
      2. Now /Scripts/script.js points to Script/Index
  4. Add a view for CssController/Index
    1. <%= Url.Content(“~/Content/test.jpg”) %>
  5. Change contenttype in page directive of Views/Scripts/Index.aspx to “text/javascript”
  6. That should do it.

Adding strongly typed objects to javascript is now simple to achieve and instead of adding javascript to the <head> in your master page you can just have a dynamically generated and cached .js file.

You may download a sample MVC2 project here.

Dynamic CSS using ASP.NET MVC

I’ve been considering the usefulness of adding a CSS management system to my CMS that I’ve been working on. Here are the steps I’ve taken to implement it.

  1. Create a new MVC applictaion
  2. Open /Views/Shared/Site.Master
    1. <link href=”/Css/Site.css” rel=”stylesheet” type=”text/css” />
    2. This doesn’t point to anything yet
  3. Open Global.asax
    1. Add a MapRoute
      1. routes.MapRoute(“Css”, “Css/{cssFile}.css”, new { controller = “Css”, action = “Index”, cssFile = “Site” });
      2. Now /Css/Site.css points to Css/Index
  4. Add a class Css.cs to Models
    1. Add public string Body { get; set; }
    2. Add public string Width { get; set; }
    3. Add public string Background { get; set; }
  5. Add definitions as desired
  6. Add a view for CssController/Index
    1. Make it strongly typed with CSScontrol.Models.Css as the model
  7. Change contenttype in page directive of Views/Css/Index.aspx to “text/css”
  8. That should do it.

I’m not sure that I’m convinced of the usefulness of this idea but it’s possible and easy to implement in your ASP.NET MVC project. The possibility of using variables in a CSS file is intriguing.

You may download a sample of the MVC2 project here.MVC3 project here. Let me know if this is a good idea, a horrible idea or just a bit interesting.

Edit – I’ve added a Response.Filter to this to remove extra spaces, tabs, carriage returns/new lines, final semicolons and comments. It brought the 4.96kb file down to 2.74kb. It can be enabled/disbled in Web.config using appSettings key CompressCSS (bool)

Adding links to all pages on a site using CSS

OK, I named this post that so that perhaps google will pick it up and those new to CSS will find this post.

There is a really good reason that there are no tutorials on the internet concerning how to add content (a site menu is the most common request) to all the pages on your web site using CSS. That’s because CSS doesn’t control content. It controls styling and nothing more. You don’t use styling to add content.

Why not look into some sort of server side includes. PHP includes will handle the situation. ASP.old can handle it but don’t use it unless you have no other choice (and you do). If you’re really fancy and modern and handsome and awesome you can just use ASP.NET MasterPages and/or User Controls. 🙂

To wrap it up, CSS doesn’t do that. Stop asking about it! Thank you.

Finding the current season using C#

Recently someone challenged me to write a server-side method for finding the current season and changing a style sheet accordingly.

The first step is deciding how to differentiate the seasons. I figured to use the day of the year so that astronomically Spring begins on March 21st, the 80th day of the year. Summer begins on the 172nd day, Autumn, the 266th and Winter the 355th. Of course, on a leap year add one day to each, 81, 173, 267 and 356.

Now to find the day of the year use the DayOfYear property. Also, use the IsLeapYear property to take a day away on leap year if the current day is after February 28th (the 59th day of the year). This is easily done by converting the bool IsLeapYear to an Int32 giving a 0 during non-leap years and 1 during leap year.
int doy = DateTime.Now.DayOfYear - Convert.ToInt32((DateTime.IsLeapYear(DateTime.Now.Year)) && DateTime.Now.DayOfYear > 59);

Then find the current season using a few nested ternary operators (I like ternary operators)
string currentSeason = String.Format("{0}.css",((doy < 80 || doy >= 355) ? "winter" : ((doy >= 80 && doy < 172) ? "spring" : ((doy >= 172 && doy < 266) ? "summer" : "fall"))));

I use this in the head of my MasterPage:
<link rel="Stylesheet" runat="server" id="seasonSheet" type="text/css" />

So all I have to do to add the correct style sheet for the current season is this:
seasonSheet.Attributes.Add("href",currentSeason);

Now a stylesheet named spring.css, summer.css, fall.css or winter.css will be added to your rendered MasterPage.

I hope you’ve found this helpful.

SCOPE_IDENTITY() with LINQ

While reading about a recent question concerning @@Identity and the reasons to use SCOPE_IDENTITY() instead I experimented with LINQ to get the SCOPE_IDENTITY() results.

 using (var dbc = new siteDataContext())
    {
        dbc.Log = Console.Out;
        repertoire newSkill = new repertoire
            {
                skill = "a new item"
            };
        dbc.repertoires.InsertOnSubmit(newSkill);
        dbc.SubmitChanges();
        Console.Write(newSkill.id.ToString());
    }

It seems that calling the id column of the inserted object gives you the SCOPE_IDENTITY(). Here is the SQL Log:

INSERT INTO [dbo].[repertoire]([skill])
VALUES (@p0)
SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]
-- @p0: Input NVarChar (Size = 10; Prec = 0; Scale = 0) [a new item]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

Adding AJAX to an existing project that includes Routing

I was working on a project and just on a whim decided to try out some of .NET’s AJAX controls. I chose a random page, added a ScriptManager, tossed in a TextBox and a CalendarExtender.

F5. Page shows up. Javascript error:

Line: 121
Char: 1
Error: 'Sys' is undefined
Code: 0
Url: http://localhost:49329/admin.aspx

Hmm.

Try a new project. Add a ScriptManager, tossed in a TextBox and a CalendarExtender. Works fine. Huh?

I go through the Web.Config files of the two. Nothings changed except the version number on everything:

non working: Version=3.5.0.0
working: Version=1.0.61025.0

Ah ha! That must be it. I reset the working project as a 3.5 app and run it. I was so sure it was going to fail. Nope. Worked fine.

Must be something else. *grumble*

I start taking pieces out of my existing app and when I came to the Global.asax I took out the RouteTables and AJAX comes to life! FINALLY!

Here is what I had:

Global.asax

		protected void Application_Start(object sender, EventArgs e)
		{
			// Code that runs on application startup
			RegisterRoutes(RouteTable.Routes);
		}
		private static void RegisterRoutes(ICollection<RouteBase> Routes)
		{
			RouteTable.Routes.Add(
				new Route("{Parameter}/{pageID}", new RouteHandler()));
			RouteTable.Routes.Add(
				new Route("{Parameter}", new RouteHandler()));
		}

With my routing handler file showing this little gem:

RouteHandler.cs

				string virtualPath = string.Format("~/{0}.aspx", pageName);
				return (Page)BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(Page));

So basically it was swiping the file extensions from my httpHandlers and replacing them with .aspx meaning they were not found.

Web.Config

		<httpHandlers>
			<remove verb="*" path="*.asmx"/>
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</httpHandlers>

To handle the situation I added the following to Global.asax:

Global.asax

		protected void Application_Start(object sender, EventArgs e)
		{
			// Code that runs on application startup
			RegisterRoutes(RouteTable.Routes);
		}
		private static void RegisterRoutes(ICollection<RouteBase> Routes)
		{
			RouteTable.Routes.Add(new System.Web.Routing.Route("{resource}.axd/{*pathInfo}",
					   new System.Web.Routing.StopRoutingHandler()));
			RouteTable.Routes.Add(new System.Web.Routing.Route("{service}.asmx/{*path}",
					   new System.Web.Routing.StopRoutingHandler()));
			RouteTable.Routes.Add(
				new Route("{Parameter}/{pageID}", new RouteHandler()));
			RouteTable.Routes.Add(
				new Route("{Parameter}", new RouteHandler()));
		}

I hope this helps. 🙂

Working on Bible Verse Tags for ASP.NET (C#)

To do:

  • build Regex to detect bible verses in tags
  • put in named back-references
  • find a way to choose different tables with LINQ
  • make it work for an entire chapter
  • add error messages
  • move it to a class file instead of in the page
  • run it from the filterText method if IndexOf(“[bible]”) !=-1
  • fix toVerse in case it goes out of range
  • fix misspelled or abbreviated bookName with value from database
  • change to Compiled Queries
  • add footnotes
  • pretty up error messages
  • clean up final code
public class bibleParts
{
	public static Func<bibleDataContext, string, IQueryable<bibleParts>>
		theVersion = CompiledQuery.Compile((bibleDataContext context, string bibleVersion) =>
			(from v in context.bibles_infos
			 where v.bibleName == bibleVersion
			 select new bibleParts
				 {
					 version = v.bibleID,
					 language = v.language,
					 copyright = v.copyright
				 }));

	public static Func<bibleDataContext, int, string, IQueryable<bibleParts>>
		theBook = CompiledQuery.Compile((bibleDataContext context, int bookLang, string book) =>
			(from b in context.book_names
			 where (b.book == book || b.abbreviation == book || b.alt == book) && b.language == bookLang
			 select new bibleParts
			 {
				 bookID = b.book_id,
				 book = b.book
			 }));
	public static Func<bibleDataContext, int, int, int, IQueryable<bibleParts>>
		theVerses = CompiledQuery.Compile((bibleDataContext context, int version, int book, int chapter) =>
			(from v in context.verses
			 where v.versionID == version && v.bookID == book && v.chapter == chapter
			 select new bibleParts
			 {
				 verseNum = v.verse1,
				 thisVerse = v.text
			 }));

	public int version {get;set;}
	public int language {get;set;}
	public string copyright {get;set;}
	public int bookID {get;set;}
	public string book {get;set;}
	public int verseNum {get;set;}
	public string thisVerse {get;set;}
}
</pre></pre>
<pre><pre>private string verseMod(string text)
{
	string textVal = text;
	string errorValue = "";
	string verseNumBegin = "<sup>";
	string verseNumEnd = "</sup>";
	string footerBegin = "<em> - ";
	string footerEnd = "</em>";
	string bibleVersion = "kjv";  //default version if none is specified
	string pat = @"\[bible[=]?(?<version>[a-zäëïöüæø]*)](?<entire>(?<book>([0-9][\s]?)?[a-zäëïöüæø]*[\s]{1}([a-zäëïöüæø]*[\s]?[a-zäëïöüæø]*[\s]{1})?)(?<chapter>[0-9]{1,3})(:{1}(?<verse>[0-9]{1,3})(-{1}(?<toVerse>[0-9]{1,3}))?)?)\[/bible]";

	Regex r = new Regex(pat, RegexOptions.IgnoreCase);

	MatchCollection m = r.Matches(textVal);
	foreach (Match match in m)
	{
		string verseVal = "";
		string errorText = "";
		if (!String.IsNullOrEmpty(match.Groups["version"].Value))
			bibleVersion = match.Groups["version"].Value;
		string thisBook = match.Groups["book"].Value;
		int fromVerse = 0;
		int toVerse;
		if (!String.IsNullOrEmpty(match.Groups["verse"].Value))
			fromVerse = Convert.ToInt32(match.Groups["verse"].Value);
		toVerse = fromVerse;
		if (!String.IsNullOrEmpty(match.Groups["toVerse"].Value))
			toVerse = Convert.ToInt32(match.Groups["toVerse"].Value);

		using (var bdc = new bibleDataContext())
		{
			var searchVersion = bibleParts.theVersion(bdc, bibleVersion).SingleOrDefault();
			if (searchVersion != null)
			{
				var searchBook = bibleParts.theBook(bdc, searchVersion.language, thisBook).SingleOrDefault();
				if (searchBook != null)
				{
					var searchVerses = bibleParts.theVerses(bdc, searchVersion.version, searchBook.bookID, Convert.ToInt32(match.Groups["chapter"].Value));
						if (fromVerse != 0)
						{
							searchVerses = from v in searchVerses
										   where v.verseNum >= fromVerse && v.verseNum <= toVerse
										   select v;
						}
							string realToVerse = "";
							verseVal += String.Format("{1}{0}{2}", match.Groups["entire"].Value.Replace(match.Groups["book"].Value.Trim(), searchBook.book), "<span class=\"bibleHead\">", "</span>");
							verseVal += "<span class=\"bibleContent\">";
							foreach (var theVerse in searchVerses)
							{
								string verseFormat = "{2}{1}{3}{0} ";
								if (String.IsNullOrEmpty(match.Groups["toVerse"].Value) && !String.IsNullOrEmpty(match.Groups["verse"].Value))
									verseFormat = "{0} ";

								verseVal += String.Format(verseFormat, theVerse.thisVerse, theVerse.verseNum, verseNumBegin, verseNumEnd);
								realToVerse = theVerse.verseNum.ToString();
							}
							verseVal += String.Format("{1}{0}{2}</span>", searchVersion.copyright, footerBegin, footerEnd);
							verseVal = verseVal.Replace(String.Format("-{0}", toVerse), String.Format("-{0}", realToVerse));
							verseVal = verseVal.Replace("-</span>", "</span>");
				}
				else
				{
					errorText = "The book \"{0}\" does not exist.  Please check the spelling and try again.";
					errorValue = match.Groups["book"].Value;
				}
			}
			else
			{
				errorText = "The version \"{0}\" is not installed on this server";
				errorValue = match.Groups["version"].Value;
			}
			if (String.IsNullOrEmpty(errorText))
			{
				textVal = textVal.Replace(match.Groups[0].Value, verseVal);
			}
			else
			{
				textVal = textVal.Replace(match.Groups[0].Value,String.Format(errorText,errorValue.Trim()));
			}
		}
	}
	return textVal;
}

Currently active at newcastlechurchofChrist.com.

Firebug primer by Hugo

For those that are not aware Firebug is a add-on for Firefox, and is essentially a development debugging tool, that allows you to inspect various aspects of a web page.

It has become – for those that have used it for a while – one of those indispensable tools that make day to day coding life that much more productive.

This post is by way of introducing those unfamiliar with it to it’s most basic functionality, I do not attempt to explore any of the deeper functions but concentrate on the HTML / CSS tools available.

The image below shows the Firebug console on initial activation.

The HTML tab is selected and this shows an initial view of the pages markup in the panel to the left hand side at the bottom. To the right is a view of the CSS rules that apply to this page and to this element specifically in the initial view and is selected using the tab above marked ‘CSS’ (more about the other views later).

The image above shows the options selectable for the HTML markup view.
The important options are the three bottom ones:

  • ‘Highlight changes’ this will place a background to the element being viewed or that is receiving focus and helps greatly when the markup dynamically changes
  • ‘Expand changes’ this feature will automatically reveal collapsed branches in the markup (note the plus sign against the element nodes in the makup view which are clickable to inspect nested detail) when the page refreshes or one inspects an element in the main viewport (see later explanation on ‘inspecting’)
  • ‘Scroll Changes into view’ very useful as this moves the html view to the element in question rather than you have to find it in a large and complicated page

Next is where Firebug starts to get interesting!

The image below shows a view when one uses the ‘inspect’ button whilst in html view

Note the blue bounding border around the text in the viewport; when you click the ‘Inspect’ button you can then move your pointer over any portion of the rendered viewport display, as you highlight elements they will be demarcated by the blue border, as this happens you will notice two things occurring firstly the html markup view will be scrolling to the element that you have hovered over and the CSS view in the right hand pane will jump to the specific CSS rulesets that style this element.

When an element is highlighted you may click on the element and this will ‘fix’ this element in the two view panes in Firebug allowing you to further inspect aspects without loosing the focus on that element.

The image above shows a further method to inspecting elements and one that provides a further level of detail that is extremely useful. By clicking on any element in the left hand Firebug pane showing the page markup you will be able to highlight the elements padding and margins, this can be seen as the yellow highlight which represents the margins of the element and the purple highlight which represents the elements padding applied.

Moving on to the CSS aspect of Firebug demonstrates some invaluable tools and information that make dealing with CSS cascade and inheritance much easier and is perhaps is a feature above all others that would justify installing and learning to work with Firebug.

Looking at the right hand pane showing CSS rulesets shows us some very important information firstly it show us all the rulesets and properties that have been applied to the element highlighted in the left hand pane but much more than that it shows us specifically the specificity order of those rulesets in other words it shows us those rules that carry the heaviest most important weight first it then shows rulesets of a lesser value but that have been applied to the element, and thirdly it shows us properties that have been inherited by the element from parents or ancestors, note the “Inherited from div.content” heading, this is telling us that there was a font-size applied to any div with a class ‘.content’ and that as .submit and/or a paragraph was a child element of that div.content it had inherited that font-size; which brings us to the final feature of this CSS view, note the strikethrough on that inherited ruleset font-size, Firebug is telling us that in actual fact although this property was inherited in reality it was overwritten bu a more specific font-size described on the child element.

This set of features and information make debugging CSS problems extremely fast and far easier than having to wade through the stylesheet trying to understand where there might be an inheritance or specificity issue. On a final note please observe the line numbers to the right of the rulesets these correspond to the actual line numbers in your stylesheet which further speeds up locating specific rulesets; In the examples I have used grabbed from the forum It went unnoticed until too late that cetain styles/stylesheets appear to be ‘packed’ or ‘minified’ and thus all rulesets are in fact collapsed to a single line to preserve space and reduce file size, hence we mainly see ‘(line 1)’ normally this would show as mentioned earlier, an example of actual line numbers can be seen if you look further down at the third rulest that has a file name html.css and a line number of ‘(line 65)’

A further aspect of the right hand view can be seen in the image below where the ‘layout’ button has been selected. This speaks for itself but briefly it shows the aspects of the elements box model.

Lastly in either viewing pane one can edit in real time either the markup or, as shown in the image, the CSS rulesets, you can add new properties, delete existing ones or simply modify existing ones.

Conclusion:

Firebug is a very powerful tool and one that simply increases ones productivity; I can’t stress enough though that I have only scrapped at the surface of what it can show and do and concentrated on the basic HTML/CSS features, if you’re working with client side scripting Firebug becomes equally indispensable in allowing you to observe in real time dynamic changes to the page.

There are other aspects that I leave to the reader to discover but once you do you’ll realise why you can’t really do without this tool 🙂