Saturday, January 26, 2013

Debian 6.0.6 with Hyper-V networking support



What I did:
Install clean debian (with a legacy network adapter attached, using a fixed mac address)

Prepare build environment
apt-get update
apt-get install build-essential libncurses5-dev bzip2 linux-source-2.6.32
Unpack linux sources
cd /usr/src
tar -jxvf linux-source-2.6.32.tar.bz2
ln -s linux-source-2.6.32 linux
cd linux
Cleanup (not really needed because we just unpacked it all)
make clean
make mrproper
Configure kernel
cp /boot/config-2.6.32-5-amd64 ./.config
make menuconfig

 - Load an Alternative Configuration File
  - .config [OK]
 - General setup --->
  - Local version - append to kernel release
   - -hyperv (mind the hyphen in front of it)
 - Device Drivers --->
  - Staging drivers --->
   < >  VIA Technologies VT6656 support   (BUGFIX http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=568454) 
     Microsoft Hyper-V client drivers
 - Kernel hacking --->
  [ ] Compile the kernel with debug info
 Exit and save!
Build kernel
make
make modules_install
make install
depmod 2.6.32-hyperv
Create initramfs
mkinitramfs -o /boot/initrd.img-2.6.32-hyperv 2.6.32-hyperv
Update grub
nano /etc/default/grub
 Default=2 (To make the 3rd menu option selected)
update-grub
Add Hyper-V modules
nano /etc/initramfs-tools/modules
  hv_vmbus
  hv_storvsc
  #hv_blkvsc (THIS IS STILL BUGGY, SO WE DISABLE THIS FOR NOW)
  hv_netvsc
Some bugfixing...
nano /etc/modprobe.d/blacklist.conf
 #fix: Driver 'pcspkr' is already registered, aborting...
 blacklist snd-pcsp
 #fix: SMBus base address uninitialized - upgrade bios or use force_addr=0xaddr
 blacklist i2c_piix4
update-initramfs -u -k 2.6.32-hyperv
Fix networking
nano /etc/network/interfaces
  edit eth0 to seth0
poweroff
In Hyper-V settings remove legacy network adapter and add normal one
Start up, you will get an message saying: Fixing recursive fault but reboot is needed!
Just poweroff and power on again
You're done!

Known issues:
 - Mouse still isn't working
 - hv_blkvsc isn't working
 - When using more then 4 GB of memory you get SRAT: Hotplug area too small

Sunday, January 20, 2013

Reverse proxy on openSUSE

My previous article was about creating a reverse proxy on Debian.
Due to incompatibilities between Debian and Hyper-V I had to recreate the setup in an openSUSE environment.

How I did it:
1. Install openSUSE 12.2 as clean as possible.
2. Fix a error that causes yast to f#ckup the lines in the menus (disable all graphicall boot stuff in grub)
3. Fix a error "piix4_smbus", edit /etc/modprobe.d/blacklist.conf -> blacklist i2c_piix4
4. start yast2
    - Add "apache" + "yast2-httpserver"
5. Configure http-server from yast
    - Enable http
    - Open firewall port
    - Start apache on boot
    - Add modules (proxy, proxy-http, headers, rewrite)
    - Add vhost
6. Edit /etc/apache/vhost.d/IIS01.wouterspaans.nl.config
7. Reboot

Thursday, January 17, 2013

Reverse proxy on Debian

Solution: Reverse proxy.

What I did:

1. Download Debian 6.0.6 (64bit)
2. Install smallest possible version
3. apt-get install apache2
4. a2enmod proxy_http
5. a2enmod headers
6. a2enmod rewrite
7. nano /etc/apache2/sites-available/default

 ServerName server1.wouterspaans.nl
 ProxyPass / http://IIS01.wouterspaans.local/
 ProxyPassReverse / http://IIS01.wouterspaans.local/



 ServerName server2.wouterspaans.nl
 ProxyPass / http://IIS02.wouterspaans.local/
 ProxyPassReverse / http://IIS02.wouterspaans.local/

8. /etc/init.d/apache restart

Done!

Debugging when something goes wroong can be done looking at the logs...
tail -f /var/log/apache2/error.log

Friday, December 7, 2012

Get path for app.config

When building an application and debugging it we often use app.config. But which app.config is really looked at? We can find it's path using: string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; Example using an app.config or web.config could be: string connStr = ConfigurationManager.ConnectionStrings["CustomConnectionString"].ConnectionString

Wednesday, November 21, 2012

RGB Led Color Picker using C# and an Arduino

Used:
 1x Windows Computer with Visual Studio
 1x Arduino UNO
 1x RGB Led
 3x 330 ohm resistors (I needed to use 2 more to calibrate the RGB led, Green and Blue where to bright compared to Red)
 1x Breadboard
 Some jumpwires

Result:

How did i do it?

C# Code:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;

namespace RGBLedColorPicker
{
    public partial class Form1 : Form
    {
        // Initialize serial port
        SerialPort port = new SerialPort("COM3", 9600);

        // Initialize the default color to black
        private Color defaultColor = Color.FromArgb(0, 0, 0);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Open connection to Arduino
            port.Open();

            // Set default color
            this.SetColor(defaultColor);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Set default color
            this.SetColor(defaultColor);
            
            // Close connection to Arduino
            port.Close();
        }

        private void panel1_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                SetColor(colorDialog1.Color);
            }
        }

        private void SetColor(Color color)
        {
            // Update color in the panel
            panel1.BackColor = color;

            // Write color to Arduino
            port.Write(new[] { color.R, color.G, color.B }, 0, 3);
        }
    }
}

Arduino Code:
const int RED_LED_PIN = 9;
const int GREEN_LED_PIN = 10;
const int BLUE_LED_PIN = 11;

void setup() { 
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() == 3)
  {
    analogWrite(RED_LED_PIN, Serial.read());
    analogWrite(GREEN_LED_PIN, Serial.read());
    analogWrite(BLUE_LED_PIN, Serial.read());
  }
}

Thursday, November 15, 2012

WCF Service in a console app

Create a new console app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// Add Reference.... Select System.ServiceModel from the .NET tab and click OK.
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCFConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Service1));
            host.Open();
            Console.Write("Service is up and running");
            Console.ReadKey();
            host.Close();
        }
    }

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GreetingMessage(string Name);
    }

    public class Service1 : IService1
    {
        public string GreetingMessage(string name)
        {
            return "Welcome to WCF " + name;
        }
    }
}

