Navigation

Archive

<January 2009>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

Categories

Blogroll

Contact

Send mail to the author(s) Email Me

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way

Sign In
Copyright ©  2009   Jeff Klawiter . All rights reserved.
My Amazon.com Wish List

Pick a theme:
# Tuesday, October 28, 2008
by Jeff Klawiter - Tuesday, October 28, 2008 8:13:13 AM (Central Standard Time, UTC-06:00)
While browsing through MSDN blogs I came across this nice little post. http://blogs.msdn.com/dparys/archive/2008/10/28/neue-m-glichkeiten-in-c-4-0.aspx . After translating the page I found that he linked to the new C# 40 page http://code.msdn.microsoft.com/csharpfuture

I played around with VS 2010 last night. I was able to test the dynamic keyword. It works as advertised but the biggest thing one has to realize is using it removes intellisense for that variable. Compiling type safety as well. I hope they'll be able to add some sort of limited intellisense by looking at the last assigned type.

Also on the Dynamic front is DynamicObject. A new base object type that allows for on the fly Property declaration. The DynamicObject uses a PropertyBag (looks like a Dictionary<string,object>). You can declare properties on the fly. Like
public class MyBag : DynamicObject
{
// überschreibt Getter / Setter
} 
dynamic b = new MyBag();
b.Id = 124;
b.Name = "Windows 7"
b.Price = 499.99m;
b.IsAvailable = false;

One thing I was unable to figure out was the optional, default and named parameters. Again the blog provided some answers.

public void InsertCustomer( int customerId,
                          string companyName = "Neue Firma",
                          decimal creditLimit = 2000m )
{
}

InsertCustomer( 1, creditLimit: 2000m );  

InsertCustomer( creditLimit: 2000m, customerId: 1 );





Comments [0] #      C# | C# 4.0  |  kick it on DotNetKicks.com
# Monday, October 27, 2008
by Jeff Klawiter - Monday, October 27, 2008 7:03:34 PM (Central Standard Time, UTC-06:00)
Well I spent most of the day working on some peculiar problems with PICK. Then left to take my girlfriend out for her birthday. Just now catching up on whats gone on today at PDC. Man it seems like it was a huge day.

First off Windows Azure and the new .NET Services. From what I've read so far I can see some compelling uses for the .NET services and sharing content, id's and roles around the web.

The big one that I haven't seen much press on yet is C# 4.0. Looks like we are getting dynamic binding in the language. While this loses compile type safety it gives C# good ground against things like Ruby and PHP.

Named, Optional and Default parameters. Oh how I've been waiting for these since switching to .NET from PHP. I used to take advantage of these features all the time. It annoys me when I can use them in Attributes in C# but not on actual methods. I'm going to love this.

VS2010 and C# will CTP are available in a virtual PC here

Here's a better overview stolen from http://blogs.msdn.com/samng/archive/2008/10/28/microsoft-visual-studio-2010.aspx
  1. Dynamic binding. We've introduced a new type, dynamic, which behaves much like object, but allows the operations performed on your object to be bound at runtime instead of compile time.
  2. Named and Optional parameters. You can now specify default values for your parameters, allowing them to be optionally specified at the call site. We've also added the ability for your arguments to be passed by name, so that you can specify exactly which arguments you want to give, and refrain from specifying the rest (assuming they're optional).
  3. Com interop features. We've done quite a bit of work to improve COM interop. These include:
    • No ref for COM calls. For all COM calls that take ref arguments, you can specify an argument without a ref, and the compiler will generate a local for you and generate a ref to that local as the argument.
    • No PIA. We have introduced the ability to deploy your applications which use Primary Interop Assemblies (PIAs) without referencing the actual PIA at runtime. This allows compiling against them, but not needing to ship them with your application.
    • Implicit dynamic for COM types. We now give you the option of turning all objects returned from COM into dynamics so that you can perform late bound calls off of them instead of having to cast the result in order to make it useful.

Comments [0] #      C#  |  kick it on DotNetKicks.com
# Friday, September 19, 2008
by Jeff Klawiter - Friday, September 19, 2008 8:42:40 AM (Central Standard Time, UTC-06:00)
The company I work for, Sierra Bravo Corp, got its start connecting legacy PICK systems to the modern world. They accomplished this via a proprietary client-server protocol we internally call db_server (Official name is SierraDBC or BravoConnecter). Sure there are other PICK connection technologies out there none of them support multiple PICK systems and OS Platforms. Currently we support : D3, Universe, UniData, JBase, MvBase and others I don't remember right now.

I maintain the .NET client library. It was originally a port of the Java library which was a port of the COM library. It's come quite a long way since then. Recently we've found the need for compression to be added for some of our client. One in particular has many employees out in the field connecting via AirCards where bandwidth availability can be a problem. On top of that the application needs to retrieve quite a bit of real time data from the home office. Retrieving 2mb of client history is not unheard of.

