My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.


8 hours ago: Here's a use-case for datapod format, recording human-readable data that later can be used as a datasource: http://is.gd/eSsLg @pholdings.
9 hours ago: "Subscriptions are available to U.S. addresses only." http://www.highlights.com another global economy #fail.
9 hours ago: "Subscriptions are available to U.S. addresses only." http://www.highlights.com another global #fail.
11 hours ago: My notes on podcast with author Aimee Bender's Lemoncake book, "a normal kid punished by expectations of giftedness": http://is.gd/eSsLg.
12 hours ago: Interesting: "one page per book": http://openlibrary.org/about.
12 hours ago: Another after-work 8K, did 5K in 23:33, getting cooler here as #berlin #marathon approaches: http://is.gd/eSp95.
yesterday: C# CODE EXAMPLE: Extension method for checking regex in one line: http://is.gd/eQzyg.
yesterday: New podcast source: "I don't want to put you to sleep, but I want to be as rich, and rewarding, and resident as a dream.":http://is.gd/eQrdC.
yesterday: An intense colin marshall interview with michael silverblatt on the art of interviewing & more: http://is.gd/eQqve (search for "blatt").
yesterday: The stackexchange site for wordpress is up: get your answers / establish your reputation @cottonr http://wordpress.stackexchange.com.
yesterday: "I've always felt that any time you can use a tuple, you should use a struct.": http://is.gd/eQm9V.
Extension method for checking regex in one line This simple extension method allows you to check strings against regular expressions in one line. ![]()
using System;
using System.Text.RegularExpressions; using System.Collections.Generic; namespace TestRegex2342343 { class Program { static void Main(string[] args) { List<string> texts = new List<string>() { "233-2887", "2332887", "442-1121", "", null }; foreach (var text in texts) { if (text.MatchesRegex("^[0-9]{3}-[0-9]{4}$")) Console.WriteLine(text + " matches"); else Console.WriteLine(text + " does NOT match"); } Console.ReadLine(); } } public static class Helpers { public static bool MatchesRegex(this string text, string regex) { if (text == null || regex == null) return false; else { Match match = Regex.Match(text, regex); return match.Success; } } } } |
How to use a Dictionary<> with struct key to save a dynamic matrix of objects The following is an example of how you can save both a fixed matrix of objects and a dynamic matrix of objects (size determined at runtime) using first a multi-dimensional array and then a generic dictionary with a struct key. In both examples you can pick the object out of the map with the x/y coordinates. ![]()
using System; using System.Windows; using System.Windows.Controls; using System.Collections.Generic; namespace TestDoubarray { public partial class Window1 : Window { public Window1() { InitializeComponent(); StaticMatrixExampleWithArray(); DynamicMatrixExampleWithDictionary(10, 10); DynamicMatrixExampleWithDictionary(20, 20); } private void StaticMatrixExampleWithArray() { CheckBox[,] checkBoxes = new CheckBox[10, 10]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { CheckBox cb = new CheckBox(); cb.Tag = String.Format("x={0}/y={1}", x, y); checkBoxes[x,y] = cb; } } CheckBox cbOut = checkBoxes[4, 8]; Message.Text += cbOut.Tag.ToString() + Environment.NewLine; } private void DynamicMatrixExampleWithDictionary(int xMax, int yMax) { Dictionary<MatrixCoordinates, CheckBox> checkboxes = new Dictionary<MatrixCoordinates, CheckBox>(); for (int x = 0; x < xMax; x++) { for (int y = 0; y < yMax; y++) { CheckBox cb = new CheckBox(); cb.Tag = String.Format("x={0}/y={1}", x, y); checkboxes.Add(new MatrixCoordinates { X = x, Y = y }, cb); } } CheckBox cbOut = checkboxes[new MatrixCoordinates { X = 4, Y = 8 }]; Message.Text += cbOut.Tag.ToString() + Environment.NewLine; } private struct MatrixCoordinates { public int X { get; set; } public int Y { get; set; } } } } |
A simple jquery search machine for a web page This example shows how easy it is with JQuery to put a little form on the page that allows a user to search for a keyword which highlights that keyword on the page. ![]()
<!DOCTYPE html>
<html> <head> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('jquery', '1.4.2'); google.setOnLoadCallback(function() { $('#searchButton').click(function() { $('p').removeClass('highlight'); $('p:contains("' + $('#searchText').val() + '")').addClass('highlight'); }); }); </script> <style> p { color: brown; } p.highlight { background-color: orange; } body { background-color: beige; } </style> </head> <body> <input id="searchText" value="second" /> <button id="searchButton">Search</button> <p>This is the first entry.</p> <p>This is the second entry.</p> <p>This is the third entry.</p> <p>This is the fourth entry.</p> </body> </html> |
Wrapper class to simplify the creation of Excel files in C# 4.0 This class uses of the improved COM Interop in C# 4.0 and makes it simple to create Excel files from data in your application. Note that in your visual studio project you have to add a reference to (in COM tab) the Microsoft Excel 14.0 Object Library. ![]()
using System;
using Microsoft.Office.Interop.Excel; namespace test_excel { class Program { static void Main(string[] args) { ExcelManager em = new ExcelManager(@"c:testreport1234.xlsx"); em.FillCell(1, 2, "Jan"); em.FillCell(1, 3, "Feb"); em.FillCell(1, 4, "Mar"); em.FillCell(2, 1, "Boston"); em.FillCell(3, 1, "New York"); em.Save(); } } public class ExcelManager { Application _excelApp; Workbook _wb; Worksheet _ws; Range _range; string _pathAndFileName; public ExcelManager(string pathAndFileName, string sheetName = "Data") { _pathAndFileName = pathAndFileName; _excelApp = new Application(); if (_excelApp == null) throw new Exception("excel sheet could not be created, check your office installation"); //_excelApp.Visible = true; //uncomment to see it being created _wb = _excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); _ws = (Worksheet)_wb.Worksheets[1]; if (_ws == null) throw new Exception("workshop could not be craeted, check your office installation"); _ws.Name = sheetName; _range = _ws.UsedRange; } public void FillCell(int row, int column, string value) { _ws.Cells[row, column] = value; } public void Save() { _wb.SaveAs(_pathAndFileName); _wb.Close(); } } } |
How to make clickable flashcards in plain javascript for your mobile phone I realized that my Sony Ericsson C510 phone doesn't support JQuery (NetFront browser) so had to recreate the flashcards in plain Javascript, thanks to bobince via stackoverflow it works nicely. ![]()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> window.onload= function() { var divs= document.getElementsByTagName('div'); for (var i= divs.length; i-->0;) if (divs[i].className==='question') Toggler(divs[i]); }; function Toggler(div) { var state= false; var toggled= div.nextSibling; while (toggled.nodeType!==1) toggled= toggled.nextSibling; div.onclick= function() { state= !state; toggled.style.display= state? 'block' : 'none'; }; }; </script> <style> div.flashcard { margin: 0 10px 10px 0; } div.flashcard div.question { background-color:#ddd; width: 400px; padding: 5px; cursor: hand; cursor: pointer; } div.flashcard div.answer { background-color:#eee; width: 400px; padding: 5px; display: none; } </style> </head> <body> <div id="1" class="flashcard"> <div class="question">Who was Wagner?</div> <div class="answer">German composer, conductor, theatre director and essayist, primarily known for his operas (or "music dramas", as they were later called). Unlike most other opera composers, Wagner wrote both the music and libretto for every one of his works.</div> </div> <div id="2" class="flashcard"> <div class="question">Who was Thalberg?</div> <div class="answer">a composer and one of the most distinguished virtuoso pianists of the 19th century.</div> </div> </body> </html> |
Simple example of javascript which loads jquery locally Just download the latest version from jquery.com (click the button and copy/paste the text into e.g. the file /jquery-1.4.2.min.js). ![]()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="javascript/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("div > div.question").click(function() { if($(this).next().is(':hidden')) { $(this).next().fadeIn("slow"); } else { $(this).next().fadeOut("slow"); } }); }); </script> <style> div.flashcard { margin: 0 10px 10px 0; } div.flashcard div.question { background-color:#ddd; width: 400px; padding: 5px; cursor: hand; cursor: pointer; } div.flashcard div.answer { background-color:#eee; width: 400px; padding: 5px; display: none; } </style> </head> <body> <div id="1" class="flashcard"> <div class="question">Who was Wagner?</div> <div class="answer">German composer, conductor, theatre director and essayist, primarily known for his operas (or "music dramas", as they were later called). Unlike most other opera composers, Wagner wrote both the music and libretto for every one of his works.</div> </div> <div id="2" class="flashcard"> <div class="question">Who was Thalberg?</div> <div class="answer">a composer and one of the most distinguished virtuoso pianists of the 19th century.</div> </div> </body> </html> |
How to stop regular expression greediness This example shows how you can tell a regular expression to only get the text before the first colon, thanks Matthew and Jason. ![]()
using System;
using System.Text.RegularExpressions; namespace TestRegex92343 { class Program { static void Main(string[] args) { //Regex regex = new Regex(@"(?<label>.+):s*(?<text>.+)"); //wont' work in second case { string line = "title: The Way We Were"; Regex regex = new Regex(@"(?<label>[^:]+):s*(?<text>.+)"); Match match = regex.Match(line); Console.WriteLine("LABEL IS: {0}", match.Groups["label"]); Console.WriteLine("TEXT IS: {0}", match.Groups["text"]); } { string line = "title: The Way We Were: A Study of Youth"; Regex regex = new Regex(@"(?<label>[^:]+):s*(?<text>.+)"); Match match = regex.Match(line); Console.WriteLine("LABEL IS: {0}", match.Groups["label"]); Console.WriteLine("TEXT IS: {0}", match.Groups["text"]); } Console.ReadLine(); } } } |
How to use a generic dictionary to total enum values This code example shows how you can use a generic dictionary to add up the total of each kind of item in an enum collection. It is flexible so that if you add an enum value, it automatically is totalled as well. ![]()
using System;
using System.Collections.Generic; namespace TestDict2394343 { class Program { static void Main(string[] args) { List<LessonStatus> lessonStatuses = new List<LessonStatus>(); lessonStatuses.Add(LessonStatus.Defined); lessonStatuses.Add(LessonStatus.Recorded); lessonStatuses.Add(LessonStatus.Defined); lessonStatuses.Add(LessonStatus.Practiced); lessonStatuses.Add(LessonStatus.Prepared); lessonStatuses.Add(LessonStatus.Defined); lessonStatuses.Add(LessonStatus.Practiced); lessonStatuses.Add(LessonStatus.Prepared); lessonStatuses.Add(LessonStatus.Defined); lessonStatuses.Add(LessonStatus.Practiced); lessonStatuses.Add(LessonStatus.Practiced); lessonStatuses.Add(LessonStatus.Prepared); lessonStatuses.Add(LessonStatus.Defined); Section section = new Section(lessonStatuses); section.ShowTotals(); Console.ReadLine(); } public class Section { protected Dictionary<string, int> _lessonStatusTotals = new Dictionary<string, int>(); public Section(List<LessonStatus> lessonStatuses) { foreach (var lessonStatus in Enum.GetNames(typeof(LessonStatus))) { _lessonStatusTotals.Add(lessonStatus, 0); } foreach (var lessonStatus in lessonStatuses) { _lessonStatusTotals[lessonStatus.ToString()]++; } } public void ShowTotals() { foreach (KeyValuePair<string, int> lst in _lessonStatusTotals) { Console.WriteLine("{0}: {1}", lst.Key, lst.Value); } } } public enum LessonStatus { Defined, Prepared, Practiced, Recorded } } } |
Generic method to case-insensitively convert a string to any enum This generic static method takes an enum type and a string and converts it, ignoring case, and if the string is invalid, it will return the first (default) item in the enum collection. I'm returning the default value in a catch since IsDefined doesn't have an ignoreCase parameter, but there are more elegant ways to do this, especially in C#4 . ![]()
using System; namespace TestEnum2934234 { class Program { static void Main(string[] args) { LessonStatus lessonStatus = StringHelpers.ConvertStringToEnum<LessonStatus>("pxrepared"); ReportStatus reportStatus = StringHelpers.ConvertStringToEnum<ReportStatus>("finished"); Console.WriteLine(lessonStatus.ToString()); Console.WriteLine(reportStatus.ToString()); Console.ReadLine(); } } public static class StringHelpers { public static T ConvertStringToEnum<T>(string text) { try { return (T)Enum.Parse(typeof(T), text, true); } catch (ArgumentException ex) { return default(T); } } } public enum LessonStatus { Defined, Prepared, Practiced, Recorded } public enum ReportStatus { Draft, Revising, Finished } } |
How to create a TextBlock that has various font formatting in code behind When you create a TextBlock, you can assign it a text and then assign formatting only to the whole text, e.g. the whole TextBlock can be one color. If you want different parts of the TextBlock.Text to be various colors and have various formatting (e.g. italic/bold), you can create as many Run elements as you need and add them to the TextBlock with Inlines collection. ![]() XAML:
<UserControl x:Class="TestRun2343.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> <StackPanel HorizontalAlignment="Left" Margin="10"> <ContentControl Content="{Binding MainContent}"/> </StackPanel> </UserControl> Code Behind:
using System.ComponentModel;
using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace TestRun2343 { public partial class MainPage : UserControl, INotifyPropertyChanged { #region ViewModelProperty: MainContent . private object _mainContent; public object MainContent { get { return _mainContent; } set { _mainContent = value; OnPropertyChanged("MainContent"); } } #endregion . public MainPage() : base() { InitializeComponent(); DataContext = this; TextBlock tb = new TextBlock(); tb.FontSize = 14; tb.FontFamily = new FontFamily("Courier"); Run runLabel = new Run(); runLabel.Foreground = new SolidColorBrush(Colors.Brown); runLabel.Text = "Test 1: "; Run runContent = new Run(); runContent.Foreground = new SolidColorBrush(Colors.Black); runContent.FontStyle = FontStyles.Italic; runContent.Text = "This is the first test."; tb.Inlines.Add(runLabel); tb.Inlines.Add(runContent); MainContent = tb; } #region INotifiedProperty Block . public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion . } } |









