Archive for category Programming

Xsl and excluding a child node

I was writing an xsl stylesheet to do xml transformation and I wanted to eliminate nodes based on their children, specifically if the parent nodes were the same. It was taking way to long to figure out how to exclude an xml node based on its descendant or child and poking around on the internet. I finally got it working and thought it might save others some time. Here is the xml and xsl:

xml:

<test>

  <parent>

    <mychild>hello</mychild>

  </parent>

  <parent>

    <ourchild>world</ourchild>

  </parent>

</test>

xsl:

<?xml version=1.0?>

<xsl:stylesheet version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/Transform>

 

  <xsl:template match=test>

    <output>

      <xsl:apply-templates select=parent/>

    </output>

  </xsl:template>

 

 

  <xsl:template match=parent>

    <xsl:if test=not(./mychild)>

      <correctChild>

        <xsl:value-of select=./>

      </correctChild>

    </xsl:if>

  </xsl:template>

</xsl:stylesheet>

result:

<?xml version=1.0 encoding=utf-16 ?>

<output>

  <correctChild>world</correctChild>

</output>

1 Comment

Knowbody Knows for Facebook

About 2-3 years ago a friend of mine wrote a board game called Knowbody Knows. I was able to play a prototype of the game when it was being developed and knew right then that this game would be great. So, over Thanksgiving we had some friends over and we played this game again. Well, afterwards I thought that Knowbody Knows would be a great game to play on Facebook. So I called up my buddy who came up with the game and he gave me his approval. Well…a week later I was able to get it up on Facebook! Feel free to try the game here: http://apps.facebook.com/knowbodyknows/ and purchase the full board game here: Knowbody Knows Website.

I used the Facebook.NET apis and they worked great, so take a look at that library for developing Facebook apps.

2 Comments

Design Patterns Repository

I went to a talk yesterday by net objectives called “Mocks, stubs and patterns”. Towards the end Scott Bain (the instructor) made mention to a design patterns repository that they were attempting to grow. I made note of the site and after looking it over, find it to be a pretty good resource. The reasons that I like the site are that the pattern pages show analogs to a non-technical example, limitations of writing tests on the patterns, and the cost-benefit(gain-loss) to using the patterns. Its in a wiki style, so as they update I can see this site becoming a great reference point for new patterns that are used that are newer than what’s in the GoF book. So, if you want to know the best way to write a unit test around the Decorator pattern, this is the place for you!

The Net Objectives Pattern Repository: http://www.netobjectivesrepository.com/

No Comments

Copy PC files to Windows Mobile Smartphone

I use my Smartphone (Dash) to store files that I frequently update and carry them back and forth from work to home, etc. I was finding myself manually copying some of these files a couple times a day, and also ran into the situation where I needed information on a file at home that I had saved to the file at work. So, out of this frustration, I wrote another tool. This tool maintains syncing files from your PC to your smartphone. Here’s how it works:

Upon installation, it places a shortcut to the application in the startup folder. Now it will start when your PC does. In order to get it to run right after installation go to your startup folder under your start menu, and click the Phone File Sync item. You’ll notice a little phone icon in the bottom windows taskbar right panel: Main Screen

This icon will have 3 states:

1. Green - phone is connected
2. Yellow - phone is syncing files
3. Red - phone is not connected

If you right click on the icon you get three (3) options:

1) Show Files to Sync: Opens up the application for file mappings. (double click on the icon does the same thing).
2) Sync Files: Forces a sync.
3) Exit: Exits the application.

Once in the main application (option 1 from above), you’ll see this screen:

Main Screen

I labeled each section and here is an explanation on what each does:

A: The list of files or directories on your PC to be sync’d with your smartphone.
B: Click to add a file to be sync’d
C: Click to add a directory to be sync’d
D: Once you do [B] or [C], and select a location in [E], click this button to add the mapping.
E: Smartphone file system. Select the destination after clicking on an item in [A] and then before clicking [D] to add the mapping.
F: Displays the mapped path on your phone. Click an item in [A] to see the mapping. There will not be anything there if you haven’t added a mapping yet.

Here’s the screen once you added a file from the PC:

Main Screen

Same file but now after I have a mapping, notice the mapped path now says where it is mapped:

Main Screen

The checkbox next to the item means that it is active and will sync with your device.

If you would like to delete a mapping, right click on an item in [A] from above and you’ll get a menu that pops up with the delete item:

Main Screen

The application will sync with the phone every 3 hours, or if you right click on the taskbar icon and force a sync.

You can use this with my password app and have some very cool ways of having your data on you at all times!

Also - I only tested this app using the Dash which has Windows Mobile 6 standard on it, and ActiveSync 4.5.

