Android + PhoneGap: Ajax requests failing silently in a release build

Having mysterious problems with ajax requests when you drop the android:debuggable=”true” from your AndroidManifest.xml? Are you calling REST APIs over https with no response whatsoever? Check your SSL certificate. I had neglected to install the intermediate certificate on my production server, which is no problem for iOS nor most desktop browsers.

Having debugging enabled in your Android app relaxes the SSL policies in your Chromium web view to a point where self-signed certificates are fine. Disabling debugging, however, makes Android quite particular about the legitimacy of your cert.

More info on installing the intermediate cert: http://www.digicert.com/ssl-certificate-installation-nginx.htm

LINQ extension method equivalents in Ruby: ElementAtOrDefault

This applies equally to ElementAt. Not that there’s much to translate here, but it’s a noteworthy language feature that Ruby arrays return nil when you go out of range.

LINQ: ElementAtOrDefault

Returns the element at a specified index in a sequence or a default value if the index is out of range.

string[] names =
  { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
    "Hedlund, Magnus", "Ito, Shu" };
 
int index = 20;
 
string name = names.ElementAtOrDefault(index);
 
Console.WriteLine(
    "The name chosen at index {0} is '{1}'.",
    index,
    String.IsNullOrEmpty(name) ? "<no name at this index>" : name);
 
/*
 This code produces the following output:
 
 The name chosen at index 20 is '<no name at this index>'.
*/

Ruby: at(index) → obj or nil

Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range. See also Array#[].

names = ["Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu"]
index = 20
value = names.at(index)
puts "The name chosen at index #{index} is " + (value == nil ? "<no value at this index>" : value)

Redesign and relocation

I gave the old blog a new face and switched to a more economically viable hosting solution. I got a chance to brush up on my HTML+CSS skills, got my hands dirty with configuring lighttpd and took a peek into customizing WordPress themes. I also replaced the OOTB commenting system – that wasn’t exactly working, anyway – with Disqus and gave the About page a long overdue update.

I’m not really much of a design guy but I’m fairly happy with the way it turned out. It’s simple, green and works on smaller screens as well. Happy days.

LINQ extension method equivalents in Ruby: Distinct

Skipped some non-applicable and painfully obvious ones. This one’s pretty obvious too, apart from the spelling of the method in Ruby. Derp.

LINQ: Distinct

Returns distinct elements from a sequence by using the default equality comparer to compare values.

List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };
 
IEnumerable<int> distinctAges = ages.Distinct();
 
Console.WriteLine("Distinct ages:");
 
foreach (int age in distinctAges)
{
	Console.WriteLine(age);
}
 
/*
 This code produces the following output:
 
 Distinct ages:
 21
 46
 55
 17
*/

Ruby: uniq → new_ary

Returns a new array by removing duplicate values in self.

ages = [21, 46, 46, 55, 17, 21, 55, 55]
distinct_ages = ages.uniq
puts "Distinct ages:"
distinct_ages.each_entry{|e| puts e}

LINQ extension method equivalents in Ruby: Concat

I skipped Average and Cast. The former has no equivalent in the Ruby standard library and is really straight forward to implement anyway. Latter isn’t exactly applicable in a duck-typed language.

LINQ: Concat

Concatenates two sequences.

class Pet
{
	public string Name { get; set; }
	public int Age { get; set; }
}
 
static Pet[] GetCats()
{
	Pet[] cats = { new Pet { Name="Barley", Age=8 },
			new Pet { Name="Boots", Age=4 },
			new Pet { Name="Whiskers", Age=1 } };
	return cats;
}
 
static Pet[] GetDogs()
{
	Pet[] dogs = { new Pet { Name="Bounder", Age=3 },
			new Pet { Name="Snoopy", Age=14 },
			new Pet { Name="Fido", Age=9 } };
	return dogs;
}
 
public static void ConcatEx1()
{
	Pet[] cats = GetCats();
	Pet[] dogs = GetDogs();
 
	IEnumerable<string> query =
		cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));
 
	foreach (string name in query)
	{
		Console.WriteLine(name);
	}
}
 
// This code produces the following output: 
// 
// Barley 
// Boots 
// Whiskers 
// Bounder 
// Snoopy 
// Fido

Ruby: concat(other_ary) → ary

Appends the elements of other_ary to self.

class Pet
  attr_accessor :name
  attr_accessor :age
  def initialize(name, age)
    @name = name
    @age = age
  end
end
 
def get_cats
  [Pet.new("Barley", 8), Pet.new("Boots", 4), Pet.new("Whiskers", 1)]
end
 
def get_dogs
  [Pet.new("Bounder", 3), Pet.new("Snoopy", 14), Pet.new("Fido", 9)]
end
 
cats = get_cats
dogs = get_dogs
 
cats.map{|c| c.name}.concat(dogs.map{|d| d.name}).each_entry{|e| puts e}

LINQ extension method equivalents in Ruby: Any

I’m translating two examples for this one.

LINQ: Any

Determines whether a sequence contains any elements.

List<int> numbers = new List<int> { 1, 2 };
bool hasElements = numbers.Any();
 
Console.WriteLine("The list {0} empty.",
	hasElements ? "is not" : "is");
class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Person
{
    public string LastName { get; set; }
    public Pet[] Pets { get; set; }
}
 
