Tag Archives: C#

Converting Picasa ini dates to directory dates

One issue I faced in the process of migrating from Picasa to Adobe Lightroom is that Picasa stores event dates in .picasa.ini files. I had spent many hours setting correct dates in my events (folders) and wanted to import them. So I wrote the following C# script (should work for Windows and OS X – I ran in via Mono).

Update: This code is on github @ https://github.com/DavidVeksler/EmbedPicasaProperties

The below will not be updated.

using System;
using System.IO;
namespace ConvertPicasaToFolderDates
        class MainClass
                private const string IniFileName = @".picasa.ini";
                private static void Main(string[] args)
                        string startFolder = @"/Users/davidv/Pictures/";
                private static void UpdateFoldersInPath(string folder)
                        string[] directories = Directory.GetDirectories(folder);
                        if (directories.Length > 0)
                                Console.WriteLine("{0} folders in {1}", directories.Length, folder);
                        foreach (string directory in directories)
                                        string iniPath = Path.Combine(directory, IniFileName);
                                        if (File.Exists(iniPath))
                                                Console.WriteLine("Parse " + iniPath);
                                                foreach (string line in File.ReadAllLines(iniPath))
                                                        // date=29586.603900
                                                        if (!line.StartsWith("date=")) continue;
                                                        string dateString = line.Substring(5);
                                                        DateTime date = ConverPicasaDateToDateTime(dateString);
                                                        DateTime originalTime = Directory.GetCreationTime(directory);
                                                        if (originalTime != date && date.Year < 2010)
                                                                Console.WriteLine("{0} to {1}", originalTime, date);
                                                                Directory.SetCreationTime(directory, date);
// (For Mono SetCreationTime did not work correctly, so use SetLastWriteTime.)
                                catch (Exception ex)
                                catch (Exception ex)
                // convert =29586.603900 to date time format
                private static DateTime ConverPicasaDateToDateTime(string dateString)
                        var startDate = new DateTime(1900, 1, 1);
                        DateTime date = startDate.AddDays(Convert.ToDouble(dateString) -2);
                        Console.WriteLine("new date: " + date);
                        return date;


In-memory cashing for an auto-complete list

