Monday, July 6, 2009

Select * from table where column in %

This method allows you to filter a column based on a list supplied by the user or when the user doesn't supply anything to return all the results without using dynamic SQL.  You can use ANDs in the where clause to include additional filters.  In our application we parse a comma delimited string in SQL to get our list of user input.  SQL 2005 introduced table variables and you could probably use those instead.
--pretend this table contains all the states.
      declare @states table (identifier varchar(2))
      insert into @states
            select 'MI' UNION
            select 'CO' UNION
            select 'NY'

--this simulate states selected in the application
      declare @selectedStates table (identifier varchar(2))

--insert a state to simulate the user selecting a state.
      insert into @selectedStates --comment this line to see @allStates flip
            select 'MI'           --comment this line to see @allStates flip
declare @allStates bit

--if the user hasn't selected a state get all the results.
if ((select count(*) from @selectedStates) = 0)
      select @allStates = 1

--give back the results:
select identifier from @states
      where (identifier in (select identifier from @selectedStates) OR @allStates = 1) AND 1=1 --additional filters could go here instead of 1=1


Monday, June 15, 2009

Untrusted Project Location When Opening Solution

I downloaded source from a CodePlex project last night.  After unzipping the source to my hard drive and opening the solution I was bombarded with errors of The project location is not trusted: c:\... Running the application may result in security exceptions when it attempts to perform actions which require full trust."  I had to click OK for the solution and once for each project file.

Searching the web I ran across Colin Mackay's blog with a post explaining since Windows XP Service Pack 2 when downloading zip files an Alternate Data Streams (ADS) with a zone identifier are added in NTFS.  During unzipping the zone identifier is propagated to the solution and project files.  As Colin explains there are programs which can remove the ADS zone identifier.  I found out the best way to resolve this without downloading a tool is to right click on the properties of the archive, and at the bottom of the properties dialog in the security section click the Unblock button.  Then when the archive is unzipped the solution and project files won't have a zone identifier included.  One can also click the unblock button on each project and solution file after unzipping although this isn't as efficient.

Monday, June 1, 2009

Milton Friedman for your reading pleasure

These quotes made me laugh out loud. Not necessarily because I disagreed: http://www.brainyquote.com/quotes/authors/m/milton_friedman.html

Enjoy :)

Monday, May 25, 2009

Customizing the Microsoft .NET Framework (Book Review)

Last week I finished Customizing the Microsoft® .NET Framework Common Language Runtime.  This book was mildly interesting with lots of code samples making it a good reference book for those writing CLR hosts within their application.  Most of the chapters discussed features from the perspective of SQL Server requirements and then an implementation of the feature.  It seems like a lot of work to leverage the full customization capabilities of the CLR with minimal benefits.  A lot of the configuration can be done via XML as well further reducing the benefits of writing your own CLR host.

Monday, April 13, 2009

Why did my machine blue screen?

My machine blue screened this morning and restarted itself.  I went into safe mode and then restarted normally with no problems.
But I was concerned about why my computer blue screened.
Using WinDbg, which is part of the Debugging Tools for Windows package I was able to determine the cause:
ERROR_CODE: (NTSTATUS) 0xc0000218 - {Registry File Failure}  The registry cannot load the hive (file):  %hs  or its log or alternate.  It is corrupt, absent, or not writable.
ADDITIONAL_DEBUG_TEXT:  \SystemRoot\System32\Config\SOFTWARE - hive could not be loaded.
Here are the steps I followed:
  1. Installed debugging tools.
  2. Looked at my System Properties --> Startup and Recovery Settings --> small dump location
  3. From a command prompt:"c:\Program Files\Debugging Tools for Windows (x86)\windbg.exe" -y srv*c:\symbols*http://msdl.microsoft.com/download/symbols -z c:\windows\Minidump\Mini032709-01.dmp
  4. from the WinDbg prompt: !analyze -v
  5. Read the results.

Monday, April 6, 2009

My Personality Type

My type: ENTJ

Outgoing, logical and decisive, the ENTJ leads by providing conceptual structure and setting goals, rather than by detailing and enforcing procedures, codes and regulations. This “big picture” type rises naturally to conspicuous positions of power and responsibility in all organizational settings (business, military, educational, governmental.) Disorganization, confusion, emotion, inefficiency and illogic drive ENTJs to take charge of situations and institutions. Their intuition fuels their vision and defines their goals. They deal with the world boldly, in an assertive, analytical, objective and organized way which inspires others to salute them and do whatever the ENTJ needs done--including all the detail work! ENTJs certainly do get things done, both at home and at work, but often at substantial cost in terms of wear and tear on the human spirit, for they may neglect the importance of the personal element in accomplishing their purpose. More than any other, this type seems to struggle between an inner drive toward creative spontaneity and the desire for order in the universe.

Final Score: Extrovert: 7 Sensing:5 Thinking:9 Perception:1 Introvert: 2 iNtuition:4 Feeling:0 Judging:8

Monday, March 30, 2009

Marketing Your Business in Detroit via Viral and Social Media