Add App.config:

  
    
      
        
        
          
          
            
          
        
        
        
          
            
          
        
      
    
    
      
        
          
          
          
          
        
      
    
  

soapUI Compatible App.config:
Remember to activate WS-A options in your request:
Add default wsa:Action
Add default wsa:To


  
    
    
    
      
        
          
            
          
        
      
    
    

    
      
        
        
          
          
            
          
        
        
        
          
            
          
        
      
    
    
      
        
          
          
          
          
        
      
    
  
  
  

Wednesday, February 29, 2012

Generate type safe classes for sharepoint - vol2

I created a T4 template file that will:
1 - Search for SharePoint content types.
2 - Generate type safe Names and ID's for them.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<# 
// GET fileNamespace -> http://lennybacon.com/CommentView,guid,6ba5f768-6325-4f09-8341-201122804f52.aspx
var hostServiceProvider = (IServiceProvider)Host;
var dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
var activeSolutionProjects = (Array)dte.ActiveSolutionProjects;
var dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0);
var defaultNamespace = dteProject.Properties.Item("DefaultNamespace").Value;
var templateDir = Path.GetDirectoryName(Host.TemplateFile);
var fullPath = dteProject.Properties.Item("FullPath").Value.ToString();
fullPath = fullPath.EndsWith("\\") ? fullPath.Substring(0, fullPath.Length-1) : fullPath;
var subNamespace = templateDir.Replace(fullPath, string.Empty).Replace("\\", ".");
var fileNamespace = string.Concat(defaultNamespace, subNamespace);

// GET All XML files -> http://weblogs.asp.net/lhunt/pages/CSharp-Coding-Standards-document.aspx
var searchPath = new DirectoryInfo(fullPath).Parent.FullName;
var folderList = new Stack<string>();
var allXmlFiles = new List<string>();
string[] currentFolders = null;
string[] currentFiles = null;
string thisFolder = null;
folderList.Push(searchPath);
while(folderList.Count > 0)
{
    thisFolder = folderList.Pop();
    currentFiles = Directory.GetFiles(thisFolder, "*.xml");
    foreach(string file in currentFiles) if (!file.Contains("\\Debug\\")) allXmlFiles.Add(file);      
    currentFolders = Directory.GetDirectories(thisFolder);
    if(currentFolders != null && currentFolders.Length > 0) foreach(string folder in currentFolders) folderList.Push(folder);    
}

