FizzBuzz one-liner in C#
FizzBuzz: Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". Reference
Console.WriteLine(String.Join(Environment.NewLine, Enumerable.Range(1, 100) .Select(i => (i % 3 == 0) ? new { n = i, w = "Fizz" } : new { n = i, w = "" }) .Select(o => (o.n % 5 == 0) ? new { n = o.n, w = o.w + "Buzz" } : o) .Select(o => o.w == "" ? o.n.ToString() : o.w)));
jQuery Autocomplete and Rails
This is an example of how I used the jQuery Automcomplete Widget with Rails 3.2 for a recipe search field. Some of the jQuery stuff mentioned below is included out of the box with a new Rails application.
- Make sure the jQuery gem is referenced in the Gemfile
gem 'jquery-rails'- Include the jQuery javascripts in app/assets/javascripts/application.js
//= require jquery //= require jquery_ujs //= require jquery-ui
- Download one of the jQuery-ui css files, or a custom one, and put it in one of you asset locations. I put mine in vendor/assets/stylesheets/jquery-ui-1.8.18.custom.css. Include the css file in app/assets/stylesheets/application.css
*= require jquery-ui-1.8.18.custom.css
- Create a controller action to search and return values for the autocomplete dropdown menu. In my Recipes controller (you could also create a seperate Search controller), I created an Action to return a list of matching recipe titles as a json array. The search can also be applied to recipes in a single category, hence the category_id parameter.
def search_on_title # search_on_title is a method on the model to do a wildcard search on keyword recipes = Recipe.search_on_title(params[:term], params[:category_id]) render json: recipes.map(&:title) end
- Add a route for the search_on_title action.
resources :recipes do get 'search_on_title', :on => :collection end
- The search form is just a normal form.
<%= form_tag '', :method => :get do %> <%= search_field_tag :term, params[:term], :class=> "input-large" %> <%= submit_tag "Filter", :name => nil, :class => 'button btn', :id => "search_bn" %> <% end %>
- The javascript to hook up the autocomplete functionality looks like this. Notice the extra parameter to the source url - that's how you would pass multiple values to your filter.
$("input#term").autocomplete({ source: '<%=search_on_title_recipes_path%>?category_id=<%=params[:category_id]%>', minLength: 2, delay: 500 });
There's also a Rails gem to make autocomplete easier, but I found this to be easy enough such that I didn't have to depend on an additional plugin.
WCF Client and the “using” Statement
As I was researching patterns and practices for a WCF client implementation, I came across a bug in the .Net implementation of ClientBase<T> (whether it's actually a bug is arguable). It's well documented on the web, but it could cause major headaches if you happened to miss it.
The core of the issue is that ClientBase<T> implements IDisposable. With this knowledge, just about any programmer would naturally wrap its usage in a using{} block. Digging deeper, you'll find that the ClientBase<T> Dispose() method simply calls Close() on the underlying connection. This is problematic because in certain connection states (such as "Faulted"), the Close() will fail. As I said, this is well documented elsewhere, for example: on MSDN, Stack Overflow, and here.
There are a few different solutions to this issue. I went with a simple Disposable wrapper...
// Get a disposable MyClientWrapper object using(var clientWrapper = ClientFactory.GetMyClientWrapper()) { clientWrapper.Client.DoSomething(); } public class MyClientWrapper : IDisposable { private readonly MyClient _client; public MyClientWrapper(Binding binding, Uri endpoint) { // creates an instance of MyClient, which is derived from ClientBase<T> _client = new MyClient(binding, new EndpointAddress(endpoint.ToString())); } public MyClient Client { get { return _client; } } public void Dispose() { // safe dispose with extension method (below) _client.CloseProxy(); } } // extension method for safe Close() on ClientBase<T> public static void CloseProxy(this ClientBase<T> proxy) where T : class { try { if (proxy.State != CommunicationState.Closed && proxy.State != CommunicationState.Faulted) { proxy.Close(); // may throw exception while closing } else { proxy.Abort(); } } catch (CommunicationException) { proxy.Abort(); throw; } }
Find/Kill a Linux Process by Name
I was doing some research to figure out how to easily kill a Linux process given part of it's name. It's fairly simple to do it manually, but if you didn't already know, programmers are lazy.
The first thing I was doing...
> ps aux | grep Foo
find the process ID (PID) with my eyes, and then kill it...
> kill -9 123456
Next, I started finding complex piped commands to find and extract the PID. For instance...
> pid=`ps -eo pid,args | grep Foo | grep -v grep | cut -c1-6`
and slightly simpler...
> ps aux | grep Foo | grep -v grep | awk '{print $2}'
Finally, I discovered pgrep and pkill. There are quite a few options for each command, but simply put:
To get the PID for a process with a name containing 'Foo'...
> pgrep Foo
To get the PID for a process with a command line containing 'Bar' (as in > Foo -n Bar)...
> pgrep -f Bar
Canning Fever

Pasta Sauce and Blueberry Jam
Originally uploaded by cleverswine
Bren has canning fever. It all started with a canning book that she received as a Christmas present. Now, she has canned (or jarred as I like to call it) Salsa, Pasta Sauce, Blueberry Jam, and Sweet Pickles. The nice thing is that we'll be well stocked with food that we know is locally grown and chemical free.
Slow Gardening

Bellpepper
Originally uploaded by cleverswine
This summer is getting off to a slow start, as are our vegetables. We planted tomatoes, cucumbers, zucchini, various peppers, and carrots. So far we haven't picked a thing. We've barely reached the 80s in temperature, and we've had more rain than usual. However, despite the lack of veggies, I'm personally enjoying the cool summer.
Simple Moq
I recently worked on a project in which 90% of its tests were integration tests because the core purpose of the project was to interact with external entities. In an effort create more unit tests, I employed Moq (and lots of refactoring). This is an example of basic Moq usage.
Let's say we have a repository that gets documents from a database. The assumption is that a repository interface, IDocumentRepository, is being implemented.
In my case, I found it easier to deserialize results from file, rather than building the results by hand for each mocked response. I used System.Xml.Serialization to serialize real responses to file.
Let's Moq it...
var mockRepository = new Mock<IDocumentRepository>(); // if the query is for text/plain documents only, mock a response for that mockRepository.Setup(p => p.FindDocuments( It.Is<DocumentQueryParams>(q => q.MimeType == "text/plain"))) .Returns(DeSerializeResults<List<Document>>("TextDocuments.xml")); // use It.IsAny to return the same result regardless of the parameters mockRepository.Setup(p => p.FindDocuments( It.IsAny<DocumentQueryParams>())) .Returns(DeSerializeResults<List<Document>>("AllDocuments.xml"));
My Favorite Albums (Right Now)
This is what I'm listening to...
The Record by FEAR
This is old school punk from the early 80s, when punk rock was a means of expression and rebellion. This particular album is humorous and offensive, as punk should be.
Gothic Kabbalah by Therion
This isn't my favorite Therion album, but I've been listening to it a lot lately because of some catchy songs. I find it good to write code to because it takes you to another world.
Soviet Kitsch by Regina Spektor
This is something that's generally outside of my musical tastes, but I like her quirky voice and odd lyrics. She reminds me of a disturbed version of Tori Amos.
The Other Side of Time by Mary Fahl
I once claimed that Tarja has the greatest female voice, but I actually meant Mary Fahl. This album is completely not my style of music (folk/new age/soft rock), but her voice is irresistible and addictive.
Complex XSDs as Embedded Resources
I was recently tasked with validating XML files against a very complex set of XSD schema files. This is easily accomplished if your XSD files live on the filesystem, because the .Net xml resolver can find referenced schemas via a relative or absolute Uri. In my case, the schema files were compiled as embedded resources in my project. As expected, the XML schema loader didn't know how to find referenced schemas - it was likely searching for them in the path of the running application. To solve this, I had to help out the schema loader by implementing a custom resolver that knew how to pull schema from the embedded resources. The code...
Implement a custom XmlUrlResolver to find schema references as embedded resources.
public class ManifestResourceResolver : XmlUrlResolver { private readonly Assembly _resourceAssembly; private readonly string _baseNamespaceForReferences; public ManifestResourceResolver(Assembly resourceAssembly, string baseNamespaceForReferences) { _resourceAssembly = resourceAssembly; _baseNamespaceForReferences = baseNamespaceForReferences.EndsWith(".") ? baseNamespaceForReferences : baseNamespaceForReferences + "."; } override public object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { if (absoluteUri.IsFile) { var file = Path.GetFileName(absoluteUri.AbsolutePath); var stream = _resourceAssembly.GetManifestResourceStream(_baseNamespaceForReferences + file); return stream; } return null; } }
Create a XmlSchemaSet, and set the XmlResolver property to the custom resolver implemented above. Then, load up the main XSD schema.
var xmlSchemaSet = new XmlSchemaSet(); xmlSchemaSet.XmlResolver = new ManifestResourceResolver(Assembly.GetExecutingAssembly(), "MyApp.Schemas"); using (var stream = Assembly.GetCallingAssembly().GetManifestResourceStream("MyApp.Schemas.MainSchema.xsd")) { var xmlSchema = XmlSchema.Read(stream, null); xmlSchemaSet.Add(xmlSchema); }
Create a XmlReaderSettings object and set the Schemas property to the schema set loaded above. Lastly, load up an XML file with an XmlReader and read it.
XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = xmlSchemaSet; settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); XmlReader reader = XmlReader.Create("SomeXml.xml", settings); while (reader.Read());
The validation callback function will be invoked on each validation error while reading the file with the XmlReader.
private static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); }
References:
- Validation Using the XmlSchemaSet
- Loading XmlSchema files out of Assembly Resources
(contains some obsoleted code, but it was still helpful)
Local Groceries
We did this week's grocery shopping at Food Front in the Hillsdale neighborhood. They carry many local and organic food products. And, it may be my imagination, but local eggs fresh from the chicken taste so much better than the mass produced commercial eggs.