When implementing an auto-complete control on your site, you may want to cache the results to keep the database queries to a minimum. Here’s a quick way to do that:

        public static Dictionary AutoCompleteHashList = new Dictionary();
        const string resultsFormatString ="{0}|{1}rn";
        private static string GetSuggestedResults(string s)
            const int maxHashLengthToCache = 9;
            if (s.Length 
                            results.AppendFormat(resultsFormatString, recipe.Key, recipe.Value)
            if (s.Length < maxHashLengthToCache)
                AutoCompleteHashList.Add(s, results.ToString());
            return results.ToString();

Stanza Catalog Update

I’ve continued enhancing the Stanza catalog I created earlier. New features include purchase links and Google Analytics tracking. I reverse-engineered the FeedBooks API and the AllRomanceBooks.com feeds to figure out how to do some of these things. Also I’ve been reading the OPDS spec (an industry-standard successor to the Stanza format) to add support for e-readers on other platforms. For example Aldiko officially supports OPDS, but it recognizes Stanza tags as well.  It crashes if you try to open a PDF file however – so it just needs to be sent the right mime type.

Here’s the snippet where I reference the custom Analytics class I added:

 p.StoreDescription += Mises.Domain.Mobile.Analytics.GetAnalyticsImageTag(this.request.RequestContext.HttpContext);
                            var content = new TextSyndicationContent(p.StoreDescription,
                            item.Content = content;

And here’s how to add external links to a book info view:

                                new SyndicationLink(
                                    new Uri(string.Format("http://mises.org/store/Product.aspx?ProductId={0}&utm_source=MisesCatalog", p.ProductId)), "alternate", "Purchase at the Mises Store",
                                    "text/html", 0));

Get the MD5 hash of a file in .Net

MSDN has a page on how to get the MD5 hash of a string.

Easy enough, but if you follow their example exactly for a file and use File.ReadAllText() to get the string, you will get the wrong MD5 string for binary files. Instead, use File.ReadAllBytes() to bypass encoding issues. (This also applies to SHA1 hashing.)

private static string GetMD5Hash(string filePath)
            byte[] computedHash = new MD5CryptoServiceProvider().ComputeHash(File.ReadAllBytes(filePath));
            var sBuilder = new StringBuilder();
            foreach (byte b in computedHash)
            return sBuilder.ToString();

Creating a Stanza Catalog with ASP.Net MVC 2.0

Stanza is a book reader for the iPhone/iPad.  One of Stanza’s features is the ability to browse specially formatted book catalogs.  While it has a number of built-in catalogs, you can also add your own.  I have created such a catalog with ASP.Net MVC 2.0 (screenshots).  The Stanza catalog format is pretty simple – just AtomPub with some proprietary attributes for images and things like search.  This was a quick and easy project because the .Net Framework 4.0 has the System.ServiceModel.Syndication namespace which does all the RSS/Atom feed generation.  We just have to add some custom attributes and serialize the feed to the browser.

Here is a quick overview of the code (Links are to the latest version of the source code in my SVN browser.  You can get the project from SVN here (guest/guest).)  The LiteratureCatalog and LiteratureCatalog.Tests projects have the relevant code.

Update: The Stanza catalog format works equally well with Aldiko, an e-reader for Android.


This is the default controller specified in global.asax.  It defers to MisesFeeds to generate the feed items and to FeedResult to serialize and write out the feed.

Sample Method:

public FeedResult Journal(int journalId)
var feeds = new MisesFeeds(Request);
SyndicationFeed feed = feeds.GetJournalFeed(journalId);
return new FeedResult(new Atom10FeedFormatter(feed));


MisesFeed contains all the code to generate a SyndicationFeed object containing a List of SyndicationItem.  Note the Stanza-specific links added in search list-builder and the final helper method:

item.Links.Add(new SyndicationLink(new Uri(DataFormat.GetAbsoluteURL(p.Logo)),
"x-stanza-cover-image-thumbnail", "", "image/jpeg", 0));
public SyndicationFeed CreateFeedFromSyndicationItemList(IEnumerable postItems, string title,
string description)
var feed = new SyndicationFeed(title, description, new Uri(feedUri), postItems)
Copyright = new TextSyndicationContent(Configuration.Copyright),
Language = "en-US"
var self = new SyndicationLink(new Uri(Host + HttpUtility.UrlEncode("/Catalog/")), "self", "", Type, 0);
feed.Links.Add(new SyndicationLink(new Uri(Host + "/Catalog/Search/?q={searchTerms}",true),"search","Search Catalog",Type,0));
return feed;


FeedWriter inherits from ActionResult.  It just writes the SyndicationFeed out with an XmlTextWriter:

public override void ExecuteResult(ControllerContext context)
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/atom+xml";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (feed != null)
using (var xmlwriter = new XmlTextWriter(response.Output))
xmlwriter.Formatting = Formatting.Indented;

Thanks to DamienG for the FeedResult class.

To see the catalog, get the Stanza app, tap “Get Books”, “Shared”, “Add Book Source”, then add the URL mises.org/catalog.

Using Reflection to serialize DTO’s

Suppose that you have a DTO (data transfer object) that you want to convert into a parameter array to be saved to file or sent over the web. You could serialize it and convert it to XML or JSON. But maybe you want to send it in an HTTP POST or GET and you don’t want to know anything about the class itself. You could use Reflection to iterate through the properties and extract the property names and values and output them to a string.

For example, this code will convert a class into a string suitable for a REST API call:

var properties = prefs.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
           properties.ToList().ForEach(property =>
                                               var hasDataMemberAttribute = property.GetCustomAttributes(typeof(DataMemberAttribute), false);
                                               if (hasDataMemberAttribute.Length == 1)
                                                   string name = property.Name.ToLower();
                                                   string value = String.Empty;
                                                   object objValue = property.GetValue(prefs, null);
                                                   if (null != objValue)
                                                       value = objValue.ToString();
                                                   // Only serialize properties marked with the [DataMember] attribute:
                                                   var hasBrokerMapAttribute = property.GetCustomAttributes(typeof(DataMemberBrokerMapAttribute),
                                                   if (hasBrokerMapAttribute.Length == 1)
                                                       name = ((DataMemberBrokerMapAttribute)hasBrokerMapAttribute[0]).Key;
                                                   if (value.Length > 0)
                                                       filter.Append(String.Concat("/", name, "=", value));
           Debug.WriteLine("Search Filter:" + filter);
           return filter.ToString();

.Net Graphics: drawing text on a bitmap

I use this code here.

Graphics backgroundGraphics;
backgroundImage = (Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\images\Header.jpg");
backgroundGraphics = Graphics.FromImage(backgroundImage);
var font = new Font("Perpetua Titling MT", 24F, FontStyle.Regular);
backgroundGraphics.DrawString(authorname.ToUpper(), font, new SolidBrush(Color.FromArgb(100, 0, 0, 0)), 10, 5);

Now save – or output to the browser:

backgroundImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);

Response.Redirect and 302 and 301 status codes

If you use Response.Redirect to direct users to a new location, you should be aware that it issues a status code of 302, which means that “the resource resides temporarily under a different URI.” If you intend to communicate that the resource has permanently changed locations, you should not use Response.Redirect. This is important for search engines and other crawlers that might need to know the definitive url.

To send a 301 redirect:

Response.Status = "301 Moved Permanently";
Response.StatusCode = 301;
Response.AddHeader("Location", url);

Update: ASP.Net 4.0 ads a Response.RedirectPermanent() method.