// GET All Fields from XML files
var fields = new List<KeyValuePair<string, KeyValuePair<string, KeyValuePair<string, string>>>>();
foreach (string xmlFile in allXmlFiles)
{
 var doc = new XmlDocument();
    doc.Load(xmlFile);
    XmlElement root = doc.DocumentElement;
    foreach (XmlNode node in root.ChildNodes)
        if (node.Name == "ContentType" && node.Attributes != null)
  {
            var attributeName = node.Attributes["Name"];
            var attributeID = node.Attributes["ID"];
            var attributeDisplayName = node.Attributes["Description"];
   fields.Add(new KeyValuePair<string, KeyValuePair<string, KeyValuePair<string, string>>>((attributeName != null) ? attributeName.InnerText.Replace(" ", string.Empty).Replace(
                                            "-", string.Empty) : "",new KeyValuePair<string, KeyValuePair<string, string>>(xmlFile.Replace(searchPath + "\\",""), new KeyValuePair<string, string>((attributeID != null) ? attributeID.InnerText : "",(attributeDisplayName != null) ? attributeDisplayName.InnerText : ""))));
  }
}
#>// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContentTypes.cs" company="Imtech ICT Integrated Solutions">
//   Copyright 2012 by Imtech ICT Integrated Solutions. All rights reserved. This material may not be duplicated for any profit-driven enterprise.
// </copyright>
// <summary>
//   Static ContentType Names And Ids
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace <#= fileNamespace #>
{
    using Microsoft.SharePoint;

    /// <summary>
    /// Static ContentTypeNames
    /// </summary>
    public static partial class ContentTypeNames
    {
<#
string previousFile = "";
bool firstTimeRun = true;
foreach (var field in fields.OrderBy(t => t.Value.Key).ThenBy(t => t.Key))
{
 if (previousFile != field.Value.Key)
 { if (!firstTimeRun)
  { #>

<# }
  if (firstTimeRun){firstTimeRun = false;} #>
        // <#= field.Value.Key #>
<#   previousFile = field.Value.Key;
 } #>
        public static readonly string <#= field.Key #> = "<#= field.Key #>";
<#}#>
    }

    /// <summary>
    /// Static ContentTypeIds
    /// </summary>
    public static partial class ContentTypeIds
    {
<#
previousFile = "";
firstTimeRun = true;
foreach (var field in fields.OrderBy(t => t.Value.Key).ThenBy(t => t.Key))
{
 if (previousFile != field.Value.Key)
 { if (!firstTimeRun)
  { #>

<# }
  if (firstTimeRun){firstTimeRun = false;} #>
        // <#= field.Value.Key #>
<#   previousFile = field.Value.Key;
 } #>
        public static readonly SPContentTypeId <#= field.Key #> = new SPContentTypeId("<#= field.Value.Value.Key #>");
<#  } #>
    }
}

Generate type safe classes for sharepoint - vol1

I created a T4 template file that will:
1 - Search for SharePoint fields.
2 - Generate type safe FieldNames and ID's for them.


<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<# // GET fileNamespace -> http://lennybacon.com/CommentView,guid,6ba5f768-6325-4f09-8341-201122804f52.aspx
var hostServiceProvider = (IServiceProvider)Host;
var dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
var activeSolutionProjects = (Array)dte.ActiveSolutionProjects;
var dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0);
var defaultNamespace = dteProject.Properties.Item("DefaultNamespace").Value;
var templateDir = Path.GetDirectoryName(Host.TemplateFile);
var fullPath = dteProject.Properties.Item("FullPath").Value.ToString();
fullPath = fullPath.EndsWith("\\") ? fullPath.Substring(0, fullPath.Length-1) : fullPath;
var subNamespace = templateDir.Replace(fullPath, string.Empty).Replace("\\", ".");
var fileNamespace = string.Concat(defaultNamespace, subNamespace);
// END GET fileNamespace

// GET All Fields from XML files -> http://weblogs.asp.net/lhunt/pages/CSharp-Coding-Standards-document.aspx
string searchPath = new DirectoryInfo(fullPath).Parent.FullName;
Stack<string> folderList = new Stack<string>();
List<string> allXmlFiles = new List<string>();
string[] currentFolders = null;
string[] currentFiles = null;
string thisFolder = null;
folderList.Push(searchPath);
while(folderList.Count > 0)
{
thisFolder = folderList.Pop();
currentFiles = Directory.GetFiles(thisFolder, "*.xml");
foreach(string file in currentFiles)
if (!file.Contains("\\Debug\\"))
allXmlFiles.Add(file);
currentFolders = Directory.GetDirectories(thisFolder);
if(currentFolders != null && currentFolders.Length > 0)
foreach(string folder in currentFolders)
folderList.Push(folder);
}
var fields = new List<KeyValuePair<string, KeyValuePair<string, KeyValuePair<string, string>>>>();
foreach (string xmlFile in allXmlFiles)
{
var doc = new XmlDocument();
doc.Load(xmlFile);
XmlElement root = doc.DocumentElement;
foreach (XmlNode node in root.ChildNodes)
if (node.Name == "Field" && node.Attributes != null)
{
var attributeName = node.Attributes["Name"];
var attributeID = node.Attributes["ID"];
var attributeDisplayName = node.Attributes["DisplayName"];
string fieldName = "";
string fieldId = "";
string fieldDisplayName = "";
if (attributeName != null) fieldName = attributeName.InnerText;
if (attributeID != null) fieldId = attributeID.InnerText;
if (attributeDisplayName != null) fieldDisplayName = attributeDisplayName.InnerText;
fields.Add(
new KeyValuePair<string, KeyValuePair<string, KeyValuePair<string, string>>>(
fieldName,
new KeyValuePair<string, KeyValuePair<string, string>>(
xmlFile.Replace(searchPath + "\\",""), new KeyValuePair<string, string>(fieldId, fieldDisplayName))));
}
}
// Get All SiteColumn Files
#>// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Fields.cs" company="Imtech ICT Integrated Solutions">
// Copyright 2012 by Imtech ICT Integrated Solutions. All rights reserved. This material may not be duplicated for any profit-driven enterprise.
// </copyright>
// <summary>
// Static Field Names And Ids
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace <#= fileNamespace #>
{
using System;

/// <summary>
/// Static FieldNames
/// </summary>
public static partial class FieldNames
{
<#
string previousFile = "";
foreach (var field in fields.OrderBy(t => t.Value.Key).ThenBy(t => t.Key))
{
if (previousFile != field.Value.Key)
{ #>

// <#= field.Value.Key #>
<# previousFile = field.Value.Key;
} #>
public static readonly string <#= field.Key #> = "<#= field.Key #>";
<#}#>
}

/// <summary>
/// Static FieldIds
/// </summary>
public static partial class FieldIds
{
<#
foreach (var field in fields.OrderBy(t => t.Value.Key).ThenBy(t => t.Key))
{
if (previousFile != field.Value.Key)
{ #>

// <#= field.Value.Key #>
<# previousFile = field.Value.Key;
} #>
public static readonly Guid <#= field.Key #> = new Guid("<#= field.Value.Value.Key #>");
<# } #>
}
}


This will create code like:



// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Fields.cs" company="Imtech ICT Integrated Solutions">
// Copyright 2012 by Imtech ICT Integrated Solutions. All rights reserved. This material may not be duplicated for any profit-driven enterprise.
// </copyright>
// <summary>
// Static Field Names And Ids
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ZP.Intranet.Helpers
{
using System;

/// <summary>
/// Static FieldNames
/// </summary>
public static partial class FieldNames
{

// Intranet\Content\SiteColumns\SiteColumns\Elements.xml
public static readonly string ColumnAuthor = "ColumnAuthor";
public static readonly string DocumentDescription = "DocumentDescription";
public static readonly string DocumentThema = "DocumentThema";
public static readonly string DocumentThemaTaxHTField0 = "DocumentThemaTaxHTField0";
public static readonly string FAQAntwoord = "FAQAntwoord";
public static readonly string GoogleMapsUrl = "GoogleMapsUrl";
public static readonly string isSticky = "isSticky";
public static readonly string JobTitle2 = "JobTitle2";
public static readonly string ListIndex = "ListIndex";
public static readonly string NewsExpirationDate = "NewsExpirationDate";
public static readonly string PublishingPageIntro = "PublishingPageIntro";
public static readonly string RouteContactDescription = "RouteContactDescription";
public static readonly string StickyExpirationDate = "StickyExpirationDate";
public static readonly string SummaryLinks1 = "SummaryLinks1";
public static readonly string WijzigingenTonen = "WijzigingenTonen";
public static readonly string Workingdays = "Workingdays";
public static readonly string ZMobiel = "ZMobiel";
public static readonly string ZPFax = "ZPFax";
public static readonly string ZPPicture = "ZPPicture";
public static readonly string ZPSecretariaat = "ZPSecretariaat";
public static readonly string ZPTelefoon = "ZPTelefoon";

// Kwaliteit\Content\SiteColumns\SiteColumns\Elements.xml
public static readonly string DocumentEigenaar = "DocumentEigenaar";
public static readonly string DocumentVersie = "DocumentVersie";
public static readonly string EvaluatieDatum = "EvaluatieDatum";
public static readonly string EvaluatieDatumVoorstel = "EvaluatieDatumVoorstel";
public static readonly string EvaluatieResultaat = "EvaluatieResultaat";
public static readonly string EvaluatieStatus = "EvaluatieStatus";
public static readonly string GewijzigdToelichting = "GewijzigdToelichting";
public static readonly string KwaliteitThema = "KwaliteitThema";
public static readonly string KwaliteitThemaTaxHTField0 = "KwaliteitThemaTaxHTField0";
public static readonly string Reactie = "Reactie";
public static readonly string ReactiePersoon = "ReactiePersoon";
public static readonly string RedenAfkeur = "RedenAfkeur";
public static readonly string RedenUitstel = "RedenUitstel";
public static readonly string Uitstel = "Uitstel";
}

/// <summary>
/// Static FieldIds
/// </summary>
public static partial class FieldIds
{

// Intranet\Content\SiteColumns\SiteColumns\Elements.xml
public static readonly Guid ColumnAuthor = new Guid("{8fed943f-9baf-44fe-b7c6-623abadabd42}");
public static readonly Guid DocumentDescription = new Guid("{1828f1f6-35fb-4795-92c9-477dcd54a921}");
public static readonly Guid DocumentThema = new Guid("{cd323e0e-665a-4709-81dc-5746d741e492}");
public static readonly Guid DocumentThemaTaxHTField0 = new Guid("{a3e9d854-9997-449a-97f3-8d7066bab16f}");
public static readonly Guid FAQAntwoord = new Guid("{bf170ac7-397c-4d58-97a3-6918d4c3b340}");
public static readonly Guid GoogleMapsUrl = new Guid("{863efa7c-a265-452e-97a2-52836ffbfa82}");
public static readonly Guid isSticky = new Guid("{88f5eeb8-ec0c-419b-9c30-c4c3295e5547}");
public static readonly Guid JobTitle2 = new Guid("{2ace342a-be43-4412-92c0-504cc73f2675}");
public static readonly Guid ListIndex = new Guid("{0cbd1771-2b6e-4f68-93ea-70f9bb2c16ca}");
public static readonly Guid NewsExpirationDate = new Guid("{0fe49e6f-e953-410b-99f5-44cfc71bd393}");
public static readonly Guid PublishingPageIntro = new Guid("{1b72fc77-3add-486c-869c-5c71c25a4c77}");
public static readonly Guid RouteContactDescription = new Guid("{4c9f4081-adbf-40c2-9cb7-ff464463b6d4}");
public static readonly Guid StickyExpirationDate = new Guid("{fbae95fc-0e10-47bc-8ef1-2cf61a417d12}");
public static readonly Guid SummaryLinks1 = new Guid("{3b4e0c4d-6dea-49c9-b80d-b536d301817a}");
public static readonly Guid WijzigingenTonen = new Guid("{1ec13dcd-adbd-485b-91ab-d703e7ce3ebc}");
public static readonly Guid Workingdays = new Guid("{65a02752-d6fe-4806-9813-f48f23e47cc8}");
public static readonly Guid ZMobiel = new Guid("{7e10bf64-6f59-4f01-b5e9-df6e63da3dc7}");
public static readonly Guid ZPFax = new Guid("{1dfd705e-77eb-4c06-9c81-7464b90df58e}");
public static readonly Guid ZPPicture = new Guid("{57bf7368-a9f4-4fc4-a746-b20ab49dc81c}");
public static readonly Guid ZPSecretariaat = new Guid("{8a797061-3daa-45a1-8d12-8f122ba5be57}");
public static readonly Guid ZPTelefoon = new Guid("{ca259e0c-055a-41e5-82f4-1705b4884c45}");

// Kwaliteit\Content\SiteColumns\SiteColumns\Elements.xml
public static readonly Guid DocumentEigenaar = new Guid("{4dd34746-7b40-4235-99a7-06cfec789291}");
public static readonly Guid DocumentVersie = new Guid("{e457c652-b3d7-4301-b485-e709256c2dd2}");
public static readonly Guid EvaluatieDatum = new Guid("{814e7328-1ede-42e6-8c36-49b852ca99ed}");
public static readonly Guid EvaluatieDatumVoorstel = new Guid("{c2c3cb23-dc2c-45e0-ac35-8ba706601f71}");
public static readonly Guid EvaluatieResultaat = new Guid("{84145504-5e19-4ffd-b023-d8b44562ae6a}");
public static readonly Guid EvaluatieStatus = new Guid("{9355964F-EA27-4CB4-ACD6-083E6E8165B1}");
public static readonly Guid GewijzigdToelichting = new Guid("{bd1743f0-6af7-4211-a340-50c0fa883f54}");
public static readonly Guid KwaliteitThema = new Guid("{2efce8ed-eb88-4afb-b3d7-ba01db53f0b4}");
public static readonly Guid KwaliteitThemaTaxHTField0 = new Guid("{c32bb43b-54f7-4e08-a169-cdec83885bbb}");
public static readonly Guid Reactie = new Guid("{9e89ed0d-bc55-4d3b-a908-568a93925327}");
public static readonly Guid ReactiePersoon = new Guid("{11189fed-e050-4317-8d67-0a5b90f48073}");
public static readonly Guid RedenAfkeur = new Guid("{21486E8F-A1E9-4104-AFD7-2871599C058B}");
public static readonly Guid RedenUitstel = new Guid("{4e331dd7-51ab-4a35-b996-7b8617bfa4c2}");
public static readonly Guid Uitstel = new Guid("{084d857a-546d-41bc-b95b-a535c375524e}");
}
}

Saturday, February 4, 2012

Manipulating query string, the type safe way!

Our goal for today: Safe some valuable time.

Everyone who is developing for the web will come across the use of query string parameters.

SNAGHTML1a40b7f2

Handling these little buggers has proven to be quite time consuming.
Say we have: ../Default.aspx?PageNumber=1
Methods like Page.Request.QueryString[] are far from intuitive:

The old way:

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
int pageNumber;
const string qsParam = "PageNumber";
object qsObject = Page.Request.QueryString[qsParam];
if (qsObject != null)
{
int qsValue;
if (int.TryParse(qsObject.ToString(), out qsValue))
pageNumber = qsValue;
else
pageNumber = -1;
}
else
pageNumber = -1;
}
}

The better way:

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
var queryString = new QueryStringParam();
int pageNumber = queryString.PageNumber ?? -1;
}
}

public class QueryStringParam : QueryStringParser
{
public int? PageNumber;
}

Source code of QueryStringParser:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Specialized;
using System.Web;
using System.Reflection;

namespace Helpers
{
public abstract class QueryStringParser
{
private NameValueCollection _queryString;

private FieldInfo[] _fields;
private IEnumerable<FieldInfo> Fields
{
get { return _fields ?? (_fields = GetType().GetFields()); }
}

protected QueryStringParser()
{
InitializeQueryString();
}

private void InitializeQueryString()
{
foreach (var fieldInfo in Fields) fieldInfo.SetValue(this, null);
_queryString = HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);
if (_queryString.Keys.Count > 0)
foreach (string key in _queryString.Keys)
{
var foundField = Fields.FirstOrDefault(cust => cust.Name == key);
if (foundField != null)
{
Object tempObject = null;
var value = _queryString[key];
var fieldType = foundField.FieldType;
try
{
if (fieldType == typeof(Guid?)) tempObject = new Guid(value);
if (fieldType == typeof(string)) tempObject = value;
if (fieldType == typeof(int?)) tempObject = int.Parse(value);
if (fieldType == typeof(bool?)) tempObject = bool.Parse(value);

// check for enum
var underlyingType = Nullable.GetUnderlyingType(fieldType);
if (underlyingType != null && underlyingType.IsEnum)
tempObject = Enum.Parse(underlyingType, value, true);

if (tempObject != null) foundField.SetValue(this, tempObject);
}
catch (Exception)
{
} // Can not convert querystring value into strongly typed parameter
}
}
}

public override string ToString()
{
foreach (var field in Fields)
{
var fieldValue = field.GetValue(this);
if (fieldValue != null)
_queryString[field.Name] = fieldValue.ToString();
else
_queryString.Remove(field.Name);
}
string returnValue = String.Format("?{0}", _queryString);
InitializeQueryString();
return returnValue;
}
}
public static class QueryStringParserExtensionMethods
{
public static bool HasValue(this string input)
{
return (!string.IsNullOrEmpty(input));
}
public static string Value(this string input)
{
return input;
}
}
}