After the server developer added compression to the result stream I started working on the client end. I figured it should be a snap. If we have compression turned on, just pass in a DeflateStream (fed by the NetworkStream of the TcpClient connection) to the StreamReader we already use to retrieve the results.

StreamReader ResultReader;
if (IsConnectionTypeSet(ConnectionOptionTypes.EnableCompression))
{
    DeflateStream dfs = new DeflateStream(ns,CompressionMode.Decompress);
    ResultReader = new StreamReader(dfs, Encoding.ASCII, false);
}
else
{
    ResultReader = new StreamReader(ns, Encoding.ASCII, false);
}
One would think that's all that it would take, right?

I was sadly mistaken. I would receive an exception (System.IO.InvalidDataException:"Block length does not match with its complement.") every time I would try to read from the stream.

The issue lies in the use of zlib for the compressed stream. zlib and DEFLATE use the same algorithm for compression. The difference is zlib sends two bytes of header data. So all the answers I found were to pop off the first two bytes of the stream.
StreamReader ResultReader;
if (IsConnectionTypeSet(ConnectionOptionTypes.EnableCompression))
{
    DeflateStream dfs = new DeflateStream(ns,CompressionMode.Decompress);
    ResultReader = new StreamReader(dfs, Encoding.ASCII, false);
    ns.ReadByte();
    ns.ReadByte();
}
else
{
    ResultReader = new StreamReader(ns, Encoding.ASCII, false);
}
 This worked just fine but I was annoyed about how ugly it looked. I needed to move that ugliness out of there. So I wrote a ZlibStream class to do this for me. I made it for only Decompressing streams since I didn't have the budget to go and actually implement the zlib headers.

[ZlibStream.cs]
    /// <summary>
    /// Supports decompressing a DeflateStream created by the zlib library
    /// </summary>
    class ZlibStream : DeflateStream
    {
        #region Fields

        private bool HasRead = false;

        #endregion

        #region Constructors
        /// <summary>
        /// Initiates ZlibStream in Decompress mode
        /// </summary>
        /// <param name="stream">One of the System.IO.Compression.CompressionMode values that indicates the action to take</param>
        public ZlibStream(Stream stream)
            : base(stream, CompressionMode.Decompress)
        {

        }
        /// <summary>
        /// Initiates ZlibStream in Decompress mode
        /// </summary>
        /// <param name="stream">One of the System.IO.Compression.CompressionMode values that indicates the action to take</param>
        /// <param name="leaveOpen">true to leave the stream open; otherwise, false.</param>
        public ZlibStream(Stream stream, bool leaveOpen)
            : base(stream, CompressionMode.Decompress, leaveOpen)
        {

        }
        #endregion

        #region Public Methods

        public override int Read(byte[] array, int offset, int count)
        {
            if (HasRead == false)
            {
                this.BaseStream.ReadByte();
                this.BaseStream.ReadByte();
                this.HasRead = true;
            }
            return base.Read(array, offset, count);
        }

        #endregion

    }
As you can see it is very simple. Since all the StreamReader does is call the Read method I just needed to remove those bytes during the first pass.  This class is extremely simple and limited in its functionality. Doing Asynchronous reads with BeginRead will not work. I checked via reflector and it does not use the DeflateStream.Read method. It handles the BaseStream's Read methods on its own.

The one thing I may need to expand is doing the popping of the two bytes. Currently it's not checking to see if the stream has any bytes to read. So far in testing this hasn't been a problem. I'm going to try and see if I can create a situation where the bytes are not available initially. I have a suspicion that the ReadByte() waits for a Byte to be available and errors out on the Timeout value

So my result is as elegant as can be
StreamReader ResultReader;
if (IsConnectionTypeSet(ConnectionOptionTypes.EnableCompression))
{
    ZlibStream dfs = new ZlibStream(ns);
    ResultReader = new StreamReader(dfs, Encoding.ASCII, false);
}
else
{
    ResultReader = new StreamReader(ns, Encoding.ASCII, false);
}

Comments [0] #      C#  |  kick it on DotNetKicks.com
# Monday, August 11, 2008
by Jeff Klawiter - Monday, August 11, 2008 1:20:39 PM (Central Standard Time, UTC-06:00)
Over the weekend I started Reading "CLR Via C#". I picked it up at Borders earlier this year with a certification book. I was trying to get more MCTS certs at the time and never ended up reading it. Also every time I look at it I feel like it's that black box I'll never be able to understand. I realized this is a bad attitude to have, so I opened it up and began reading. Instead of becoming lost, I feel like some things are becoming found.

I realize I should have read this book right away. So far nothing has been entirely over my head. I have had to reread some paragraphs due to sentences being heavy on the the terms. Also the author "Jeff Richter" tries to use the correct CLR terms and they sometimes clash with C# and general OO terms. An example is he uses "type" as the term for a static class.

