Using Custom Converter in XAML

In my previous post : WPF-LINQ To SQL Sample, I had to resort to modifying .dbml file to get the images stored as varbinary into the WPF ListView control. I had to change the Type of image fields to System.Byte[], instead of using System.Data.Linq.Binary. A better way to do this is to use a custom converter. WPF allows you to specify custom converter as part of the Binding in .xaml, like this -

<Image Grid.Row=\"2\"
Source=\"{Binding Path=ThumbNailPhoto ,
Converter={StaticResource imageConverter}}\"></Image>

The custom converter is declared in the same .xaml file as a resource -

<Window.Resources>
<local:ImageDataConverter x:Key=\"imageConverter\" />
</Window.Resources>

ImageDataConverter is implemented in .xaml.cs file -

public class ImageDataConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter,
   System.Globalization.CultureInfo culture)
   {
      byte[] image = ((System.Data.Linq.Binary)value).ToArray();
      return image;
   }
	
   public object ConvertBack(object value, Type targetType, object parameter,
   System.Globalization.CultureInfo culture)
   {
      throw new NotSupportedException();
   }
}

The updated sample code can be downloaded here : WPF-LINQ to SQL Sample
License : Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

Posted in C#, WPF, code, xaml | Tagged , , , , | Leave a comment

WPF – LINQ to SQL Sample

This exercise in binding a WPF ListView control with LINQ to SQL was a lot of fun ! The following image shows data from AdventureWorks sample database displayed in the ListView control. The end result is very admirable, even in this very basic demo. Feeling a complete sense of freedom is unavoidable when working with WPF.

Linq2SqlSample1.Png

This sample demonstrates :

  1. LINQ to SQL mapping.
  2. WPF ListView Control DataBinding.
  3. Displaying images stored in database as varbinary in WPF control.

The sample code can be downloaded here : WPF-LINQ to SQL Sample
License : Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

Creative Commons License

Posted in C#, LINQ, WPF, code, database, sql | Tagged , , , , , , , , , , , , , , , , | 2 Comments

Customize log4net Output Path

The default log4net output path is relative to the startup directory of your executable. To customize the output path, you can override the base Appender’s File property in your own Appender class. The following example describes how to route the log files relative to the temp folder :

   public class MyOwnAppender : log4net.Appender.RollingFileAppender
   {
         public override string File
         {
             get
             {
                 return base.File;
             }
	
            set
            {
                if (Path.IsPathRooted(value))
                {
                    base.File = value;
                }
                else
                {
                    base.File = Path.Combine(Path.GetTempPath(), value);
                }
            }
        }
    }

Your log4net config file must be modified so that log4net can locate and use your custom Appender. If MyOwnAppender is in MyNamespace and you have implemented it in MyLoggerLib.dll :


Posted in C#, code, log4net, tips | Tagged , , , , | Leave a comment

Career Advice

The value of any advice is tied to the degree of its relevance to your particular situation and circumstances. Very specific advice, like legal and medical advice, is very expensive. It is very relevant to the individual’s situation and therefore quite valuable. The degree of relevance of inexpensive/free advice to your specific circumstances is usually very low. Inexpensive/free advice, as in sayings and quotes, but also in everyday personal and business communication, is very generic. The same message is usually perceived differently by different people. Especially when the entire message is very succinct and pithy. Various aspects of the message are accentuated differently as it is filtered through individual perception. Developing a sense of how generic advice applies to your individual situation is invaluable. Experience, observation and reading feeds the awareness. Trying and learning from mistakes is essential. Applying the lessons completes the circle.

The best career advice I ever got was to read Spencer Johnson’s Who Moved My Cheese ? The message in this book is timeless. I had been through many significant changes in my life and I think I have handled those changes quite well. After reading this book in 2001, I became consciously aware of the existence of change and my own patterns of behavior and responses to events of change. This awareness has helped me anticipate change, prepare better, make better decisions and handle change more productively.

Posted in books, career advice, psychology, tips | Tagged , , , , , , , , , , , , , | Leave a comment

Database Schema Version Control Tool

It is essential to treat database schema as source code and apply all the norms and best practices applicable to it. From what I hear and read, database schema version control is non-existent in too many projects.

Various techniques to accomplish version control of database schemas have been discussed and published. Martin Fowler and Pramod Sadagale has written a comprehensive article on Evolutionary Database Design. It is a must-read for everyone involved with database development.

K. Scott Allen writes in detail about an excellent system here – Versioning Databases – Change Scripts. This approach is sufficiently light-weight (for my taste) and provides complete control over the whole process.