Friday, October 7, 2011

Visual Studio Extension: JQuery Google CDN

I created a little item template for simply adding JQuery support to your SharePoint project.

More info to come...

Tuesday, December 28, 2010

APK Edit

Ever wanted to simply change an icon on your Android phone and found yourself lost in the endless lists of forum posts saying: you have to change heaven and earth to do this...
NOT ANYMORE!!!!

APK Edit is born!











With this little program you can simply change icons of your android application.
It even lets you change the applications name.
But wait mike..... there's more.....
It even lets you edit the text used in applications.

Sounds to good to be true...
Well... to be honest.... it is.
But I've come a long way from that initial question to the final answer.
My conclusion so far, it works for most of my applications.
It probably will work on most of yours as well.
Try it out now: APK Edit

Thursday, April 8, 2010

Passed exam 70-235

Victory Is Mine!!!
Today I successfully passed the exam 70-235 meaning that from now on I can call myself technical specialist in:
Developing Business Process and Integration Solutions by Using Microsoft BizTalk Server 2006

Next one will be exam: 70-241
Developing Business Process and Integration Solutions by Using Microsoft  BizTalk  Server  2006 R2

Friday, March 26, 2010

Let BizTalk automatically send a WCF Response message on delivery without the use of orchestrations.

Recently I faced the challenge of returning a delivery acknowledgement message to an WCF service when it shoots a new message in our BizTalk environment. All this needs to be done using “context based routing”, in other words, without the use of an orchestration. Main reason for this is the extra performance overhead you get using orchestrations.

