Generic Literals in VB.Net 2010

31. March 2011 12:57

Okay, something very cool in VB.Net as of VS2010 is that you can use literals for assignments to generic collections...

'List from Literal
Dim myList As New List(Of Integer)() From {1,2,3,4,5}

'Dictionary from Literal
Dim myDic As New Dictionary(Of String, Integer)() From {
    {"key1", 1},
    {"key2", 2}
}

Then when trying to load with Tuple's as the value, I ran into a snag, since it didn't understand the conversion of the tuple literal values. I found that by creating the needed extension methods into this module that I could do what I wanted to accomplish.

Dim myQueue= New Queue(Of Tuple(Of Integer, Integer)) From {
    {19, 63},
    {20, 63}
}

As you can see, it really isn't so difficult to use, but can be really useful when using paired values in a given collection. Generic classes such as Tuple, and Generic collections can help a lot in data iteration.


TupleExtensionsForGenericCollectionsModule.vb.txt (4.45 kb)

Tags:

101 reasons why Java is NOT better than .Net in 2010

27. May 2010 10:19

Okay, I'm getting really tired of seeing posts like this one... So I figured I'd take some time to debunk the thing.

More...

Tags: , , ,

ASP.Net MVC and Progressive enhancement...

28. April 2010 14:40

I was reading an article on Google's use of hash-bang in order to provide a consistent means of Ajaxy content for crawling/display. There are three points to resolve here. 1. Handling those cases where someone posts an ajaxy url, with the hash endpoint to facebook or twitter so that the search engines have a convention to handle these types of urls. 2. Being able to deal with the Ajaxy endpoint, the original content and the ajax callback content. 3. Being able to deal with those browsers that don't have scripting.

It got me thinking, how would one could work with progressive URL's via MVC and a few thoughts occurred to me. First, if the controller name is always the first portion of the url from the application base, if the MVC routing engine could simply replace the ?_escaped_fragment_= portion of the uri to be equal to the original route. For example http://mysite/controller/action/1?_escaped_fragment_=/otheraction/2 would be equivalent to http://mysite/controller/otheraction/2 on the backend. Second, How difficult would it be for the default view engine to be transposed in the instances of an expected response type give html, vs js. Similar to how WCF over http handles JSON via the same endpoints as XML. I know this has been discussed in the past.

Where this leads me, is thinking it might be nice to have an ASP.Net MVC 2 based framework, with conventions for handling these scenarios as a default. I like ASP.Net MVC quite a bit, and have followed Castle and Fubu as well. I'm merely thinking that it would be nice if there were a default starter kit towards creating a browser and search engine friendly Ajaxy application. It really isn't easy. I think that the google hash-bang solution leaves out the people that don't have scripting enabled, getting a hash-bang endpoint is near worthless, save for a <noscript>script disabled indexable links here</noscript>. And progressive enhancement (aka Hijax) techniques don't allow for a browser engine to properly index copy/pasted urls. Having some level of convention to support both is necessary. I think it's equally necessary for google to post the _escaped_fragment_ based urls in the search results for those users who have scripting disabled.

Tags: , ,

HttpContext Items Collection

19. April 2010 11:07

Just a short little post, I do intend to followup my last post with a post with code on combining/minifying your JavaScript and CSS, this just caught my attention, and wanted to mention it. 

In the process of doing some technical screenings, it is really suprising how many people don't understand or even know about the HttpContext Items Collection in ASP.Net.  More...

Getting the Server-Side Offset to the JavaScript Epoch in C#

3. September 2009 16:50

Just in case anyone else needs it, here's my method for getting the millisecond offset of a server's local time to UTC time in milliseconds, for use in client-side JavaScript.

private int ServerSideJsUtcOffset
{
    get {
        DateTime epoch = new DateTime(1970,1,1);
        int offset = (int)epoch.ToUniversalTime().Subtract(epoch).TotalMilliseconds;
        return offset;
    }
}

There's really not much to it, it's mainly so that I can handle converting serialized dates to a proper local time on the client. The DateTime objects in question are stored in a database as the UTC date-time, via an ORM tool, and sent to the client with System.Web.Script.Serialization.JavaScriptSerializer. All the server-side code uses the same ORM tool, and all the client-side JSON is processed via the same local parser. So it was simply easier adjusting the client-side parser than it was to adjust the server-side class hierarchy.

I should note that I could have set the initial date to DateTime.Now instead of implicitely using the JS epoch, as the difference would be the same for any localized DateTime, just felt the clarity was worth it.

Compressing Bytes In .Net

20. August 2009 10:57