Download here: Phone File Sync [ 448 Downloads ]

1 Comment

JamBase.com Yahoo Widget

I just created a widget that you can use in the yahoo widget engine for JamBase. The “hidden” screen displays today’s date and the number of venues that have bands playing there. The full “open” screen shows all the events and has an info link back to JamBase.com so you can view the event. Now it’s as easy as a glance to see who’s playing in your home town.

Yahoo JamBase Widget: download

I recently ported the code to work as a Vista / Windows7 gadget, just rename the zip extension to “gadget” and you can load it up. Plus you can tweak more preferenes than in the Yahoo widget.

Vista Sidebar Gadget: JamBase Gadget [ 261 Downloads ]

Here’s a screen shot from my desktop:
JamBase Widget

No Comments

Generate a class file from an xml file - Visual Studio 2005 Add-in

I wrote an add-in for Visual Studio 2005 that generates a class file from an xml file.

Follow this link to download

No Comments

Using MSBuild for automated builds

So, what if you want to do automated builds that will be doing a lot of custom stuff? Well, you use the MSBuild namespace and tasks, targets, etc to create a solution. Below is an example of some code for performing a build. What the code below does is build a solution file (.sln) in a local directory that you specify in the <SolutionFile> element. I used the AssemblyInfoTask target to change version numbers during a build. This way you can dynamically change the build number for each build. The CreateItem task coupled with the copy task will drop the output files in the bin directories from the build to a different directory on your build server specified in the <OutputDirectory> element. There is more code controlling the build than what is posted but you can do a simple build using the following lines of code and the following xml file.

Engine engine = new Engine(ConfigurationManager.AppSettings["MSBuildPath"]);

Microsoft.Build.BuildEngine.Project project = engine.CreateNewProject();

project.Load(FileSystemPath + ConfigurationManager.AppSettings["BuildProjectFile"]);

project.Build();

Build.proj

<Project xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema

        DefaultTargets=UpdateAssemblyInfoFiles;BuildAll;CopyFiles xmlns=http://schemas.microsoft.com/developer/msbuild/2003>

  <Import Project=$(MSBuildExtensionsPath)\Microsoft\AssemblyInfoTask\Microsoft.VersionNumber.Targets />

  <PropertyGroup>

    <AssemblyTitle>My Assembly Title</AssemblyTitle>

    <AssemblyBuildNumberType>NoIncrement</AssemblyBuildNumberType>

    <AssemblyRevisionType>NoIncrement</AssemblyRevisionType>

    <AssemblyMajorVersion>0</AssemblyMajorVersion>

    <AssemblyMinorVersion>0</AssemblyMinorVersion>

    <AssemblyBuildNumber>0</AssemblyBuildNumber>

    <AssemblyRevision>0</AssemblyRevision>

    <AssemblyFileBuildNumberType>NoIncrement</AssemblyFileBuildNumberType>

    <AssemblyFileRevisionType>NoIncrement</AssemblyFileRevisionType>

    <AssemblyFileMajorVersion>0</AssemblyFileMajorVersion>

    <AssemblyFileMinorVersion>0</AssemblyFileMinorVersion>

    <AssemblyFileBuildNumber>0</AssemblyFileBuildNumber>

    <AssemblyFileRevision>0</AssemblyFileRevision>

    <OutputDirectory>c:\temp\</OutputDirectory>

  </PropertyGroup>

  <ItemGroup>

    <SolutionFile Include=“” />

  </ItemGroup>

  <ItemGroup>

    <BuildFiles Include=**\bin\**\*.* />

  </ItemGroup>

  <Target Name=BuildAll>

    <MSBuild Projects=@(SolutionFile) Properties=Configuration=Debug;Platform=Any CPU />

    <MSBuild Projects=@(SolutionFile) Properties=Configuration=Release;Platform=Any CPU />

    <CreateItem Include=@(BuildFiles)>

      <Output TaskParameter=Include ItemName=OutputFiles/>

    </CreateItem>

  </Target>

  <Target Name=CopyFiles DependsOnTargets=BuildAll>

    <Copy SourceFiles=@(OutputFiles) SkipUnchangedFiles=false DestinationFiles=@(OutputFiles->’$(OutputDirectory)%(Identity)’) />

  </Target>

</Project>

No Comments

Phone contacts from Outlook contact to SIM card