I went to my frist Model D event which was co sponsored by Open City
Charlie Wolborg and Terry Bean gave an captivating presentation on social media giving me a lot to think about over the past couple days.  It is why I signed up on Twitter as smithd98.
Here are my notes from the meeting:
Social Media Categories:
  • Online Rolodexes
  • Blogging
  • Feeds - like magazine subscriptions
  • Video
  • Photos - Facebook has the most photos of any social sites.
  • Podcasts
  • Bookmarks
  • Networks
Passion - be remarkable
In six months more content is uploaded to YouTube than has been created in 60 years of NBC and CBS programming.
Facebook's #1 growing demographic is 30 and older.  This means your customers are on or will be on Facebook.
  1. Ready. Fire. Aim.  - it is most important to have a presence on these networks and refine the presence later than getting it right the first time.
  2. Join All.  Participate Few.  - The flood of information from all the social sites will overwhelm you.  Find out which sites your customers use and play in that space.
  3. Go to Where Your Prospects Play
    1. LinkedIn --> web jobs --> simplyhired shows who works there.
    2. MySpace - important for entertainers and artists
    3. MotorCityConnect - if you are in the Detroit area.
    4. Facebook - allows you to connect with your past.
      1. People hang out on Facebook like it was a club.  This is different than transactional where users seek out a service from a site.
      2. Fan pages can be created for companies and products.
    5. Twitter - this is where you can go to initially make contacts.  These are the early adoptors.
  4. Personal Brand Optimization
  5. Social Media is a conversation not a sales pitch.
  6. Feed Your Networks and stay visible.  FriendFeed can help
  7. ROI or Die
  8. Find your golden ratio - give value to these networks, don't just try to monetize them.
  9. Build it before you need it - relationships take a long time to build and need nurturing.  Do that in advance of a need.
  10. Tools are not the tactics - hire a professionals like Networked inc

Wednesday, February 4, 2009

Binding to XAML declared types with non-default constructors using ElementName binding syntax

Some of our XAML files were using Element name binding like this Binding="{Binding ElementName=Window}" to bind to the class itself.  While refactoring and adding a non default constructor Visual Studio complains: "The type CLASSNAME cannot have a Name attribute. Value types and types without a default constructor can be used as items within a ResourceDictionary."

For most of the day I changed class bindings to use DataContext = this in the constructor or FindAncestor calls at the binding declaration.  Late in the day I ran into an infinite recursion problem.  Not wanting to diagnose it I found an MSDN article pointing me to use RegisterName("Window", this); in the constructor after InitializeComponent() to work around the issue.

Wednesday, January 28, 2009

Tracking down boxing

I just found a cool extension, CodeSearch, for Reflector, a disassembler for .NET assemblies.  I used it to search some of our code for the Intermediate Language box instructions and unbox.

I found a lot more of those than I'd hoped.  But in my test cases they all seemed to be necessary.

Wednesday, January 21, 2009

Converting Com ErrorCodes to friendly messages

Using PerfMon to do some .NET profiling today, I wanted the ability to easily retarget my counters at a specific application running on my machine.

Everything went very well except for the error handling.  When adding my counters a  COMException may be thrown.  The Exception's message has the hex error code while the ErrorCode property has the value as an integer. I used the following code to convert the ErrorCode to be comparable against hex values provided by MSDN.

UInt32 errorCodeLookup = 0;
unchecked
{
    errorCodeLookup = (UInt32)comException.ErrorCode;
}

I didn't end up using this method as it was my own application.  I thought about using a uint enumeration to store all the error codes and then a dictionary to go lookup the user friendly error messages provided by MSDN, but since it is just a scrap app I didn't bother.

Wednesday, January 14, 2009

Identifying Duplicated Code (Refactoring Opportunities)

On our project we have some accidentally similar code and some knowingly similar code.  Today I found a great tool we could easily incorporate into our Continuous Integration Process to stop code duplication.

Simian, a configurable command line utility, took less than 5 minutes to setup and cranked through 204,930 lines of C# in about 6.5 seconds.  The application is free for noncommercial use and can be evaluated free of charge for 15 days.

Friday, December 19, 2008

Coding WPF styles in C#

WPF styles let you specify the look of your controls consistently across your application.  Today I needed to create menu items in a different part of the application based on the currently focused element.
I got the menu creation code to work, and then wanted to apply my WPF style instead of typing a bunch of header names in and then maybe having to change them later.

Here is the WPF style:
<Button.ContextMenu>
   
<ContextMenu>
       
<ContextMenu.Resources>
           
<Style x:Key="{x:Type MenuItem}" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
               
<Setter Property="Header" Value="{Binding Command.Name, RelativeSource={RelativeSource Self}}"/>
           
</Style>
       
</ContextMenu.Resources>
   
<MenuItem Command="ApplicationCommands.Cut"/>
</Button.ContextMenu>

Here is the C# equivalent:

