using System;
using System.Xml;
using System.Xml.Xsl;
using System.IO;

namespace XSLTSample
{
	/// <summary>
	/// The following sample shows one of the simplest possible XSLT-related 
	/// programs in C#. Given a source filename, a stylesheet filename, and 
	/// a destination filename, it transforms the source into the destination 
	/// using the stylesheet. It will work with any XML source file and any 
	/// XSLT stylesheet.
	/// </summary>
	/// 
	class XSLTRun
	{
		static void Transform(string source, string stylesheet, string destination) 
		{
			XslTransform transform = new XslTransform( );
			transform.Load(stylesheet);

			// Create a resolver with default credentials.
			XmlUrlResolver resolver = new XmlUrlResolver();
			resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;

			transform.Transform(source, destination, resolver);
		}

		static void Main(string[] args)
		{
			if (args.Length < 2) {
				Console.WriteLine("Usage: xsltrun docwrap.xml page_index.xsl docwrap.html");
				Console.WriteLine("       xsltrun xmldir bookmarks.xsl");
				return;
			}

			try
			{
				if (args.Length == 2) 
				{
					string dir = args[0];
					string stylesheet = args[1];

					string[] docs = Directory.GetFiles(Path.GetFullPath(dir), "*.xml");
					foreach(string xmlfile in docs)
					{
						Transform(xmlfile, stylesheet, Path.GetFileNameWithoutExtension(xmlfile) + ".html");
					}
				}
				else if (args.Length == 3) 
				{
					string source = args[0];
					string stylesheet = args[1];
					string destination = args[2];
					Transform(source, stylesheet, destination);
				}
			} 
			catch(Exception ex) 
			{
				Console.Write("Error: ");
				Console.WriteLine(ex.ToString());
				return;
			}			
		}
	}
}