To sum it all up, our goal for today is:

  • DON’T USE ORCHESTRATIONS!
  • Send a dummy message to the WCF service.
  • Wait for the message to be placed into the BizTalk messagebox.
  • Receive an acknowledgement that the message is indeed accepted by BizTalk.

After some “intelli searching” on the web I came across this article of Daniel Probert. In this article he shares his vision on the problem at hand. Being a total newby in BizTalk world his explanation was a bit mindboggling for me. After a couple of hours playing with the concept I manage to recreated his concept to the point I actually understood what was going on beneath the shiny surface.

It all has to do with a “magical” subscription that will be created on the fly by BizTalk when the receive-port receives a new message. But first things first!

To be able to send messages to BizTalk using a webservice we can use the “BizTalk WCF Service Publishing Wizard”. This Wizard will guide you thru the process of setting up your Webservice and “connecting” it to your BizTalk application, resulting in a newly created “receive port / location” in your BizTalk Application. This newly created port is by default a Two Way receive port, meaning it can talk both ways (Request/ Response). Exactly what I wished for… NOT!

The problem lies is the response handling, when BizTalk receives a new incoming message it will try to deliver it to its subscribers and.. that’s about it…. There’s no build-in response system! So what you will experience using the Web-service is a time-out (lack of response) on you WCF request.

Back to the “magical” subscription part… every time BizTalk accepts a message from a two way port it automatically creates a new subscription for its “response” port subscribing it to ALL messages containing the following promoted properties:

  • EpmRRCorrelationToken == {*****}
  • RouteDirectToTP == True

Sadly these properties can’t be promoted the usual way since they are some sort of special system properties. To accomplish the impossible we will have to create a custom pipeline that will do exactly that for us. And that’s exactly what I did, using a little code snippet from Daniel. clip_image002

After using this custom pipeline as your “Receive Pipeline” BizTalk will send back a copy of the incoming message as an acknowledgement to the initial WCF request.

Yeah! No more timeout’s, problem solved!
Installer: Windows Installer File (MSI)
Sourcecode: CodePlex
Documentation: Word Document

Wednesday, January 7, 2009

Getting a SharePoint Feature GUID, the easy way!

Today my colleague Waldek pointed me to an interesting way to find out the "GUID" of a SharePoint Feature.
Only prerequisite is that you have installed the Internet Explorer Developer Toolbar
Go to your feature page "Site Settings > Site Features" or more directly go to /_layouts/ManageFeatures.aspx?Scope=Site
Here you will find the list of deployed features.
Now choose "Select Element by Click" en select the "Activate" of "Deactivate" button of your feature.




Now you can see the "GUID" in the elements window

Friday, February 22, 2008

I'm in love, her name is MSBuild.

A colleague of me pointed out that there are several stages of emotion when developing SharePoint. Ignorance, Anger, and finally Acceptance. This makes you wonder… Why the anger?
So after experience them all, I found out that the default SharePoint Development workstation provided by Microsoft (Visual Studio in combination with MOSS) was lacking, how should I bring this… Completeness! Every developer in town will automatically say, is there any software that truly complete, well have to acknowledge that I haven’t found any in my lifetime, but the search continues. What I want to point out is that there is a LOT of room in SharePoint Development for tooling. A great resource for all sorts of tooling that will make life easier you can find at http://www.sharepointblogs.com/ But we are drifting a bit off topic here. One of the main thing’s that made me angry was the seemingly endless repeating of steps needed while developing in SharePoint. Creating a simple WebPart will take a lot of steps I can tell you (all those xml files, you know what I mean).