new returnValue = ContextMenu();
//base our style on the current MenuItem Style. No need for null check.
var headerStyle = new Style(typeof(MenuItem), TryFindResource(typeof(MenuItem)) as Style);
var commandNameBinding = new Binding("Command.Name");
commandNameBinding.RelativeSource =
RelativeSource.Self;
headerStyle.Setters.Add( new Setter(HeaderedItemsControl.HeaderProperty, commandNameBinding));
returnValue.Resources.Add(typeof(MenuItem), headerStyle);
returnValue.Items.Add(new MenuItem() { Command = ApplicationCommands.Cut });

Thursday, November 27, 2008

XAML factoring


We are using the Infragistics Ribbon component in our application.  Our application has the same Ribbon Group content specified in multiple tabs.  I was looking for a way to share the group content so it wasn't copied and pasted in both locations.

I searched online and found a forum where one of their staff said it was not a feature.

This is not a problem as WPF allows you to share UI elements for compiled resource dictionaries.

When we compile XAML we get BAML stored inside the assembly as a resource.  This allows the x:Shared keyword to enable special functionality not available from C#.   Why not IL?  BAML is more compact than IL, can be localized after compilation, and is less of a security threat.

Specifying x:Shared in a resource dictionary means the content will be fetched new each time it is requested allowing the same user interface elements to be added in multiple places.

Here is an example:
    <Window.Resources>
        <StackPanel x:Key="moreContent" x:Shared="false">
            <TextBlock Text="local" />
        </StackPanel>
    </Window.Resources>
    <StackPanel>
        <StaticResourceExtension ResourceKey="moreContent" />
        <StaticResourceExtension ResourceKey="moreContent" />
    </StackPanel>
One may also put the shared content in another XAML file to share the resource with other XAML files in your application:
Window1.xaml

    <Window.Resources>
        <ResourceDictionary >
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Ribbon.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <StackPanel x:Key="moreContent" x:Shared="false">
                <TextBlock Text="local" />
            </StackPanel>
        </ResourceDictionary>
    </Window.Resources>
    <StackPanel>
        <StaticResourceExtension ResourceKey="moreContent" />
        <StaticResourceExtension ResourceKey="content" />
        <StaticResourceExtension ResourceKey="moreContent" />
    </StackPanel>

Ribbon.xaml:
    <StackPanel x:Key="content" x:Shared="false">
        <TextBlock Text="From Ribbon" />
    </StackPanel>
</ResourceDictionary>

Thursday, November 20, 2008

Clarity of intent and newing up structs

Sometimes it is useful to see if a struct hasn't been set.  Of course this can get you into trouble if the unset value is a legal value, but sometimes it's not, like when dividing an int 0 will throw.

Previously I had been using code like if (divisor != new int() ) to check the value prior to calling my function.

This struck me as very odd to be newing up a struct.

Then I recalled the default keyword, which I'd only used for generics before.  It turns out default works the same and declares intent better.

if (divisor != default(int) )
{

}

Of course in this contrived example it makes more sense to do != 0, but when more complex structs are involved the syntax works quite nicely.

Tuesday, November 11, 2008

Visual Studio Post-Build Events.

I haven't been a fan of Visual Studio Post-build command line events.

Problem:
We need to copy app.config during the build process and it needs to be mstest.exe.config in the test out directory.  During our Unit Testing process on the build server we've been referencing a static class to provide all of our configurations.  Now we are switching over to a real file.  This makes all the unit tests referencing our configurations fail because System.Configuration.ConfigurationManager.GetSection returns null.  The problem is our unit tests are being executed by MS test.  Ideally we would maintain a configuration class reading from a file and a configuration class for testing which uses test values.  Unfortunately due to time pressures that is not an option.

Solution:
By going into Visual Studio, project properties, Build Events Tab, Post-build event command line and typing copy "$(ProjectDir)app.config" "$(TargetDir)mstest.exe.config" /y
MSDN describes the $(ProjectDir) and $(TargetDir) variables
In our testrunconfig file we have a Deployment section and then a DeploymentItem with filename set to mstest.exe.config.  My frist thought was to do the file copy on our build server after getting the source files and then have our testrunconfig file copy the mstest.exe.config using a DeploymentItem.  Thinking about it for a minute I realized this would cause differences when we are building in Visual Studio and when we are building on the server which would easily cause confusion in the future.

Not to happy we are relying on the filesystem for our test, but happy that the build behaves the same on desktops and servers and anyone can figure out what is going on.

Wednesday, October 29, 2008

Freeing space on your computer by customizing Visual Studio

My computer has been running slowly lately which really bothers me.  I went to defrag my hard drive and didn't have 10% free space disk defragmentor recommends.

I use a utility called TreeSize which presents a navigable tree view of how much space each folder is consuming.

Previously I took for granted the fact that Visual Studio 2005 consumes 2,730 MB and Visual Studio 2008 eats up 2,562 MB.  This time I decided to look at why the are such hogs.  It turns out in my Visual Studio 2005 installation c:\program Files\Microsoft Visual Studio 8 there is a sub folder VC taking up 1,574MB.  This is for Visual C++ 2005 which I never plan to use.  Using Add / Remove Programs and clicking Change/Remove on Microsoft Visual Studio 2005 Team Suite - ENU allowed me to easily remove Visual C++ 2005.

