<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>Medo&#039;s Home Page</title> <atom:link href="http://www.jmedved.com/feed/" rel="self" type="application/rss+xml" /><link>http://www.jmedved.com</link> <description></description> <lastBuildDate>Wed, 16 May 2012 13:45:52 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <item><title>CA2000 and using statement</title><link>http://www.jmedved.com/2012/05/ca2000-and-using-statement/</link> <comments>http://www.jmedved.com/2012/05/ca2000-and-using-statement/#comments</comments> <pubDate>Wed, 16 May 2012 00:00:45 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Programming]]></category> <category><![CDATA[C#]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6247</guid> <description><![CDATA[I started with code like this (give-or-take few white-spaces): Running code analysis on this returned CA2000 (Microsoft.Reliability) error. It simply stated &#8220;In method &#8216;Aes256CbcStream.Aes256CbcStream(Stream, CryptoStreamMode, byte[])&#8217;, object &#8216;g__initLocal0&#8242; is not disposed along all exception paths. Call System.IDisposable.Dispose on object &#8216;g__initLocal0&#8242; before all references to it are out of scope.&#8221; Problem here is that all object <a href='http://www.jmedved.com/2012/05/ca2000-and-using-statement/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>I started with code like this (give-or-take few white-spaces):</p><pre class="brush: csharp; highlight: [1]; title: ; notranslate">
using (var aes = new RijndaelManaged() { BlockSize = 128, KeySize = 256, Key = key, IV = iv, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) {
    this.Transform = aes.CreateEncryptor();
    this.Stream = new CryptoStream(stream, this.Transform, CryptoStreamMode.Write);
}
</pre><p>Running code analysis on this returned <code><a href="http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&#038;k=k(%22DISPOSE+OBJECTS+BEFORE+LOSING+SCOPE%22)">CA2000</a></code> (<code>Microsoft.Reliability</code>) error. It simply stated &#8220;In method &#8216;Aes256CbcStream.Aes256CbcStream(Stream, CryptoStreamMode, byte[])&#8217;, object &#8216;<>g__initLocal0&#8242; is not disposed along all exception paths. Call System.IDisposable.Dispose on object &#8216;<>g__initLocal0&#8242; before all references to it are out of scope.&#8221;</p><p>Problem here is that all object references ARE being released by using statement. Or so I thought.</p><p>If you are using <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx">Object Initializer</a>, compiler will generate code to support it. And that compiler-generated code is culprit for that message. And yes, there is <a href="http://stackoverflow.com/questions/1679780/when-using-object-initializers-why-does-the-compiler-generate-an-extra-local-va">a reason</a> for why it behaves like this.</p><p>Personally I often ignore this warning. Strictly speaking this is not a real solution and definitely not a best practice. However it is quite often acceptable. If you are generating just few of these objects and there is no failure expected (famous last words), little bit more work for garbage collector is acceptable scenario.</p><p>Real solution for now would be not to use Object Initializer syntax when dealing with <code>using</code> statement. In our example that would mean:</p><pre class="brush: csharp; highlight: [2,3,4,5,6,7]; title: ; notranslate">
using (var aes = new RijndaelManaged()) {
    aes.BlockSize = 128;
    aes.KeySize = 256;
    aes.Key = key;
    aes.IV = iv;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;
    this.Transform = aes.CreateEncryptor();
    this.Stream = new CryptoStream(stream, this.Transform, CryptoStreamMode.Write);
}
</pre>]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/05/ca2000-and-using-statement/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Smoothing</title><link>http://www.jmedved.com/2012/05/smoothing/</link> <comments>http://www.jmedved.com/2012/05/smoothing/#comments</comments> <pubDate>Sun, 13 May 2012 00:00:17 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Electronics]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6076</guid> <description><![CDATA[If you are making some measuring device with display it is always a challenge to select proper rate of refresh. Usually your measurement takes only small amount of time and it is very hard to resist updating display after each one. I saw number of devices that have displays that are just too fast to <a href='http://www.jmedved.com/2012/05/smoothing/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>If you are making some measuring device with display it is always a challenge to select proper rate of refresh. Usually your measurement takes only small amount of time and it is very hard to resist updating display after each one. I saw number of devices that have displays that are just too fast to read.</p><p>Slowing rate at which measurement is taken is almost always beneficial for both user comfort and battery life. And that is valid solution, especially if value is relatively stable. However, if measurement fluctuates a bit, that results in jumps between values.</p><p>To cure that you should be doing averaging. If your measurement takes 10ms to complete, you can do 10 of them, average the result and still have quite a decent 10/second refresh rate. This is probably solution gets most use but it is not the only one.</p><p>My favorite way of slowing display is simplified weighted average. Between two measurements one that is current always carries more weight than newer one. Exact weight is matter of trial but I found small numbers like 23% work the best.</p><p>To clarify it a bit, let&#8217;s say that we have measurement of 10 and measurement of 20. Our new &#8220;average&#8221; value will become 12.3. If third measurement is also 20, value becomes 14.1, then 15.4 and so on. Value keeps getting closer and closer to real reading but speed with which it does that is very limited.</p><p>If you have measurements that are relatively stable this method works almost like an average. If value jumps occasionally this method will smooth such temporary change. That gives much nicer end user feeling as far as measurement goes. And since we are doing this at much faster rate than actually showing data, if permanent jump does occur, user will see such change relatively quickly.</p><p>Code for this might look like:</p><pre class="brush: cpp; highlight: [6]; title: ; notranslate">
float value = measure();
while (1) {
    showValue(value);
    for (int i=0; i&lt;10; i++) {
        float newValue = measure();
        value = value + (newValue - value) * 0.23; //to smooth it a little
        value = (int)(value * 1000.0) / 1000.0; //rounding
        //do other stuff
    }
}
</pre><p>In this particular code, we show a value to user as soon as we can (to enhance perceived speed). After that we average next 10 values (each new one is given 23% of consideration). Then we display new average to user. Rinse and repeat. Optional rounding step additionally limits small changes.</p><p>This code is not that good if measurement takes a long time. E.g. If you have one measurement per second you will find it takes eternity to change a value. For such cases you are probably better off just displaying current measurement to user. Or, if some smoothing is required, using higher values (e.g. 0.79 or similar).</p><p>P.S. This method might not work as expected for your measurements. Do test first.</p><p>P.P.S. This is intended for human display only. If you are logging values, it is probably best to write measurements without any adjustment. If you average them before writing, you are losing details.</p><p>P.P.P.S. If you are doing averaging in full-blown desktop application, ignore this code. You can use proper moving average (linear, exponential, weighted&#8230;) that allows for much greater control. This method is just a workaround to get similar results when working on memory-limited PIC.</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/05/smoothing/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Case for TryGetValue</title><link>http://www.jmedved.com/2012/05/case-for-trygetvalue/</link> <comments>http://www.jmedved.com/2012/05/case-for-trygetvalue/#comments</comments> <pubDate>Thu, 10 May 2012 00:00:35 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Programming]]></category> <category><![CDATA[C#]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6086</guid> <description><![CDATA[When I am reviewing code, I always check how program retrieved items from dictionary. Most often I find following pattern: Whenever I see it, I wonder why somebody would use it over TryGetValue: If you deal with dictionary of objects, later code is something around 25% (depends on size of dictionary and bunch of other <a href='http://www.jmedved.com/2012/05/case-for-trygetvalue/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>When I am reviewing code, I always check how program retrieved items from dictionary. Most often I find following pattern:</p><pre class="brush: csharp; title: ; notranslate">
if (dict.ContainsKey(key)) {
    object obj = dict[key];
    //do something with obj
}
</pre><p>Whenever I see it, I wonder why somebody would use it over <code>TryGetValue</code>:</p><pre class="brush: csharp; title: ; notranslate">
object obj;
if (dict.TryGetValue(i, out obj)) {
    //do something with obj
}
</pre><p>If you deal with dictionary of objects, later code is something around 25% (depends on size of dictionary and bunch of other stuff) faster. If you deal with dictionary of structures, difference is much smaller (7-8%) since in later case you need to deal with memory allocations (remember that there is no null for structures).</p><p>Most of the time, dictionaries are used in time critical code so changing code to later is almost a no-brainer.</p><p>I only ever came to see one single scenario where key check separated from retrieval is desired. On case your dictionary has structures in it and you expect lot of look-up failures you will be better off using first example. Second code will use much more memory and need to create structure before each key check will offset any time savings you might get when item is found.</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/05/case-for-trygetvalue/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>MagiWOL 3.30</title><link>http://www.jmedved.com/2012/05/magiwol-3-30/</link> <comments>http://www.jmedved.com/2012/05/magiwol-3-30/#comments</comments> <pubDate>Tue, 08 May 2012 00:00:03 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Updates]]></category> <category><![CDATA[MagiWOL]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6186</guid> <description><![CDATA[Nothing to look here, just an evolution. New version of MagiWOL changes import progress dialog a bit by adding time remaining text. As it always goes, it is precise full 0.1% of time. There are some internal changes as response to crash reports but nothing too exciting to talk about. Download and use.]]></description> <content:encoded><![CDATA[<p><a href="/content/media//magiwolimportprogress.png"><img src="/content/media//magiwolimportprogress-300x98.png" alt="" title="MagiWOL - Import progress" width="300" height="98" class="alignright size-medium wp-image-6188" /></a>Nothing to look here, just an evolution.</p><p>New version of MagiWOL changes import progress dialog a bit by adding time remaining text. As it always goes, it is precise full 0.1% of time.</p><p>There are some internal changes as response to crash reports but nothing too exciting to talk about.</p><p><a href="/magiwol/">Download</a> and use.</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/05/magiwol-3-30/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Cheaper Windows</title><link>http://www.jmedved.com/2012/05/cheaper-windows/</link> <comments>http://www.jmedved.com/2012/05/cheaper-windows/#comments</comments> <pubDate>Sun, 06 May 2012 00:00:22 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Windows]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6173</guid> <description><![CDATA[Next version of Windows will be cheaper. At least that is how I understand it after Windows 8 engineering team brought us nice DVD playback guide. DVD playback has it&#8217;s cost. And that cost was shared among all versions of Windows. Microsoft stated that $2 will get you MPEG-2 decoder. And frankly that is probably <a href='http://www.jmedved.com/2012/05/cheaper-windows/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p><a href="/content/media//warpdrive.jpg"><img src="/content/media//warpdrive-271x300.jpg" alt="" title="warpdrive" width="271" height="300" class="alignright size-medium wp-image-6178" /></a>Next version of Windows will be cheaper. At least that is how I understand it after Windows 8 engineering team brought us nice <a href="http://blogs.msdn.com/b/b8/archive/2012/05/04/q-amp-a-dvd-playback-and-windows-media-center-in-windows-8.aspx">DVD playback guide</a>.</p><p>DVD playback has it&#8217;s cost. And that cost was shared among all versions of Windows. Microsoft stated that $2 will get you MPEG-2 decoder. And frankly that is probably everything you need since PCM codec is available on every DVD for your stereo. Since Dolby codec is nice thing to have, let&#8217;s say that it costs additional $2 (Microsoft didn&#8217;t state cost).</p><p>My expectation is that next version of Windows will cost $4 less than Windows 7. If you are among those Windows users with lot of legacy MPEG-2 based media, you can upgrade your Windows for $5 (additional $1 is for covering distribution cost). I think that everybody wins!</p><p>And I am taking bets.</p><p>Who really thinks that Windows will be cheaper and that you will be able to buy DVD playback option for $5?</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/05/cheaper-windows/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Quick, hide it</title><link>http://www.jmedved.com/2012/05/quick-hide-it/</link> <comments>http://www.jmedved.com/2012/05/quick-hide-it/#comments</comments> <pubDate>Thu, 03 May 2012 22:00:01 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Electronics]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6068</guid> <description><![CDATA[Last half of year I live in a hotel. I do not have my workbench here nor do I have extensive electronics part collection but I do have some basic equipment. And I do use it. Pictured here is last thing that I made &#8211; voltage and current monitor. It has one input, three outputs, <a href='http://www.jmedved.com/2012/05/quick-hide-it/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p><a href="/content/media//vout.jpg"><img src="/content/media//vout-225x300.jpg" alt="" title="Vout" width="225" height="300" class="alignright size-medium wp-image-6070" /></a>Last half of year I live in a hotel. I do not have my workbench here nor do I have extensive electronics part collection but I do have some basic equipment. And I do use it.</p><p>Pictured here is last thing that I made &#8211; voltage and current monitor. It has one input, three outputs, display and two switches (that I forgot to order). On bottom there is an <a href="http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en530013">PIC</a>, sense and LED resistors. Pretty simple SMD board (45&#215;72 mm) as it goes.</p><p>What it does? Basically it just displays voltage, current or power on it&#8217;s display for selected input or output.</p><p>Once I assembled it, I left it turned on for a while, pressing button here and there. Ok, since buttons are missing, pressing is probably not the correct word for what I was doing, but you get the drift. There is nothing like long-term abuse to bring code bugs out.</p><p>As I was leaving for work, I took one last glance at device, stopped, powered it off and hid it in the drawer. Call me crazy but I haven&#8217;t dared to leave it on like that for cleaning lady to see.</p><p>Somehow I think that she would only see some clock-like device with some wires coming out and numbers that change. Even more innocent-looking things were <a href="http://en.wikipedia.org/wiki/2007_Boston_bomb_scare">misidentified</a>.</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/05/quick-hide-it/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>How annoying can you get?</title><link>http://www.jmedved.com/2012/04/how-annoying-can-you-get/</link> <comments>http://www.jmedved.com/2012/04/how-annoying-can-you-get/#comments</comments> <pubDate>Mon, 30 Apr 2012 00:00:48 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Electronics]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6053</guid> <description><![CDATA[Most of my electronics is geared toward micro-controllers. And there my undisputed champion is Microchip PIC. They are cheap, full of options and readily available. And development environment is not too bad. When I say not too bad, I think of MPLAB 8 IDE. Kind of old fella but it gets job done. I did <a href='http://www.jmedved.com/2012/04/how-annoying-can-you-get/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>Most of my electronics is geared toward micro-controllers. And there my undisputed champion is <a href="http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&#038;nodeId=2551">Microchip PIC</a>. They are cheap, full of options and readily available. And development environment is not too bad.</p><p>When I say not too bad, I think of <a href="http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&#038;nodeId=1406&#038;dDocName=en019469&#038;part=SW007002">MPLAB 8</a> IDE. Kind of old fella but it gets job done. I did try a beta of their flagship MPLAB X but we <a href="http://www.jmedved.com/2011/10/say-no-word/">never clicked</a>. It didn&#8217;t help that it would not load my projects either.</p><p>Since I was just starting new project it seemed like a good time to finally get newest and greatest IDE. So I went to their <a href="http://ww1.microchip.com/downloads/mplab/X/">download page</a> and I was greeted by total of 2:30 minutes of video with voice narrative.</p><p>I am not sure whether problem lies in me but stealing my speakers for something like download of a tool is <strong>ANNOYING</strong>. And, of course, some idiot decided to <strong>LOOP</strong> the video. Probably the same idiot who though that putting stop control was too much work. I though that kind of annoying behavior was reserved for porn sites but Microchip never ceases to amaze me.</p><p>Only image that gives me any peace is seeing manager whose idea this was in tenth circle of hell listening to these instructions over and over again. Well at least looping comes handy.</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/04/how-annoying-can-you-get/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Get a Float from RandomNumberGenerator</title><link>http://www.jmedved.com/2012/04/get-float-from-randomnumbergenerator/</link> <comments>http://www.jmedved.com/2012/04/get-float-from-randomnumbergenerator/#comments</comments> <pubDate>Fri, 27 Apr 2012 00:00:10 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Programming]]></category> <category><![CDATA[C#]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6029</guid> <description><![CDATA[Standard Random class works perfectly fine most of time. However, on bigger sample, you will see some non-random tendencies. Much better random source is RandomNumberGenerator. Unfortunately RandomNumberGenerator does not actually return random numbers. It returns random bytes. It is our duty to change those random bytes to single double value ranging from 0 to 1 <a href='http://www.jmedved.com/2012/04/get-float-from-randomnumbergenerator/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>Standard <a href="http://msdn.microsoft.com/en-us/library/system.random.aspx">Random class</a> works perfectly fine most of time. However, on bigger sample, you will see some non-random tendencies. Much better random source is <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator.aspx">RandomNumberGenerator</a>.</p><p>Unfortunately RandomNumberGenerator does not actually return random numbers. It returns random bytes. It is our duty to change those random bytes to single double  value ranging from 0 to 1 (as from <a href="http://msdn.microsoft.com/en-us/library/system.random.nextdouble.aspx">NextDouble</a> function).</p><p>Idea is to get 4 random bytes and to convert them to unsigned integer (negative numbers are so passé). If that number was to be in 0 to 1 range it would be enough to divide it by UInt32.MaxValue. Since we need result to be less than 1, we have slightly larger divisor:</p><pre class="brush: csharp; highlight: [8]; title: ; notranslate">
private RandomNumberGenerator Rnd;

private double GetRandom() {
    if (this.Rnd == null) { this.Rnd = RandomNumberGenerator.Create(); }
    var bytes = new byte[4];
    this.Rnd.GetBytes(bytes);
    var number = BitConverter.ToUInt32(bytes, 0);
    return number / (UInt32.MaxValue + 1.0);
}
</pre>]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/04/get-float-from-randomnumbergenerator/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>* Drive</title><link>http://www.jmedved.com/2012/04/drive/</link> <comments>http://www.jmedved.com/2012/04/drive/#comments</comments> <pubDate>Wed, 25 Apr 2012 00:00:46 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Uncategorized]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6050</guid> <description><![CDATA[It seems to me that Internet drives are everywhere. For a while we had DropBox as undisputed king of remotely synchronized files. When it prove successful, we got bunch of others, among which SugarSync seemed like most serious contender. This week things got interesting with Microsoft introducing SkyDrive. And today we got Google onboard with <a href='http://www.jmedved.com/2012/04/drive/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>It seems to me that Internet drives are everywhere.</p><p>For a while we had <a href="http://db.tt/v8pD14yL">DropBox</a> as undisputed king of remotely synchronized files. When it prove successful, we got bunch of others, among which <a href="https://www.sugarsync.com/referral?rf=ez98yx2ri830p&#038;utm_source=txemail&#038;utm_medium=email&#038;utm_campaign=referral">SugarSync</a> seemed like most serious contender.</p><p>This week things got interesting with Microsoft introducing <a href="http://blogs.msdn.com/b/b8/archive/2012/04/23/the-next-chapter-for-skydrive-personal-cloud-storage-for-windows-available-anywhere.aspx">SkyDrive</a>. And today we got Google onboard with <a href="http://googledocs.blogspot.com/2012/04/introducing-google-drive-yes-really.html">Google Drive</a>.</p><p>Only company missing action is Amazon. Yes, they have <a href="https://www.amazon.com/clouddrive/">their drive</a> also but they are missing half-decent sync client.</p><p>With so many heavyweight players around, things are bound to get interesting soon. :)</p> ]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/04/drive/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Not too unique</title><link>http://www.jmedved.com/2012/04/not-too-unique/</link> <comments>http://www.jmedved.com/2012/04/not-too-unique/#comments</comments> <pubDate>Sun, 22 Apr 2012 00:00:16 +0000</pubDate> <dc:creator>Josip Medved</dc:creator> <category><![CDATA[Programming]]></category><guid isPermaLink="false">http://www.jmedved.com/?p=6014</guid> <description><![CDATA[My personal favorite when it comes to databases is Microsoft SQL Server. However, reality dictates that I sometime have to use different database. Actually quite often I need to have one application supporting different database servers. I might need application to work on SQL Server, PostgreSQL and (god forbid) Oracle. With time I got used <a href='http://www.jmedved.com/2012/04/not-too-unique/' class='excerpt-more'>[...]</a>]]></description> <content:encoded><![CDATA[<p>My personal favorite when it comes to databases is Microsoft SQL Server. However, reality dictates that I sometime have to use different database. Actually quite often I need to have one application supporting different database servers. I might need application to work on SQL Server, PostgreSQL and (god forbid) Oracle.</p><p>With time I got used to prefer standardized parts of SQL. It makes life a lot simpler and SQL Server is usually ok with that plan. Except when it comes to NULLs where things can get little bit quirky. Setting ANSI_NULLS to true does sort most of issues but one.</p><p>If you have unique index on nullable column, SQL compliant behavior is to force uniqueness on all values except null ones. That means that having <code>"a", "b", null, null</code> is valid scenario. In SQL Server that second null will not be allowed under premise that such value already exists and thus violates unique index. That &#8220;feature&#8221; is part of SQL Server since it&#8217;s very first days and it is very unlikely that it will be changed in the future. Compatibility is a bitch sometime.</p><p>Fortunately there is a workaround since SQL Server 2008 in form of <a href="http://technet.microsoft.com/en-us/library/cc280372.aspx">filtered indexes</a>. That enables unique index on only some values. In our scenario we just need to ignore nulls and standard behavior here we come:</p><pre class="brush: plain; title: ; notranslate">
CREATE UNIQUE INDEX UX_MyIndex ON MyTable(MyColumn) WHERE MyColumn IS NOT NULL;
</pre>]]></content:encoded> <wfw:commentRss>http://www.jmedved.com/2012/04/not-too-unique/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: basic
Database Caching 1/25 queries in 0.008 seconds using disk: basic
Object Caching 581/628 objects using disk: basic

Served from: www.jmedved.com @ 2012-05-17 12:33:36 -->