A little less angry…
First thing a developer will say when they are confronted with repeating steps, lets automate the process as much as possible.
Here is where I met the powerful build system Microsoft provides called: MSBuild.
For example, lets look at the developing process of a WebPart.

  • You will startup Visual Studio and begin to write your code and create an .webpart file (or previously an .dwp file)
  • You will then create the necessary feature structure required for creating an WSP file.
  • You will create the WSP file using the command MakeCab.exe
  • You will deploy and publish this feature to your website using the command STSADM.exe
  • You will activate and try the newly installed feature.

This process (or something similar, like (un)registering your DLL in the GAC for instance) will be used a lot of times during development. Previously we were using batch files for automating our solutions as much as possible.
But now that we have discovered MSBuild targets we are in the process of getting rid of these batch files and replace them with .target files.
There are a couple of reasons why I think you should consider using this feature:

  • More control, There is a tight integration between Visual Studio and MSBuild providing us with more control over what when happens based on al sort’s of states of your project.
  • Reusability, given the fact that MSBuild has tight integration it will give you the power of create more flexible scripts, thereby giving you a more reusable solution.
  • Cleaner, A lot of “plumbing” is done behind the scene therefore making your solution cleaner. output of the scripts will be displayed in the output window within Visual Studio instead of separate log files for example (although that’s definitely still one of the possibility’s)
  • Intellisense, I will not go into this deeper than necessary, Most likely you know what Intellisense can do for you, less code errors due to human type errors ect. ect.

Drawback’s:
So, is this MSBuild your answer to all your developing questions?
Definitely not! On the contrarily, there are some little “problems” with using this.

  • Changing any target files (read: script files) require you to reload your solution. This is because the imported target files will only be evaluated during loading of the projectfile.
    This is mainly a problem when you are creating new template’s and need to change the target files a lot.
  • Although using MSBuild instead of Batch Files is more clean, this “behind the scene’s plumbing” can make the whole process less transparent. So here come in the reason that you always need to communicate (read: create documentation) about what's is happening during the process. I myself find it very useful to use the output windows for showing what is happening in the MSBuild process.

How to use it:
So, now that you have read the benefit's and drawback's you may find yourself questioning, can this MSBuild target thing do something for me, and where do i start exploring?
Well,  just Google "MSBuild Target" you will find a lot of in depth information about how to do the magic. In this post I will explain my conceptual point of view which I used for my recently created template. The template will consist of a couple of xml based files, all sharing the extension .target

Here's my concept:

\SolutionDir\MSBuild\
    Imtech.Common.Import.targets
    Imtech.Common.Properties.targets
    Imtech.Common.Targets.targets
    Imtech.Common.Tasks.targets

\SolutionDir\ProjectDir\MSBuild\
    Imtech.Project.Properties.targets
    Imtech.Project.Targets.targets
    Imtech.Project.Tasks.targets

I will break these file's up into pieces for you
As you can see in the used naming convention there are really only 4 thinks to explain here namely: Import, Properties, Targets and Tasks (except from the fact that I used 2 different folders to put these files in, but more about that later on).

  • *.Import.targets
    This is the file that will connect all the other file's in the right order and an reference to this file will be placed in your .proj file.
  • *.Properties.targets
    In these file's you will define you "dynamic" properties.
    for example, the path of your local IIS folder or the location of your STSADM.EXE tool.
  • *.Targets.targets
    These file's will be your "coordinator", and will provide you with the possibility to enforce logic based on the selected "Solution Configuration" and properties you defined in the Properties.targets. It will call tasks defined in your Task.target files based upon the implemented logic.
    In other words: this will be your router (I used to be a network engineer, and sometimes still think in terms of networks)
  • *.Tasks.target
    In these file's you will find separate pieces of functionality that will be referenced in your Targets.target file.
    Here you will define the actual commands that will be executed and name/group them using some sort of logical convention.

So now that we have covered the difference's between the file's I will explain the 2 folders I used. Earlier I explain that one of the benefits of using MSBuild targets is that it's reusable. This means that in a new project, I can use the same template as I used before. In order to do this, you have to separate any execution logic from your project dependency's. This is where the properties target file kick's into place. In the properties you will define all your project dependant things. And because you probably have more than one project in your solution you have to deal with some "global" and some "local" dependencies. That's why I used 2 folder's, one where you can declare your globally used targets, task and properties an one folder where you can (re)define these properties, or even extend your targets and tasks.

If needed I will post some sample's of the target files we use.
As always, if you have some comment, don't hesitate to... comment!

Thursday, February 21, 2008

Silverlight and SharePoint, a beautiful marriage?

So after almost 2 months of silence I decided it’s time for some new postings. As you may know by now, I have been very busy with Sharepoint the last couple of months. Currently I’m creating a whole new Internet facing website as requested by my boss. Work is progressing, ok not that very fast, I’m still learning more of the sometimes mystical world of SharePoint every day (didn’t I use the word mystical in a previous post, well the word has its purpose, believe me).

So without any further ado, I created a SharePoint WebPart that will show an entire Picture Library in the form of a SilverLight slideshow. The WebPart is mainly based on a project called Silverlight Slideshow initiated by Koen Zwikstra from Firstfloorsoftware.com All I had to do add a little functionality and wrap the whole package into an WSP.
First problem I had to tackle was the logic needed to retrieve information from an SharePoint Picture Library and somehow inject this info into the slideshow.
The original program uses an XML file as its main source of information, making the world a little better place for me ;-)
I created a nice Handler that will do this for me and present the found information in a way the slideshow will “swallow”.
This handler will create the XML based on 3 properties of the library (Image, Thumbnail and Title).
By default there are a lot of configurable properties build into this great SilverLight control. I wrapped all these properties into the WebPart public properties, giving you the great power of controlling the presentation of the control without leaving your SharePoint GUI.
For example, you can turn on/off the buttons, thumbnail, tracker of just change the colors used to render it.
Ok well, how does this thing work in real life then….