I'm keeping Visual C++ 2008 because I hope to play with it in the next six months or so.

During this exercise I also noticed OneNote sucking up 2,616 MB.  1,646 of it for backup files.  Our notebooks are on a network location so I don't need to be backing these up.  I turned it off by opening OneNote going to Tools, Options, Backup and unchecking "Automatically Backup".

Wednesday, October 22, 2008

Books I've read this past year

These are the books I've read this past year in roughly the order I read them.

Programming .NET Components, 2nd Edition - Covers many advanced topics on application maintainability, extensibility, and reusability.  Some of the greatness was lost on me at the time because I didn't see the applications of the ideas.  I recommend reading this book after having a thorough understanding of .NET and programming.  I forgot how great this book was and I'll probably be re-reading it.

MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 Application Development Foundation - Good introductory book about the .NET framework.  Skip it if you are already comfortable with framework classes.

Extreme Programming Adventures in C# - A fun quick read.  It makes some interesting points about extreme programming.  The book discusses a small project developed by one and a half developers.  I would be more interested in a book discussing a larger team to see how the process scales.

Code Complete: A Practical Handbook of Software Construction - Should be read by all programmers.  It goes into great depth discussing seemingly mundane topics and explains why they aren't trivial.

Software Project Survival Guide - Another great book by Steve McConnell.  It is thought provoking and may enlighten you to aspects of your development process you can improve.

The Pragmatic Programmer: From Journeyman to Master - Seemed to be Code Complete light to me.  It covered a lot of the same issues in less depth.  If you read Code Complete you can skip this book or read it first to whet your appetite.

The Mythical Man-Month: Essays on Software Engineering, Anniversary Edition (2nd Edition) - Discusses large scale software construction and team scalability challenges.  People often summarize it by saying you can't make a baby in nine months.  I don't think this summary does justice to the book and recommend you read it.

Windows Presentation Foundation Unleashed (WPF) (Unleashed) - This was a good introduction and overview of WPF.  You should read this book or something like it before professionally programming in WPF.

Programming WPF - This book deep dives into WPF.  After you've been professionally programming WPF for a couple weeks this book should help increase your understanding of the technology.

The Build Master: Microsoft's Software Configuration Management Best Practices - Short guide to building and deploying software.  Good read for developers who've been appointed the build master for their project.  If you find yourself in this situation consider using Windows Installer XML (WiX).  It allows you to build your install files via XML and fits perfectly with MSBuild.

Thursday, May 1, 2008

Extreme Programming Adentures in C# (book review)

At the Central Ohio Day of .NET last week I won Extreme Programming Adventures in C# (DV-Microsoft Professional) by Ron Jeffries. The book is a case study about using XP programming on a small scale project and team. It is well written and immediately sucked me in. I have been experimenting at work by trying the simplest thing that works and using test driven development.

Wednesday, April 23, 2008

Central Ohio Day of .NET 2008 Synopsis

I rode down to the Central Day of Central Ohio Day of .NET 2008 with Rich Hamilton and Joe Kunk on Saturday.



I attended these session:


  1. A Linq to Everything (Leon Gersing)

  2. User Interface Design for Programmers (Chris Poteet)

  3. Happy Marriage of Agile and TFS (Alexei Govorine)

  4. Test Driven Development (Phil Japikse)

  5. Well, Isn't that Spatial... (Jason Follas)

I had heard of recording users running an application but have never done it before. Chris's presentation had some recorded user sessions. It was interesting to watch the sessions and listen to his commentary about the design changes viewing the user interaction caused.


After the conference Jeff Blankenburg held a poker tournament back in his hotel room. It was a lot of fun to hang out with like minded individuals in a casual atmosphere. This was my favorite part of the conference.

Tuesday, April 22, 2008

00 Querying Named instance Linked SQL Server

This is how you query against a linked named instance of sql server.


sp_addlinkedserver 'servername\instanceName' --create the link.

select * from [servername\instanceName].databaseName.dbo.TableName --execute the query.

Wednesday, April 16, 2008

Search for Detroit Software Developer Community

I ran across an interesting group this morning in my search for the Detroit Software Developer Community: the detroit software engineers' grotto. The group's goal is interesting for anyone to read. They are trying to rent a space for software engineers to work instead of their office. The space will have comfortable couches, chairs, and like minded individuals. It is modeled on a Writer's Grotto founded in San Francisco.

Unfortunately for me it states Windows is a legacy operating system, Web 2.0 is dead, and Mac OS X is the wave of the future. Interesting ideas.

I'm looking to get involved in the Detroit software developer community. We have companies with lots of developers here: Compuware, Electronic Data Systems (EDS), Accenture, and Deloitte come to mind right off the top of my head.

The Great Lakes .net Users Group, but as that is in Southfield I have to battle traffic to get out there. I came from the Lansing area which has a great developer community especially for the relatively low population of the area. Being involved in the Greater Lansing User Group .net continues to positively impact my life.

This morning I went looking for the Detroit developer community. My assumption is that it must exist given the larger population and I'm just not connected. Yet :)

Tuesday, April 1, 2008