public static void AnyEx2()
{
    List<Person> people = new List<Person>
        { new Person { LastName = "Haas",
                       Pets = new Pet[] { new Pet { Name="Barley", Age=10 },
                                          new Pet { Name="Boots", Age=14 },
                                          new Pet { Name="Whiskers", Age=6 }}},
          new Person { LastName = "Fakhouri",
                       Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}},
          new Person { LastName = "Antebi",
                       Pets = new Pet[] { }},
          new Person { LastName = "Philips",
                       Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2},
                                          new Pet { Name = "Rover", Age = 13}} }
        };
 
    IEnumerable<string> names = from person in people
                                where person.Pets.Any()
                                select person.LastName;
 
    foreach (string name in names)
    {
        Console.WriteLine(name);
    }
 
    /* This code produces the following output:
 
       Haas
       Fakhouri
       Philips
    */
}

Ruby: any?

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.

numbers = [1, 2]
has_elements = numbers.any? ? "is not" : "is"
puts "The list #{has_elements} empty."
class Pet
  attr_accessor :name
  attr_accessor :age
  def initialize(name, age)
    @name = name
    @age = age
  end
end
class Person
  attr_accessor :last_name
  attr_accessor :pets
  def initialize(last_name, pets)
    @last_name = last_name
    @pets = pets
  end
end
 
people = 
  [Person.new("Haas", [Pet.new("Barley", 10), Pet.new("Boots", 14), Pet.new("Whiskers", 6)]), 
   Person.new("Fakhouri", [Pet.new("Snowball", 1)]),
   Person.new("Antebi", []),
   Person.new("Philips", [Pet.new("Sweetie", 2), Pet.new("Rover", 13)])]
 
names = people.find_all{|p| p.pets.any?}.collect{|p| p.last_name}
names.each_entry{|p| puts p}

LINQ extension method equivalents in Ruby: All

LINQ: All

Determines whether all elements of a sequence satisfy a condition.

class Pet
{
	public string Name { get; set; }
	public int Age { get; set; }
}
 
public static void AllEx()
{
	Pet[] pets = { new Pet { Name="Barley", Age=10 },
		new Pet { Name="Boots", Age=4 },
		new Pet { Name="Whiskers", Age=6 } };
 
	bool allStartWithB = pets.All(pet =>
		pet.Name.StartsWith("B"));
 
	Console.WriteLine(
		"{0} pet names start with 'B'.",
		allStartWithB ? "All" : "Not all");
}

Ruby: all?

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is all? will return true only if none of the collection members are false or nil.)

class Pet
	attr_accessor :name
	attr_accessor :age
	def initialize(name, age)
		@name = name
		@age = age
	end
end
pets = [Pet.new("Barley", 10), Pet.new("Boots", 4), Pet.new("Whiskers", 6)]
allStartWithB = pets.all?{|pet| pet.name.start_with?("B")} ? "All" : "Not all"
puts "#{allStartWithB} pet names start with 'B'."

LINQ extension method equivalents in Ruby: Aggregate

I’m currently in the process of learning Ruby, and I thought I’d share some findings that might be useful for other C# developers getting into Ruby. In this series of posts, I go through the LINQ extension methods found in C#, provide equivalents in Ruby and do my best at translating the C# examples on MSDN into Ruby.

LINQ: Aggregate

Applies an accumulator function over a sequence.

string sentence = "the quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' ');
string reversed = words.Aggregate((workingSentence, next) =>
	next + " " + workingSentence);

Ruby: reduce

Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split
reversed = words.reduce{|working_sentence, next_word| 
	"#{next_word} #{working_sentence}"}

NHibernate and the dark secrets of unneeded cascaded updates

I was having trouble with NHibernate cascading an update to a related entity regardless of cascade=”none”. During my investigation I learned that when you pass an entity to ISession.Save, .Update or .SaveOrUpdate, NHibernate goes through the entire object graph and updates persisted entities if it thinks they’re “dirty” – as in a changed state compared to the cached one – regardless of your cascade setting. NHibernate has several ways to determine whether an object is dirty, the last resort one being comparing the values of each individual field of an entity.

Turns out, I had my mapping screwed up. My related entity Y had two enumeration fields that I’d mapped as Int32. This throws off the comparisons. Int32.Equals doesn’t consider an enum of value 0 equal to the Int32 value 0. So every time I saved an entity referring to Y it considered entity Y dirty and updated it. Solution: in your mapping file, define the type of the field as the actual enumeration type or just leave the type out and let NHibernate figure it out.

“Value does not fall within the expected range” while opening a file in Visual Studio 2008

I came across a curious problem a couple of days ago. Visual Studio greeted me with a “Value does not fall within the expected range” when trying to open some of the configuration and text files in one of my solutions.

This occurred even if I closed the solution and tried to open the individual files. ProcessMonitor.exe revealed nothing. Disabling plugins didn’t help. Deleting .suo and .user files didn’t help.

Googling for a solution revealed a couple of patterns. People were getting this either in VB.NET Windows Forms projects, profiling C++ applications or trying to open TFS work items. The latter resonated. TFS, my long-time nemesis, we meet in battle again.

I tried removing the local path mapping for the project in my TFS workspace, deleted the folder and recreated the mapping. Win.