All you have to do is:
1. Deploy the WSP to your Sharepoint site.
2. Activate the newly deployed feature in your Site Settings
SlideShow - Feature  
3. Add the WebPart to your site.
SlideShow - AddWebPart
4. Select the Picture Library for your image resource SlideShow - Properties
5. Change the properties of the WebPart to reflect your inner desires.
 
Volia, a fully functional slideshow on your page!
So, where can I download it you might wondering…
Before sharing the code with the community, I first have to check with the original creator of the Silverlight control and see if he’s ok with me releasing this as a WebPart.
For now you will have to do with a screenshot of the WebPart in action.
SlideShow - Preview

Friday, December 28, 2007

My first SharePoint webpart

A few months ago I created my first SharePoint webpart.
The conceptual idea was to have a webpart where items from the contenttype calendar would be aggregated and displayed to the enduser in the form of an eventlist.
Something like:
EvenementenWebPart01
When the users clicks on an item, a new page would be displayed with more information about the selected event.
Something like:
EvenementenWebPart02

1st step in creating this WebPart was to find out what components are involved.
So the WebPart will do the following basic steps every time it is viewed.
1. Get all the listitems (based on a public property's "SiteName" and "ListName" )
2. Sort the listitems
3. Cut the list to the appropriate size (based on a public property "NumberOfEvents")
4. Transform the list to an appropriate XML representation
5. Transform the XML representation by using a XLS (based on a public property "XSL")
6. Additionally if an event happens in the future, add a link to an InfoPath form where the user can subscribe to the upcoming event. This form will be forwarded by email.

Next time I will post some short pieces of code.
For now I just send you to this great resource on how to build your own WebPart for SharePoint

Thursday, December 27, 2007

Regular expression? No Wiener Melange for me please....

This is what most of us will say when we hear the term "Regular expression". No it's not a brand new coffee brand, no it isn't the most common used (and therefore regular) facial expression of the world. No this time I'm talking about some sort of query language used by freaky developers. Recently my program experience is expanding (fast or slow, it IS expanding) and from time to time I literally bounce of a new subject.
Regular expressions is just one of them.
The concept really is fascinating!
These expressions can do almost anything, except make you a delicious Wiener Melange (on the other hand, could your coffee machine make one for you "without" regular expressions? that the question!).
Well jokes aside, I really was fascinated by the concept and couldn't resist taking a little sneak preview in this crazy world of expressions.
An there come's the "bounce"...
Really, can anyone tell me what the hack this means???
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-
\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!
\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-
\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?
<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|
[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-
\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Well, if you break it down piece by piece you will eventually see some logic in the above syntax. To safe you all some backtracking time, here is the answer: The above syntax can be used for validating the syntax of an email address. Well, for me this isn't that logical. From a conceptual point of view these sort of expression can have tremendous power and can be used in very complex situations like pattern recognition. For now I say: Back to the schoolbooks, we've got a lot to learn!

AltirisSVS Class

It's been a while since my last post and progress on my first little side-project is.... slow... The more I think of this project, the more I realize that I'm sort of reinventing the wheel. There are some great free alternative ways of doing what i want and i will look into them as soon as possible. So for now, 
* 1st project status: on-hold

As many of you programmers over the world would recognize, There's ALWAYS plenty of room for new ideas in a programmers head, but way to little free time to actually program those wonderful ideas. One of those ideas I challenged before is the idea of creating a general .NET class that will provide me with various methods for the purpose of controlling the SUPER COOL program AltirisSVS (Software Virtualization).

A little time ago I created a little solution but as messy as i am i don't know where I have the sourcecode of this little thingy. Didn't have a backup, so I'm forced to recreate the whole program, this time I will code my thing in C# (as apposed to the previous version that was created in VB.NET).
To give you a short overview of what the hell I'm going to do we will dive in a little deeper in the magical world of virtualization.

So what is AlririsSVS?
The guys at Altiris created a program that well... virtualizes software installations. To give you a more understandable image, imagine yourself having a pc. That's probably not that hard to imagine, since most of you reading this post are doing this on there own personal desktop. Next step is look at your word processor. Most likely you will find a program like Microsoft Word 2003 or something similar like it. Nothing crazy going on at this stage. Until your boss sends you an MS Word document that was created with the newer version of Microsoft Office 2007 (XDOC format). This is a document format that isn't supported by your older 2003 version of Office. Still not that big of a problem, just upgrade your Office version to the newer 2007 version and off we go! But maybe you just liked office 2003 or corporate policies prohibits you to delete this version. Now what to do???

Here is when AltirisSVS come's into play!!!
Most program's on your pc don't "bite" each other, but some programs will! Program's like Microsoft Office are using so called shared dll files. These files are transferred to your computer during installation and will nestle themselves wherever they are comfortable. Nothing wrong with this, those little dll's will do there work just fine and you probable will never notice them, until you want to run 2 different version of the same program next to another on one pc. Then the new installation will probably overwrite some of these shared dll files without notifying other programs on your pc.

Now you can find yourself with a computer who was 2 versions installed of the same program (for example MS Word 2003 / MS Word 2007). The shared files on your computer will all be version 2007 and you will have trouble running the older 2003 version.
So this is a big NO GO!!!
This problem doesn't occur if you virtualize these installations and run them in separated virtualized environments. Well, lets install VMware or Virtual PC, and install the software into a new virtual pc most of the people will think, but there are WRONG! Install AltirisSVS and you will be able to create the so called "Layers"
In this layer you can then install an application. The layer will be an "sandboxed" environment where all the program files and shared dll will be found. This layer is very flexible, you can enable/disable it, making it possible to totally hide you installed application from the operating systems perspective. You can download a free version from the website (need to be a registered user, so first register on there website). Just play with the software for a while and you will see!

Question some people might ask, if this software is that great, why wanna code something around it? Well, at Altiris they did a great job building the whole virtualisation platform, and on top of that, they created a nice WMI interface so that you can manage your layers through code. And, where there are interfaces, there are those annoying programmers who just can't resist to talk to it.
Well, that's the main reason i started this project.
Why? because i can!
So the first thing to do is making a little framework as a base, letting me extend this framework in the future.

  • Create a little WMI Wrapper for the Altiris WMI class
  • Create a C# Class
    • Activate_Layer(string LayerName)
    • DeActivate_Layer(string LayerName)
    • EnumerateLayers()

Additional resources:
Microsoft WMI Code Creator
Good article on how to make a SVS wmi script
Tech MOSS team, created some nice tools for developers

A little sample code preview (written by rcboenne)

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Text;

    4 using System.Management;

    5 using System.Windows.Forms;

    6 

    7 namespace Focus_XP_SVS_Layer_Console

    8 {

    9     public class WMITest

   10     {

   11         public static void Test()

   12         {

   13             try

   14             {

   15 

   16                 ManagementScope scope = new ManagementScope("root\\default");

   17                 scope.Connect();

   18                 ManagementClass classInstance = new ManagementClass(

   19                 scope,

   20                 new ManagementPath("AltirisVSProv"),

   21                 null);

   22 

   23                 // Obtain in-parameters for the method

   24                 ManagementBaseObject inParams =

   25                 classInstance.GetMethodParameters("EnumerateLayers");

   26 

   27                 // Add the input parameters.

   28                 inParams["Verbose"] = 1;

   29 

   30                 // Execute the method and obtain the return values.

   31                 ManagementBaseObject outParams =

   32                 classInstance.InvokeMethod("EnumerateLayers", inParams, null);

   33 

   34                 // List outParams

   35                 Console.WriteLine("Out parameters:");

   36                 Console.WriteLine("EnumData: " + outParams["EnumData"]);

   37                 Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);

   38             }

   39             catch (ManagementException err)

   40             {

   41                 MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);

   42             }

   43         }

   44 

   45     }

   46 }