I am providing a free tool here that you can use to implement this system. It will even create the SchemaVersionsLog table for your database, if it doesn’t exist. If you are using this tool with MSSQL Server, you can get started with very little effort. If you are using a different DBMS, you can still use this tool. It uses NHibernate to access the SchemaVersionsLog table. So, any DBMS supported by NHibernate is acceptable, as long as it comes with a command line tool to execute the sql scripts.

Download DbUpdater here.

Posted in C#, database, freeware, sql, version-control | Tagged , , , , , , , , , , , , , , , , , , , , , , , , , , | 5 Comments

Printing Blog Posts

I like printing blog posts and reading them later, but too many blogs don’t provide functionality to print well formatted posts. I end up printing sidebars, advertisements and other clutter along with the post, thanks to lousy print formatting in browsers. What a waste !

It is actually quite easy to add a “Print This Post” button to a WordPress blog. One great option (the one I use on this blog) is WP-Print. Make sure you read Installation and Usage instructions. Brilliant job !

Another option is HP Blog Printing. This works with some other blogging platforms also. I like the simplicity of WP-Print more than the feature set of HP plugin. HP also requires you to sign up.

How do you format posts for printing, when a blog doesn’t have such feature ?

Posted in blog, plugin, wordpress | Tagged , , , , , , , , , , , | Leave a comment

OpenSimSim 1.0-RC is out

OpenSimSim : Your Password Solution. Download 1.0 Release Candidate here : OpenSimSim 1.0-RC

opensimsim-screenshot

Posted in code, freeware, opensource | Tagged , , , , , , | Leave a comment

Leveraging XPATH Axes

XPATH axes come in very handy when nodes need to be selected based on (attribute’s or child element’s) values that must match those of other nodes elsewhere in the xml tree. Consider the following log4net configuration file :



<?xml version=\"1.0\"?>
	
<configuration>
    <configSections>
        <section name=\"nhibernate\"
            type=\"System.Configuration.NameValueSectionHandler, System,
            Version=2.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089\" />
        <section name=\"log4net\"
            type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />
    </configSections>
    <nhibernate>
        <add key=\"hibernate.connection.provider\"
            value=\"NHibernate.Connection.DriverConnectionProvider\" />
        <add key=\"hibernate.connection.driver_class\"
            value=\"NHibernate.Driver.SqlClientDriver\" />
        <add key=\"hibernate.connection.connection_string\"
            value=\"Server=servername; Database=dbname;
            User=username; Password=secret;\" />
        <add key=\"hibernate.connection.isolation\" value=\"ReadCommitted\" />
        <add key=\"hibernate.dialect\"
            value=\"NHibernate.Dialect.MsSql2000Dialect\" />
    </nhibernate>
	
    <log4net>
        <appender name=\"NHibernateFileLog\"
        type=\"log4net.Appender.RollingFileAppender\">
            <file value=\"Logs/nhibernate.txt\" />
            <appendToFile value=\"true\" />
            <rollingStyle value=\"Size\" />
            <maxSizeRollBackups value=\"10\" />
            <maximumFileSize value=\"100KB\" />
            <staticLogFileName value=\"true\" />
            <layout type=\"log4net.Layout.PatternLayout\">
                <conversionPattern
                value=\"%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n\"  />
            </layout>
        </appender>
	
        <appender name=\"GeneralLog\"
            type=\"log4net.Appender.RollingFileAppender\">
            <file value=\"Logs/general.txt\" />
            <appendToFile value=\"true\" />
            <maximumFileSize value=\"100KB\" />
            <rollingStyle value=\"Size\" />
            <maxSizeRollBackups value=\"5\" />
            <layout type=\"log4net.Layout.PatternLayout\">
                <conversionPattern
                value=\"%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n\"  />
            </layout>
        </appender>
        <appender name=\"DataLog\"
            type=\"log4net.Appender.RollingFileAppender\">
            <file value=\"Logs/data.txt\" />
            <appendToFile value=\"true\" />
            <maximumFileSize value=\"100KB\" />
            <rollingStyle value=\"Size\" />
            <maxSizeRollBackups value=\"5\" />
            <layout type=\"log4net.Layout.PatternLayout\">
                <conversionPattern
                value=\"%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n\"  />
            </layout>
        </appender>
	
        <!-- levels: DEBUG, INFO, WARN, ERROR, FATAL -->
	
        <root>
            <level value=\"DEBUG\"/>
            <appender-ref ref=\"GeneralLog\" />
        </root>
	
        <logger name=\"NHibernate\" additivity=\"false\">
            <level value=\"DEBUG\"/>
            <appender-ref ref=\"NHibernateFileLog\"/>
        </logger>
        <logger name=\"Pushable.Data\" additivity=\"false\">
            <level value=\"DEBUG\"/>
            <appender-ref ref=\"DataLog\"/>
        </logger>
    </log4net>