I've made it 11 chapters in and so far it has been full of those "so thats how that works" and "thats good to know" moments. The biggest one so far has been the Events chapter. He covers a C# feature that has not been covered in any of the C# books I have read.

In C# you can declare Events like Properties. That is instead of using "get" and "set" blocks, one can use "add" and "remove" blocks. He covers this because the default implementation of events in the CLR is a bit flawed when it comes to thread safety. The CLR will lock the full object when adding and removing event delegates. He gives an example of overcoming these flaws by implementing manual locking in the "add" and "remove" blocks.

private event EventHandler<SomeEventArgs> somethingHappend;
private Object mLock = new Object();
public event EventHandler<SomeEventArgs> SomethingHappend
{
    add
    {
        lock (mLock)
        {
            this.somethingHappend += value;
        }
    }
    remove
    {
        lock (mLock)
        {
            this.somethingHappend -= value;
        }
    }
}
As you can see it looks much like a C# property. It uses a private event that is exposed publically through two blocks. Other than the keywords the other major difference is you cannot set access modifers on the "add" and "remove" blocks. It would be very bad programming to let someone add an event delegate but not let them remove it.

I have one application that I maintain where this will come in very handy. Planning on testing out the difference very soon.

I highly recommend this book for any serious .NET developer. I kick myself for not learning more about the CLR in the first place. Visual Studio sometimes babies the programmer too much I think. That and many programmers are lazy and love to just know enough to get by. I find these kinds of programmers have a very hard time working at Sierra Bravo. We have such a large variety of projects that one must learn quickly and know enough to jump the entire gammut of .NET applications. As a .NET developer here it's impossible to just be an ASP.NET developer or WinForms developer. I like it that way, it ensures that I'm never board and am learning all the time.

In my tenure so far I have written, Winforms Applications, entire .NET CF warehouse management applications, fully globalized ASP.NET web sites, various web services, various windows services, System Tray utilities, a Vending Machine controller program (implementing various serial protocols), written TCP clients for propietary protocols and much more. I have also helped companies migrate to/from MSSQL databases with various front ends. Heck, I'm even working on a C++ Win32 mobile application this week. I have done more in 3 1/2 years than a typical programmer does in 10 years.

Understanding how something works makes it much easier to implement a project with it. I found when I was a PHP programmer that I really went from amatuer to professional when I studied how PHP parses the script, allocates memory for variables. This is not an easy thing to do without looking at the source code. There are no good books out there about the "PHP Runtime". Knowing the rammifications of taking advantage of variable variables and not unsetting after use helped me take one of my more complext php programs and reduce it's memory usage 3 fold.

Comments [2] #      C#  |  kick it on DotNetKicks.com
# Sunday, June 29, 2008
by Jeff Klawiter - Sunday, June 29, 2008 7:57:50 PM (Central Standard Time, UTC-06:00)
Documenting code is one of those things that programmers tend to leave out while under a tight dealine or just building a new project. It's one of those things we tend to say, if we have time when we're done we can do it. It can be time consuming and sometimes hard to see the benefit up front. I'm very guilty of poor documentation and commenting. I rarely get to work in a team so I always end up relying on my own memory for what does what and where. Then two years go by and I forget it all.
Comments [0] #      C# | Documentation  |  kick it on DotNetKicks.com
# Tuesday, June 24, 2008
by Jeff Klawiter - Tuesday, June 24, 2008 6:25:49 PM (Central Standard Time, UTC-06:00)
Well I'm finally opening a real blog. Not sure how much I will be updating this but hey I have a real online presence again. The old J-Maxx Net will stay as it is. Still get a decent amount of traffic on there (kicking myself for not installing adsense years ago).

To start off with.. I love LINQ. I've been looking into it for over a year now but finally have a project where I get to use it fully. C# 3.0 has added so many features I no longer pine for PHP as I once did. Here's a sample below of something I wrote the other day.

            var result = from c in CurrentDataContext.Categories
                         join localinfo in CurrentDataContext.CategoryLocalizationInfos
                            on c.CategoryID equals localinfo.CategoryID
                         where c.CategoryID == CategoryID
                         && localinfo.Language == Language
                         select new Business.Data.Category()
                         {
                             ID = c.CategoryID,
                             Description = localinfo.Description,
                             Languages = GetLanguagesForCategory(c.CategoryID),
                             Name = c.Name,
                             SortOrder = c.SortOrder,
                             Title = localinfo.Title,
                             NavImage = c.NavImage,
                             Language = localinfo.Language,
                             Links = GetLinksForCategory(c.CategoryID, Language),
                             IsDataLoadedFromSql = true
                         };

Comments [0] #      C# | LINQ  |  kick it on DotNetKicks.com