Friday, December 7, 2007

Fighting against my own ignorance

Yesterday I started, what seemed like, a little side project. The idea was very straightforward, just write a little GUI to control some installation scripts. Soon after finishing the brainstorm session I eagerly started to code the little thingy.

  • First thing I wanted in place was a little decompression class for the purpose of decompressing a cabinet file. After searching a way to do this from within the code I came across several problems so I thought, what the hack, let’s just make a call from within our code to the external windows program Expand.exe and save some time instead of trying to reinvent the wheel. This eventually did the trick for me! 1 down, a little more to go ;-)


       29         private void StartProcces(string FileName, string Arguments, TextBox OutputTextBox)

       30         {

       31             System.Diagnostics.Process extractCmd = new System.Diagnostics.Process();

       32             extractCmd.EnableRaisingEvents = true;

       33             extractCmd.StartInfo.FileName = FileName;

       34             extractCmd.StartInfo.Arguments = Arguments;

       35             extractCmd.StartInfo.RedirectStandardOutput = true;

       36             extractCmd.StartInfo.RedirectStandardInput = true;

       37             extractCmd.StartInfo.UseShellExecute = false;

       38             extractCmd.StartInfo.CreateNoWindow = true;

       39             extractCmd.Start();

       40             if (OutputTextBox != null)

       41             {

       42                 string StringToWrite = null;

       43                 while (null != (StringToWrite = extractCmd.StandardOutput.ReadLine()))

       44                 {

       45                     AddToProccesViewer(StringToWrite, OutputTextBox);

       46                 }

       47             }

       48             extractCmd.WaitForExit();

       49         }





  • 2nd part of this little adventure was the creation of a class that made it possible to actually run external program’s and that give me the option to redirect it’s output to something like a textbox for instance. The main part of this code I already created for the extraction of the cabinet file. At first a had a little problem writing the output real-time, but after some little tweak’s I had it, a working class to run some simple dos programs.
  • 3rd part would be the easiest of them all, just read the little XML file into the program and iterate through the imported document letting me run the scripted programs. Well, this sounds simpler than it truly is (taking into consideration that the whole XML stuff is quite new to me). First I started off importing the whole XML into a dataset, this didn’t work that well for me. ok, let’s thinks, the problem I had was that I was missing some sort of relation between the imported items. Maybe XSD could help me out of this mess after playing a little with the program XSD.exe I suddenly a whole class that was created from my little XML file. A little overkill if you ask me. So I started it all over. The trick I now use is that I added a little attribute to the program elements called id. Now I’m using only the xml file (no extra schema’s) and iterating thru the file using several XPath expressions instead of relying of the internal relationship of the document, so for now, no usage of the crazy ChildElements.


       79         private void ReadXml()

       80         {

       81             if (System.IO.File.Exists(TMP_PATH + XML_FILENAME))

       82             {

       83                 string myXMLfile = @"" + TMP_PATH + XML_FILENAME;

       84                 string myXMLschema = @"" + TMP_PATH + XSD_FILENAME;

       85                 doc = new System.Xml.XmlDocument();

       86                 doc.Load(TMP_PATH + XML_FILENAME);

       87                 foreach (System.Xml.XmlNode n in doc.SelectNodes("//Program[@id]"))

       88                 {

       89                     AddToProccesViewer("Title: " + n.SelectSingleNode("Title").InnerText, textBox1);

       90                     AddToProccesViewer("Command: " + n.SelectSingleNode("Command").InnerText, textBox1);

       91                     AddToProccesViewer(BuildParameter(n.SelectSingleNode(".").Attributes[0].InnerText), textBox1);

       92 

       93                     string cmd = n.SelectSingleNode("Command").InnerText;

       94                     string param = BuildParameter(n.SelectSingleNode(".").Attributes[0].InnerText);

       95                     string showoutput = n.SelectSingleNode("ShowOutputInWindow").InnerText;

       96                     if (showoutput == "True")

       97                     {

       98                         StartProcces(cmd, param, textBox1);

       99                     }

      100                     else

      101                     {

      102                         StartProcces(cmd, param, null);

      103                     }

      104                 }

      105             }

      106         }






  • 4th part of the project would be putting the whole thing together. This is the currently state of the project. I discovered a little inconvenience, Dos program’s that require user input seem to “hang”, so I have to trigger some sort of event in case this happens and let the user (or the Deploy.xml scripting file) choose the appropriate action. After having resolved this issue I will take on another challenge. I have to build some sort of functionality that makes it possible to editing file’s that are extracted from the cab file based on some sort of user input (Example: The installation program asks a destination directory and has to change several batchfile’s in the cab file to make the necessary changes that will make the batchfile’s copy file’s to this user provided path)

That’s it for now, back to code!