</configuration>


The <appender>s are referenced by <logger>s using ‘ref’ attribute of their ‘appender-ref’ child elements, using the same value as the ‘name’ attribute of the <appender>. This type of linking is quite common in xml documents. Now, The first question is : How to list files that are referenced by <logger>s ?
In order to solve this problem you will need to reach the <appender>s that are referenced by each <logger> and then extract the ‘value’ of their <file>s.

Solution:

<?xml version=\"1.0\"?>
<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"
                version=\"1.0\">
	
    <xsl:output method=\"text\"/>
    <xsl:strip-space elements=\"*\"/>
	
    <xsl:template match=\"log4net\">
        <xsl:apply-templates
            select=\"appender[@name=parent::log4net/logger/appender-ref/@ref]\"/>
    </xsl:template>
	
    <xsl:template match=\"appender\">
        <xsl:value-of
            select=\"file/@value\"/> <xsl:text>&#10;</xsl:text>
    </xsl:template>
	
</xsl:stylesheet>


The second question is : How to write an xslt script to transform this xml document into an html document with a table that looks like this -

NHibernate Logs/nhibernate.txt
Pushable.Data Logs/data.txt

Solution:

<?xml version=\"1.0\"?>
<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"
                version=\"1.0\">
	
    <xsl:output method=\"html\"/>
	
    <xsl:template match=\"log4net\">
        <HTML>
            <HEAD>
                <TITLE>www.tewari.info : using xpath axes</TITLE>
            </HEAD>
            <BODY>
                <TABLE border=\"1\" width=\"25%\">
                    <TR><TH>Logger</TH><TH>File</TH></TR>
                    <xsl:apply-templates select=\"logger\"/>
                </TABLE>
            </BODY>
        </HTML>
    </xsl:template>
	
    <xsl:template match=\"logger\">
            <xsl:variable name=\"aName\" select=\"appender-ref/@ref\"/>
            <TR>
            <TD><xsl:value-of select=\"@name\"/></TD>
            <TD><xsl:value-of
                select=\"parent::log4net/appender[@name=$aName]/file/@value\"/></TD>
            </TR>
    </xsl:template>
	
</xsl:stylesheet>


Credits :

  • SketchPath is a brilliant tool to play with xpath. I love the “New Context” button : Click on a node and hit “New Context” to change the context for the xpath query processor !
Posted in code, tips | Tagged , , , , , , , , , , , , , | Leave a comment
  • Twitter Updates

  • Notes

    Using DbUpdater with MySql
    DbUpdater can be used with mysql. Here are the files you need to jumpstart the integration – DbUpdater-MySql.zip 1. You might need to change the path to mysql.exe in mysql-exec.bat. 2. Modify values in mysql-sample-command-line.bat. Make sure mysql.data.dll is placed in GAC or in the same directory as DbUpdater.exe. Connector binaries can be downloaded from here - http://dev.mysql.com/downloads/connector/net/6.1.html (0)

    Online Backup Solution
    Finalized online backup solution : JungleDisk. I can run it on all of my machines without paying extra. I get to keep the ownership of my data – by using my own Amazon S3 storage. Backed up all family photos – all 30 GBs. Feeling good (0)

    Switched to Thematic
    I have switched to Thematic theme on this blog over the weekend. I created a child theme after playing around with the customization hooks. I added a widgetized area below main asides, did some css modifications and created a three column, flexible layout just the way I wanted. I am so glad I switched to Thematic. ThemeShaper forums are very helpful. These articles were just what I needed to get started : How to make a child theme for WordPress and How I used a WordPress Child Theme To Redesign My Blog. (0)

  • BookShelf

    Planned books:

    • ASP.NET MVC in Action

      ASP.NET MVC in Action by Jeffrey Palermo, Ben Scheirman, Jimmy Bogard

    Current books:

    • Pragmatic Thinking and Learning: Refactor Your Wetware (Pragmatic Programmers)

      Pragmatic Thinking and Learning: Refactor Your Wetware (Pragmatic Programmers) by Andy Hunt

    • Working Effectively with Legacy Code

      Working Effectively with Legacy Code by Michael Feathers

    Recent books:

    • How I Got Published: Famous Authors Tell You in Their Own Words

      How I Got Published: Famous Authors Tell You in Their Own Words by Ray White

    • Pro WPF: Windows Presentation Foundation in .NET 3.0

      Pro WPF: Windows Presentation Foundation in .NET 3.0 by Matthew MacDonald

    • Programming Windows Presentation Foundation

      Programming Windows Presentation Foundation by Chris Sells, Ian Griffiths

    • Advanced MVVM

      Advanced MVVM by Josh Smith

    View full Library

Close
E-mail It