Clustered Index slows down BCP signiificantly

Our 19 hour job was reduced to about 30 minutes using this technique.

We had to import 110 million rows into a SQL Server table containing 5 ints during 4 import sessions. There was a clustered index over 4 of those ints.

We used the System.Data.SqlClient.SqlBulkCopy class to do the import (class mirroring the sql server bcp utility). The initial import took ~19 hours. On a new table we removed the clustered index and inserted all the rows again. This took about 12 minutes. Applying the clustered index took about 20 minutes.

Monday, March 24, 2008

Programmatically Executing SQL Scripts

I didn't realize GO is not a SQL keyword. When I was trying to execute a script that worked in SQL Server Management Studio I was getting SQLException Incorrect syntax near 'Go'. The solution is to split the input script on GOs and execute those scripts.

const char splitChar = '☻'; //this character should never appear in command files
if (createDatabaseScript.Contains(splitChar.ToString()) == true)
throw new Exception("Aborting. Splitting this file may break the script because the script contains the split character");
using (dbConnnection)
{
dbConnnection.Open();
SqlCommand createDbCommand = new SqlCommand(string.Empty, dbConnnection);

//split the input script into multiple scripts based on GOs
foreach (string command in createDatabaseScript.Replace("GO", splitChar.ToString()).Split(new Char[] { splitChar }))
{
try
{
createDbCommand.CommandText = command;
createDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
//log the error for later review.
results += ex.Message + Environment.NewLine;
}
}
}
Console.Write(results);

Monday, March 17, 2008

FxCop bug - CA1709 & CA 1707

CA 1707 IdentifiersShouldNotContainUnderscores
CA 1709 IdentifiersShouldBeCasedCorrectly

I ran into a surprise last week. FxCop is throwing warnings for properties on 2 out of 5 interfaces in a particular project. Interface A implements interface B.

I'm assuming the bug described in this article is causing it: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2344375&SiteID=1 and that it will be fixed in Visual Studio 2008 Service Pack 1.

Monday, March 10, 2008

Unit Testing Graphics Operations

We decided to verify our graphic operations here by doing a binary comparison.
Here is a simple implementation using Linq.

Setting up the expected value:

Bitmap aBitmap = new Bitmap(181,46); //exact size of the bitmap to reduce the number of bits
Graphics aGraphic = Graphics.FromImage(aBitmap);
target.DrawGrid(aGraphic); //the operation you want to verify
MemoryStream actual = new MemoryStream();
aBitmap.Save(actual,ImageFormat.Bmp);
string aBunch = string.Join(",", actual.ToArray().Select(b => b.ToString()).ToArray());

Copy the string aBunch. We will use this to create the expected byte array.
create the byte array like this but use your pasted values instead of my values
byte[] expected = new byte[] {66,77,78... };

Finishing the unit test:

Bitmap aBitmap = new Bitmap(181,46);
Graphics aGraphic = Graphics.FromImage(aBitmap);
target.DrawGrid(aGraphic);
MemoryStream actual = new MemoryStream();
aBitmap.Save(actual,ImageFormat.Bmp); // get our actual result.
byte[] expected = getExpected("DrawGridTest");

Assert.IsTrue(actual.ToArray().SequenceEqual(expected),"Binary comparison failed.");