When I purchased my smartphone I placed all of my contacts from my previous phone on my SIM card, then I just moved the SIM card to my new smartphone and all my contacts were there. But, they were all there on my SIM card under a SIM contact. This is not ideal for the smartphone. With the smartphone you would like to be able to sync up the contacts with Outlook on your PC, or to have additional functionality that goes with the Outlook contact in the phone (images, custom rings, etc). One feature that you can not use with SIM contacts is if you have a huge phone list the phone provides a “quick search” where it shows you the letter and then hops to that letter in your phone book without going through all your contacts. But, with the SIM contact it does not do any of that. So, the obvious thing is to move your SIM contacts to your Outlook contacts in bulk. There is a program out there that I used, M2SIMCopy, that does a good job in moving over the contact to the phone, but it puts them in a category “SIM” and is only one way directional. By this I mean it can only go from SIM to the phone and not the phone to the SIM. So, I decided to take a stab at it. I decided to use the Compact Framework 2.0 with Windows Mobile 5.0 and Visual Studio 2005. I found one library somewhat useful to start with the SIM functions. The SIM method I needed was SimWritePhonebookEntry in the cellcore.dll. This method is not wrapped in the .NET CF 2.o, so you would have to use PInvoke to try to get at it. The method returns a reference to a structure and you would have to try to mimic that structure in .NET, which is not a straight conversion. I looked a while for something on the internet, and found the OpenNETCF library does a pretty good job on encapsulating the SIM calls into .NET methods.

If you need the .NET Compact Framework 2.0 you can download it here.

I finally had time to dig around in the OpennetCF and get it to work with adding my Outlook contacts in bulk to my SIM card, and then back from my SIM card to my Outlook Contacts in bulk. I had to tweak one method in the Opennetcf to get it to work.

The first screen is a little slow when loading the contacts, so when you click one of the menu items to bring up the contacts it will take about 3 seconds to bring up the screen with the contacts on it.

When installing it will prompt you with a screen that asks you to Confirm the installation. Something along the lines of “The program is from an unknown publisher, Do you want to continue?” Select “Yes”. Then the program will install.

I put a shortcut under the start menu called “BRobinson Contact Manager” and you can launch the application from there. Or you can navigate in your smartphone to Program Files -> ContactManager and then click on the executable to launch the program. Now you can copy all your Outlook contacts to your SIM card!

Here are some screen shots:

Version 1.0
          

UPDATE: The program now has a new version (1.1) that can export your SIM or Outlook contacts to a pipe “|” delimited text file. You can also import this file to either your SIM or Outlook contacts. Also, when exporting from Outlook it will put an “H” for home number, “B” for business number and “M” for mobile. See new pictures:

Version 1.1 (in addition to 1.0 features)
new home screen     new outlook screen     new import screen

Download the installation cab file here (version 1.1): Installation File [ 3078 Downloads ]

old version here (version 1.0): Contact Manager 1.0

24 Comments

.NET Custom Installer for multiple environments

Deploying applications in a distributed environment and creating a standard procedure for the IT staff can be a tricky thing to do. It often involves people outside of your development group and an understanding of what the installation is supposed to do. One major issue that developers worry about is their config file settings and placing the proper values in the config as they move through different environments. This begins the debate between who should maintain the configuration files. Should the developer be responsible for changing the config file in production or should the Network Admins be the ones responsible for changing config values? There are many opinions on who should change the values and how it should be done. I answered this question in a solution that I prototyped that involved a custom dialog during the installation process that would allow an non-IT professional to install the application to the proper environment (if told what environment they are installing to). The first step involves adding a few elements in the config file that specify settings for each environment like so:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<SIT>
<appSettings>
<add key=”user” value=”Brett”/>
<add key=”DbInstance” value=”SIT_BRETT”/>
</appSettings>
</SIT>
<UAT>
<appSettings>
<add key=”user” value=”Brett”/>
<add key=”DbInstance” value=”UAT_BRETT”/>
</appSettings>
</UAT>
<PROD>
<appSettings>
<add key=”user” value=”Brett”/>
<add key=”DbInstance” value=”PROD_BRETT”/>
</appSettings>
</PROD>
</configuration>

Once you have this in place you can start building your custom installer class which will override the install command from the installer to do some custom stuff. Start by creating a class project that inherits from the installer class. Then override the install function and create your custom function. From there I used the XmlDocument class to load in the config file and determine which environment setting was passed through from the installer. I then remove the other environment settings leaving the proper config settings in place. Here is the code for the class, that I called EnvironmentInstaller, that inherits from the installer class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Configuration.Install;
using System.ComponentModel;
using System.Xml;
using System.Reflection;