Okay, this started when I wanted to store a bit of JSON that gets rendered into the ASP.Net cache.  Each entry would be unique to a given user, and I wanted to save a little memory, each entry would be about 8KB in size.  I looked into this and found the System.IO.Compression namespace that is available in .Net 3.5.  I created a small class with some helper extensions to be able to compress/decompress an array of byte, and handle to/from a native string.  Here's what I came up with.


CompressionExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Sample
{
    public static class CompressionExtensions
    {
        const int KB = 1024;

        public static byte[] Compress(this byte[] input)
        {
            using (var ms = new MemoryStream(input.Length + 8))
            {
                ms.Write(BitConverter.GetBytes(input.Length), 0, 4); //record original length

                if (input.Length < KB)
                {
                    //if less than 1KB, don't compress original
                    ms.Write(input, 0, input.Length);
                    return ms.ToArray().Take(input.Length + 4).ToArray();
                }

                //compress the original input
                using (var ds = new DeflateStream(ms, CompressionMode.Compress))
                {
                    //send the original input to the compressed stream
                    ds.Write(input, 0, input.Length);

                    //add null padding. the decompress gets wonky without it.
                    ds.Write(new byte[4], 0, 4);
                    ds.Flush();
                    ms.Flush();
                    return ms.ToArray();
                }
            }
        }

        public static byte[] Decompress(this byte[] input)
        {
            if (input == null || input.Length < 4)
                throw new ApplicationException("Invalid compressed bytes, no length header.");
        
            var bitlen = BitConverter.ToInt32(input, 0);

            //if less than 1KB, return the non-compressed original
            if (bitlen < KB) return input.Skip(4).ToArray();

            var buffer = new byte[bitlen];
            using (var ms = new MemoryStream(input.Length - 4))
            {
                ms.Write(input, 4, input.Length - 4);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                using (var ds = new DeflateStream(ms, CompressionMode.Decompress))
                {
                    //this always returns a -1 for the first read
                    //    subsequent reads will work properly
                    ds.ReadByte();

                    //read the input stream into the return buffer
                    if (bitlen > ds.Read(buffer, 0, bitlen))
                        throw new ApplicationException("Invalid compressed bytes.");
                }
            }

            //only return the number of bytes originally saved, trim excess
            return buffer;
        }

        public static byte[] ToCompressedBytes(this string input)
        {
            return Encoding.UTF8.GetBytes(input).Compress();
        }

        public static string ToDecompressedString(this byte[] b)
        {
            return Encoding.UTF8.GetString(b.Decompress());
        }
    }
}

I found that without adding some padding of at least two null bytes, the decompression of the data would sometimes give me an invalid final byte. I also push in a 4-byte length header for a sanity check. This also helps me to not compress anything under 1KB in size, where compression really doesn't work very well.

The conversion of the string to UTF8 helps more with strings that will mostly contain values within the ASCII character set. It is worth noting that if there are mostly multibyte characters, the byte array itself could get bloated. For my usage, I'm getting an 8KB string down to around 2KB, you could extend this to support UTF8/Unicode encoding by appending a character to the end before compressing. This may be useful if the string is >2KB and more than 1/3 is multibyte characters, this would take a little more CPU time to inspect the input string in this case.

Your milage may vary. Void where prohibited. Quantities limited. Some restrictions may apply. Batteries not included.

Tags: ,

Apollo.Common in Codeplex

19. December 2008 04:53

The past few weeks, I've been working on Apollo.Common, which is meant to provide some easier to use functionality to enterprise applications.  A lot of this functionality, and more is provided by the MS PnP team's Microsoft Enterprise Library.  However, ent-lib tends to be overly complex, difficult to use, and require a lot of customization before you can get moving.  I want Apollo.Common to be easy to use, implement and deploy with a minimal learning curve. More...

C# Tip: Creating an Octal String from a Byte in C#

3. December 2008 18:19

Okay, so C# (.Net) has some awesome functionality for creating a hex string from a numeric value.  But what if you need an octal string for a binary value.  The real key is realizing that you need to move the value by 3 bits at a time for each octal number, and to XAND the value by 7 which is the highest value an octal number can hold. More...

Tags:

Refactoring

19. November 2008 19:29

Okay, there are two main reasons to refactor.  The first is clarity of code.  Since we have a working base, we can now concentrate on making our logic readable, breaking major blocks of code into separate methods, as well as possibly change how certain calls work.  The second major reason to refactor is for performance or scale.  One needs to first realize that scale and performance aren't always the same thing.  Scaling is about consistency, where performance is about speed.  The two often have the same result, but not always. More...

Tags:

MySite - Part 1

11. November 2008 22:14

My goal is to create a personal website application that implements the features needed, and wanted for someone who wants to create a personal site that extends beyond just a blogging engine.  I've been wanting to work with ASP.Net MVC and some other technologies, so I'll be focusing on using them in MySite. More...

Tags: , , ,

Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.