This method is getting expected from a function because Visual Studio responds slowly when there are long lines of text. I created a partial class containing the instantiation of expected (I'm using a switch statement). I thought about putting the results in a resource or a file, but I'm preferring code for now.

Friday, February 29, 2008

Speeding up Unit Testing in Visual Studio 2008

I've been doing unit testing in Visual Studio 2008. I noticed it takes a while for the tests to execute after I start the test run.

Initially I thought it was copying data into the TestResults directory. Some of our unit tests rely on files and our test run copies ~30 MB of data into the TestResults directory.

I found out it was the code coverage instrumentation process slowing it down. On my machine it seems to take about a second to instrument an assembly for code coverage. Our project has 8 assemblies which adds ~8 seconds to every run. While it is important for our server build to have all the assemblies instrumented, when I'm creating unit tests I just need to have my assembly instrumented. Going into the GeneralRun.testrunconfig --> Code Coverage and instrumenting only the assembly I'm working on reduces the run speed by about 7 seconds.

If you do this, ensure you don't accidentally check this change into Team Foundation Server or you won't get complete code coverage results.

Skipping the deployment of the 30MB of data had no noticeable effect on the test run times.

Monday, February 25, 2008

Creating a metafile in .NET

Metafiles are a way to save scalable vectory graphics. This blog creates a simple image containing a diagonal line. It also shows the proper way to save the metafile, as the class method saves it as a png file.

MSDN article on MetaFiles: http://msdn2.microsoft.com/en-us/library/ms536391.aspx



using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;




MemoryStream metafileStream = new MemoryStream();


Graphics offScreenDC = Graphics.FromHwndInternal(IntPtr.Zero);


IntPtr myImagePointer = offScreenDC.GetHdc();


Metafile meta =
//new Metafile(myImagePointer, EmfType.EmfOnly); //unable to do memoryStreamSave
new Metafile(metafileStream, myImagePointer, EmfType.EmfOnly); //able to do memoryStreamSave


Graphics aGraphic = Graphics.FromImage(meta);


aGraphic.DrawLine(new Pen(Brushes.Black), new Point(0, 0), new Point(29, 29));


aGraphic.Dispose(); //Dispose must be called to flush the drawing instructions.


offScreenDC.ReleaseHdc();
meta.Save(@"c:\metaSave.wmf"); //saves as a png file.


FileStream aWrite = new FileStream(@"c:\StreamSave.wmf",FileMode.Create); //saves as a wmf file


metafileStream.WriteTo(aWrite);

Saturday, September 22, 2007

Rudolf Melik, CEO of Tenrox speaks at PMI-MCAC

I'm the Vice President of Programs for the Project Management Institute Michigan Capital Area Chapter (PMI-MCAC). Our 2007-2008 program year inaugural meeting featured Rudolf Melik, CEO and one of the founders of Tenrox. He gave a great presentation on Empowering Your Project Workforce. During his presentation he mentioned how business is changing due to globalization, workflow tools, outsourcing, off shoring, and the internet. Mr. Melik discussed ways to avoid MESS (Meetings Email & Spreadsheets) to increase productivity. On a personal level he recommended committing to projects, de-commoditizing your job, leveraging other individuals, keeping up with innovations, and using 21st century tools.

Thursday, September 13, 2007

Jay Wren speaks at Flint branch of GLUG.net

Jay Wren gave an excellent demonstration of Test Driven Development at the Flint branch of GLUG.net monthly meeting last night. We had nine members in attendance and everyone got a prize.

Jay is relatively new to speaking. I was very impressed by his personable, enthisiastic, and engaging style. He replied with well thought out answers to each question he was asked. He introduced Test Driven Development with a few slides and then dove into a live demo of NUnit. He asked the audience for sample requirements and used the non trivial task of developing a two way dictionary as his sample. Generally I dislike live coding samples because things go wrong. Jay showed his .net prowess and mastery of Coderush by quickly correcting all type os and errors.

I think Jay summarized test driven development with this statement "How do I use this vs. what do I need." When we code first we are creating what we need. When Jay codes tests first he is consuming his API and thus gains a new perspective on the API which leads to better design and usability.

Jay briefly gave a demo of NCoverExplorer and Coderush. I recently installed Coderush, and thanks to Jay's brief demo I started effectively learning it today. NCoverExplorer is a test analysis tool which shows executed lines, cover % how many times a particular method was called etc.

I was reading Jay's blog today which has some good entries.

Friday, August 17, 2007

Jeff McWherter speaks at GLUG.net

Chris Woodruff was scheduled to speak at our .net user group last night. Unfortunately he came down with the flue. Luckily Jeff, one of our program directors, stepped up and gave a presentation on Optimizing and Performance Tuning your ASP.net Applications.

Jeff has a cool website where you can do a bit of stalking to see what TV shows he is going to record, and if he is at home (based on if his laptop is on the network or not).

We had 17 members attend and everyone won a prize!

Thursday, August 16, 2007

Inagural Flint branch of GLUG.net Meeting

We had 10 members attend our inagural Flint branch GLUG.net meeting yesterday. Paul Kimmel presented on Visual Studio 2008. His presentation was very technical and interactive. The smaller audience size allowed us to ask questions and prompted discussions. If you are interested in some of the new features in Visual Studio 2008 have a look at Paul's blog.

Friday, August 10, 2007

SQL Server random number generator

This SQL Script generates a random number between 1 and 5.

It demonstrates a few interesting ideas:
1) Temporary tables - These are in memory temporary tables (I use these all the time)
2) SQL Server looping with While (you may use these instead of cursors. I've heard cursors are slower)
3) Random number generation with newid() (select top 5 * from [table] order by newid() returns 5 random rows.
4)

declare @tempTable table (column1 int) --declaring a temporary table
declare @i int
set @i =1
While @i <=1000000 begin insert into @temptable (column1) select abs(cast(cast(newid() as varbinary) as int))%5+1 set @i = @i +1 end

--select * from @temptable

select column1 as [value],count(*) as [Occurrences],
cast(count(*)*100 / cast((select count(*) from @temptable) as decimal) as int) as [Percentage] from @temptable
group by column1

Wednesday, July 18, 2007

Jing, a Free Image Capture & Screen Recording tool

TechSmith released a free image capture / screen recorder tool yesterday called Jing. I focused on the video recording features because we have SnagIt here at work. Jing is very easy to use. I installed it, configured it (setting up Screencast), and created a video in about 10 minutes. Jing is cool because it allows you to record your entire screen, an entire application or objects within applications. After recording one click sends your video up to Screencast and even puts the URL to your video in your clipboard!

We will probably use this tool for training.

Thursday, July 12, 2007

Greater Lansing User Group .net (GLUG.net) July Meeting

Where: 1145 Engineering Building, Michigan State University

When: Thursday July 19th 6:00-8:00 PM