namespace MyInstaller
{
[RunInstaller(true)]
public class EnvironmentInstaller : Installer
{
private enum Environments
{
SIT = 1, UAT, PROD
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Environments environment = (Environments)Convert.ToInt32(Context.Parameters["ENVIRONMENT"]);
setProperEnvironment(environment);
}
private void setProperEnvironment(Environments environment)
{
// load config document for current assembly
string[] configLocation = loadConfigDocument();

for (int i = 0; i < configLocation.Length; i++)
{
XmlDocument doc = new XmlDocument();
doc.Load(configLocation[i]);

XmlNode configurationNode = doc.SelectSingleNode("//configuration");
XmlNode currentEnvironmentNode = null;
XmlNode environmentNode1 = null;
XmlNode environmentNode2 = null;

switch (environment)
{
case Environments.SIT:
currentEnvironmentNode = doc.SelectSingleNode("//" + Environments.SIT.ToString() + "");
environmentNode1 = doc.SelectSingleNode("//" + Environments.UAT.ToString() + "");
environmentNode2 = doc.SelectSingleNode("//" + Environments.PROD.ToString() + "");
break;
case Environments.UAT:
currentEnvironmentNode = doc.SelectSingleNode("//" + Environments.UAT.ToString() + "");
environmentNode1 = doc.SelectSingleNode("//" + Environments.SIT.ToString() + "");
environmentNode2 = doc.SelectSingleNode("//" + Environments.PROD.ToString() + "");
break;
case Environments.PROD:
currentEnvironmentNode = doc.SelectSingleNode("//" + Environments.PROD.ToString() + "");
environmentNode1 = doc.SelectSingleNode("//" + Environments.SIT.ToString() + "");
environmentNode2 = doc.SelectSingleNode("//" + Environments.UAT.ToString() + "");
break;
}
environmentNode1.ParentNode.RemoveChild(environmentNode1);
environmentNode2.ParentNode.RemoveChild(environmentNode2);
XmlNode appSettingNode = currentEnvironmentNode.FirstChild;
configurationNode.ReplaceChild(appSettingNode, currentEnvironmentNode);
doc.Save(configLocation[i]);
}
}
private string[] loadConfigDocument()
{
Assembly callingAssembly = Assembly.GetCallingAssembly();
string location = callingAssembly.Location.Replace(callingAssembly.ManifestModule.Name, "");
string[] files = System.IO.Directory.GetFiles(location, "*.config");
return files;
}
}
}

When you compile this it will produce a dll file that you will include in your setup project. First add a new Setup project into your solution from Other Project Types -> Setup and Deployment in .NET. The first screen is the File System screen. Add in a your project output and any other files that you need to deploy from your solution. Last, add in the dll from the class project that you built before.


Now we need to add in a custom dialog that specifies which environment we are deploying to. Click on the User Interface editor:

and add a new Radio Buttons (3 buttons) dialog:

Change the properties of the dialog to look like the following:

Next click on the custom actions editor, and add a new action to the Install directory. Choose the dll that you included in the File System screen.

Change the properties to look like the following:

What you are doing here is specifying the enter button of your new dialog to send the radio button results to the custom installer class we created as a parameter in the EnvironmentInstaller class.

Click the save all button and rebuild the solution and the setup project. Now when you install the application you will see this screen:

and your config file will have the proper settings in the installation folder.

You can download the code sample here: My Installer demo [ 497 Downloads ]

No Comments

Parse Comma Delimited File with quotes and commas in .NET

I have had some developers here ask me about parsing strings with commas and quotes in the line to parse. I decided to post this because my searching on the web was not super successful in finding the answer. I orginally tried to use the matching methods in the RegEx class and it did not work very well. I used the RegEx.Matches() method and then I created a collection of matches and looped through the matches and got unexpected results. I used Espresso to test my regular expression and it worked fine with this expression: \s*(?!$)*\”(?[^\s]*([^\"]*)*\”)|(?[^,]*)\s*. When I put this into .NET and used the for each to loop through the matches and specify the group “value”, I got every other line being a blank space, which is not what I wanted. After some searching and tweaking, I have this solution, which works great.

Here is the sample line to be parsed:

“Field1,Field2,Field3,Field4,Field5,”Field6, Field7″”

Here is the code:

string line = “Field1,Field2,Field3,Field4,Field5,\”Field6, Field7\”";
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(”,(?=(?:[^\"]*\”[^\"]*\”)*(?![^\"]*\”))”);
string[] result = r.Split(line);
for(int i =0;i<result .Length;i++)
{
Console.WriteLine(result[i].ToString());
}
Console.ReadLine();

(You can convert the C# to VB.NET here: http://www.developerfusion.co.uk/utilities/convertcsharptovb.aspx)

The results looks like this:

Field1
Field2
Field3
Field4
Field5
“Field6, Field7″

2 Comments