Click here to Skip to main content
15,891,907 members
Articles / Programming Languages / Visual Basic

Template Based Code Generator

Rate me:
Please Sign up or sign in to vote.
4.67/5 (33 votes)
20 Nov 2007CPOL13 min read 93.4K   4.1K   116  
A template based, command-line oriented .NET code generator
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using Arebis.CodeGeneration;

namespace Arebis.CodeGenerator.Templated
{
	[System.Diagnostics.DebuggerStepThrough]
	public class DefaultFileWriter : BaseFileWriter
	{
		private bool overwriteReadonly = false;
		private string tabspaces = String.Empty;

		public override IGenerationHost Host
		{
			get
			{
				return base.Host;
			}
			set
			{
				base.Host = value;

				this.overwriteReadonly = Convert.ToBoolean(this.Host.Settings["overwritereadonly"]);
				this.tabspaces = new String(' ', Convert.ToInt32(this.Host.Settings["tabspaces"]));
			}
		}

		public override void WriteFile(string filename, string content)
		{
			// Replace tabs by spaces if 'tabspaces' setting > 0
			if (this.tabspaces.Length > 0) content = content.Replace("\t", this.tabspaces);

			// Retrieve fileinfo and make file writable:
			FileInfo fileinfo = new FileInfo(filename);
			if (this.overwriteReadonly)
			{
				if ( fileinfo.Exists && fileinfo.IsReadOnly) fileinfo.IsReadOnly = false;
			}

			// Write file:
			try
			{
				this.Host.Log("Writing file \"{0}\".", filename);
				fileinfo.Directory.Create();
				System.IO.File.WriteAllText(filename, content);
			}
			catch (UnauthorizedAccessException)
			{
				if (this.overwriteReadonly)
				{
					this.Host.Log("Warning: Failed to overwrite file '{0}'", filename);
				}
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect AREBIS
Belgium Belgium
Senior Software Architect and independent consultant.

Comments and Discussions