What: We always have give away hundreds or thousands of dollars worth of swag along with free pizza and pop for everyone. This month we will also be announcing the opening of the Flint branch and our Vice President Vivek has secured all our membership 100 MB of free hosting from Verio.

Julia Lerman will be our first female speaker. She will be presenting on ADO.NET Entity Framework.

Visit our website for more details: www.glugnet.org

Friday, July 6, 2007

Updating Binary Data in a Gridview

Our customer needed the ability to update an image in a database. I wanted them to be able to view and edit all the data through the datagrid.

In your data source you need to specify the select command to display the data and the updateCommand to update the data:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:campDBConnection %>"

SelectCommand="usp_CAMP_get_rejected_batches"
SelectCommandType="StoredProcedure"
UpdateCommand="usp_camp_resubmit_deposit_ticket"
UpdateCommandType="StoredProcedure">


<UpdateParameters>
<asp:Parameter Name="deposit_id" Type="Int32" />
<asp:Parameter Name="deposit_slip_no" Type="String" />
<asp:Parameter Name="deposit_date" Type="DateTime" />
<asp:Parameter Name="Amount" Type="Decimal" />
<asp:Parameter Name="image" /> </UpdateParameters>
</asp:SqlDataSource>


I used a TemplateField to include the FileUpload control which allows a user to select a file from their computer for upload. This also allowed the same column to be used to display the image and change it.

<asp:TemplateField HeaderText="Deposit Ticket">
<EditItemTemplate>
<asp:FileUpload ID="imgUpload" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Image ImageUrl='<%#DataBinder.Eval(Container.DataItem, "DEPOSIT_IMAGE_URL")%>' runat = "server" />
</ItemTemplate>
</asp:TemplateField>

I needed to add in the binary data into e.NewValues:

Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating

e.NewValues.Add("image", CType(GridView1.Rows(e.RowIndex).Cells.Item(5).Controls(1), FileUpload).FileBytes)

End Sub


I also found a couple more gotchas:

  1. To format data in the grid you need to have HtmlEncode
    turned off

  2. For the upldate to send the primary key field and have that field set to invisible you need to specify the primary key in the DataKeyNames property for the GridView.

Friday, June 15, 2007

ArcREADY: Reinforcing the Foundations of Solutions Architecture

I went to ArcREADY: Reinforcing the Foundations of Solutions Architecture in Grand Rapids. It was presented by Josh Holmes. Josh presented these ideas by making analogies between software and other products (Wii, Xbox, can openers, Espresso makers etc.)

Here are my main take aways from the presentation:

Steps in architecting the user experience:
  • User Interface Design
  • User Research
  • Design Planning
  • Information Design
  • Usability Testing

There are 4 concepts to consider when architecting the user experience:

  1. Function (works great)
  2. Aesthetics (looks great)
  3. Interaction (relates to you)
  4. Process

There are 3 business principles to consider:

  1. What is possible?
  2. What is viable?
  3. What is desirable to users?

Tuesday, June 12, 2007

XSLT Tool - Cooktop

I've been using XML Notepad to help view XML files. Unfortunately XML Notepad doesn't have an XSLT editor.

I found a free one today: Cooktop

It worked for what I wanted and it was free. I would like to have one tool for viewing XML files and editing XSLT, but I don't like CookTop's display as well as I like XML Notepad's hierarchical view

Tuesday, May 29, 2007

Visual Studio 2005 Class Diagrammer

I like the Visual Studio 2005 Class Diagrammer

I looked at the Visual Studio 2005 Class Diagrammer briefly when I first started using the product. I didn't think it did much, thought Visio was better, and didn't use it anymore. End of story.

While preparing a presentation on my current project I found Visio wasn't creating the pretty diagrams I wanted. I decided to try the Diagrammer again. After you create a class diagram, you can hit the + key or hit the triple upside down ^ icon to get the diagram to expand. It does a nice job of displaying your class.

I've found a few useful features in the class diagram menu: Show Base Class, Show Derived Class, Change Members Format --> display full signature. There is also a Refactor -->Extract Interface which looks handy.

Changes made to the diagram or in code are instantly synchronized between the two.

Unfortunately there is no integration between Visio and the Class Diagrammer. You can click on an object in the class designer and copy paste it as a picture into PowerPoint Visio (I took independent pictures of each object and created new connector lines in Visio)

.NET report viewer page display problem

We had a problem getting our report viewer to display the current page and page count in the ReportViewer Control.

After searching around on the internet we found a fix. This fix has to be implemented after the page renders (trying to do it right after setting the zoomMode or after form.show won't update the page numbers)

'''
''' This is to get around a bug in the report viewer which caused it not to display the page numbers.
'''

''' ReportViewer1.SetDisplayMode(DisplayMode.PrintLayout)
''' ReportViewer1.ZoomMode = ZoomMode.PageWidth
'''

'''

''' The fix was found here; http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=297814&SiteID=1
Private Sub ReportViewer1_RenderingComplete(ByVal sender As Object, ByVal e As Microsoft.Reporting.WinForms.RenderingCompleteEventArgs) Handles ReportViewer1.RenderingComplete ReportViewer1.SetDisplayMode(DisplayMode.PrintLayout)

ReportViewer1.ZoomMode = ZoomMode.PageWidth

End Sub

Wednesday, April 18, 2007

Elected to Greater Lansing User Group .net

I was elected as a Program Director for the Greater Lansing User Group .net this evening.



Attendance is around 35 people per meeting which puts us in the top 10% of .net user groups nationwide.

Friday, April 6, 2007

April 2, 2007 Emerging Trends on the Internet
Sasha Verhage, Design lead for Google

Technology - focus on usability and the end result not technology ie. Ajax - some product managers want to 'ajaxify' products. Only do it where it makes sense.
· Google Maps
o Craig's list mashup
· Yahoo Mail – looks like Outlook.
· Ajax programming reduces page views and companies need to find alternate revenue streams (less ad views)

Live Testing
· Google Ads
o in one test changing the font can impact revenue. One test showed bolding search terms in ad results increased revenue 8%
o colors are also important. Green link colors for ads tested very high
o bucket testing (segmenting users into control groups and test groups)
o changing colors can increase revenue (7%-15% in one example based on 200,000 people
· blue color schemes generally win across all demographics
· Brand, Brand Halo - blind 'taste tests' remove branding from websites for blind
User Generated Content
· Use when appropriate (ie travel rating sites, Google Sketchup/Google Earch)

Attention Economy is real
· People trying to do more at once with technology (cell phones, ipods, facebook, myspace)
· multitasking is overrated (it takes ~15 minutes to return to a task you were deeply concentrating on prior to interruption)
· one study estimated interruptions and recovery time at 28% of employee time
· attention has economic value (free cell phones with voice ads, Slate.com customers can pay to have ads removed)

Search Engine Optimization
· SEO increases your likely hood of showing up based on the algorithm and what the user expressed
· trip Advisor gaming Google (the phrase 'Las Vegas' was memtioned 62 times per page on this small site)

Friday, January 19, 2007

Book Summary: Agile Software Development with Scrum

Agile Software Development with Scrum Ken Schwaber Mike Beedle

I really liked this book. Sounds like an interesting methodology. I'm trying to use some of the concepts at work (particularly the do work first and show it instead of discuss how to do it). Unfortunately my work environment isn't structured to fully support this development methodology.

Rough Schedule:
  1. Sprint Planning meeting to determine what goals to set for a sprint
  2. builds a product increment (working code) after a sprint (30 days of development time) Sprint Backlog cannot be changed from outside the team during a sprint
  3. demonstrates product increment to team management and client after a sprint (Sprint Review Meeting 4 hours)
  4. End of Sprint Meeting - reflect on what was accomplished during the sprint
  5. **Ongoing-15 minute daily team (ideally sized at 5-8 staff) meetings stating:
  1. what have I done since the last meeting
  2. what will I do until the next meeting
  3. what impediments are getting in my way
Scrum teams:
  1. autonomous
  2. self organizing
  3. don't have roles assigned by management (no titles)
  4. must not be disturbed or given direction by anyone outside the team during a sprint
  5. need to be cross functional
Terms:
  1. Scrum Master-facilitates meetings and removes impediments
  2. Product Backlog -prioritized list of business and technical functionality that needs to be completed for the system
  3. Product Owner-the only one who changes the product backlog
  4. Sprint Backlog-states what needs to be done in the current sprint
  5. Pigs-Team members
  6. Chickens-interested parties who will not be assigned work (they may attend scrum meetings but not speak)
  7. Release backlog - subset of the product backlog that is scheduled for a release
  8. Shared Resource Scrum Teams - responsible for code used across multiple Scrum teams

Saturday, January 6, 2007

Social Networking Sites (LinkedIn)

I use Facebook, MySpace, and LinkedIn.

Facebook primarily keeps me in touch with high school and college friends.
MySpace isn't as focused on school friends, it encompasses more people.

LinkedIn - This site focuses on professional connections. I've had it for a few years but haven't used it much because I don't know many people on it. Leo Dion just sent me this article on LinkedIn and I've decided to ramp up use of it. I think you should read the article and then decide if LinkedIn makes sense for you.

I've heard there are websites which will aggregate social networking sites (similar to the way Trillian works). I haven't found any of these to try out.

LinkedIn supports importing contacts from email clients which may help you start your network. I use Gmail. I had to export my contacts to csv files and then import them into LinkedIn to get it to work.

Saturday, December 30, 2006

Chat Applications & Interoperability (Google Talk)

I subscribed to many Google services last week, including Google Talk.

I like the Chat application very much because:
  1. The application is simple.
  2. Chat Histories are saved on Google Servers and available from anywhere in the world.
  3. You can access Google Chat from the Gmail web interface.
The only problem is most of the people I know don't use Google Talk. Well, today I found out Google Talk can also chat with most other Chat clients (in my case MSN and AIM)

Problem solved.

I followed these comprehensive instructions except that I wasn't able to get it to work with the servers they had listed. I used jaim.at for AIM and msn.jabber.anywise.com for MSN. Here is a List of Jabber servers.