adapdev-commits Mailing List for Adapdev.NET (Page 9)
Status: Beta
Brought to you by:
intesar66
You can subscribe to this list here.
2005 |
Jan
|
Feb
|
Mar
(26) |
Apr
(59) |
May
(37) |
Jun
(53) |
Jul
(13) |
Aug
(7) |
Sep
(5) |
Oct
(74) |
Nov
(404) |
Dec
(14) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(10) |
Feb
(26) |
Mar
(64) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Windows.Forms/Commands In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Windows.Forms/Commands Added Files: AbstractGUICommand.cs IGUICommand.cs ShowErrorMessageCommand.cs vssver.scc Log Message: --- NEW FILE: AbstractGUICommand.cs --- using System; using Adapdev.Commands; namespace Adapdev.Windows.Commands { using System.Windows.Forms; /// <summary> /// Summary description for AbstractGUICommand. /// </summary> public abstract class AbstractGUICommand : IGUICommand { private IWin32Window _owner = null; public AbstractGUICommand(IWin32Window owner) { this._owner = owner; } public IWin32Window Owner { get { return this._owner; } set { this._owner = value; } } public abstract void Execute(); } } --- NEW FILE: IGUICommand.cs --- using System; using System.Windows.Forms; using Adapdev.Commands; namespace Adapdev.Windows.Commands { /// <summary> /// Summary description for IGUICommand. /// </summary> public interface IGUICommand : ICommand { IWin32Window Owner{get;set;} } } --- NEW FILE: vssver.scc --- (This appears to be a binary file; contents omitted.) --- NEW FILE: ShowErrorMessageCommand.cs --- using System; using Adapdev.Commands; namespace Adapdev.Windows.Commands { using System.Windows.Forms; /// <summary> /// Summary description for MessageBoxCommand. /// </summary> public class ShowErrorMessageCommand : AbstractGUICommand { private Exception _exception = null; private bool _showStackTrace = false; private DialogResult _result; public ShowErrorMessageCommand(IWin32Window owner, Exception e, bool showStackTrace):base(owner) { this._exception = e; this._showStackTrace = showStackTrace; } public override void Execute() { this._result = MessageBox.Show(this.GetMessage(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } private string GetMessage() { if(this._showStackTrace) { return this._exception.Message + " : " + this._exception.StackTrace; } else { return this._exception.Message; } } public DialogResult Result { get{return this._result;} } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Util Added Files: Iterator.cs SimplePool.cs StringUtils.cs Log Message: --- NEW FILE: StringUtils.cs --- namespace NVelocity.Util { using System; using System.Collections; using System.IO; using System.Text; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> This class provides some methods for dynamically /// invoking methods in objects, and some string /// manipulation methods used by torque. The string /// methods will soon be moved into the turbine /// string utilities class. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a> /// </author> /// <version> $Id: StringUtils.cs,v 1.5 2005/11/16 07:01:52 intesar66 Exp $ /// /// </version> public class StringUtils { public StringUtils() { InitBlock(); } private void InitBlock() { //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangSystemgetProperty_javalangString"' EOL = Environment.NewLine; EOL_LENGTH = EOL.Length; } /// <summary> Line separator for the OS we are operating on. /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'EOL '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'EOL' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private static String EOL; /// <summary> Length of the line separator. /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'EOL_LENGTH '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' //UPGRADE_NOTE: The initialization of 'EOL_LENGTH' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private static int EOL_LENGTH; /// <summary> Concatenates a list of objects as a String. /// * /// </summary> /// <param name="list">The list of objects to concatenate. /// </param> /// <returns> A text representation of the concatenated objects. /// /// </returns> public virtual String concat(IList list) { StringBuilder sb = new StringBuilder(); int size = list.Count; for (int i = 0; i < size; i++) { sb.Append(list[i].ToString()); } return sb.ToString(); } /// <summary> Return a package name as a relative path name /// * /// </summary> /// <param name="String">package name to convert to a directory. /// </param> /// <returns>String directory path. /// /// </returns> public static String getPackageAsPath(String pckge) { return pckge.Replace('.', Path.DirectorySeparatorChar.ToString()[0]) + Path.DirectorySeparatorChar.ToString(); } /// <summary> <p> /// Remove underscores from a string and replaces first /// letters with capitals. Other letters are changed to lower case. /// </p> /// * /// <p> /// For example <code>foo_bar</code> becomes <code>FooBar</code> /// but <code>foo_barBar</code> becomes <code>FooBarbar</code>. /// </p> /// * /// </summary> /// <param name="data">string to remove underscores from. /// </param> /// <returns>String /// </returns> /// <deprecated>Use the org.apache.commons.util.StringUtils class /// instead. Using its firstLetterCaps() method in conjunction /// with a StringTokenizer will achieve the same result. /// /// </deprecated> public static String removeUnderScores(String data) { String temp = null; StringBuilder out_Renamed = new StringBuilder(); temp = data; SupportClass.Tokenizer st = new SupportClass.Tokenizer(temp, "_"); while (st.HasMoreTokens()) { String element = (String) st.NextToken(); out_Renamed.Append(firstLetterCaps(element)); } return out_Renamed.ToString(); } /// <summary> <p> /// 'Camels Hump' replacement of underscores. /// </p> /// * /// <p> /// Remove underscores from a string but leave the capitalization of the /// other letters unchanged. /// </p> /// * /// <p> /// For example <code>foo_barBar</code> becomes <code>FooBarBar</code>. /// </p> /// * /// </summary> /// <param name="data">string to hump /// </param> /// <returns>String /// /// </returns> public static String removeAndHump(String data) { return removeAndHump(data, "_"); } /// <summary> <p> /// 'Camels Hump' replacement. /// </p> /// * /// <p> /// Remove one string from another string but leave the capitalization of the /// other letters unchanged. /// </p> /// * /// <p> /// For example, removing "_" from <code>foo_barBar</code> becomes <code>FooBarBar</code>. /// </p> /// * /// </summary> /// <param name="data">string to hump /// </param> /// <param name="replaceThis">string to be replaced /// </param> /// <returns>String /// /// </returns> public static String removeAndHump(String data, String replaceThis) { String temp = null; StringBuilder out_Renamed = new StringBuilder(); temp = data; SupportClass.Tokenizer st = new SupportClass.Tokenizer(temp, replaceThis); while (st.HasMoreTokens()) { String element = (String) st.NextToken(); out_Renamed.Append(capitalizeFirstLetter(element)); } //while return out_Renamed.ToString(); } /// <summary> <p> /// Makes the first letter caps and the rest lowercase. /// </p> /// * /// <p> /// For example <code>fooBar</code> becomes <code>Foobar</code>. /// </p> /// * /// </summary> /// <param name="data">capitalize this /// </param> /// <returns>String /// /// </returns> public static String firstLetterCaps(String data) { String firstLetter = data.Substring(0, (1) - (0)).ToUpper(); String restLetters = data.Substring(1).ToLower(); return firstLetter + restLetters; } /// <summary> <p> /// Capitalize the first letter but leave the rest as they are. /// </p> /// * /// <p> /// For example <code>fooBar</code> becomes <code>FooBar</code>. /// </p> /// * /// </summary> /// <param name="data">capitalize this /// </param> /// <returns>String /// /// </returns> public static String capitalizeFirstLetter(String data) { String firstLetter = data.Substring(0, (1) - (0)).ToUpper(); String restLetters = data.Substring(1); return firstLetter + restLetters; } /// <summary> Create a string array from a string separated by delim /// * /// </summary> /// <param name="line">the line to split /// </param> /// <param name="delim">the delimter to split by /// </param> /// <returns>a string array of the split fields /// /// </returns> public static String[] split(String line, String delim) { ArrayList list = new ArrayList(); SupportClass.Tokenizer t = new SupportClass.Tokenizer(line, delim); while (t.HasMoreTokens()) { list.Add(t.NextToken()); } return (String[]) list.ToArray(typeof (String)); } /// <summary> Chop i characters off the end of a string. /// This method assumes that any EOL characters in String s /// and the platform EOL will be the same. /// A 2 character EOL will count as 1 character. /// * /// </summary> /// <param name="string">String to chop. /// </param> /// <param name="i">Number of characters to chop. /// </param> /// <returns>String with processed answer. /// /// </returns> public static String chop(String s, int i) { return chop(s, i, EOL); } /// <summary> Chop i characters off the end of a string. /// A 2 character EOL will count as 1 character. /// * /// </summary> /// <param name="string">String to chop. /// </param> /// <param name="i">Number of characters to chop. /// </param> /// <param name="eol">A String representing the EOL (end of line). /// </param> /// <returns>String with processed answer. /// /// </returns> public static String chop(String s, int i, String eol) { if (i == 0 || s == null || eol == null) { return s; } int length = s.Length; /* * if it is a 2 char EOL and the string ends with * it, nip it off. The EOL in this case is treated like 1 character */ if (eol.Length == 2 && s.EndsWith(eol)) { length -= 2; i -= 1; } if (i > 0) { length -= i; } if (length < 0) { length = 0; } return s.Substring(0, (length) - (0)); } // public static System.Text.StringBuilder stringSubstitution(System.String argStr, System.Collections.Hashtable vars) // { // return stringSubstitution(argStr, (Map) vars); // } /// <summary> Perform a series of substitutions. The substitions /// are performed by replacing $variable in the target /// string with the value of provided by the key "variable" /// in the provided hashtable. /// * /// </summary> /// <param name="String">target string /// </param> /// <param name="Hashtable">name/value pairs used for substitution /// </param> /// <returns>String target string with replacements. /// /// </returns> public static StringBuilder stringSubstitution(String argStr, Hashtable vars) { StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; ) { char ch = argStr[cIdx]; switch (ch) { case '$': StringBuilder nameBuf = new StringBuilder(); for (++cIdx; cIdx < argStr.Length; ++cIdx) { ch = argStr[cIdx]; if (ch == '_' || Char.IsLetterOrDigit(ch)) nameBuf.Append(ch); else break; } if (nameBuf.Length > 0) { String value_Renamed = (String) vars[nameBuf.ToString()]; if (value_Renamed != null) { argBuf.Append(value_Renamed); } } break; default: argBuf.Append(ch); ++cIdx; break; } } return argBuf; } /// <summary> Read the contents of a file and place them in /// a string object. /// * /// </summary> /// <param name="String">path to file. /// </param> /// <returns>String contents of the file. /// /// </returns> public static String fileContentsToString(String file) { String contents = ""; FileInfo f = new FileInfo(file); bool tmpBool; if (File.Exists(f.FullName)) tmpBool = true; else tmpBool = Directory.Exists(f.FullName); if (tmpBool) { try { StreamReader fr = new StreamReader(f.FullName); char[] template = new char[(int) SupportClass.FileLength(f)]; fr.Read((Char[]) template, 0, template.Length); contents = new String(template); fr.Close(); } catch (Exception e) { Console.Out.WriteLine(e); SupportClass.WriteStackTrace(e, Console.Error); } } return contents; } /// <summary> Remove/collapse multiple newline characters. /// * /// </summary> /// <param name="String">string to collapse newlines in. /// </param> /// <returns>String /// /// </returns> public static String collapseNewlines(String argStr) { char last = argStr[0]; StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; cIdx++) { char ch = argStr[cIdx]; if (ch != '\n' || last != '\n') { argBuf.Append(ch); last = ch; } } return argBuf.ToString(); } /// <summary> Remove/collapse multiple spaces. /// * /// </summary> /// <param name="String">string to remove multiple spaces from. /// </param> /// <returns>String /// /// </returns> public static String collapseSpaces(String argStr) { char last = argStr[0]; StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; cIdx++) { char ch = argStr[cIdx]; if (ch != ' ' || last != ' ') { argBuf.Append(ch); last = ch; } } return argBuf.ToString(); } /// <summary> Replaces all instances of oldString with newString in line. /// Taken from the Jive forum package. /// * /// </summary> /// <param name="String">original string. /// </param> /// <param name="String">string in line to replace. /// </param> /// <param name="String">replace oldString with this. /// </param> /// <returns>String string with replacements. /// /// </returns> public static String sub(String line, String oldString, String newString) { int i = 0; if ((i = line.IndexOf(oldString, i)) >= 0) { char[] line2 = line.ToCharArray(); char[] newString2 = newString.ToCharArray(); int oLength = oldString.Length; StringBuilder buf = new StringBuilder(line2.Length); buf.Append(line2, 0, i).Append(newString2); i += oLength; int j = i; while ((i = line.IndexOf(oldString, i)) > 0) { buf.Append(line2, j, i - j).Append(newString2); i += oLength; j = i; } buf.Append(line2, j, line2.Length - j); return buf.ToString(); } return line; } /// <summary> Returns the output of printStackTrace as a String. /// * /// </summary> /// <param name="e">A Throwable. /// </param> /// <returns>A String. /// /// </returns> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' public static String stackTrace(Exception e) { String foo = null; try { // And show the Error Screen. MemoryStream ostr = new MemoryStream(); StreamWriter temp_writer; temp_writer = new StreamWriter(ostr); temp_writer.AutoFlush = true; SupportClass.WriteStackTrace(e, temp_writer); char[] tmpChar; byte[] tmpByte; tmpByte = ostr.GetBuffer(); tmpChar = new char[tmpByte.Length]; tmpByte.CopyTo(tmpChar, 0); foo = new String(tmpChar); } catch (Exception f) { // Do nothing. } return foo; } /// <summary> Return a context-relative path, beginning with a "/", that represents /// the canonical version of the specified path after ".." and "." elements /// are resolved out. If the specified path attempts to go outside the /// boundaries of the current context (i.e. too many ".." path elements /// are present), return <code>null</code> instead. /// * /// </summary> /// <param name="path">Path to be normalized /// </param> /// <returns>String normalized path /// /// </returns> public static String normalizePath(String path) { // Normalize the slashes and add leading slash if necessary String normalized = path; if (normalized.IndexOf((Char) '\\') >= 0) { normalized = normalized.Replace('\\', '/'); } if (!normalized.StartsWith("/")) { normalized = "/" + normalized; } // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.IndexOf("//"); if (index < 0) break; normalized = normalized.Substring(0, (index) - (0)) + normalized.Substring(index + 1); } // Resolve occurrences of "%20" in the normalized path while (true) { int index = normalized.IndexOf("%20"); if (index < 0) break; normalized = normalized.Substring(0, (index) - (0)) + " " + normalized.Substring(index + 3); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.IndexOf("/./"); if (index < 0) break; normalized = normalized.Substring(0, (index) - (0)) + normalized.Substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.IndexOf("/../"); if (index < 0) break; if (index == 0) return (null); // Trying to go outside our context int index2 = normalized.LastIndexOf((Char) '/', index - 1); normalized = normalized.Substring(0, (index2) - (0)) + normalized.Substring(index + 3); } // Return the normalized path that we have completed return (normalized); } /// <summary> If state is true then return the trueString, else /// return the falseString. /// * /// </summary> /// <param name="boolean"> /// </param> /// <param name="String">trueString /// </param> /// <param name="String">falseString /// /// </param> public virtual String select(bool state, String trueString, String falseString) { if (state) { return trueString; } else { return falseString; } } /// <summary> Check to see if all the string objects passed /// in are empty. /// * /// </summary> /// <param name="list">A list of {@link java.lang.String} objects. /// </param> /// <returns> Whether all strings are empty. /// /// </returns> public virtual bool allEmpty(IList list) { int size = list.Count; for (int i = 0; i < size; i++) { if (list[i] != null && list[i].ToString().Length > 0) { return false; } } return true; } } } --- NEW FILE: SimplePool.cs --- namespace NVelocity.Util { using System; /* * $Header: /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util/SimplePool.cs,v 1.5 2005/11/16 07:01:52 intesar66 Exp $ * $Revision: 1.5 $ * $Date: 2005/11/16 07:01:52 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ /// <summary> Simple object pool. Based on ThreadPool and few other classes /// * /// The pool will ignore overflow and return null if empty. /// * /// </summary> /// <author> Gal Shachor /// </author> /// <author> Costin /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: SimplePool.cs,v 1.5 2005/11/16 07:01:52 intesar66 Exp $ /// /// </version> public sealed class SimplePool { public int Max { get { return max; } } /* * Where the objects are held. */ private Object[] pool; /// <summary> max amount of objects to be managed /// set via CTOR /// </summary> private int max; /// <summary> index of previous to next /// free slot /// </summary> private int current = - 1; public SimplePool(int max) { this.max = max; pool = new Object[max]; } /// <summary> Add the object to the pool, silent nothing if the pool is full /// </summary> public void put(Object o) { int idx = - 1; lock (this) { /* * if we aren't full */ if (current < max - 1) { /* * then increment the * current index. */ idx = ++current; } if (idx >= 0) { pool[idx] = o; } } } /// <summary> Get an object from the pool, null if the pool is empty. /// </summary> public Object get() { int idx = - 1; lock (this) { /* * if we have any in the pool */ if (current >= 0) { /* * take one out, so to speak - * separate the two operations * to make it clear that you * don't want idx = --current; :) */ idx = current; current--; /* * and since current was >= 0 * to get in here, idx must be as well * so save the if() opration */ return pool[idx]; } } return null; } /// <summary>Return the size of the pool /// </summary> } } --- NEW FILE: Iterator.cs --- namespace NVelocity.Util { using System; public interface Iterator { /// <summary> Move to next element in the array. /// </summary> /// <returns>The next object in the array. /// </returns> Object next(); /// <summary> Check to see if there is another element in the array. /// </summary> /// <returns>Whether there is another element. /// </returns> bool hasNext(); } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Resource Added Files: ContentResource.cs Resource.cs ResourceCache.cs ResourceCacheImpl.cs ResourceFactory.cs ResourceManager.cs ResourceManagerImpl.cs Log Message: --- NEW FILE: ResourceFactory.cs --- namespace NVelocity.Runtime.Resource { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; /// <summary> Class responsible for instantiating <code>Resource</code> objects, /// given name and type. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceFactory.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ResourceFactory { public static Resource getResource(String resourceName, int resourceType) { Resource resource = null; switch (resourceType) { case ResourceManager_Fields.RESOURCE_TEMPLATE: resource = new Template(); break; case ResourceManager_Fields.RESOURCE_CONTENT: resource = new ContentResource(); break; } return resource; } } } --- NEW FILE: ContentResource.cs --- namespace NVelocity.Runtime.Resource { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; /// <summary> This class represent a general text resource that /// may have been retrieved from any number of possible /// sources. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ContentResource.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ContentResource : Resource { /// <summary>Default empty constructor /// </summary> public ContentResource() { } /// <summary>Pull in static content and store it /// </summary> public override bool Process() { try { StringWriter sw = new StringWriter(); //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' StreamReader reader = new StreamReader(new StreamReader(resourceLoader.getResourceStream(name), System.Text.Encoding.GetEncoding(encoding)).BaseStream); char[] buf = new char[1024]; int len = 0; // -1 in java, 0 in .Net while ((len = reader.Read(buf, 0, 1024)) > 0) { sw.Write(buf, 0, len); } data = sw.ToString(); return true; } catch (Exception e) { rsvc.error("Cannot process content resource : " + e.ToString()); return false; } } } } --- NEW FILE: ResourceCacheImpl.cs --- namespace NVelocity.Runtime.Resource { using System; using System.Collections; /// <summary> Default implementation of the resource cache for the default /// ResourceManager. /// * /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a> /// </author> /// <version> $Id: ResourceCacheImpl.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ResourceCacheImpl : ResourceCache { /// <summary> /// Cache storage, assumed to be thread-safe. /// </summary> //UPGRADE_NOTE: The initialization of 'cache' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' protected internal Hashtable cache = new Hashtable(); /// <summary> /// Runtime services, generally initialized by the /// <code>initialize()</code> method. /// </summary> protected internal RuntimeServices rsvc = null; public ResourceCacheImpl() { } public virtual void initialize(RuntimeServices rs) { rsvc = rs; rsvc.info("ResourceCache : initialized. (" + this.GetType() + ")"); } public virtual Resource get(Object key) { return (Resource) cache[key]; } public virtual Resource put(Object key, Resource value_Renamed) { Object o = cache[key]; cache[key] = value_Renamed; return (Resource) o; } public virtual Resource remove(Object key) { Object o = cache[key]; cache.Remove(key); return (Resource) o; } public virtual IEnumerator enumerateKeys() { return cache.Keys.GetEnumerator(); } } } --- NEW FILE: ResourceCache.cs --- namespace NVelocity.Runtime.Resource { using System; using System.Collections; /// <summary> Interface that defines the shape of a pluggable resource cache /// for the included ResourceManager /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceCache.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public interface ResourceCache { /// <summary> initializes the ResourceCache. Will be /// called before any utilization /// * /// </summary> /// <param name="rs">RuntimeServices to use for logging, etc /// /// </param> void initialize(RuntimeServices rs); /// <summary> retrieves a Resource from the /// cache /// * /// </summary> /// <param name="resourceKey">key for Resource to be retrieved /// </param> /// <returns>Resource specified or null if not found /// /// </returns> Resource get(Object resourceKey); /// <summary> stores a Resource in the cache /// * /// </summary> /// <param name="resourceKey">key to associate with the Resource /// </param> /// <param name="resource">Resource to be stored /// </param> /// <returns>existing Resource stored under this key, or null if none /// /// </returns> Resource put(Object resourceKey, Resource resource); /// <summary> removes a Resource from the cache /// * /// </summary> /// <param name="resourceKey">resource to be removed /// </param> /// <param name="Resource">stored under key /// /// </param> Resource remove(Object resourceKey); /// <summary> returns an Iterator of Keys in the cache /// </summary> IEnumerator enumerateKeys(); } } --- NEW FILE: Resource.cs --- namespace NVelocity.Runtime.Resource { using System; using NVelocity.Runtime.Resource.Loader; /// <summary> This class represent a general text resource that /// may have been retrieved from any number of possible /// sources. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: Resource.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public abstract class Resource { private void InitBlock() { encoding = RuntimeConstants_Fields.ENCODING_DEFAULT; } public virtual RuntimeServices RuntimeServices { set { rsvc = value; } } public virtual long ModificationCheckInterval { set { this.modificationCheckInterval = value; } } public virtual String Name { get { return name; } set { this.name = value; } } public virtual String Encoding { get { return encoding; } set { this.encoding = value; } } public virtual long LastModified { get { return lastModified; } set { this.lastModified = value; } } public virtual ResourceLoader ResourceLoader { get { return resourceLoader; } set { this.resourceLoader = value; } } public virtual Object Data { get { return data; } set { this.data = value; } } protected internal RuntimeServices rsvc = null; /// <summary> The template loader that initially loaded the input /// stream for this template, and knows how to check the /// source of the input stream for modification. /// </summary> protected internal ResourceLoader resourceLoader; /// <summary> The number of milliseconds in a minute, used to calculate the /// check interval. /// </summary> protected internal const long MILLIS_PER_SECOND = 1000; /// <summary> How often the file modification time is checked (in milliseconds). /// </summary> protected internal long modificationCheckInterval = 0; /// <summary> The file modification time (in milliseconds) for the cached template. /// </summary> protected internal long lastModified = 0; /// <summary> The next time the file modification time will be checked (in /// milliseconds). /// </summary> protected internal long nextCheck = 0; /// <summary> Name of the resource /// </summary> protected internal String name; /// <summary> Character encoding of this resource /// </summary> //UPGRADE_NOTE: The initialization of 'encoding' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' protected internal String encoding; /// /// <summary> Resource might require ancillary storage of some kind /// </summary> protected internal Object data = null; /// /// <summary> Default constructor /// </summary> public Resource() { InitBlock(); } /// <summary> Perform any subsequent processing that might need /// to be done by a resource. In the case of a template /// the actual parsing of the input stream needs to be /// performed. /// </summary> public abstract bool Process(); public virtual bool IsSourceModified() { return resourceLoader.isSourceModified(this); } /// <summary> Set the modification check interval. /// </summary> /// <param name="interval">The interval (in minutes). /// /// </param> /// <summary> Is it time to check to see if the resource /// source has been updated? /// </summary> public virtual bool RequiresChecking() { /* * short circuit this if modificationCheckInterval == 0 * as this means "don't check" */ if (modificationCheckInterval <= 0) { return false; } /* * see if we need to check now */ return ((DateTime.Now.Ticks - 621355968000000000)/10000 >= nextCheck); } /// <summary> 'Touch' this template and thereby resetting /// the nextCheck field. /// </summary> public virtual void Touch() { nextCheck = (DateTime.Now.Ticks - 621355968000000000)/10000 + (MILLIS_PER_SECOND*modificationCheckInterval); } /// <summary> Set the name of this resource, for example /// test.vm. /// </summary> /// <summary> Get the name of this template. /// </summary> /// <summary> set the encoding of this resource /// for example, "ISO-8859-1" /// </summary> /// <summary> get the encoding of this resource /// for example, "ISO-8859-1" /// </summary> /// <summary> Return the lastModifed time of this /// template. /// </summary> /// <summary> Set the last modified time for this /// template. /// </summary> /// <summary> Return the template loader that pulled /// in the template stream /// </summary> /// <summary> Set the template loader for this template. Set /// when the Runtime determines where this template /// came from the list of possible sources. /// </summary> /// /// <summary> Set arbitrary data object that might be used /// by the resource. /// </summary> /// <summary> Get arbitrary data object that might be used /// by the resource. /// </summary> } } --- NEW FILE: ResourceManager.cs --- namespace NVelocity.Runtime.Resource { using System; /// <summary> Class to manage the text resource for the Velocity /// Runtime. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:pau...@kr...">Paulo Gaspar</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceManager.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public struct ResourceManager_Fields { public const int RESOURCE_TEMPLATE = 1; public const int RESOURCE_CONTENT = 2; } public interface ResourceManager { //UPGRADE_NOTE: Members of interface 'ResourceManager' were extracted into structure 'ResourceManager_Fields'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1045"' /// <summary> A template resources. /// </summary> /// <summary> A static content resource. /// </summary> /// <summary> Initialize the ResourceManager. It is assumed /// that assembleSourceInitializers() has been /// called before this is run. /// </summary> void initialize(RuntimeServices rs); /// <summary> Gets the named resource. Returned class type corresponds to specified type /// (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>). /// * /// </summary> /// <param name="resourceName">The name of the resource to retrieve. /// </param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <param name="encoding"> The character encoding to use. /// </param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// /// </returns> Resource getResource(String resourceName, int resourceType, String encoding); /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> String getLoaderNameForResource(String resourceName); } } --- NEW FILE: ResourceManagerImpl.cs --- namespace NVelocity.Runtime.Resource { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Exception; using NVelocity.Runtime.Resource.Loader; /// <summary> Class to manage the text resource for the Velocity /// Runtime. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:pau...@kr...">Paulo Gaspar</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ResourceManagerImpl.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ResourceManagerImpl : ResourceManager { public ResourceManagerImpl() { InitBlock(); } private void InitBlock() { resourceLoaders = new ArrayList(); sourceInitializerList = new ArrayList(); sourceInitializerMap = new Hashtable(); } /// <summary> A template resources. /// </summary> public const int RESOURCE_TEMPLATE = 1; /// <summary> A static content resource. /// </summary> public const int RESOURCE_CONTENT = 2; /// <summary> token used to identify the loader internally /// </summary> private const String RESOURCE_LOADER_IDENTIFIER = "_RESOURCE_LOADER_IDENTIFIER_"; /// <summary> Object implementing ResourceCache to /// be our resource manager's Resource cache. /// </summary> protected internal ResourceCache globalCache = null; /// <summary> The List of templateLoaders that the Runtime will /// use to locate the InputStream source of a template. /// </summary> //UPGRADE_NOTE: The initialization of 'resourceLoaders' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' protected internal ArrayList resourceLoaders; /// <summary> This is a list of the template input stream source /// initializers, basically properties for a particular /// template stream source. The order in this list /// reflects numbering of the properties i.e. /// * /// <loader-id>.resource.loader.<property> = <value> /// </summary> //UPGRADE_NOTE: The initialization of 'sourceInitializerList' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private ArrayList sourceInitializerList; /// <summary> This is a map of public name of the template /// stream source to it's initializer. This is so /// that clients of velocity can set properties of /// a template source stream with its public name. /// So for example, a client could set the /// File.resource.path property and this would /// change the resource.path property for the /// file template stream source. /// </summary> //UPGRADE_NOTE: The initialization of 'sourceInitializerMap' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Hashtable sourceInitializerMap; /// <summary> Each loader needs a configuration object for /// its initialization, this flags keeps track of whether /// or not the configuration objects have been created /// for the resource loaders. /// </summary> private bool resourceLoaderInitializersActive = false; /// <summary> /// switch to turn off log notice when a resource is found for /// the first time. /// </summary> private bool logWhenFound = true; protected internal RuntimeServices rsvc = null; /// <summary> Initialize the ResourceManager. It is assumed /// that assembleSourceInitializers() has been /// called before this is run. /// </summary> public virtual void initialize(RuntimeServices rs) { rsvc = rs; rsvc.info("Default ResourceManager initializing. (" + this.GetType() + ")"); ResourceLoader resourceLoader; assembleResourceLoaderInitializers(); for (int i = 0; i < sourceInitializerList.Count; i++) { ExtendedProperties configuration = (ExtendedProperties) sourceInitializerList[i]; String loaderClass = configuration.GetString("class"); if (loaderClass == null) { rsvc.error("Unable to find '" + configuration.GetString(RESOURCE_LOADER_IDENTIFIER) + ".resource.loader.class' specification in configuation." + " This is a critical value. Please adjust configuration."); continue; } resourceLoader = ResourceLoaderFactory.getLoader(rsvc, loaderClass); resourceLoader.commonInit(rsvc, configuration); resourceLoader.init(configuration); resourceLoaders.Add(resourceLoader); } /* * now see if this is overridden by configuration */ logWhenFound = rsvc.getBoolean(RuntimeConstants_Fields.RESOURCE_MANAGER_LOGWHENFOUND, true); /* * now, is a global cache specified? */ String claz = rsvc.getString(RuntimeConstants_Fields.RESOURCE_MANAGER_CACHE_CLASS); Object o = null; if (claz != null && claz.Length > 0) { try { Type type = Type.GetType(claz); o = Activator.CreateInstance(type); } catch (Exception cnfe) { String err = "The specified class for ResourceCache (" + claz + ") does not exist (or is not accessible to the current classlaoder)."; rsvc.error(err); o = null; } if (!(o is ResourceCache)) { String err = "The specified class for ResourceCache (" + claz + ") does not implement NVelocity.Runtime.Resource.ResourceCache." + " Using default ResourceCache implementation."; rsvc.error(err); o = null; } } /* * if we didn't get through that, just use the default. */ if (o == null) { o = new ResourceCacheImpl(); } globalCache = (ResourceCache) o; globalCache.initialize(rsvc); rsvc.info("Default ResourceManager initialization complete."); } /// <summary> This will produce a List of Hashtables, each /// hashtable contains the intialization info for /// a particular resource loader. This Hastable /// will be passed in when initializing the /// the template loader. /// </summary> private void assembleResourceLoaderInitializers() { if (resourceLoaderInitializersActive) { return; } ArrayList resourceLoaderNames = rsvc.Configuration.GetVector(RuntimeConstants_Fields.RESOURCE_LOADER); for (int i = 0; i < resourceLoaderNames.Count; i++) { /* * The loader id might look something like the following: * * file.resource.loader * * The loader id is the prefix used for all properties * pertaining to a particular loader. */ String loaderID = resourceLoaderNames[i] + "." + RuntimeConstants_Fields.RESOURCE_LOADER; ExtendedProperties loaderConfiguration = rsvc.Configuration.Subset(loaderID); /* * we can't really count on ExtendedProperties to give us an empty set */ if (loaderConfiguration == null) { rsvc.warn("ResourceManager : No configuration information for resource loader named '" + resourceLoaderNames[i] + "'. Skipping."); continue; } /* * add the loader name token to the initializer if we need it * for reference later. We can't count on the user to fill * in the 'name' field */ loaderConfiguration.SetProperty(RESOURCE_LOADER_IDENTIFIER, resourceLoaderNames[i]); /* * Add resources to the list of resource loader * initializers. */ sourceInitializerList.Add(loaderConfiguration); } resourceLoaderInitializersActive = true; } /// <summary> Gets the named resource. Returned class type corresponds to specified type /// (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>). /// * /// </summary> /// <param name="resourceName">The name of the resource to retrieve. /// </param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <param name="encoding"> The character encoding to use. /// </param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// /// </returns> public virtual Resource getResource(String resourceName, int resourceType, String encoding) { /* * Check to see if the resource was placed in the cache. * If it was placed in the cache then we will use * the cached version of the resource. If not we * will load it. */ Resource resource = globalCache.get(resourceName); if (resource != null) { /* * refresh the resource */ try { refreshResource(resource, encoding); } catch (ResourceNotFoundException rnfe) { /* * something exceptional happened to that resource * this could be on purpose, * so clear the cache and try again */ globalCache.remove(resourceName); return getResource(resourceName, resourceType, encoding); } catch (ParseErrorException pee) { rsvc.error("ResourceManager.getResource() exception: " + pee); throw pee; } catch (Exception eee) { rsvc.error("ResourceManager.getResource() exception: " + eee); throw eee; } } else { try { /* * it's not in the cache, so load it. */ resource = loadResource(resourceName, resourceType, encoding); if (resource.ResourceLoader.isCachingOn()) { globalCache.put(resourceName, resource); } } catch (ResourceNotFoundException rnfe2) { rsvc.error("ResourceManager : unable to find resource '" + resourceName + "' in any resource loader."); throw rnfe2; } catch (ParseErrorException pee) { rsvc.error("ResourceManager.getResource() parse exception: " + pee); throw pee; } catch (Exception ee) { rsvc.error("ResourceManager.getResource() exception new: " + ee); throw ee; } } return resource; } /// <summary> /// Loads a resource from the current set of resource loaders /// </summary> /// <param name="resourceName">The name of the resource to retrieve.</param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <param name="encoding"> The character encoding to use.</param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// </returns> protected internal virtual Resource loadResource(String resourceName, int resourceType, String encoding) { Resource resource = ResourceFactory.getResource(resourceName, resourceType); resource.RuntimeServices = rsvc; resource.Name = resourceName; resource.Encoding = encoding; /* * Now we have to try to find the appropriate * loader for this resource. We have to cycle through * the list of available resource loaders and see * which one gives us a stream that we can use to * make a resource with. */ long howOldItWas = 0; // Initialize to avoid warnings ResourceLoader resourceLoader = null; for (int i = 0; i < resourceLoaders.Count; i++) { resourceLoader = (ResourceLoader) resourceLoaders[i]; resource.ResourceLoader = resourceLoader; /* * catch the ResourceNotFound exception * as that is ok in our new multi-loader environment */ try { if (resource.Process()) { /* * FIXME (gmj) * moved in here - technically still * a problem - but the resource needs to be * processed before the loader can figure * it out due to to the new * multi-path support - will revisit and fix */ if (logWhenFound) { rsvc.info("ResourceManager : found " + resourceName + " with loader " + resourceLoader.ClassName); } howOldItWas = resourceLoader.getLastModified(resource); break; } } catch (ResourceNotFoundException rnfe) { /* * that's ok - it's possible to fail in * multi-loader environment */ } } /* * Return null if we can't find a resource. */ if (resource.Data == null) { throw new ResourceNotFoundException("Unable to find resource '" + resourceName + "'"); } /* * some final cleanup */ resource.LastModified = howOldItWas; resource.ModificationCheckInterval = resourceLoader.ModificationCheckInterval; resource.Touch(); return resource; } /// <summary> Takes an existing resource, and 'refreshes' it. This /// generally means that the source of the resource is checked /// for changes according to some cache/check algorithm /// and if the resource changed, then the resource data is /// reloaded and re-parsed. /// * /// </summary> /// <param name="resource">resource to refresh /// * /// @throws ResourceNotFoundException if template not found /// from current source for this Resource /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// /// </param> protected internal virtual void refreshResource(Resource resource, String encoding) { /* * The resource knows whether it needs to be checked * or not, and the resource's loader can check to * see if the source has been modified. If both * these conditions are true then we must reload * the input stream and parse it to make a new * AST for the resource. */ if (resource.RequiresChecking()) { /* * touch() the resource to reset the counters */ resource.Touch(); if (resource.IsSourceModified()) { /* * now check encoding info. It's possible that the newly declared * encoding is different than the encoding already in the resource * this strikes me as bad... */ if (!resource.Encoding.Equals(encoding)) { rsvc.error("Declared encoding for template '" + resource.Name + "' is different on reload. Old = '" + resource.Encoding + "' New = '" + encoding); resource.Encoding = encoding; } /* * read how old the resource is _before_ * processing (=>reading) it */ long howOldItWas = resource.ResourceLoader.getLastModified(resource); /* * read in the fresh stream and parse */ resource.Process(); /* * now set the modification info and reset * the modification check counters */ resource.LastModified = howOldItWas; } } } /// <summary> Gets the named resource. Returned class type corresponds to specified type /// (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>). /// * /// </summary> /// <param name="resourceName">The name of the resource to retrieve. /// </param> /// <param name="resourceType">The type of resource (<code>RESOURCE_TEMPLATE</code>, /// <code>RESOURCE_CONTENT</code>, etc.). /// </param> /// <returns>Resource with the template parsed and ready. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if a problem in parse /// * /// </returns> /// <deprecated>Use /// {@link #getResource(String resourceName, int resourceType, /// String encoding )} /// /// </deprecated> public virtual Resource getResource(String resourceName, int resourceType) { return getResource(resourceName, resourceType, RuntimeConstants_Fields.ENCODING_DEFAULT); } /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> public virtual String getLoaderNameForResource(String resourceName) { ResourceLoader resourceLoader = null; /* * loop through our loaders... */ for (int i = 0; i < resourceLoaders.Count; i++) { resourceLoader = (ResourceLoader) resourceLoaders[i]; Stream is_Renamed = null; /* * if we find one that can provide the resource, * return the name of the loaders's Class */ try { is_Renamed = resourceLoader.getResourceStream(resourceName); if (is_Renamed != null) { return resourceLoader.GetType().ToString(); } } catch (ResourceNotFoundException e) { /* * this isn't a problem. keep going */ } finally { /* * if we did find one, clean up because we were * returned an open stream */ if (is_Renamed != null) { try { is_Renamed.Close(); } catch (IOException ioe) { } } } } return null; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/FullBuild In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/FullBuild Added Files: FullBuild.csproj Log Message: --- NEW FILE: FullBuild.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{250B6F4B-3256-4DEB-84B6-8C919058FDDC}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "FullBuild" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "FullBuild" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.XML" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Cache" Project = "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.CodeGen" Project = "{2D8FC662-0244-49F1-8017-DFE73B191017}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Data" Project = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.NVelocity" Project = "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.UnitTest" Project = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.UnitTest.Core" Project = "{B8592DE8-C10B-4ACB-A422-919C02C04B05}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Web" Project = "{49455A1D-1BBB-4356-AB83-E5690726C681}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Windows.Forms" Project = "{0BE602B6-D67E-414E-B852-A2AC61305E8E}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include/> </Files> </CSHARP> </VisualStudioProject> |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Tests Added Files: Adapdev.Tests.csproj CompositeValidatorTest.cs IValidatorTest.cs ObjectComparerTest.cs Log Message: --- NEW FILE: CompositeValidatorTest.cs --- using System; using System.Collections; using NUnit.Framework; using Adapdev; namespace Adapdev.Tests { /// <summary> /// Summary description for IValidatable. /// </summary> /// [TestFixture] public class CompositeValidatorTest { public static string BadHeightMessage = "Height must be greater than zero."; public static string BadWidthMessage = "Width must be greater than zero."; public static string NoSquareMessage = "Must be a rectangle, not a square. Please use the Square object for squares."; [Test] public void Invalid() { Rectangle rectangle = new Rectangle(); rectangle.Height = 2; rectangle.Width = 2; ValidationResult vr = rectangle.Validate(); Console.WriteLine(vr.Message); Assert.IsFalse(vr.IsValid, "Object should not be valid."); Assert.IsTrue(vr.Message.Length > 0); Assert.IsTrue(vr.Message.IndexOf(CompositeValidatorTest.NoSquareMessage) >= 0); Assert.AreEqual(CompositeValidatorTest.NoSquareMessage + Environment.NewLine + Environment.NewLine, vr.Message); } [Test] public void Valid() { Rectangle rectangle = new Rectangle(); rectangle.Height = 3; rectangle.Width = 2; ValidationResult vr = rectangle.Validate(); Assert.IsTrue(vr.IsValid); Assert.IsTrue(vr.Message.Length == 0, "Object should not have a validation message."); } } public class Rectangle : CompositeValidator { public Rectangle() { this.AddRule(new RectangleNoSquareRule(this)); this.AddRule(new RectangleHeightRule(this)); this.AddRule(new RectangleWidthRule(this)); } public int Height = 0; public int Width = 0; } public class RectangleNoSquareRule : IValidationRule { private Rectangle _rectangle; public RectangleNoSquareRule(Rectangle r) { this._rectangle = r; } #region IValidationRule Members public ValidationResult Validate() { ValidationResult vr = new ValidationResult(); if(this._rectangle.Height == this._rectangle.Width) { vr.IsValid = false; vr.AddMessage(CompositeValidatorTest.NoSquareMessage); } return vr; } #endregion } public class RectangleHeightRule : IValidationRule { #region IValidationRule Members private Rectangle _rectangle; public RectangleHeightRule(Rectangle r) { this._rectangle = r; } public ValidationResult Validate() { ValidationResult vr = new ValidationResult(); if(this._rectangle.Height <= 0) { vr.IsValid = false; vr.AddMessage(CompositeValidatorTest.BadHeightMessage); } return vr; } #endregion } public class RectangleWidthRule : IValidationRule { #region IValidationRule Members private Rectangle _rectangle; public RectangleWidthRule(Rectangle r) { this._rectangle = r; } public ValidationResult Validate() { ValidationResult vr = new ValidationResult(); if(this._rectangle.Width <= 0) { vr.IsValid = false; vr.AddMessage(CompositeValidatorTest.BadWidthMessage); } return vr; } #endregion } } --- NEW FILE: ObjectComparerTest.cs --- using System; using System.Text; using System.Threading; using Adapdev.Mock; using Adapdev.Serialization; using NUnit.Framework; namespace Adapdev.Tests { /// <summary> /// Summary description for ObjectComparerTest. /// </summary> /// [TestFixture] public class ObjectComparerTest { [Test] public void AreEqual() { DateTime now = DateTime.Now; SuppliersEntity e1 = new SuppliersEntity(); e1.Address = "Test"; e1.SupplierID = 12; e1.Created = now; SuppliersEntity e2 = new SuppliersEntity(); e2.Address = "Test"; e2.SupplierID = 12; e2.Created = now; Assert.IsTrue(ObjectComparer.AreEqual(e1, e2), "Objects should be equal."); e2.Created = DateTime.Now.AddHours(1); Assert.IsFalse(ObjectComparer.AreEqual(e1, e2), "Objects should not be equal."); } [Test] public void FailAreEqualWithFields() { DateTime now = DateTime.Now; SuppliersEntity e1 = new SuppliersEntity(); e1.Address = "Test"; e1.SupplierID = 12; e1.Created = now; Thread.Sleep(1000); SuppliersEntity e2 = new SuppliersEntity(); e2.Address = "Test"; e2.SupplierID = 12; e2.Created = now; //Console.WriteLine(e1); //Console.WriteLine(e2); Assert.IsFalse(ObjectComparer.AreEqual(e1, e2, true), "Objects should not be equal because InternalCreated is different."); } [Test] public void FailAreEqualWithFieldsSerialization() { DateTime now = DateTime.Now; SuppliersEntity e1 = new SuppliersEntity(); e1.Address = "Test"; e1.SupplierID = 12; e1.Created = now; SuppliersEntity e2 = new SuppliersEntity(); e2.Address = "Test"; e2.SupplierID = 12; e2.Created = now; string a = Serializer.SerializeToXml(e1); string b = Serializer.SerializeToXml(e2); Console.WriteLine(a); Console.WriteLine(b); Assert.IsTrue(a == b, "Objects should be equal."); e2.Created = DateTime.Now.AddHours(1); // byte[] c = Serializer.SerializeToBinary(e2); // // Assert.IsFalse(a == c, "Objects should not be equal."); } } } --- NEW FILE: IValidatorTest.cs --- using System; using NUnit.Framework; using Adapdev; namespace Adapdev.Tests { /// <summary> /// Summary description for IValidatable. /// </summary> /// [TestFixture] public class IValidatorTest { public static string BadHeightMessage = "Height must be greater than zero."; public static string BadWidthMessage = "Width must be greater than zero."; [Test] public void Invalid() { Square square = new Square(); square.Height = -1; square.Width = 0; ValidationResult vr = square.Validate(); Console.WriteLine(vr.Message); Assert.IsFalse(vr.IsValid, "Object should not be valid."); Assert.IsTrue(vr.Message.Length > 0); Assert.IsTrue(vr.Message.IndexOf(IValidatorTest.BadHeightMessage) >= 0); Assert.IsTrue(vr.Message.IndexOf(IValidatorTest.BadWidthMessage) >= 0); } [Test] public void Valid() { Square square = new Square(); square.Height = 2; square.Width = 2; ValidationResult vr = square.Validate(); Assert.IsTrue(vr.IsValid); Assert.IsTrue(vr.Message.Length == 0, "Object should not have a validation message."); } } public class Square : IValidator { #region IValidator Members public int Height = 0; public int Width = 0; public ValidationResult Validate() { ValidationResult vr = new ValidationResult(); if(this.Height <= 0) { vr.IsValid = false; vr.AddMessage(IValidatorTest.BadHeightMessage); } if(this.Width <= 0) { vr.IsValid = false; vr.AddMessage(IValidatorTest.BadWidthMessage); } return vr; } #endregion } } --- NEW FILE: Adapdev.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{6012639A-3857-46CC-80BC-32CBF1F104D7}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Tests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CompositeValidatorTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IValidatorTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ObjectComparerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\CryptoTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\CPUMeterTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\PerfTimerFactoryTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\ClassAccessorCacheTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\ClassAccessorTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\FieldAccessorTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\FieldAccessorTestObject.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\PropertyAccessorTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\PropertyAccessorTestObject.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\FullTextSearchTests.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\RegExFilterTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\SearchResultTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\SpecialCharactersFilterTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\StringTokenizerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\TokenAssertions.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\TokenLengthFilterTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Text\Indexing\WordFilterTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "XPath\XPathObjectNavigatorTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src Added Files: AdapdevAssemblyInfo.cs AdapdevFramework.sln adapdev.snk header.txt license.txt readme.txt Log Message: --- NEW FILE: license.txt --- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- NEW FILE: header.txt --- /* Copyright 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ --- NEW FILE: adapdev.snk --- (This appears to be a binary file; contents omitted.) --- NEW FILE: AdapdevAssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("Adapdev.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adapdev Technologies, LLC")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2004 Adapdev Technologies, LLC")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.8.3")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("..\\..\\..\\adapdev.snk")] [assembly: AssemblyKeyName("")] [assembly: log4net.Config.DOMConfigurator(Watch=true)] --- NEW FILE: AdapdevFramework.sln --- Microsoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev", "Adapdev\Adapdev.csproj", "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Tests", "Adapdev.Tests\Adapdev.Tests.csproj", "{6012639A-3857-46CC-80BC-32CBF1F104D7}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Data", "Adapdev.Data\Adapdev.Data.csproj", "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Data.Tests", "Adapdev.Data.Tests\Adapdev.Data.Tests.csproj", "{07695A4B-39A8-41CB-A21B-E61B3990C20F}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.CodeGen", "Adapdev.CodeGen\Adapdev.CodeGen.csproj", "{2D8FC662-0244-49F1-8017-DFE73B191017}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.CodeGen.Tests", "Adapdev.CodeGen.Tests\Adapdev.CodeGen.Tests.csproj", "{FF310091-86DF-4E18-8061-7694C0A2669B}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Cache", "Adapdev.Cache\Adapdev.Cache.csproj", "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Cache.Tests", "Adapdev.Cache.Tests\Adapdev.Cache.Tests.csproj", "{D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Web", "Adapdev.Web\Adapdev.Web.csproj", "{49455A1D-1BBB-4356-AB83-E5690726C681}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Web.Tests", "Adapdev.Web.Tests\Adapdev.Web.Tests.csproj", "{5174127E-DD36-4C32-AB42-9ADD34260BB2}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.NVelocity", "Adapdev.NVelocity\Adapdev.NVelocity.csproj", "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Windows.Forms", "Adapdev.Windows.Forms\Adapdev.Windows.Forms.csproj", "{0BE602B6-D67E-414E-B852-A2AC61305E8E}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Windows.Forms.Tests", "Adapdev.Windows.Forms.Tests\Adapdev.Windows.Forms.Tests.csproj", "{D51D807A-D70C-445A-B1D9-062D61463AB7}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest", "Adapdev.UnitTest\Adapdev.UnitTest.csproj", "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Core", "Adapdev.UnitTest.Core\Adapdev.UnitTest.Core.csproj", "{B8592DE8-C10B-4ACB-A422-919C02C04B05}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FullBuild", "FullBuild\FullBuild.csproj", "{250B6F4B-3256-4DEB-84B6-8C919058FDDC}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Tests", "Adapdev.UnitTest.Tests\Adapdev.UnitTest.Tests.csproj", "{7DC72EED-57C5-43A3-AB03-D456816A6F1A}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Core.Tests", "Adapdev.UnitTest.Core.Tests\Adapdev.UnitTest.Core.Tests.csproj", "{D0F97D76-E7A6-4059-B902-F792626A29A8}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.TestRunner", "Adapdev.UnitTest.TestRunner\Adapdev.UnitTest.TestRunner.csproj", "{2D0C35AA-CC64-4513-947D-F67C035D2B71}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.TestRunner.Tests", "Adapdev.UnitTest.TestRunner.Tests\Adapdev.UnitTest.TestRunner.Tests.csproj", "{59AFE252-CBC0-434A-8350-0A4722654CDA}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Core.AdapdevTests", "Adapdev.UnitTest.Core.AdapdevTests\Adapdev.UnitTest.Core.AdapdevTests.csproj", "{3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Debug.ActiveCfg = Debug|.NET {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Debug.Build.0 = Debug|.NET {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Release.ActiveCfg = Release|.NET {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Release.Build.0 = Release|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Debug.ActiveCfg = Debug|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Debug.Build.0 = Debug|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Release.ActiveCfg = Release|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Release.Build.0 = Release|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Debug.ActiveCfg = Debug|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Debug.Build.0 = Debug|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Release.ActiveCfg = Release|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Release.Build.0 = Release|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Debug.ActiveCfg = Debug|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Debug.Build.0 = Debug|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Release.ActiveCfg = Release|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Release.Build.0 = Release|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Debug.ActiveCfg = Debug|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Debug.Build.0 = Debug|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Release.ActiveCfg = Release|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Release.Build.0 = Release|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Debug.ActiveCfg = Debug|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Debug.Build.0 = Debug|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Release.ActiveCfg = Release|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Release.Build.0 = Release|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Debug.ActiveCfg = Debug|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Debug.Build.0 = Debug|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Release.ActiveCfg = Release|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Release.Build.0 = Release|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Debug.ActiveCfg = Debug|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Debug.Build.0 = Debug|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Release.ActiveCfg = Release|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Release.Build.0 = Release|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Debug.ActiveCfg = Debug|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Debug.Build.0 = Debug|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Release.ActiveCfg = Release|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Release.Build.0 = Release|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Debug.ActiveCfg = Debug|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Debug.Build.0 = Debug|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Release.ActiveCfg = Release|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Release.Build.0 = Release|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Debug.ActiveCfg = Debug|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Debug.Build.0 = Debug|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Release.ActiveCfg = Release|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Release.Build.0 = Release|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Debug.ActiveCfg = Debug|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Debug.Build.0 = Debug|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Release.ActiveCfg = Release|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Release.Build.0 = Release|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Debug.ActiveCfg = Debug|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Debug.Build.0 = Debug|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Release.ActiveCfg = Release|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Release.Build.0 = Release|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Debug.ActiveCfg = Debug|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Debug.Build.0 = Debug|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Release.ActiveCfg = Release|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Release.Build.0 = Release|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Debug.ActiveCfg = Debug|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Debug.Build.0 = Debug|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Release.ActiveCfg = Release|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Release.Build.0 = Release|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Debug.ActiveCfg = Debug|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Debug.Build.0 = Debug|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Release.ActiveCfg = Release|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Release.Build.0 = Release|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Debug.ActiveCfg = Debug|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Debug.Build.0 = Debug|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Release.ActiveCfg = Release|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Release.Build.0 = Release|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Debug.ActiveCfg = Debug|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Debug.Build.0 = Debug|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Release.ActiveCfg = Release|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Release.Build.0 = Release|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Debug.ActiveCfg = Debug|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Debug.Build.0 = Debug|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Release.ActiveCfg = Release|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Release.Build.0 = Release|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Debug.ActiveCfg = Debug|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Debug.Build.0 = Debug|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Release.ActiveCfg = Release|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Release.Build.0 = Release|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Debug.ActiveCfg = Debug|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Debug.Build.0 = Debug|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Release.ActiveCfg = Release|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(SolutionItems) = postSolution adapdev.snk = adapdev.snk AdapdevAssemblyInfo.cs = AdapdevAssemblyInfo.cs EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal --- NEW FILE: readme.txt --- =========================================== Legal =========================================== The Adapdev.NET project is a combination of code written by Sean McCormack, contributors, and code harvested from various projects and articles. All effort has been made to give credit where credit is do, and retain all proper copyright information. If any code does not contain proper credit or copyright information, or conflicts with the Apache License 2.0, please let us know immediately so that the issue can be resolved. Contact: adapdevnet-support <at> adapdev.com =========================================== Libraries (lib) =========================================== The /lib folder contains all necessary executables that aren't included as part of the Adapdev.NET code base. This includes NAnt, Genghis and log4net. =========================================== Source (src) =========================================== All source code is contained in the /src directory. The solution file is a VS.NET 2003 solution file. |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Web/Sgml In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Web/Sgml Added Files: SgmlParser.cs SgmlReader.cs Log Message: --- NEW FILE: SgmlReader.cs --- // Original Copyright (c) 2002 Microsoft Corporation. All rights reserved. - http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=B90FDDCE-E60D-43F8-A5C4-C3BD760564BC /* * * An XmlReader implementation for loading SGML (including HTML) converting it * to well formed XML, by adding missing quotes, empty attribute values, ignoring * duplicate attributes, case folding on tag names, adding missing closing tags * based on SGML DTD information, and so on. * * Copyright (c) 2002 Microsoft Corporation. All rights reserved. * * Chris Lovett * */ using System; using System.Xml; using System.IO; using System.Collections; using System.Text; [...1580 lines suppressed...] // e.g. p not allowed inside p, not an interesting error. } else { string closing = ""; for (int k = top; k >= i+1; k--) { if (closing != "") closing += ","; Node n2 = (Node)this.stack[k]; closing += "<"+n2.Name+">"; } Log("Element '{0}' not allowed inside '{1}', closing {2}.", name, n.Name, closing); } this.state = State.AutoClose; this.newnode = node; Pop(); // save this new node until we pop the others this.poptodepth = i+1; } } } } } --- NEW FILE: SgmlParser.cs --- // Original Copyright (c) 2002 Microsoft Corporation. All rights reserved. - http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=B90FDDCE-E60D-43F8-A5C4-C3BD760564BC /* * * An XmlReader implementation for loading SGML (including HTML) converting it * to well formed XML, by adding missing quotes, empty attribute values, ignoring * duplicate attributes, case folding on tag names, adding missing closing tags * based on SGML DTD information, and so on. * * Copyright (c) 2002 Microsoft Corporation. All rights reserved. * * Chris Lovett * */ using System; using System.IO; using System.Collections; using System.Text; using System.Net; [...2012 lines suppressed...] if (hasdef) { if (ch == '\'' || ch == '"') { string lit = this.current.ScanLiteral(this.sb, ch); attdef.Default = lit; ch = this.current.SkipWhitespace(); } else { string name = this.current.ScanToken(this.sb, SgmlDtd.WhiteSpace, false); name = name.ToUpper(); name = this.nameTable.Add(name); attdef.Default = name; // bugbug - must be one of the enumerated names. ch = this.current.SkipWhitespace(); } } } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.TestRunner.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.TestRunner.Tests Added Files: Adapdev.UnitTest.TestRunner.Tests.csproj AssemblyInfo.cs NUnitTest.cs ZanebugEnvironmentTest.cs ZanebugTest.cs Log Message: --- NEW FILE: NUnitTest.cs --- using System; using System.Text; using NUnit.Framework; using System.Diagnostics; namespace Adapdev.UnitTest.TestRunner.Tests { [TestFixture] public class NUnitTest { [Test] public void Test1() { Trace.WriteLine("One"); } [Test] public void Test2() { Trace.WriteLine("Two"); } [Test] public void Test3() { Trace.WriteLine("Three"); } [Test] public void TestFail() { Assert.Fail("Boom!"); } } } --- NEW FILE: ZanebugEnvironmentTest.cs --- using System; using Adapdev.UnitTest; namespace Adapdev.UnitTest.TestRunner.Tests { using System.Configuration; /// <summary> /// Summary description for Environment. /// </summary> /// [TestFixture] public class ZanebugEnvironmentTest { [Test(Description="Displays the Environment.CurrentDirectory")] public void CurrentDirectory() { Console.WriteLine("Environment: " + System.Environment.CurrentDirectory); } [Test(Description="Displays the current AppDomain's BaseDirectory")] public void BaseDirectory() { Console.WriteLine("AppDomain.CurrentDomain.BaseDirectory: " + AppDomain.CurrentDomain.BaseDirectory); } [Test(Description="Displays the current AppDomain's configuration file (.config)")] public void ConfigurationFile() { Console.WriteLine("Configuration File: " + AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); } } } --- NEW FILE: ZanebugTest.cs --- using System; using Adapdev.UnitTest; namespace Adapdev.UnitTest.TestRunner.Tests { [TestFixture] public class ZanebugTest { // Runs only once, when the test assembly is dynamically loaded public ZanebugTest(){} // Runs once at the beginning of each TestFixture iteration [TestFixtureSetUp] public void TestFixtureSetUp() { Console.WriteLine("TestFixtureSetUp"); } // Runs once at the beginning of each Test iteration [TestSetUp] public void TestSetUp() { Console.WriteLine("TestSetUp"); } // Runs once at the beginning of each Test iteration [SetUp] public void SetUp() { Console.WriteLine("SetUp"); } // Runs once at the beginning of SimpleTest only [TestSetUp("SimpleTest")] public void SpecificTestSetUp() { Console.WriteLine("SpecificTestSetUp runs only for SimpleTest"); } // A Test [Test(Description="Basic test")] public void SimpleTest() { Console.WriteLine("SimpleTest"); } // Runs once at the end of SimpleTest only [TestTearDown("SimpleTest")] public void SpecificTestTearDown() { Console.WriteLine("SpecificTestTearDown runs only for SimpleTest"); } // A Test with a Category [Test(Category="Some Category", Description="Demonstrates a Test that's assigned to a category")] public void TestWithCategory() { Console.WriteLine("Test with category"); } // A Test with a Description [Test(Description="Demonstrates a Test that has a description")] public void TestWithDescription() { Console.WriteLine("Test with description"); } // A Test that is expecting a specific Exception // type to be thrown or any child class [Test(Description="A Test that expects an Exception to be thrown.")] [ExpectedException(typeof(Exception))] public void ExpectedException() { Console.WriteLine("ExpectedException"); throw new Exception("This Exception is expected"); } // A Test that is expecting a specific Exception // type to be thrown with a specific message [Test(Description="A Test that expects an Exception to be thrown with a specific message.")] [ExpectedException(typeof(Exception), "This Exception is expected")] public void ExpectedExceptionWithMessage() { Console.WriteLine("ExpectedException"); throw new Exception("This Exception is expected"); } // A Test that is expecting a specific Exception // type to be thrown with a specific message and fails [Test(Description="A Test that expects an Exception to be thrown with a specific message and receives the wrong one.")] [ExpectedException(typeof(Exception), "This Exception is expected")] public void FailExpectedExceptionWithMessage() { Console.WriteLine("ExpectedException"); throw new Exception("This Exception is not expected"); } // A Test that is expecting a specific DivideByZeroException // type to be thrown or any child class [Test] [ExpectedException(typeof(Exception))] public void ExpectedDivideByZeroException() { Console.WriteLine("ExpectedException"); throw new DivideByZeroException("This Exception is expected."); } // A Test that will fail because the ExpectedException is not thrown [Test(Description="A Test that expects an Exception to be thrown, but fails because one isn't.")] [ExpectedException(typeof(Exception))] public void FailExpectedException() { Console.WriteLine("ExpectedException"); } // A Test that will be ignored (not run) by default [Test(Description="A Test that is ignored, with no reason provided.")] [Ignore] public void Ignore() { Console.WriteLine("Ignore"); } // A Test that will be ignored (not run) by default // and provides a reason [Test(Description="A Test that is ignored, with a reason provided.")] [Ignore("Some reason")] public void IgnoreWithReason() { Console.WriteLine("Ignore with reason"); } // A Test that specifies the maximum amount of memory // that the Test can consume [Test(Description="A Test who's total memory consumption should not exceed 200K")] [MaxKMemory(200)] public void MaxKMemory() { Console.WriteLine("MaxKMemory"); } // A Test that will fail if it can't be repeated // the min number of times in a second [Test(Description="A Test that should be able to run at least 10X per second.")] [MinOperationsPerSecond(10)] public void MinOperationsPerSecond() { Console.WriteLine("MinOperationsPerSecond"); } // A Test that is repeated a set number of times [Test(Description="A Test that is repeated 5X")] [Repeat(5)] public void Repeat() { Console.WriteLine("Repeat"); } // A Test that is repeated a set number of times // with a 3 second delay in between [Test(Description="A Test that is repeated 5X, with a 3 second delay between each run.")] [Ignore] [Repeat(5,3000)] public void RepeatWithDelay() { Console.WriteLine("Repeat with delay"); } // Runs once at the end of each Test iteration [TearDown] public void TearDown() { Console.WriteLine("TearDown"); } // Runs once at the end of each Test iteration [TestTearDown] public void TestTearDown() { Console.WriteLine("TestTearDown"); } // Runs once at the end of the TestFixture iteration [TestFixtureTearDown] public void TestFixtureTearDown() { Console.WriteLine("TestFixtureTearDown"); } } } --- NEW FILE: Adapdev.UnitTest.TestRunner.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{59AFE252-CBC0-434A-8350-0A4722654CDA}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.TestRunner.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.TestRunner.Tests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "G:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "G:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "G:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev.UnitTest.TestRunner" Project = "{2D0C35AA-CC64-4513-947D-F67C035D2B71}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "TestDriven.Framework" AssemblyName = "TestDriven.Framework" HintPath = "..\..\lib\TestDriven.Framework.dll" /> <Reference Name = "Adapdev.UnitTest" Project = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NUnitTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ZanebugEnvironmentTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ZanebugTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; using Adapdev.UnitTest.TestRunner; using TestDriven.Framework; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CustomTestRunner(typeof(AdapdevTestRunner))] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:14
|
Update of /cvsroot/adapdev/Adapdev/src/FullTests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/FullTests Added Files: FullTests.csproj Log Message: --- NEW FILE: FullTests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{77BDAE21-B7D5-4EC7-BA7A-B24D3D95106E}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "FullTests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "FullTests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.XML" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev.Cache.Tests" Project = "{D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.CodeGen.Tests" Project = "{FF310091-86DF-4E18-8061-7694C0A2669B}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Data.Tests" Project = "{07695A4B-39A8-41CB-A21B-E61B3990C20F}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Tests" Project = "{6012639A-3857-46CC-80BC-32CBF1F104D7}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Web.Tests" Project = "{5174127E-DD36-4C32-AB42-9ADD34260BB2}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Windows.Forms.Tests" Project = "{D51D807A-D70C-445A-B1D9-062D61463AB7}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Cache" Project = "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.CodeGen" Project = "{2D8FC662-0244-49F1-8017-DFE73B191017}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Data" Project = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.NVelocity" Project = "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.UnitTest" Project = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.UnitTest.Core" Project = "{B8592DE8-C10B-4ACB-A422-919C02C04B05}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Web" Project = "{49455A1D-1BBB-4356-AB83-E5690726C681}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include/> </Files> </CSHARP> </VisualStudioProject> |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest Added Files: Adapdev.UnitTest.csproj Assert.cs Assertion.cs AssertionException.cs AssertionFailureMessage.cs ExpectedExceptionAttribute.cs IgnoreAttribute.cs IgnoreException.cs MaxKMemoryAttribute.cs MinOperationsPerSecondAttribute.cs RepeatAttribute.cs RollbackTransaction.cs RollbackTransactionAttribute.cs SetUpAttribute.cs TearDownAttribute.cs TestAttribute.cs TestContext.cs TestFixtureAttribute.cs TestFixtureSetUpAttribute.cs TestFixtureTearDownAttribute.cs TestSetUpAttribute.cs TestTearDownAttribute.cs TestType.cs Transaction.cs TransactionAttribute.cs Log Message: --- NEW FILE: RollbackTransactionAttribute.cs --- using System; namespace Adapdev.UnitTest { /// <summary> /// Summary description for RollbackTransaction. /// </summary> /// [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public class RollbackTransactionAttribute : Attribute { } } --- NEW FILE: TestContext.cs --- using System; namespace Adapdev.UnitTest { /// <summary> /// Summary description for TestContext. /// </summary> public class TestContext { public TestContext() { // // TODO: Add constructor logic here // } } } --- NEW FILE: TransactionAttribute.cs --- using System; namespace Adapdev.UnitTest { /// <summary> /// Summary description for Transaction. /// </summary> /// [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public class TransactionAttribute : Attribute { } } --- NEW FILE: RollbackTransaction.cs --- using System; namespace Adapdev.UnitTest { /// <summary> /// Summary description for RollbackTransaction. /// </summary> /// [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public class RollbackTransaction : Attribute { } } --- NEW FILE: TestSetUpAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a place for code that should be run prior to a Test /// /// Unless a Test name is specified, this will run prior to each Test. /// </summary> /// <example> /// [TestSetUp] /// public void SetUp(){ /// // this will run for each test /// } /// /// [TestSetUp(Test="SomeTest")] /// public void SetUpForSomeTest(){ /// // this will run only for SomeTest /// } /// /// [Test] /// public void SomeTest(){ /// // code /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public class TestSetUpAttribute : Attribute { private string _test = ""; /// <summary> /// Constructor /// </summary> public TestSetUpAttribute() : base() { } /// <summary> /// Constructor /// </summary> /// <param name="test">The name of the Test that this should run for.</param> public TestSetUpAttribute(string test) { this._test = test; } public string Test { get { return this._test; } set { this._test = value; } } } } --- NEW FILE: IgnoreException.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: TestAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// A Test that will be run. The result is either a Pass or Fail, unless /// the Test is being Ignored /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class TestAttribute : Attribute { private string _category = ""; private string _description = ""; private TestType _testType = TestType.Unit; /// <summary> /// A category that the Test will be associated with /// </summary> public string Category { get { return this._category; } set { this._category = value; } } /// <summary> /// Gets or sets the description. /// </summary> /// <value></value> public string Description { get{ return this._description;} set{ this._description = value;} } /// <summary> /// Gets or sets the test type /// </summary> public TestType TestType { get{return this._testType;} set{this._testType = value;} } } } --- NEW FILE: IgnoreAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Signifies that this Test should be ignored. /// /// The Zanebug engine will ignore this Test by default each time the /// engine starts up, but it can be overriden at run-time /// </summary> /// <example> /// [Test] /// [Ignore] /// public void Ignore(){ /// // this Test will be ignored /// } /// /// [Test] /// [Ignore] /// public void IgnoreWithReason(){ /// // this Test will be ignored and provides a reason why /// } /// </example> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed class IgnoreAttribute : Attribute { private string reason = ""; /// <summary> /// Constructor /// </summary> public IgnoreAttribute() { } /// <summary> /// Constructor /// </summary> /// <param name="reason">The reason the Test is being ignored</param> public IgnoreAttribute(string reason) { this.reason = reason; } /// <summary> /// The reason the Test is being ignored /// </summary> public string Reason { get { return reason; } } } } --- NEW FILE: TestFixtureAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a TestFixture, which is a designation for a class that contains /// one or more Tests. /// /// If a class contains Tests, but is not marked with the TestFixture attribute then /// the class will be ignored by the test engine. /// </summary> /// <example> /// using System; /// using Adapdev.UnitTest; /// /// namespace Tests /// { /// [TestFixture] /// public class SomeTest /// { /// [Test] /// public void Test1(){...} /// /// [Test] /// public void Test2(){...} /// } /// } /// </example> [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed class TestFixtureAttribute : Attribute { private bool _multiThreaded = false; public bool IsMultiThreaded { get { return _multiThreaded; } set { _multiThreaded = value; } } } } --- NEW FILE: SetUpAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a place for code that should be run prior to a Test /// /// Unless a Test name is specified, this will run prior to each Test. /// </summary> /// <remarks> /// This is a deprecated attribute that was created for backwards compatability with NUnit. /// New tests should use TestTearDown, since the name better communicates the scope. /// </remarks> /// <example> /// [SetUp] /// public void SetUp(){ /// // this will run for each test /// } /// /// [SetUp(Test="SomeTest")] /// public void SetUpForSomeTest(){ /// // this will run only for SomeTest /// } /// /// [Test] /// public void SomeTest(){ /// // code /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class SetUpAttribute : TestSetUpAttribute { } } --- NEW FILE: Assertion.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: Adapdev.UnitTest.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.UnitTest" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.UnitTest" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Assert.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Assertion.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssertionException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssertionFailureMessage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ExpectedExceptionAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IgnoreAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IgnoreException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MaxKMemoryAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MinOperationsPerSecondAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "RepeatAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "RollbackTransaction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SetUpAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TearDownAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestFixtureAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestFixtureSetUpAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestFixtureTearDownAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestSetUpAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestTearDownAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Transaction.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: MaxKMemoryAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies the maximum amount of memory that a Test can use. /// /// If the memory used by the tests exceeds this value, then the Test /// will fail. /// </summary> /// <remarks> /// The Zanebug memory measurement feature is currently buggy, and /// should not be relied upon for accurate measurements /// </remarks> /// <example> /// [Test] /// [MaxKMemory(200)] /// public void MaxKMemory() /// { /// // this test will fail if the memory usage /// // exceeds 200kb /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class MaxKMemoryAttribute : Attribute { private int maxK; /// <summary> /// The maximum amount of memory that should be used (in kb) /// </summary> public int MaxK { get { return maxK; } } /// <summary> /// Constructor /// </summary> /// <param name="n">The maximum amount of memory that should be used (in kb)</param> public MaxKMemoryAttribute(int n) { maxK = n; } } } --- NEW FILE: RepeatAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies how many times a Test or TestFixture should be repeated /// </summary> /// <example> /// [Test] /// [Repeat(5)] /// public void Repeat(){ /// // this test will be run 5 times in a row /// } /// /// [Test] /// [Repeat(5,3000)] /// public void Repeat(){ /// // this test will be run 5 times in a row /// // with a 3 second delay between each run /// } /// </example> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed class RepeatAttribute : Attribute { private int repCount = 1; private int delayBetweenReps = 0; //ms /// <summary> /// The number of times the Test or TestFixture should be repeated /// </summary> public int RepeatCount { get { return repCount; } } /// <summary> /// The number of milliseconds that the engine should wait /// before repeating the Test /// </summary> public int RepeatDelay { get { return delayBetweenReps; } } /// <summary> /// Constructor /// </summary> /// <param name="count">The number of times the Test or TestFixture should be repeated</param> public RepeatAttribute(int count) { repCount = count; delayBetweenReps = 0; } /// <summary> /// Constructor /// </summary> /// <param name="count">The number of times the Test or TestFixture should be repeated</param> /// <param name="delay">The number of milliseconds that the engine should wait /// before repeating the Test</param> public RepeatAttribute(int count, int delay) { repCount = count; delayBetweenReps = delay; } } } --- NEW FILE: MinOperationsPerSecondAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies the minimum number of times a Test should be able /// to run within 1 second. /// </summary> /// <remarks> /// The MinOps/s value is derived by dividing 1 by the Test duration: /// /// 1/(test duration) = MinOps/s /// </remarks> /// <example> /// [Test] /// [MinOperationsPerSecond(10)] /// public void MinOpsPerSecond(){ /// // this test will fail if it can't be run /// // 10 times in 1 second /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class MinOperationsPerSecondAttribute : Attribute { private int minOpsPerSecond; /// <summary> /// The minimum number of times a Test should run /// within a second /// </summary> public int MinOps { get { return minOpsPerSecond; } } /// <summary> /// Constructor /// </summary> /// <param name="n"> /// The minimum number of times a Test should run /// within a second /// </param> public MinOperationsPerSecondAttribute(int n) { minOpsPerSecond = n; } } } --- NEW FILE: Transaction.cs --- using System; namespace Adapdev.UnitTest { /// <summary> /// Summary description for Transaction. /// </summary> /// [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public class Transaction : Attribute { } } --- NEW FILE: AssertionFailureMessage.cs --- #region Original Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig, Douglas de la Torre /************************************************************************************ ' ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' Copyright 2000-2002 Philip A. Craig ' Copyright 2001 Douglas de la Torre ' ' This software is provided 'as-is', without any express or implied warranty. In no ' event will the authors be held liable for any damages arising from the use of this ' software. ' ' Permission is granted to anyone to use this software for any purpose, including ' commercial applications, and to alter it and redistribute it freely, subject to the ' following restrictions: ' ' 1. The origin of this software must not be misrepresented; you must not claim that ' you wrote the original software. If you use this software in a product, an ' acknowledgment (see the following) in the product documentation is required. ' ' Portions Copyright 2002 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov ' Copyright 2000-2002 Philip A. Craig, or Copyright 2001 Douglas de la Torre ' ' 2. Altered source versions must be plainly marked as such, and must not be ' misrepresented as being the original software. ' ' 3. This notice may not be removed or altered from any source distribution. ' '***********************************************************************************/ #endregion #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change SMM 091004 Changed namespace to Adapdev.UnitTest */ #endregion namespace Adapdev.UnitTest { using System; using System.Text; /// <summary> /// Summary description for AssertionFailureMessage. /// </summary> public class AssertionFailureMessage { /// <summary> /// Protected constructor, used since this class is only used via /// static methods /// </summary> protected AssertionFailureMessage() {} /// <summary> /// Number of characters before a highlighted position before /// clipping will occur. Clipped text is replaced with an /// elipses "..." /// </summary> static protected int PreClipLength { get { return 35; } } /// <summary> /// Number of characters after a highlighted position before /// clipping will occur. Clipped text is replaced with an /// elipses "..." /// </summary> static protected int PostClipLength { get { return 35; } } /// <summary> /// Called to test if the position will cause clipping /// to occur in the early part of a string. /// </summary> /// <param name="iPosition"></param> /// <returns></returns> static private bool IsPreClipped( int iPosition ) { if( iPosition > PreClipLength ) { return true; } return false; } /// <summary> /// Called to test if the position will cause clipping /// to occur in the later part of a string past the /// specified position. /// </summary> /// <param name="sString"></param> /// <param name="iPosition"></param> /// <returns></returns> static private bool IsPostClipped( string sString, int iPosition ) { if( sString.Length - iPosition > PostClipLength ) { return true; } return false; } /// <summary> /// Property called to insert newline characters into a string /// </summary> static private string NewLine { get { return "\r\n\t"; } } /// <summary> /// Renders up to M characters before, and up to N characters after /// the specified index position. If leading or trailing text is /// clipped, and elipses "..." is added where the missing text would /// be. /// /// Clips strings to limit previous or post newline characters, /// since these mess up the comparison /// </summary> /// <param name="sString"></param> /// <param name="iPosition"></param> /// <returns></returns> static protected string ClipAroundPosition( string sString, int iPosition ) { if( null == sString || 0 == sString.Length ) { return ""; } return BuildBefore( sString, iPosition ) + BuildAfter( sString, iPosition ); } /// <summary> /// Clips the string before the specified position, and appends /// ellipses (...) to show that clipping has occurred /// </summary> /// <param name="sString"></param> /// <param name="iPosition"></param> /// <returns></returns> static protected string PreClip( string sString, int iPosition ) { return "..." + sString.Substring( iPosition - PreClipLength, PreClipLength ); } /// <summary> /// Clips the string after the specified position, and appends /// ellipses (...) to show that clipping has occurred /// </summary> /// <param name="sString"></param> /// <param name="iPosition"></param> /// <returns></returns> static protected string PostClip( string sString, int iPosition ) { return sString.Substring( iPosition, PostClipLength ) + "..."; } /// <summary> /// Builds the first half of a string, limiting the number of /// characters before the position, and removing newline /// characters. If the leading string is truncated, the /// ellipses (...) characters are appened. /// </summary> /// <param name="sString"></param> /// <param name="iPosition"></param> /// <returns></returns> static private string BuildBefore( string sString, int iPosition ) { if( IsPreClipped(iPosition) ) { return PreClip( sString, iPosition ); } return sString.Substring( 0, iPosition ); } /// <summary> /// Builds the last half of a string, limiting the number of /// characters after the position, and removing newline /// characters. If the string is truncated, the /// ellipses (...) characters are appened. /// </summary> /// <param name="sString"></param> /// <param name="iPosition"></param> /// <returns></returns> static private string BuildAfter( string sString, int iPosition ) { if( IsPostClipped(sString, iPosition) ) { return PostClip( sString, iPosition ); } return sString.Substring( iPosition ); } /// <summary> /// Text that is rendered for the expected value /// </summary> /// <returns></returns> static protected string ExpectedText() { return "expected:<"; } /// <summary> /// Text rendered for the actual value. This text should /// be the same length as the Expected text, so leading /// spaces should pad this string to ensure they match. /// </summary> /// <returns></returns> static protected string ButWasText() { return " but was:<"; } /// <summary> /// Raw line that communicates the expected value, and the actual value /// </summary> /// <param name="sbOutput"></param> /// <param name="expected"></param> /// <param name="actual"></param> static protected void AppendExpectedAndActual( StringBuilder sbOutput, Object expected, Object actual ) { sbOutput.Append( NewLine ); sbOutput.Append( ExpectedText() ); sbOutput.Append( DisplayString( expected ) ); sbOutput.Append( ">" ); sbOutput.Append( NewLine ); sbOutput.Append( ButWasText() ); sbOutput.Append( DisplayString( actual ) ); sbOutput.Append( ">" ); } /// <summary> /// Display an object as a string /// </summary> /// <param name="obj"></param> /// <returns></returns> static protected string DisplayString( object obj ) { if ( obj == null ) return "(null)"; else if ( obj is string ) return Quoted( (string)obj ); else return obj.ToString(); } /// <summary> /// Quote a string /// </summary> /// <param name="text"></param> /// <returns></returns> static protected string Quoted( string text ) { return string.Format( "\"{0}\"", text ); } /// <summary> /// Draws a marker under the expected/actual strings that highlights /// where in the string a mismatch occurred. /// </summary> /// <param name="sbOutput"></param> /// <param name="iPosition"></param> static protected void AppendPositionMarker( StringBuilder sbOutput, int iPosition ) { sbOutput.Append( new String( '-', ButWasText().Length + 1 ) ); if( iPosition > 0 ) { sbOutput.Append( new string( '-', iPosition ) ); } sbOutput.Append( "^" ); } /// <summary> /// Tests two objects to determine if they are strings. /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <returns></returns> static protected bool InputsAreStrings( Object expected, Object actual ) { if( null != expected && null != actual && expected is string && actual is string ) { return true; } return false; } /// <summary> /// Tests if two strings are different lengths. /// </summary> /// <param name="sExpected"></param> /// <param name="sActual"></param> /// <returns>True if string lengths are different</returns> static protected bool LengthsDifferent( string sExpected, string sActual ) { if( sExpected.Length != sActual.Length ) { return true; } return false; } /// <summary> /// Tests if two arrays are different lengths. /// </summary> /// <param name="sExpected"></param> /// <param name="sActual"></param> /// <returns>True if array lengths are different</returns> static protected bool LengthsDifferent( object[] expected, object[] actual ) { if( expected.Length != actual.Length ) { return true; } return false; } /// <summary> /// Used to construct a message when the lengths of two strings are /// different. Also includes the strings themselves, to allow them /// to be compared visually. /// </summary> /// <param name="sbOutput"></param> /// <param name="sExpected"></param> /// <param name="sActual"></param> static protected void BuildLengthsDifferentMessage( StringBuilder sbOutput, string sExpected, string sActual ) { BuildContentDifferentMessage( sbOutput, sExpected, sActual ); } /// <summary> /// Reports the length of two strings that are different lengths /// </summary> /// <param name="sbOutput"></param> /// <param name="sExpected"></param> /// <param name="sActual"></param> static protected void BuildStringLengthDifferentReport( StringBuilder sbOutput, string sExpected, string sActual ) { sbOutput.Append( "String lengths differ. Expected length=" ); sbOutput.Append( sExpected.Length ); sbOutput.Append( ", but was length=" ); sbOutput.Append( sActual.Length ); sbOutput.Append( "." ); sbOutput.Append( NewLine ); } /// <summary> /// Reports the length of two strings that are the same length /// </summary> /// <param name="sbOutput"></param> /// <param name="sExpected"></param> /// <param name="sActual"></param> static protected void BuildStringLengthSameReport( StringBuilder sbOutput, string sExpected, string sActual ) { sbOutput.Append( "String lengths are both " ); sbOutput.Append( sExpected.Length ); sbOutput.Append( "." ); sbOutput.Append( NewLine ); } /// <summary> /// Reports whether the string lengths are the same or different, and /// what the string lengths are. /// </summary> /// <param name="sbOutput"></param> /// <param name="sExpected"></param> /// <param name="sActual"></param> static protected void BuildStringLengthReport( StringBuilder sbOutput, string sExpected, string sActual ) { if( sExpected.Length != sActual.Length ) { BuildStringLengthDifferentReport( sbOutput, sExpected, sActual ); } else { BuildStringLengthSameReport( sbOutput, sExpected, sActual ); } } /// <summary> /// Reports the length of two arrays that are different lengths /// </summary> /// <param name="sbOutput"></param> /// <param name="expected"></param> /// <param name="actual"></param> static protected void BuildArrayLengthDifferentReport( StringBuilder sbOutput, Array expected, Array actual ) { sbOutput.Append( "Array lengths differ. Expected length=" ); sbOutput.Append( expected.Length ); sbOutput.Append( ", but was length=" ); sbOutput.Append( actual.Length ); sbOutput.Append( "." ); sbOutput.Append( NewLine ); } /// <summary> /// Reports the length of two arrays that are the same length /// </summary> /// <param name="sbOutput"></param> /// <param name="expected"></param> /// <param name="actual"></param> static protected void BuildArrayLengthSameReport( StringBuilder sbOutput, Array expected, Array actual ) { sbOutput.Append( "Array lengths are both " ); sbOutput.Append( expected.Length ); sbOutput.Append( "." ); sbOutput.Append( NewLine ); } /// <summary> /// Reports whether the array lengths are the same or different, and /// what the array lengths are. /// </summary> /// <param name="sbOutput"></param> /// <param name="expected"></param> /// <param name="actual"></param> static protected void BuildArrayLengthReport( StringBuilder sbOutput, Array expected, Array actual ) { if( expected.Length != actual.Length ) { BuildArrayLengthDifferentReport( sbOutput, expected, actual ); } else { BuildArrayLengthSameReport( sbOutput, expected, actual ); } } /// <summary> /// /// </summary> /// <param name="sbOutput"></param> /// <param name="sExpected"></param> /// <param name="sActual"></param> /// <param name="iPosition"></param> static private void BuildContentDifferentAtPosition( StringBuilder sbOutput, string sExpected, string sActual, int iPosition ) { BuildStringLengthReport( sbOutput, sExpected, sActual ); sbOutput.Append( "Strings differ at index " ); sbOutput.Append( iPosition ); sbOutput.Append( "." ); sbOutput.Append( NewLine ); // // Clips the strings, then turns any hidden whitespace into visible // characters // string sClippedExpected = ConvertWhitespace(ClipAroundPosition( sExpected, iPosition )); string sClippedActual = ConvertWhitespace(ClipAroundPosition( sActual, iPosition )); AppendExpectedAndActual( sbOutput, sClippedExpected, sClippedActual ); sbOutput.Append( NewLine ); // Add a line showing where they differ. If the string lengths are // different, they start differing just past the length of the // shorter string AppendPositionMarker( sbOutput, FindMismatchPosition( sClippedExpected, sClippedActual, 0 ) ); sbOutput.Append( NewLine ); } /// <summary> /// Turns CR, LF, or TAB into visual indicator to preserve visual marker /// position. This is done by replacing the '\r' into '\\' and 'r' /// characters, and the '\n' into '\\' and 'n' characters, and '\t' into /// '\\' and 't' characters. /// /// Thus the single character becomes two characters for display. /// </summary> /// <param name="sInput"></param> /// <returns></returns> static protected string ConvertWhitespace( string sInput ) { if( null != sInput ) { sInput = sInput.Replace( "\r", "\\r" ); sInput = sInput.Replace( "\n", "\\n" ); sInput = sInput.Replace( "\t", "\\t" ); } return sInput; } /// <summary> /// Shows the position two strings start to differ. Comparison /// starts at the start index. /// </summary> /// <param name="sExpected"></param> /// <param name="sActual"></param> /// <param name="iStart"></param> /// <returns>-1 if no mismatch found, or the index where mismatch found</returns> static private int FindMismatchPosition( string sExpected, string sActual, int iStart ) { int iLength = Math.Min( sExpected.Length, sActual.Length ); for( int i=iStart; i<iLength; i++ ) { // // If they mismatch at a specified position, report the // difference. // if( sExpected[i] != sActual[i] ) { return i; } } // // Strings have same content up to the length of the shorter string. // Mismatch occurs because string lengths are different, so show // that they start differing where the shortest string ends // if( sExpected.Length != sActual.Length ) { return iLength; } // // Same strings // Assert.IsTrue( sExpected.Equals( sActual ) ); return -1; } /// <summary> /// Constructs a message that can be displayed when the content of two /// strings are different, but the string lengths are the same. The /// message will clip the strings to a reasonable length, centered /// around the first position where they are mismatched, and draw /// a line marking the position of the difference to make comparison /// quicker. /// </summary> /// <param name="sbOutput"></param> /// <param name="sExpected"></param> /// <param name="sActual"></param> static protected void BuildContentDifferentMessage( StringBuilder sbOutput, string sExpected, string sActual ) { // // If they mismatch at a specified position, report the // difference. // int iMismatch = FindMismatchPosition( sExpected, sActual, 0 ); if( -1 != iMismatch ) { BuildContentDifferentAtPosition( sbOutput, sExpected, sActual, iMismatch ); return; } // // If the lengths differ, but they match up to the length, // show the difference just past the length of the shorter // string // if( sExpected.Length != sActual.Length ) { BuildContentDifferentAtPosition( sbOutput, sExpected, sActual, Math.Min(sExpected.Length, sActual.Length) ); } } /// <summary> /// Called to append a message when the input strings are different. /// A different message is rendered when the lengths are mismatched, /// and when the lengths match but content is mismatched. /// </summary> /// <param name="sbOutput"></param> /// <param name="expected"></param> /// <param name="actual"></param> static private void BuildStringsDifferentMessage( StringBuilder sbOutput, string expected, string actual ) { sbOutput.Append( NewLine ); if( LengthsDifferent( expected, actual ) ) { BuildLengthsDifferentMessage( sbOutput, expected, actual ); } else { BuildContentDifferentMessage( sbOutput, expected, actual ); } } /// <summary> /// Called to append a message when the input arrays are different. /// A different message is rendered when the lengths are mismatched, /// and when the lengths match but content is mismatched. /// </summary> /// <param name="sbOutput"></param> /// <param name="expected"></param> /// <param name="actual"></param> static private void BuildArraysDifferentMessage( StringBuilder sbOutput, int index, Array expected, Array actual ) { sbOutput.Append( NewLine ); BuildArrayLengthReport( sbOutput, expected, actual ); sbOutput.Append( "Arrays differ at index " ); sbOutput.Append( index ); sbOutput.Append( "." ); sbOutput.Append( NewLine ); if ( index < expected.Length && index < actual.Length ) { if( InputsAreStrings( expected.GetValue(index), actual.GetValue(index) ) ) { BuildStringsDifferentMessage( sbOutput, (string)expected.GetValue(index), (string)actual.GetValue(index) ); } else { AppendExpectedAndActual( sbOutput, expected.GetValue(index), actual.GetValue(index) ); } } else if( expected.Length < actual.Length ) { sbOutput.Append( NewLine ); sbOutput.Append( " extra:<" ); DisplayElements( sbOutput, actual, index, 3 ); sbOutput.Append( ">" ); } else { sbOutput.Append( NewLine ); sbOutput.Append( " missing:<" ); DisplayElements( sbOutput, expected, index, 3 ); sbOutput.Append( ">" ); } return; } static private void DisplayElements( StringBuilder sbOutput, Array array, int index, int max ) { for( int i = 0; i < max; i++ ) { sbOutput.Append( DisplayString( array.GetValue(index++) ) ); if ( index >= array.Length ) return; sbOutput.Append( "," ); } sbOutput.Append( "..." ); } /// <summary> /// Used to create a StringBuilder that is used for constructing /// the output message when text is different. Handles initialization /// when a message is provided. If message is null, an empty /// StringBuilder is returned. /// </summary> /// <param name="message"></param> /// <returns></returns> static protected StringBuilder CreateStringBuilder( string message, params object[] args ) { StringBuilder sbOutput; if (message != null) { if ( args != null && args.Length > 0 ) sbOutput = new StringBuilder( string.Format( message, args ) ); else sbOutput = new StringBuilder( message ); } else { sbOutput = new StringBuilder(); } return sbOutput; } /// <summary> /// Called to create a message when two objects have been found to /// be unequal. If the inputs are strings, a special message is /// rendered that can help track down where the strings are different, /// based on differences in length, or differences in content. /// /// If the inputs are not strings, the ToString method of the objects /// is used to show what is different about them. /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <param name="message"></param> /// <param name="args"></param> /// <returns></returns> static public string FormatMessageForFailNotEquals(Object expected, Object actual, string message, params object[] args) { StringBuilder sbOutput = CreateStringBuilder( message, args ); if( null != message ) { if( message.Length > 0 ) { sbOutput.Append( " " ); } } if( InputsAreStrings( expected, actual ) ) { BuildStringsDifferentMessage( sbOutput, (string)expected, (string)actual ); } else { AppendExpectedAndActual( sbOutput, expected, actual ); } return sbOutput.ToString(); } /// <summary> /// Called to create a message when two arrays are not equal. /// </summary> /// <param name="message"></param> /// <param name="expected"></param> /// <param name="actual"></param> /// <returns></returns> static public string FormatMessageForFailArraysNotEqual(int index, Array expected, Array actual, string message, params object[] args) { StringBuilder sbOutput = CreateStringBuilder( message, args ); if( null != message ) { if( message.Length > 0 ) { sbOutput.Append( " " ); } } BuildArraysDifferentMessage( sbOutput, index, expected, actual ); return sbOutput.ToString(); } } } --- NEW FILE: TestFixtureSetUpAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a place for code that should be run at the beginning of the TestFixture /// </summary> /// <remarks> /// Any initialization code should be done here, instead of within the class constructor. /// /// This is because the constructor is only run ONCE, at the start of the test engine, whereas /// the TestFixtureSetUp will be run at the beginning of each TestFixture iteration. /// </remarks> /// <example> /// [TestFixtureSetUp] /// public void TestFixtureSetUp(){ /// // this will run at the beginning of the TestFixture /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class TestFixtureSetUpAttribute : Attribute { } } --- NEW FILE: TestFixtureTearDownAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a place for code that should be run at the end of the TestFixture /// </summary> /// <remarks> /// Any finalization code should be done here, instead of within the class destructor. /// /// This is because the destructor is only run ONCE, when the test engine shuts down, whereas /// the TestFixtureTearDown will be run at the end of each TestFixture iteration. /// </remarks> /// <example> /// [TestFixtureTearDown] /// public void TestFixtureTearDown(){ /// // this will run at the end of the TestFixture /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class TestFixtureTearDownAttribute : Attribute { } } --- NEW FILE: TestTearDownAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a place for code that should be run after a Test /// /// Unless a Test name is specified, this will run after each Test. /// </summary> /// <example> /// [TestTearDown] /// public void TestTearDown(){ /// // this will run for each test /// } /// /// [TestTearDown(Test="SomeTest")] /// public void TestTearDownForSomeTest(){ /// // this will run only for SomeTest /// } /// /// [Test] /// public void SomeTest(){ /// // code /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public class TestTearDownAttribute : Attribute { private string _test = ""; /// <summary> /// Constructor /// </summary> public TestTearDownAttribute() : base() { } /// <summary> /// Constructor /// </summary> /// <param name="test">The name of the Test that this should run for.</param> public TestTearDownAttribute(string test) { this._test = test; } /// <summary> /// The name of the Test that this should run for. /// </summary> public string Test { get { return this._test; } set { this._test = value; } } } } --- NEW FILE: AssertionException.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: ExpectedExceptionAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies an Exception type that is expected to be thrown. /// /// If that Exception type, or one of its children, is thrown then /// the Test will pass. /// /// If the Exception type, or one of its children, is not thrown then /// the Test will fail. /// </summary> /// <example> /// [Test] /// [ExpectedException(typeof(DivideByZeroException))] /// public void ExpectedDivideByZeroException() /// { /// Console.WriteLine("ExpectedException"); /// throw new DivideByZeroException("This Exception is expected."); /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class ExpectedExceptionAttribute : Attribute { private string expectedException = String.Empty; private string message = String.Empty; /// <summary> /// The ExceptionType that is expected to be thrown. /// </summary> public string ExceptionType { get { return expectedException; } } public string Message { get { return this.message;} set { this.message = value;} } /// <summary> /// Constructor /// </summary> /// <param name="exception">The ExceptionType that is expected to be thrown.</param> public ExpectedExceptionAttribute(Type exception) { expectedException = exception.FullName; } public ExpectedExceptionAttribute(Type exception, string message) { this.expectedException = exception.FullName; this.message = message; } } } --- NEW FILE: TearDownAttribute.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UnitTest { using System; /// <summary> /// Specifies a place for code that should be run after a Test /// /// Unless a Test name is specified, this will run after each Test. /// </summary> /// <remarks> /// This is a deprecated attribute that was created for backwards compatability with NUnit. /// New tests should use TestTearDown, since the name better communicates the scope. /// </remarks> /// <example> /// [TearDown] /// public void TearDown(){ /// // this will run for each test /// } /// /// [TearDown(Test="SomeTest")] /// public void TearDownForSomeTest(){ /// // this will run only for SomeTest /// } /// /// [Test] /// public void SomeTest(){ /// // code /// } /// </example> [AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)] public sealed class TearDownAttribute : TestTearDownAttribute { } } --- NEW FILE: TestType.cs --- using System; namespace Adapdev.UnitTest { /// <summary> /// Summary description for TestType. /// </summary> /// [Serializable] [Flags] public enum TestType : int { /// <summary> /// /// </summary> Unit = 1, /// <summary> /// /// </summary> Integration = 2, /// <summary> /// /// </summary> System = 4, /// <summary> /// /// </summary> Database = 8, /// <summary> /// Function testing of the target-of-test should focus on any requirements for test that can be traced directly to use cases or business functions and business rules. The goals of these tests are to verify proper data acceptance, processing, and retrieval, and the appropriate implementation of the business rules. This type of testing is based upon black box techniques; that is verifying the application and its internal processes by interacting with the application via the Graphical User Interface (GUI) and analyzing the output or results. /// </summary> Functional = 16, /// <summary> /// Business Cycle Testing should emulate the activities performed over time. A period should be identified, such as one year,... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:13
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Windows.Forms/Progress In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Windows.Forms/Progress Added Files: ProgressWindow.cs ProgressWindow.resx Log Message: --- NEW FILE: ProgressWindow.resx --- <?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 1.3 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">1.3</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1">this is my long string</data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> [base64 mime encoded serialized .NET Framework object] </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> [base64 mime encoded string representing a byte array form of the .NET Framework object] </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used forserialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>1.3</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="txtMessage1.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="txtMessage1.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="txtMessage1.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="cancelButton.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="cancelButton.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="cancelButton.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="morelessButton.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="morelessButton.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="morelessButton.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="imageList.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="imageList.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="imageList.Location" type="System.Drawing.Point, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>17, 17</value> </data> <data name="imageList.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64"> <value> AAEAAAD/////AQAAAAAAAAAMAgAAAFpTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0xLjAuNTAw MC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZT eXN0ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMA AAAGDgAAAk1TRnQBSQFMAgEBBAEAAQkBAAEEAQABEAEAARABAAT/AREBEAj/AUIBTQE2BwABNgMAASgD AAFAAwABMAMAAQEBAAEQBgABGP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8AMAABlAE1AZQB NQGUATUBlAE1AZQBNQGUATUBlAE1AZQBNQGUATUKAAEgAQEBYAEFAaABBQGgAQUBYAEFASABARQAAUYB AAFoAQABigEAAYoBAAFoAQABRhYAARABAAEYAQABIAEAASABAAEYAQABFBgAAZMBMQGeAWMBfgFbAV0B UwE9AUsBHgFDAR0BQwFeAUMBlAE1BgABgAEFAYABBQFBAQoBwQEOAcEBDgHBAQ4BwQEOAUABCgGgAQUB oAEFDAABaQEAAWkBAAHQAQABFAEBARUBAQEVAQEBFAEBAdABAAFqAQABag4AARwBAAEcAQABMAEAAUAB AAFEAQABRAEAAUQBAAEwAQABHAEAARwUAAFxAS0BOwFbARoBUwH6AU4B+wFKARwBSwH8AUIBHgFDAZQB NQQAAaEBCQHhAQkBwQEOAeEBDgHBAQ4BwAEKAcEBDgHBAQ4B4QEOAeEBDgEAAQoBIAEBCAABiwEAAa0B AAEVAQEBFgEBARUBAQEUAQEBFQEBARUBAQEVAQEBFgEBAa4BAAFGCgABIAEAASgBAAFIAQABSAEAAUQB AAFAAQABRAEAAUQBAAFIAQABSAEAASgBAAEUEgABTgEpAXQBSgFTAUIBVAE+AbgBRgH7AUoBHAFLAT4B QwGUATUCAAGhAQkBAQESAeIBGgHCARIBwQEOAcABCgHBAQoBwQEOAcEBDgHBAQ4BwQEOAeEBDgEAAQoB gAEFBAABiwEAAc8BAAE4AQEBNwEBARUBAQEUAQEBFAEBARQBAQEUAQEBFAEBARUBAQEWAQEBrgEAAWoF AAEgASgBAAEsAQABUAEAAUwBAAFEAQABQAEAAUABAAFEAQABRAEAAUQBAAFEAQABSAEAASgBAAEcDgAB YAF9AQoBHQGtATUBYAF9Aa4BLQEyAToBuAFGAfsBSgE9AUsBlAE1AgABoQEJAeQBJgHjASIBwgEaAcEB DgHlARoB2wFzAf0BdwEsATcBwQEOAcEBDgHBAQ4B4QEOAYABBQQAAYsBAAFaAQEBWQEBATcBAQEVAQEB VgEJAZ4BawG/AXMB+AEhARQBAQEUAQEBFQEBARYBAQFqBQABIAEoAQABWAEAAVQBAAFMAQABRAEgAUgB egF7AbwBfwEFAVUBAAFEAQABRAEAAUQBAAFIAQABHAIAAbQBNQG0ATUBtAE1AZQBMQFxAS0BDQEhAWAB fQFgAX0BYAF9AWABfQFLASkBrgEtAVQBPgHaAU4BXgFTAZQBNQHBAQkBYwEeAQUBLwHjASIBwQESAcEB DgHCARIBcwFTAf8BfwH+AX8BKwEzAcEBDgHBAQ4B4QEOAUEBCgFgAQUBiwEAAfQBAAF9AQEBWQEBARYB AQEVAQEBFQEBAbsBPgH/AX8B/wF7AfgBHQEUAQEBFAEBARUBAQHQAQABaAEAASABLAEAAUQBAAFkAQAB VAEAAUgBAAFEAQABRAEOAWYB/wF/Ad4BfwHkAVQBAAFEAQABRAEAAUgBAAEwAQABGAGUATUBnwFjAT0B UwEcAUsBYAF9AWABfQFgAX0BYAF9AWABfQFgAX0BYAF9AWABfQFTAUIBOwFXAX0BWwGUATUBwQEJAcUB LgEFATMB5AEmAcEBEgHBAQ4BwQEOAcEBDgFxAUsB/wF/Af4BewErATMBwQEOAcEBDgGhAQoBYAEFAYsB AAFaAQEBfQEBAVoBAQEWAQEBFQEBARUBAQEVAQEBmgE2Af8BfwHfAXsB2AEdARQBAQEVAQEB8wEAAWgC AAEgAQABXAEAAWQBAAFYAQABSAEAAUQBAAFEAQABRAHMAWEB/wF/Ad4BfwHjAVQBAAFEAQABRAEAAUAB AAEYAbQBNQG/AWsBXgFbAT0BUwG5AUIBYAF9AWABfQEKARkBzgE5AWABfQFgAX0BrQExAXQBSgFxASkB kwEtAZQBNQEBAQ4BBgE3AQYBNwHZAW8BuQFrAbgBawG5AWsBuAFrAbgBZwH/AX8B/wF/Af4BewFNAT8B wQEOAcEBDgGAAQUBrgEAAZ4BAQGfAQEBXwFXAV8BVwE+AVcBXwFXAT4BUwE+AVcB/wF7Af8BfwHfAXcB OQEmARUBAQEVAQEBaQIAASwBAAFsAQABbAH1AX4B9QF6AdQBegHUAXoB1AF6AdQBegHeAX8B/wF/Ad0B fwFHAVkBAAFEAQABRAEAARwB1AE1Ad8BcwF+AWMBXQFbAdoBSgFgAX0BYAF9AQoBGQGMATEBYAF9AWAB fQHOATkBlAFOAXEBKQFbASIB1wEhASIBEgErAUMBKAE7Af8BfwH/AX8B/wF/Af8BfwH/AX8B/wF/Af8B fwH/AX8B/wF/AbcBYwHBAQ4BwQEOAaABBQHRAQAB/wEJAb8BAQH/AX8B/wF/Af8BfwH/AX8B/wF/Af8B fwH/AX8B/wF/Af8BfwEcAVMBFQEBARUBAQGKAgABNAFgAXABIAFwAf8BfwH/AX8B/wF/Af8BfwH/AX8B /wF/Af8BfwH/AX8B/wF/AdQBcgEAAUQBAAFEAQABIAHUATUB/wF7AZ4BawF9AWMBYAF9AWABfQFgAX0B YAF9AWABfQFgAX0BYAF9AWABfQH4AV4BkgEpARgBMgIAAUEBDgFNAksBRwFNAUsBTgFPAU4BTwFOAU8B TAFHAXIBVwH/AX8B/wF/AZUBXwHlASYB4gEWAcEBDgGAAQUB0QEAAT8BFgEfAQ4BPgEaAT8BGgE/ARoB PwEaAR8BEgGdATIB/wF/Af8BfwH9AUYBeAEFATcBAQEUAQEBaQIAATQB4wF0AYABcAHjAWwB4wFwAeMB cAHjAXABoQFsAewBdQH/AX8B/wF/AVABbgEgAVQBAAFMAQABQAEAARwBFwE2Af8BfwG/AXMBngFrAX0B YwEbAVMBYAF9AWABfQFgAX0BYAF9AVoBNgFaATYBWgE2AZMBLQQAAUEBDgEsAUMBkwFfAQcBOwEGATcB BwE3AQcBNwFOAUsB/QF3Af8BfwGTAVsB5AEmAeMBHgHiARYBgQEKAYABBQHRAQABHwEOAb8BMgGfAQEB fQEBAZ8BAQGfAQEBPwEaAb8BbwH/AX8BvQE+AVkBAQE4AQEBNwEBAfIBAAFpAgABNAHBAXQBywF5AQAB cAEAAWgBAAFsAQABbAHiAXABmwF/Af8BfwENAW4BAAFYAQABUAEAAUwBAAE4AQABHAEXATYB/wF/Af8B ewHfAXMBngFrAX0BYwFgAX0B2QFKAXEBLQFgAX0OAAHGASoBtwFrAXABUwEFATMBBQEzASoBQwH+AX8B /wF/AZMBWwHkASYB4wEiAcMBGgECARsBAQEKBAABfAEBAR8BSwF/ASIBfAEBAX0BAQHfAQkB/wF7Af8B fwG+AToBWQEBATkBAQE4AQEBOAEBAa4FAAEgAWgBkgF+AUUBdQEAAWABAAFkAUABbAHeAX8B/wF/AQ0B dgEAAVgBAAFUAQABUAEAAVQBAAEsAgABWgE2Af8BfwH/AX8B/wF7Ab8BcwGeAWsBtAEtAbQBLQGTATEQ AAHGASoBTgFHAdoBcwFwAVMBBgE3AQcBNwG3AWcBlQFjAQUBMwHkASoB5AEmAQMBIwGiARoBAQEKBAAB fAEBAT8BFgF/AVsBXwEiAZ8BAQGdAQEBHwFLAf8BPgF8AQEBWwEBAVoBAQFaAQEBFgEBAa4GAAFkAcIB cAH1AXoBZwF9ASABcAFAAWwBkgF+AS4BfgEAAWABAAFcAQABWAEAAVwBAAFIAQABLAIAAXsBOgH/AX8B /wF/Af8BfwH/AX8BXAFnAbQBLQEZASIBtQEpEgABpAEeAXABTwHbAXcBtQFjAU0BSwEqAUMBKAE/ASkB PwEpAT8BJwE3AcQBJgHhAQ0IAAE4AQEBfwEiAZ8BYwH/AT4BHwEWAd8BBQG/AQEBvwEFAb8BBQGfAQEB OQEBAa4KAAFQASUBcQFYAX8BbwF+AQMBeQGBAXgBYAF0AWABdAEgAXABAAFwAQABVAEAASgEAAG8AT4B /wF/Af8BfwH/AX8B/wF/AVwBbwG0AS0BOgEuFgABLAFDASwBQwG1AWMB2QFvAbcBawGUAWMBkgFbAUwB SwHFASoBxQEqDAABHwEOAR8BDgH/AT4BXwFXAR8BSwHfAToBnwEuAR8BEgFaAQEBWgEBDAABgAFwAcIB eAFPAX4B9QF+AZIBfgEuAX4BygF9AaABcAEAAVwBAAFcBgABvAE+AVoBNgFaATYBWgE2AVoBNgFaATYB tAEtHAABxgEmAQoBNwEsAUMBKwE/AegBMgGEASIUAAF8AQEB3wEFAf8BDQH/AQkBnwEBARYBARQAASAB aAFgAXQBwQF4AaEBeAEgAXQBAAFQCgABQgFNAT4HAAE+AwABKAMAAUADAAEwAwABAQEAAQEFAAGAAQEW AAP//wACAAH+AQAB+AEfAfgBHwH4AR8B/gEAAeABBwHgAQcB4AEHAf4BAAHAAQMBwAEDAcABAwH+AQAB gAEBAYABAQGAAQEB/AEAAYABAQGAAQEBgAEBIQABAQcAAQMHAAE/AYABAQGAAQEBgAEBAQABfwGAAQEB gAEBAYABAQEAAX8BwAEDAcABAwHAAQMBAAH/AeABBwHgAQcB4AEHAQEB/wH4AR8B+AEfAfgBHxYACw== </value> </data> <data name="txtMessage2.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="txtMessage2.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="txtMessage2.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="listView.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="listView.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="listView.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="ColumnHeader1.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="ColumnHeader1.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="progressBar.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="progressBar.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="progressBar.Modifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> <data name="$this.Locked" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="$this.Language" type="System.Globalization.CultureInfo, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>(Default)</value> </data> <data name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="$this.Localizable" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>False</value> </data> <data name="$this.GridSize" type="System.Drawing.Size, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>8, 8</value> </data> <data name="$this.Name"> <value>ProgressWindow</value> </data> <data name="$this.DrawGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>True</value> </data> <data name="$this.TrayHeight" type="System.Int32, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>80</value> </data> <data name="$this.SnapToGrid" type="System.Boolean, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>True</value> </data> <data name="$this.DefaultModifiers" type="System.CodeDom.MemberAttributes, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <value>Private</value> </data> </root> --- NEW FILE: ProgressWindow.cs --- // // This code based on functions from http://www.codeproject.com/cs/miscctrl/progressdialog.asp // Original Author: About Matthew Adams // using System; using System.Drawing; using System.Windows.Forms; namespace Adapdev.Windows.Forms.Progress { /// <summary> /// Summary description for ProgressWindow. /// </summary> public class ProgressWindow : System.Windows.Forms.Form, IProgressCallback { private System.ComponentModel.IContainer components; public delegate void SetTextInvoker(String text1, String text2); public delegate void IncrementInvoker( int val ); public delegate void StepToInvoker( int val ); public delegate void RangeInvoker( int minimum, int maximum ); public delegate void MoreLessInvoker( bool state ); public delegate void AddMessageInvoker (ProgressMessageTypes type, string message); private System.Threading.ManualResetEvent initEvent = new System.Threading.ManualResetEvent(false); private System.Threading.ManualResetEvent abortEvent = new System.Threading.ManualResetEvent(false); private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button morelessButton; private bool requiresClose = true; private bool morelessOpen = false; private bool completed = false; private ProgressAutoCloseTypes autoClose = ProgressAutoCloseTypes.AutoClose; private readonly int minWidth = 232; private readonly int openSize; private readonly int closedSize; private int totalErrors = 0; private bool firstMsg = true; private System.Windows.Forms.Label txtMessage1; private System.Windows.Forms.ListView listView; private System.Windows.Forms.ColumnHeader ColumnHeader1; private Adapdev.Windows.Forms.SmoothProgressBar progressBar; private System.Windows.Forms.Label txtMessage2; public ProgressWindow() { // // Required for Windows Form Designer support // InitializeComponent(); openSize = this.Height; closedSize = this.Height - (this.listView.Height + 16); DoSetMoreLess(false); } #region Implementation of IProgressCallback /// <summary> /// Call this method from the worker thread to initialize /// the progress meter. /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> public void Begin( int minimum, int maximum ) { initEvent.WaitOne(); Invoke( new RangeInvoker( DoBegin ), new object[] { minimum, maximum } ); } /// <summary> /// Call this method from the worker thread to initialize /// the progress meter. /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> public void Begin(ProgressAutoCloseTypes autoClose, int minimum, int maximum ) { initEvent.WaitOne(); this.autoClose = autoClose; Invoke( new RangeInvoker( DoBegin ), new object[] { minimum, maximum } ); } /// <summary> /// Call this method from the worker thread to initialize /// the progress callback, without setting the range /// </summary> public void Begin() { initEvent.WaitOne(); Invoke( new MethodInvoker( DoBegin ) ); } /// <summary> /// Call this method from the worker thread to reset the range in the progress callback /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> public void SetRange( int minimum, int maximum ) { initEvent.WaitOne(); Invoke( new RangeInvoker( DoSetRange ), new object[] { minimum, maximum } ); } /// <summary> /// Call this method to set the Autoclose flag /// </summary> public void SetAutoClose( ProgressAutoCloseTypes autoClose ) { this.autoClose = autoClose; } /// <summary> /// Call this method from the worker thread to update the progress text. /// </summary> /// <param name="text1">The progress heading text to display</param> /// <param name="text2">The progress sub-heading text to display</param> public void SetText( String text1, String text2 ) { Invoke( new SetTextInvoker(DoSetText), new object[] { text1, text2 } ); } public void SetText( String text ) { SetText (null, text); } /// <summary> /// Call this method from the worker thread to increase the progress counter by a specified value. /// </summary> /// <param name="val">The amount by which to increment the progress indicator</param> public void Increment( int val ) { Invoke( new IncrementInvoker( DoIncrement ), new object[] { val } ); } /// <summary> /// Call this method from the worker thread to step the progress meter to a particular value. /// </summary> /// <param name="val"></param> public void StepTo( int val ) { Invoke( new StepToInvoker( DoStepTo ), new object[] { val } ); } /// <summary> /// Call this method from the worker thread to step the progress meter to a particular value. /// </summary> public void AddMessage( string message ) { Invoke( new AddMessageInvoker( DoAddMessage), new object[] { ProgressMessageTypes.Info, message } ); } /// <summary> /// Call this method from the worker thread to step the progress meter to a particular value. /// </summary> public void AddMessage( ProgressMessageTypes type, string message ) { Invoke( new AddMessageInvoker( DoAddMessage), new object[] { type, message } ); } /// <summary> /// Called by the UI to update the UI /// </summary> private void morelessButton_Click(object sender, System.EventArgs e) { Invoke( new MoreLessInvoker(DoSetMoreLess), new object[] { !morelessOpen } ); } private void ProgressWindow_Resize(object sender, System.EventArgs e) { if (this.Height < closedSize) this.Height = closedSize; if (this.Width < minWidth) this.Width = minWidth; listView.Columns[0].Width = listView.Width; } private void cancelButton_Click(object sender, System.EventArgs e) { Invoke( new SetTextInvoker(DoSetText), new object[] { null, "Processing Cancelled!" } ); Invoke( new AddMessageInvoker( DoAddMessage), new object[] { ProgressMessageTypes.Critical, "Processing Cancelled!" } ); End(); } /// <summary> /// If this property is true, then you should abort work /// </summary> public bool IsAborting { get { return abortEvent.WaitOne( 0, false ); } } /// <summary> /// Call this method from the worker thread to finalize the progress meter /// </summary> public void End() { if( requiresClose ) { Invoke( new MethodInvoker( DoEnd ) ); } } #endregion #region Implementation members invoked on the owner thread private void DoSetText( String text1, String text2 ) { if (text1 != null) txtMessage1.Text = text1; txtMessage2.Text = text2; } private void DoIncrement( int val ) { progressBar.Increment( val ); UpdateStatusText(); } private void DoStepTo( int val ) { progressBar.Value = val; UpdateStatusText(); } private void DoBegin( int minimum, int maximum ) { DoBegin(); DoSetRange( minimum, maximum ); } private void DoBegin() { cancelButton.Enabled = true; } private void DoSetRange( int minimum, int maximum ) { progressBar.Minimum = minimum; progressBar.Maximum = maximum; progressBar.Value = minimum; UpdateStatusText(); } private void DoAddMessage( ProgressMessageTypes type, string message ) { ListViewItem li = new ListViewItem(); li.Text = message; switch (type) { case ProgressMessageTypes.Info: li.ImageIndex = 1; break; case ProgressMessageTypes.Warning: li.ImageIndex = 2; totalErrors += 1; break; case ProgressMessageTypes.Critical: li.ImageIndex = 3; totalErrors += 1; break; } listView.Items.Add(li); if (firstMsg = true) { firstMsg = false; this.morelessButton.Enabled = !(this.listView.Items.Count == 0); this.morelessButton.ForeColor = (this.listView.Items.Count == 0) ? Color.Black : Color.Red; } } private void DoSetMoreLess (bool moreless) { morelessOpen = moreless; if (moreless){ this.Height = openSize; this.morelessButton.Text = @"<<< Less"; this.FormBorderStyle = FormBorderStyle.Sizable; this.SizeGripStyle = SizeGripStyle.Show; }else{ this.Height = closedSize; this.morelessButton.Text = @"More >>>"; this.FormBorderStyle = FormBorderStyle.FixedSingle; this.SizeGripStyle = SizeGripStyle.Hide; } this.morelessButton.Enabled = !(this.listView.Items.Count == 0); } private void DoSetCompleted() { UpdateStatusText(); completed = true; this.cancelButton.Text = "Close"; } private void DoEnd() { if (!completed && requiresClose) { switch (autoClose) { case ProgressAutoCloseTypes.AutoClose: Close(); break; case ProgressAutoCloseTypes.WaitOnEnd: Invoke( new MethodInvoker( DoSetCompleted ) ); break; case ProgressAutoCloseTypes.WaitOnError: if (totalErrors == 0) { Close(); } else { Invoke( new MethodInvoker( DoSetCompleted ) ); } break; } if (totalErrors > 0) { Invoke( new MoreLessInvoker(DoSetMoreLess), new object[] { true } ); } } else { Close(); } } #endregion #region Overrides /// <summary> /// Handles the form load, and sets an event to ensure that /// intialization is synchronized with the appearance of the form. /// </summary> /// <param name="e"></param> protected override void OnLoad(System.EventArgs e) { base.OnLoad( e ); ControlBox = false; initEvent.Set(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Handler for 'Close' clicking /// </summary> /// <param name="e"></param> protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { requiresClose = false; AbortWork(); base.OnClosing( e ); } #endregion #region Implementation Utilities /// <summary> /// Utility function that formats and updates the title bar text /// </summary> private void UpdateStatusText() { this.Text = this.txtMessage1.Text.Trim() + String.Format( " - {0}% complete", (progressBar.Value * 100 ) / (progressBar.Maximum - progressBar.Minimum) ); } /// <summary> /// Utility function to terminate the thread /// </summary> private void AbortWork() { abortEvent.Set(); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ProgressWindow)); this.txtMessage1 = new System.Windows.Forms.Label(); this.cancelButton = new System.Windows.Forms.Button(); this.morelessButton = new System.Windows.Forms.Button(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.txtMessage2 = new System.Windows.Forms.Label(); this.listView = new System.Windows.Forms.ListView(); this.ColumnHeader1 = new System.Windows.Forms.ColumnHeader(); this.progressBar = new Adapdev.Windows.Forms.SmoothProgressBar(); this.SuspendLayout(); // // txtMessage1 // this.txtMessage1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMessage1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.txtMessage1.Location = new System.Drawing.Point(8, 8); this.txtMessage1.Name = "txtMessage1"; this.txtMessage1.Size = new System.Drawing.Size(326, 16); this.txtMessage1.TabIndex = 0; this.txtMessage1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Enabled = false; this.cancelButton.Location = new System.Drawing.Point(264, 64); this.cancelButton.Name = "cancelButton"; this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // morelessButton // this.morelessButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.morelessButton.Location = new System.Drawing.Point(182, 64); this.morelessButton.Name = "morelessButton"; this.morelessButton.TabIndex = 4; this.morelessButton.Text = "More >>>"; this.morelessButton.Click += new System.EventHandler(this.morelessButton_Click); // // imageList // this.imageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth16Bit; this.imageList.ImageSize = new System.Drawing.Size(16, 16); this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; // // txtMessage2 // this.txtMessage2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMessage2.Location = new System.Drawing.Point(8, 24); this.txtMessage2.Name = "txtMessage2"; this.txtMessage2.Size = new System.Drawing.Size(326, 16); this.txtMessage2.TabIndex = 5; this.txtMessage2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // listView // this.listView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.ColumnHeader1}); this.listView.FullRowSelect = true; this.listView.GridLines = true; this.listView.LargeImageList = this.imageList; this.listView.Location = new System.Drawing.Point(8, 96); this.listView.MultiSelect = false; this.listView.Name = "listView"; this.listView.Size = new System.Drawing.Size(328, 168); this.listView.SmallImageList = this.imageList; this.listView.StateImageList = this.imageList; this.listView.TabIndex = 6; this.listView.View = System.Windows.Forms.View.SmallIcon; // // ColumnHeader1 // this.ColumnHeader1.Text = "Message"; this.ColumnHeader1.Width = 500; // // progressBar // this.progressBar.Location = new System.Drawing.Point(8, 40); this.progressBar.Maximum = 100; this.progressBar.Minimum = 0; this.progressBar.Name = "progressBar"; this.progressBar.ProgressBarColor = System.Drawing.Color.Blue; this.progressBar.Size = new System.Drawing.Size(328, 16); this.progressBar.TabIndex = 7; this.progressBar.Value = 0; // // ProgressWindow // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(344, 278); this.ControlBox = false; this.Controls.Add(this.progressBar); this.Controls.Add(this.listView); this.Controls.Add(this.txtMessage2); this.Controls.Add(this.morelessButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.txtMessage1); this.MaximizeBox = false; this.Name = "ProgressWindow"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "ProgressWindow"; this.Resize += new System.EventHandler(this.ProgressWindow_Resize); this.ResumeLayout(false); } #endregion } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Web/Rss In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Web/Rss Added Files: IPersistentManager.cs RssCacheManager.cs RssCacheManager.resx RssReader.cs atom.xsd atom.xsx opml.xsd opml.xsx opmlbody.cs opmldocument.cs opmlhead.cs opmloutline.cs rss.xsd rss.xsx rsschannel.cs rsscloud.cs rssenclosure.cs rssguid.cs rssimage.cs rssitem.cs rsssource.cs rsstextinput.cs Log Message: --- NEW FILE: IPersistentManager.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: RssCacheManager.resx --- <?xml version="1.0" encoding="utf-8" ?> <root> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="ResMimeType"> <value>text/microsoft-resx</value> </resheader> <resheader name="Version"> <value>1.0.0.0</value> </resheader> <resheader name="Reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="Writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> </root> --- NEW FILE: rsscloud.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: atom.xsd --- <?xml version="1.0" encoding="UTF-8"?> <xs:schema targetNamespace="http://purl.org/atom/ns#" xmlns:atom="http://purl.org/atom/ns#" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/03/xml.xsd"/> <xs:element name="feed" type="atom:feedType"> <xs:annotation> <xs:documentation><![CDATA[ The top-level element is <feed>. ]]></xs:documentation> </xs:annotation> </xs:element> <xs:complexType name="feedType"> <xs:annotation> <xs:documentation><![CDATA[ The top-level element is <feed>. It has several <entry> children. If a property says it can apply to entries, that means that if itâs put in <feed> then itâs a default value for each <entry>. If it can also apply to <entry>, then the value in an <entry> can override the default entries value. Required children of feed: title: Equivalent to dc:title. If this feed describes a website, SHOULD be the title of the website. link: The link to the website described by this feed. If this feed describes a website, SHOULD be a link to the homepage of the website. modified: W3DTF. Equivalent to dcterms:modified. The modification date of the feed, including any changes to any of the listed entries. SHOULD be UTC. author: [defined below] One of these MUST be true: feed contains author (if so, itâs inherited by all the entries); every entry contains author (overrides any inherited one). Optional children of feed: tagline: Subproperty of dc:description. A short human-readable tagline for this feed. Examples: "All the news thatâs fit to print" (tagline of NYT). id: A URI. Permanent, globally unique ID of this feed. MUST NOT change, ever, even if the feed is moved to a new server. For this reason, it probably shouldnât be the same as feed/link, although it MAY be. Weâre currently discussing options, including tag: URIs and GUID in the COM/CORBA sense. generator: [defined below] entry*: [defined below] contributor*: [defined below] copyright: Equivalent to dc:rights. Human-readable copyright statement for this feed. For machine-readable licensing information, producers SHOULD use the <license> element (to be defined). Note that omission of this element does not mean the feed isnât copyrighted. ]]></xs:documentation> </xs:annotation> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element name="title" type="xs:string"/> <xs:element name="link" type="xs:anyURI"/> <xs:element name="modified" type="atom:iso8601dataTime"/> <xs:element name="author" type="atom:authorType" minOccurs="0"/> <xs:element name="tagline" type="xs:string" minOccurs="0"/> <xs:element name="id" type="xs:anyURI" minOccurs="0"/> <xs:element name="generator" type="atom:generatorType" minOccurs="0"/> <xs:element name="contributor" type="atom:authorType" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation><![CDATA[ Same required and optional elements as author. Suproperty of "dc:contributor". ]]></xs:documentation> </xs:annotation> </xs:element> <xs:element name="copyright" type="xs:string" minOccurs="0"/> <xs:element name="entry" type="atom:entryType" minOccurs="0" maxOccurs="unbounded"/> </xs:choice> </xs:sequence> <xs:attribute name="version" type="atom:versionType" use="required"/> <xs:attribute ref="xml:lang" use="optional"/> </xs:complexType> <xs:complexType name="authorType"> <xs:annotation> <xs:documentation><![CDATA[ Required children: name: Equivalent to dc:creator of feed or entry (depending on where author element is). MAY be name of corporation, if there are no individual authors or publisher does not wish to make their names available. See Authors on the other wiki. Optional children: url*: A URI. The URL of this author. email*: An email address, including plus signs and other allowable weird characters. The email address of this author. ]]></xs:documentation> </xs:annotation> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element name="name" type="xs:string"/> <xs:element name="url" type="xs:anyURI" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="email" type="atom:emailType" minOccurs="0" maxOccurs="unbounded"/> </xs:choice> </xs:sequence> </xs:complexType> <xs:complexType name="generatorType" > <xs:annotation> <xs:documentation><![CDATA[ Required children: link: A URI. URI of the toolkit that generated this feed. SHOULD be home page of toolkit/program/hosting provider, like http://www.movabletype.org/. MAY include version number, like: http://www.movabletype.org/?v=2.64. name: human-readable name of the toolkit that generated this feed, like "Movable Type". ]]></xs:documentation> </xs:annotation> <xs:simpleContent> <xs:extension base="xs:anyURI" > <xs:attribute name="name" type="xs:string"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="entryType"> <xs:annotation> <xs:documentation><![CDATA[ Required children: title: Eqivalent to dc:title. link: A URI. Permanent link to a representation of this entry. Is NOT defined as "link to an external resource described in the content of this entry". MUST be permanent. MUST be globally unique. MUST be clickable (not sure how to express this, perhaps "use an IANA-registered protocol and point to a resource that is viewable by ... uh, something) id: A URI. Subproperty of to dc:identifier. Permanent globally unique ID of this entry. MUST be permanent, MUST be globally unique. MAY be same as link. Current recommendations are under active discussion, same issues as feed/id. issued: W3DTF minus timezone requirement. Subproperty of dcterms:issued. SHOULD include timezone. SHOULD be expressed in publisherâs local timezone. MAY skip timezone (LiveJournal requirement). modified: W3DTF. Subproperty of dcterms:modified. SHOULD be UTC. Optional children: created W3DTF. Subproperty of dcterms:created. SHOULD be UTC. If not present, its value is presumed to be identical to modified. summary: Subproperty of dc:description. Short summary, blurb, or excerpt about this entry. MUST be plain text (i.e. no escaped HTML). Examples of use: lead on first page of news site. author: [defined above] contributor*: [defined below] content*: [defined below] ]]></xs:documentation> </xs:annotation> <xs:sequence> <xs:choice minOccurs="4" maxOccurs="unbounded"> <xs:element name="title" type="xs:string"/> <xs:element name="link" type="xs:anyURI"/> <xs:element name="id" type="xs:string"/> <xs:element name="issued" type="atom:iso8601dataTime"/> <xs:element name="modified" type="atom:iso8601dataTime"/> <xs:element name="created" type="atom:iso8601dataTime" minOccurs="0"/> <xs:element name="summary" type="xs:string" minOccurs="0"/> <xs:element name="author" type="atom:authorType" minOccurs="0"/> <xs:element name="contributor" type="atom:authorType" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="content" type="atom:contentType" minOccurs="0" maxOccurs="unbounded"/> </xs:choice> </xs:sequence> <xs:attribute ref="xml:lang" use="optional"/> </xs:complexType> <xs:complexType name="contentType" > <xs:annotation> <xs:documentation><![CDATA[ Required children: type: MIME type. Format of this content. And at most one mode of: xml: Inline XML. (Probably namespaced XHTML.) escaped: Consumers must unescape and treat as its type. base64: base64-encoded string. Consumers must decode and treat as its type. If content type is "multipart/alternative", then instead of any of the above, the content element MUST contain 1 or more content elements. These content elements MUST NOT specify type="multipart/alternative" (i.e. only one level of nesting is allowed). Consumers SHOULD look at all alternative content elements and determine which one is most suitable, based on which type and mode the consumer supports, and preferences specified by the end user (if any). Consumers SHOULD NOT render more than one content alternative. ]]></xs:documentation> <xs:documentation> I took this group and the next one from Tim Bray's Atom XSD. </xs:documentation> </xs:annotation> <xs:complexContent mixed="true"> <xs:restriction base="xs:string" > <xs:choice> <xs:element name="content" type="atom:contentType" minOccurs="0" maxOccurs="unbounded"/> <xs:sequence> <xs:any namespace="##any" processContents="lax" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </xs:choice> <xs:attribute name="type" use="required"/> <xs:attribute name="mode"> <xs:simpleType> <xs:restriction base="xs:token"> <xs:enumeration value="xml"/> <xs:enumeration value="escaped"/> <xs:enumeration value="base64"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute ref="xml:lang" use="optional"/> </xs:restriction > </xs:complexContent> </xs:complexType> <xs:simpleType name="iso8601dataTime"> <xs:union memberTypes="xs:dateTime xs:date"/> </xs:simpleType> <xs:simpleType name="versionType"> <xs:restriction base="xs:normalizedString"> <xs:pattern value="\d+\.\d+" /> </xs:restriction> </xs:simpleType> <xs:simpleType name="emailType"> <xs:restriction base="xs:normalizedString"> <xs:pattern value="\w+@(\w+\.)+\w+"/> </xs:restriction> </xs:simpleType> </xs:schema> --- NEW FILE: rsssource.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: rssitem.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: atom.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout /> --- NEW FILE: RssReader.cs --- using System; using System.Xml; using System.IO; using System.Collections; /// Version 1.0 namespace Sloppycode.net { #region Event datatype/delegate /// <summary> /// Holds details about any errors that occured /// during the loading or parsing of the RSS feed. /// </summary> public class RssReaderErrorEventArgs : EventArgs { /// <summary> /// The details of the error. /// </summary> public string Message { get { return this.message; } set { this.message = value; } } private string message; } /// <summary> /// Represents the method that will handle the RssReader error event. /// </summary> public delegate void RssReaderErrorEventHandler(object sender, RssReaderErrorEventArgs e); #endregion #region RssReader class /// <summary> /// The RssReader class provides a number of static methods for easy /// 1 or 2 step retrieval of RSS feeds. RSS feeds can be downloaded from any /// URL, and are then parsed into an <see cref="RssFeed">RssFeed</see> data type, /// which contains properties representing most aspects of an RSS Feed. A number /// of events are available for the calling application to register at the various /// stages of the feed request and parsing. /// <example> /// The following example retrieves the RSS news feed for the BBC news website, /// and creates a HTML document from the feed's details. It saves the HTML document /// to disk, and launches the default browser with the document. The number of items /// displayed is limited to 5. If there is any error, a messagebox is displayed with /// the details of the error. /// <code> /// RssFeed feed = RssReader.GetFeed("http://www.bbc.co.uk/syndication/feeds/news/ukfs_news/front_page/rss091.xml"); /// /// if ( feed.ErrorMessage == null || feed.ErrorMessage == "" ) /// { /// string template = "<a href=\"%Link%>%Title%</a><br/>%Description%<br/><br/><ul>%Items%</ul>"; /// string itemTemplate = "<li><a href=\"%Link%>%Title%</a><br/>%Description%</li>"; /// string html = RssReader.CreateHtml(feed,template,itemTemplate,"",5); /// /// StreamWriter streamWriter = File.CreateText("c:\\rss.html"); /// streamWriter.Write(html); /// streamWriter.Close(); /// /// System.Diagnostics.Process.Start("c:\\rss.html"); /// } /// else /// { /// MessageBox.Show("Error getting feed:\r\n" +feed.ErrorMessage,"Rss Demo App",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); /// } /// </code> /// </example> /// </summary> public class RssReader { // Events: XML document loaded, rss element found, // channel node found, item parsed, error /// <summary> /// This event is fired when the feed has finished loading from the URL /// provided, into the XML parser. /// </summary> public event EventHandler FeedLoaded; /// <summary> /// This event is fired when the root node (typically 'rss') has /// been found in the feed. /// </summary> public event EventHandler RssNodeFound; /// <summary> /// This event is fired when the channel/child node of the rss node /// (typically 'channel') has been found in the feed. /// </summary> public event EventHandler ChannelNodeFound; /// <summary> /// This event is fired when an item is added to the <see cref="RssFeed">RssFeed</see>'s /// collection of items. /// </summary> public event EventHandler ItemAdded; /// <summary> /// This event is fired when an error occurs in the loading or parsing /// of the feed. The same error message is also available in the ErrorMessage /// property of the <see cref="RssFeed">RssFeed</see> object that is returned /// by the <see cref="Retrieve">Retrieve</see> method. /// </summary> public event RssReaderErrorEventHandler Error; /// <summary> /// The node name for the channel element /// in the RSS feed. This will rarely ever to be /// changed. Default is 'channel'. /// </summary> public string RootNodeName { get { return this.rootNodeName; } set { this.rootNodeName = value; } } /// <summary> /// The node name for the root rss element /// in the RSS feed. This is altered automatically to 'rdf:RDF' /// when RdfMode is set to true. Default is 'rss'. /// </summary> public string ChannelNodeName { get { return this.channelNodeName; } set { this.channelNodeName = value; } } /// <summary> /// If this is set to true, then the XML document /// is parsed slightly different, to cater sites with RDF feeds (such as /// slashdot.org and register.com). The whole RDF format is not supported, /// but those items in RSS which have a corresponding RDF property, such /// as description,title for the channel, and title,description for each /// item, are matched. /// </summary> public bool RdfMode { get { return this.rdfMode; } set { if ( value ) { this.rootNodeName = "rdf:RDF"; } else { this.rootNodeName = "rss"; } this.rdfMode = value; } } /// <summary> /// Member for the public property. /// </summary> private string rootNodeName = "rss"; /// <summary> /// Member for the public property. /// </summary> private string channelNodeName = "channel"; /// <summary> /// Member for the public property. /// </summary> private bool rdfMode = false; /// <summary> /// Retrieves a <see cref="RssFeed">RssFeed</see> object using /// the url provided as the source of the Feed. /// </summary> /// <param name="Url">The url to retrieve the RSS feed from, this can /// be in the format of http:// and also file://.. (ftp?)</param> /// <param name="RdfFormat">If this is set to true, then the XML document /// is parsed slightly different, to cater sites with RDF feeds (such as /// slashdot.org and register.com). The whole RDF format is not supported, /// but those items in RSS which have a corresponding RDF property, such /// as description,title for the channel, and title,description for each /// item, are matched.</param> /// <returns>A <see cref="RssFeed">RssFeed</see> object from the /// RSS feed's details.</returns> public static RssFeed GetFeed(string Url,bool RdfFormat) { RssReader rssReader = new RssReader(); rssReader.RdfMode = RdfFormat; return rssReader.Retrieve(Url); } /// <summary> /// Retrieves a <see cref="RssFeed">RssFeed</see> object using /// the url provided as the source of the Feed. /// </summary> /// <param name="Url">The url to retrieve the RSS feed from, this can /// be in the format of http:// and also file://.. (ftp?)</param> /// <returns>A <see cref="RssFeed">RssFeed</see> object from the /// RSS feed's details.</returns> public static RssFeed GetFeed(string Url) { RssReader rssReader = new RssReader(); return rssReader.Retrieve(Url); } /// <summary> /// A simplified method of creating a HTML (or any document) from an /// RSS Feed. See <see cref="RssHtmlMaker">RssHtmlMaker</see> /// </summary> /// <param name="Feed">The <see cref="RssFeed">RssFeed</see> object to /// get the tokens' data from.</param> /// <param name="Template">The overall HTML template (or any other format) /// to replace the tokens in.</param> /// <param name="ItemPrefix">A string template that is prepended to the beginning /// of each RSS item.</param> /// <param name="ItemSuffix">A string template that is apppended to the end /// of each RSS item.</param> /// <returns>A string with the templates provided parsed of their tokens, with /// the data values in their place.</returns> public static string CreateHtml(RssFeed Feed,string Template,string ItemPrefix,string ItemSuffix) { return new RssHtmlMaker().GetHtmlContents(Feed,Template,ItemPrefix,ItemSuffix); } /// <summary> /// A simplified method of creating a HTML (or any document) from an /// RSS Feed. See <see cref="RssHtmlMaker">RssHtmlMaker</see> /// </summary> /// <param name="Feed">The <see cref="RssFeed">RssFeed</see> object to /// get the tokens' data from.</param> /// <param name="Template">The overall HTML template (or any other format) /// to replace the tokens in.</param> /// <param name="ItemPrefix">A string template that is prepended to the beginning /// of each RSS item.</param> /// <param name="ItemSuffix">A string template that is apppended to the end /// of each RSS item.</param> /// <param name="MaxItems">The maximum number of RSS items to display.</param> /// <returns>A string with the templates provided parsed of their tokens, with /// the data values in their place.</returns> public static string CreateHtml(RssFeed Feed,string Template,string ItemPrefix,string ItemSuffix,int MaxItems) { RssHtmlMaker rssHtmlMaker = new RssHtmlMaker(); rssHtmlMaker.MaxItems = MaxItems; return rssHtmlMaker.GetHtmlContents(Feed,Template,ItemPrefix,ItemSuffix); } /// <summary> /// Retrieves an RSS feed using the given Url, parses it and /// creates and new <see cref="RssFeed">RssFeed</see> object with the information. /// If an error occurs in the XML loading of the document, or parsing of /// the RSS feed, the error is trapped and stored inside the RssFeed's /// ErrorMessage property. /// </summary> /// <param name="Url">The url to retrieve the RSS feed from, this can /// be in the format of http:// and also file://.. (ftp?)</param> /// <returns>An <see cref="RssFeed">RssFeed</see> object with information /// retrieved from the feed.</returns> public RssFeed Retrieve(string Url) { RssFeed rssFeed = new RssFeed(); rssFeed.Items = new RssItems(); XmlTextReader xmlTextReader = new XmlTextReader(Url); XmlValidatingReader xmlValidatingReader = new XmlValidatingReader(xmlTextReader); xmlValidatingReader.ValidationType = ValidationType.None; XmlDocument xmlDoc= new XmlDocument(); try { xmlDoc.Load(xmlTextReader); // Fire the load event if ( this.FeedLoaded != null ) { this.FeedLoaded(this, new EventArgs()); } XmlNode rssXmlNode = null; // Loop child nodes till we find the rss one for (int i=0;i < xmlDoc.ChildNodes.Count;i++) { System.Diagnostics.Debug.Write("Child: " +xmlDoc.ChildNodes[i].Name); System.Diagnostics.Debug.WriteLine(" has " +xmlDoc.ChildNodes[i].ChildNodes.Count+" children"); if ( xmlDoc.ChildNodes[i].Name == this.rootNodeName && xmlDoc.ChildNodes[i].ChildNodes.Count > 0 ) { rssXmlNode = xmlDoc.ChildNodes[i]; // Fire the found event if ( this.RssNodeFound != null ) { this.RssNodeFound(this,new EventArgs()); } break; } } if ( rssXmlNode != null ) { XmlNode channelXmlNode = null; // Loop through the rss node till we find the channel for (int i=0;i < rssXmlNode.ChildNodes.Count;i++) { System.Diagnostics.Debug.WriteLine("Rss child: "+rssXmlNode.ChildNodes[i].Name); if ( rssXmlNode.ChildNodes[i].Name == this.channelNodeName && rssXmlNode.ChildNodes[i].ChildNodes.Count > 0 ) { channelXmlNode = rssXmlNode.ChildNodes[i]; // Fire the found event if ( this.ChannelNodeFound != null ) { this.ChannelNodeFound(this,new EventArgs()); } break; } } // Found the channel node if ( channelXmlNode != null ) { // Loop through its children, copying details to the // RssFeed struct, and parsing the items for (int i=0;i < channelXmlNode.ChildNodes.Count;i++) { System.Diagnostics.Debug.WriteLine(channelXmlNode.ChildNodes[i].Name); switch ( channelXmlNode.ChildNodes[i].Name ) { case "title": { rssFeed.Title = channelXmlNode.ChildNodes[i].InnerText; break; } case "description": { rssFeed.Description = channelXmlNode.ChildNodes[i].InnerText; break; } case "language": { rssFeed.Language = channelXmlNode.ChildNodes[i].InnerText; break; } case "copyright": { rssFeed.Copyright = channelXmlNode.ChildNodes[i].InnerText; break; } case "webmaster": { rssFeed.Webmaster = channelXmlNode.ChildNodes[i].InnerText; break; } case "pubDate": { rssFeed.PubDate = channelXmlNode.ChildNodes[i].InnerText; break; } case "lastBuildDate": { rssFeed.LastBuildDate = channelXmlNode.ChildNodes[i].InnerText; break; } case "category": { rssFeed.Category = channelXmlNode.ChildNodes[i].InnerText; break; } case "generator": { rssFeed.Generator = channelXmlNode.ChildNodes[i].InnerText; break; } case "ttl": { rssFeed.Ttl = channelXmlNode.ChildNodes[i].InnerText; break; } case "rating": { rssFeed.Rating = channelXmlNode.ChildNodes[i].InnerText; break; } case "skipHours": { rssFeed.Skiphours = channelXmlNode.ChildNodes[i].InnerText; break; } case "skipDays": { rssFeed.Skipdays = channelXmlNode.ChildNodes[i].InnerText; break; } case "managingEditor": { rssFeed.ManagingEditor = channelXmlNode.ChildNodes[i].InnerText; break; } case "item": { rssFeed.Items.Add( this.getRssItem(channelXmlNode.ChildNodes[i]) ); // Fire the found event if ( this.ItemAdded != null ) { this.ItemAdded(this,new EventArgs()); } break; } } } // If rdf mode is set, then the channel node only contains // information about the channel, it doesn't hold the item // nodes. The item nodes are children of the root node in // an RDF document, so we use this instead. if ( this.RdfMode ) { for (int i=0;i < rssXmlNode.ChildNodes.Count;i++) { switch ( rssXmlNode.ChildNodes[i].Name ) { case "item": { rssFeed.Items.Add( this.getRssItem(rssXmlNode.ChildNodes[i]) ); // Fire the found event if ( this.ItemAdded != null ) { this.ItemAdded(this,new EventArgs()); } break; } } } } } else { rssFeed.ErrorMessage = "Unable to find rss <seehannel> node"; // Fire the error event if ( this.Error != null ) { RssReaderErrorEventArgs args = new RssReaderErrorEventArgs(); args.Message = rssFeed.ErrorMessage; this.Error(this,args); } } } else { rssFeed.ErrorMessage = "Unable to find root <rss> node"; // Fire the error event if ( this.Error != null ) { RssReaderErrorEventArgs args = new RssReaderErrorEventArgs(); args.Message = rssFeed.ErrorMessage; this.Error(this,args); } } } catch (XmlException err) { // rssFeed.ErrorMessage = "Xml error: " +err.Message; // Fire the error event if ( this.Error != null ) { RssReaderErrorEventArgs args = new RssReaderErrorEventArgs(); args.Message = rssFeed.ErrorMessage; this.Error(this,args); } return rssFeed; } return rssFeed; } /// <summary> /// Creates an RSS item from an XML node with the /// corresponding child nodes (title,description etc.) /// </summary> /// <param name="xmlNode">The node to extract the details from</param> /// <returns>An RssItem object with details taken from the item node.</returns> private RssItem getRssItem(XmlNode xmlNode) { RssItem rssItem = new RssItem(); for (int i=0;i < xmlNode.ChildNodes.Count;i++) { switch ( xmlNode.ChildNodes[i].Name ) { case "title": { rssItem.Title = xmlNode.ChildNodes[i].InnerText; break; } case "description": { rssItem.Description = xmlNode.ChildNodes[i].InnerText; break; } case "link": { rssItem.Link = xmlNode.ChildNodes[i].InnerText; break; } case "author": { rssItem.Author = xmlNode.ChildNodes[i].InnerText; break; } case "comments": { rssItem.Comments = xmlNode.ChildNodes[i].InnerText; break; } case "pubdate": { rssItem.Pubdate = xmlNode.ChildNodes[i].InnerText; break; } case "guid": { rssItem.Guid = xmlNode.ChildNodes[i].InnerText; break; } } } return rssItem; } } #endregion #region Html creator class /// <summary> /// This class provides an easy method of converting a <see cref="RssFeed">RssFeed</see> /// object into a simple HTML document. This document can then be written to /// file, where it can be stored in a cached state (saving a feed request each /// time the feed is required). /// </summary> public class RssHtmlMaker { /// <summary> /// Restricts the number of items that are displayed and replaced /// using the %Items% token in the HTML template. /// </summary> public int MaxItems { get { return this.maxItems; } set { this.maxItems = value; } } /// <summary> /// Member for the public property. /// </summary> private int maxItems = 0; /// <summary> /// Creates a HTML document, or any format - this is only limited by /// the template you provide - from the provided /// <see cref="RssFeed">RssFeed</see> object. The tokens described in the /// remarks section are replaced with their values inside the template. /// The items in the RSS feed are replaced using the ItemPrefix and ItemSuffix /// templates, where the suffix is placed face, and the suffix is appended on the end. /// </summary> /// <remarks> /// The following are a list of tokens which are replaced inside the main Template, /// with their corresponding values from the provided <see cref="RssFeed">RssFeed</see> /// object. For details on each token, see its corresponding property in the /// <see cref="RssFeed">RssFeed</see> object. /// <list type="bullet"> /// <item>%Title%</item> /// <item>%Description%</item> /// <item>%Link%</item> /// <item>%Language%</item> /// <item>%Copyright%</item> /// <item>%Webmaster%</item> /// <item>%PubDate%</item> /// <item>%LastBuildDate%</item> /// <item>%Category%</item> /// <item>%Generator%</item> /// <item>%Ttl%</item> /// <item>%Rating%</item> /// <item>%Skiphours%</item> /// <item>%Skipdays%</item> /// <item>%Skipdays%</item> /// <item>%Items% - This is replaced by the parsed template of the items</item> /// </list> /// The following are a list of tokens which are replaced inside the ItemPrefix /// and ItemSuffix templates, with their corresponding values from the /// provided <see cref="RssItem">RssItem</see> object. For details /// on each token, see its corresponding property in /// the <see cref="RssItem">RssItem</see> object. /// <list type="bullet"> /// <item>%Title%</item> /// <item>%Description%</item> /// <item>%Link%</item> /// <item>%Author%</item> /// <item>%Comments%</item> /// <item>%Pubdate%</item> /// <item>%Guid%</item> /// </list> /// </remarks> /// <param name="Feed">The <see cref="RssFeed">RssFeed</see> object to /// get the tokens' data from.</param> /// <param name="Template">The overall HTML template (or any other format) /// to replace the tokens in.</param> /// <param name="ItemPrefix">A string template that is prepended to the beginning /// of each RSS item.</param> /// <param name="ItemSuffix">A string template that is apppended to the end /// of each RSS item.</param> /// <returns>A string with the templates provided parsed of their tokens, with /// the data values in their place.</returns> public string GetHtmlContents(RssFeed Feed,string Template,string ItemPrefix,string ItemSuffix) { string result = Template; // Replace all template tokens result = result.Replace("%Title%",Feed.Title); result = result.Replace("%Description%",Feed.Description); result = result.Replace("%Link%",Feed.Link); result = result.Replace("%Language%",Feed.Language); result = result.Replace("%Copyright%",Feed.Copyright); result = result.Replace("%Webmaster%",Feed.Webmaster); result = result.Replace("%PubDate%",Feed.PubDate); result = result.Replace("%LastBuildDate%",Feed.LastBuildDate); result = result.Replace("%Category%",Feed.Category); result = result.Replace("%Generator%",Feed.Generator); result = result.Replace("%Ttl%",Feed.Ttl); result = result.Replace("%Rating%",Feed.Rating); result = result.Replace("%Skiphours%",Feed.Skiphours); result = result.Replace("%Skipdays%",Feed.Skipdays); result = result.Replace("%Skipdays%",Feed.ManagingEditor); // Parse item template string itemsContent = ""; string tempContent = ""; if ( maxItems == 0 || maxItems > Feed.Items.Count ) { maxItems = Feed.Items.Count; } for (int i=0;i < maxItems;i++) { // Parse prefix template tempContent = ItemPrefix; tempContent = tempContent.Replace("%Title%",Feed.Items[i].Title); tempContent = tempContent.Replace("%Description%",Feed.Items[i].Description); tempContent = tempContent.Replace("%Link%",Feed.Items[i].Link); tempContent = tempContent.Replace("%Author%",Feed.Items[i].Author); tempContent = tempContent.Replace("%Comments%",Feed.Items[i].Comments); tempContent = tempContent.Replace("%Pubdate%",Feed.Items[i].Pubdate); tempContent = tempContent.Replace("%Guid%",Feed.Items[i].Guid); itemsContent += tempContent; // Parse suffix template tempContent = ItemSuffix; tempContent = tempContent.Replace("%Title%",Feed.Items[i].Title); tempContent = tempContent.Replace("%Description%",Feed.Items[i].Description); tempContent = tempContent.Replace("%Link%",Feed.Items[i].Link); tempContent = tempContent.Replace("%Author%",Feed.Items[i].Author); tempContent = tempContent.Replace("%Comments%",Feed.Items[i].Comments); tempContent = tempContent.Replace("%Pubdate%",Feed.Items[i].Pubdate); tempContent = tempContent.Replace("%Guid%",Feed.Items[i].Guid); itemsContent += tempContent; } // Replace %items% with items result = result.Replace("%Items%",itemsContent); return result; } } #endregion #region Data structures /// <summary> /// A data type to represent all properties of single RSS feed. /// (one XML document). The descriptions for /// the properties of RssItem are para-phrased from the /// <see href="http://blogs.law.harvard.edu/tech/rss">RSS 2 specification</see>. /// See <see cref="RssReader">RssReader</see> for properties which /// have not yet been implemented in this version of the /// the RssReader class. /// </summary> /// <remarks> /// The following elements of the RSS <channel> node aren't /// supported by this version of RssReader: /// <list type="bullet"> /// <item>image (has subelements: image,url,title,link)</item> /// <item>cloud (has attributes: domain,port,path,registerProcedure,protocol)</item> /// <item>textInput (has subelements: title,description,name,link)</item> /// </list> /// </remarks> [Serializable()] public struct RssFeed { /// <summary> /// The name of the channel. /// </summary> public string Title; /// <summary> /// Phrase or sentence describing the channel. /// </summary> public string Description; /// <summary> /// The URL to the HTML website corresponding to the channel. /// </summary> public string Link; // Optional items /// <summary> /// The language the channel is written in. This allows /// aggregators to group all Italian language sites, for example, on a single page. /// </summary> public string Language; /// <summary> /// Copyright notice for content in the channel. /// </summary> public string Copyright; /// <summary> /// Email address for person responsible for technical issues relating to channel. /// </summary> public string Webmaster; /// <summary> /// The publication date for the content in the channel. /// </summary> public string PubDate; /// <summary> /// The last time the content of the channel changed. /// </summary> public string LastBuildDate; /// <summary> /// Specify one or more categories that the channel belongs to. /// </summary> public string Category; /// <summary> /// A string indicating the program used to generate the channel. /// </summary> public string Generator; /// <summary> /// ttl stands for time to live. It's a number of minutes /// that indicates how long a channel can be cached before /// refreshing from the source /// </summary> public string Ttl; /// <summary> /// The <see href="http://www.w3.org/PICS/">PICS</see> rating for the channel. /// </summary> public string Rating; /// <summary> /// A hint for aggregators telling them which hours they can skip. /// </summary> public string Skiphours; /// <summary> /// A hint for aggregators telling them which days they can skip. /// </summary> public string Skipdays; /// <summary> /// Email address for person responsible for editorial content. /// </summary> public string ManagingEditor; /// <summary> /// A collection of RssItem datatypes, representing each /// item for the RSS feed. /// </summary> public RssItems Items; /// <summary> /// Contains any errors that occured during the loading or /// parsing of the XML document. Compare this to a blank string /// to see if any errors occured. /// </summary> public string ErrorMessage; } /// <summary> /// A data type to represent a single /// RSS item in a RSS feed. See <see cref="RssReader">RssReader</see> for /// properties of a RSS item which have not yet been implemented /// in this version of the the RssReader class. The descriptions for /// the properties of RssItem are para-phrased from the /// <see href="http://blogs.law.harvard.edu/tech/rss">RSS 2 specification.</see> /// </summary> /// <remarks> /// The following elements of a RSS item aren't /// supported by this version of RssReader: /// <list type="bullet"> /// <item>category (can have domain attribute)</item> /// <item>enclosure ( has attributes: url,length,type )</item> /// <item>source (has attributes: url)</item> /// </list> /// </remarks> [Serializable()] public struct RssItem { /// <summary> /// The title of the item. /// </summary> public string Title; /// <summary> /// The item synopsis. /// </summary> public string Description; /// <summary> /// The URL of the item. /// </summary> public string Link; /// <summary> /// Email address of the author of the item. /// </summary> public string Author; /// <summary> /// URL of a page for comments relating to the item /// </summary> public string Comments; /// <summary> /// Indicates when the item was published. /// </summary> public string Pubdate; /// <summary> /// A string that uniquely identifies the item. /// </summary> public string Guid; } /// <summary> /// Represents a collection of RSS items for /// the RSS feed. /// </summary> [Serializable()] public class RssItems : CollectionBase { public RssItem this[int item] { get { return this.getItem(item); } } public void Add(RssItem rssItem) { List.Add(rssItem); } public bool Remove(int index) { if (index > Count - 1 || index < 0) { return false; } else { List.RemoveAt(index); return true; } } private RssItem getItem(int Index) { return (RssItem) List[Index]; } } #endregion } --- NEW FILE: opmlhead.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: opmlbody.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: rsstextinput.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: opml.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout layoutVersion="2" viewPortLeft="-683" viewPortTop="0" zoom="100"> <body_XmlElement left="317" top="254" width="5292" height="2963" selected="0" zOrder="1" index="0" expanded="1"> <ref_x003D_outline_XmlElement left="317" top="3725" width="5292" height="2963" selected="0" zOrder="2" index="0" expanded="0" /> </body_XmlElement> <data_XmlElement left="6243" top="254" width="5292" height="847" selected="0" zOrder="5" index="1" expanded="1" /> <head_XmlElement left="12169" top="254" width="5292" height="2963" selected="0" zOrder="7" index="2" expanded="1"> <ref_x003D_metadata_XmlElement left="12169" top="3725" width="5292" height="2963" selected="0" zOrder="9" index="0" expanded="0" /> </head_XmlElement> <item_XmlElement left="18095" top="254" width="5292" height="2963" selected="0" zOrder="12" index="3" expanded="1" /> <metadata_XmlElement left="24021" top="254" width="5292" height="2963" selected="0" zOrder="14" index="4" expanded="1" /> <oml_XmlElement left="32910" top="254" width="5292" height="2963" selected="0" zOrder="15" index="5" expanded="1"> <ref_x003D_head_XmlElement left="29947" top="3725" width="5292" height="2963" selected="0" zOrder="16" index="0" expanded="0" /> <ref_x003D_body_XmlElement left="35873" top="3725" width="5292" height="2963" selected="0" zOrder="18" index="1" expanded="0" /> </oml_XmlElement> <outline_XmlElement left="44762" top="254" width="5292" height="2963" selected="0" zOrder="20" index="6" expanded="1"> <ref_x003D_item_XmlElement left="38836" top="3725" width="5292" height="2963" selected="0" zOrder="21" index="1" expanded="0" /> <ref_x003D_outline_XmlElement left="47725" top="3725" width="5292" height="2963" selected="0" zOrder="23" index="2" expanded="1"> <ref_x003D_item_XmlElement left="44762" top="7196" width="5292" height="2963" selected="0" zOrder="31" index="1" expanded="0" /> <ref_x003D_outline_XmlElement left="50688" top="7196" width="5292" height="2963" selected="0" zOrder="34" index="2" expanded="0" /> </ref_x003D_outline_XmlElement> </outline_XmlElement> </XSDDesignerLayout> --- NEW FILE: opml.xsd --- <?xml version="1.0" encoding="utf-8" ?> <xs:schema id="opml" targetNamespace="http://tempuri.org/opml.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/opml.xsd" xmlns:mstns="http://tempuri.org/opml.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"> </xs:schema> --- NEW FILE: rssguid.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: opmloutline.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: RssCacheManager.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: rssimage.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: rss.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout layoutVersion="2" viewPortLeft="0" viewPortTop="0" zoom="100"> <rss_XmlElement left="317" top="254" width="5292" height="2963" selected="0" zOrder="0" index="0" expanded="1"> <channel_XmlElement left="317" top="3725" width="5292" height="2963" selected="0" zOrder="54" index="0" expanded="1"> <_x0028_group1_x0029__XmlChoice left="-2646" top="7196" width="5292" height="2963" selected="0" zOrder="57" index="0" expanded="0" /> <item_XmlElement left="3280" top="7196" width="5292" height="2963" selected="0" zOrder="60" index="1" expanded="0" /> </channel_XmlElement> </rss_XmlElement> <tRss_XmlComplexType left="6243" top="254" width="5292" height="2963" selected="0" zOrder="1" index="1" expanded="1"> <channel_XmlElement left="6243" top="3725" width="5292" height="2963" selected="0" zOrder="3" index="0" expanded="0" /> </tRss_XmlComplexType> <tRssItem_XmlComplexType left="21058" top="254" width="5292" height="2963" selected="0" zOrder="6" index="2" expanded="1"> <_x0028_group1_x0029__XmlChoice left="21058" top="3725" width="5292" height="2963" selected="0" zOrder="7" index="0" expanded="1"> <category_XmlElement left="12169" top="7196" width="5292" height="2963" selected="0" zOrder="9" index="4" expanded="0" /> <enclosure_XmlElement left="18095" top="7196" width="5292" height="2963" selected="0" zOrder="12" index="6" expanded="0" /> <guid_XmlElement left="24021" top="7196" width="5292" height="2963" selected="0" zOrder="17" index="7" expanded="0" /> <source_XmlElement left="29947" top="7196" width="5292" height="2963" selected="0" zOrder="19" index="9" expanded="0" /> </_x0028_group1_x0029__XmlChoice> </tRssItem_XmlComplexType> <tRssChannel_XmlComplexType left="53651" top="254" width="5292" height="2963" selected="0" zOrder="21" index="3" expanded="1"> <_x0028_group1_x0029__XmlChoice left="50688" top="3725" width="5292" height="2963" selected="0" zOrder="22" index="0" expanded="1"> <category_XmlElement left="35873" top="7196" width="5292" height="2963" selected="0" zOrder="24" index="9" expanded="0" /> <cloud_XmlElement left="41799" top="7196" width="5292" height="2963" selected="0" zOrder="26" index="12" expanded="0" /> <image_XmlElement left="47725" top="7196" width="5292" height="2963" selected="0" zOrder="28" index="14" expanded="0" /> <textInput_XmlElement left="53651" top="7196" width="5292" height="2963" selected="0" zOrder="30" index="15" expanded="0" /> <skipHours_XmlElement left="59577" top="7196" width="5292" height="2963" selected="0" zOrder="32" index="16" expanded="0" /> <skipDays_XmlElement left="65503" top="7196" width="5292" height="2963" selected="0" zOrder="34" index="17" expanded="0" /> </_x0028_group1_x0029__XmlChoice> <item_XmlElement left="71429" top="3725" width="5292" height="2963" selected="0" zOrder="36" index="1" expanded="0" /> </tRssChannel_XmlComplexType> <tSkipHour_XmlSimpleType left="77355" top="254" width="5292" height="2963" selected="0" zOrder="38" index="4" expanded="1" /> <tSkipHoursList_XmlComplexType left="83281" top="254" width="5292" height="2963" selected="0" zOrder="39" index="5" expanded="1" /> <tSkipDay_XmlSimpleType left="89207" top="254" width="5292" height="2963" selected="0" zOrder="40" index="6" expanded="1" /> <tSkipDaysList_XmlComplexType left="95133" top="254" width="5292" height="2963" selected="0" zOrder="41" index="7" expanded="1" /> <tCategory_XmlComplexType left="101059" top="254" width="5292" height="2963" selected="0" zOrder="42" index="8" expanded="1" /> <tImage_XmlComplexType left="106985" top="254" width="5292" height="2963" selected="0" zOrder="43" index="9" expanded="1" /> <tImageHeight_XmlSimpleType left="112911" top="254" width="5292" height="2963" selected="0" zOrder="44" index="10" expanded="1" /> <tImageWidth_XmlSimpleType left="118837" top="254" width="5292" height="2963" selected="0" zOrder="45" index="11" expanded="1" /> <tCloud_XmlComplexType left="124763" top="254" width="5292" height="2963" selected="0" zOrder="46" index="12" expanded="1" /> <tCloudProtocol_XmlSimpleType left="130689" top="254" width="5292" height="2963" selected="0" zOrder="47" index="13" expanded="1" /> <tTextInput_XmlComplexType left="136615" top="254" width="5292" height="2963" selected="0" zOrder="48" index="14" expanded="1" /> <tEmailAddress_XmlSimpleType left="142541" top="254" width="5292" height="2963" selected="0" zOrder="49" index="15" expanded="1" /> <tRfc822FormatDate_XmlSimpleType left="148467" top="254" width="5292" height="2963" selected="0" zOrder="50" index="16" expanded="1" /> <tSource_XmlComplexType left="154393" top="254" width="5292" height="2963" selected="0" zOrder="51" index="17" expanded="1" /> <tEnclosure_XmlComplexType left="160319" top="254" width="5292" height="2963" selected="0" zOrder="52" index="18" expanded="1" /> <tGuid_XmlComplexType left="166245" top="254" width="5292" height="2963" selected="0" zOrder="53" index="19" expanded="1" /> </XSDDesignerLayout> --- NEW FILE: rss.xsd --- <?xml version="1.0" encoding="UTF-8" ?> <!-- XML Schema for RSS v2.0 Copyright (C) 2003 Jorgen Thelin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified" version="2.0.1.10"> <xs:annotation> <xs:documentation>XML Schema for RSS v2.0 feed files.</xs:documentation> <xs:documentation>Revision: 10</xs:documentation> <xs:documentation>Date: 23-June-2003</xs:documentation> <xs:documentation>Based on the RSS 2.0 specification document at http://feeds.archive.org/validator/docs/rss2.html</xs:documentation> <xs:documentation>Author: Jorgen Thelin</xs:documentation> <xs:documentation>Feedback to: http://www.thearchitect.co.uk/weblog/archives/2003/03/000118.html</xs:documentation> </xs:annotation> <xs:element name="rss" type="tRss" /> <xs:complexType name="tRss"> <xs:sequence> <xs:element name="channel" type="tRssChannel" /> <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="version" type="xs:decimal" use="required" fixed="2.0" /> <xs:anyAttribute namespace="##any" /> </xs:complexType> <xs:complexType name="tRssItem"> <xs:annotation> <xs:documentation>An item may represent a "story" -- much like a story in a newspaper or magazine; if so its description is a synopsis of the story, and the link points to the full story. An item may also be complete in itself, if so, the description contains the text (entity-encoded HTML is allowed), and the link and title may be omitted.</xs:documentation> </xs:annotation> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element name="title" type="xs:string" minOccurs="0"> <xs:annotation> <xs:documentation>The title of the item.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="description" type="xs:string" minOccurs="0"> <xs:annotation> <xs:documentation>The item synopsis.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="link" type="xs:anyURI" minOccurs="0"> <xs:annotation> <xs:documentation>The URL of the item.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="author" type="tEmailAddress" minOccurs="0"> <xs:annotation> <xs:documentation>Email address of the author of the item.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="category" type="tCategory" minOccurs="0"> <xs:annotation> <xs:documentation>Includes the item in one or more categories. </xs:documentation> </xs:annotation> </xs:element> <xs:element name="comments" type="xs:anyURI" minOccurs="0"> <xs:annotation> <xs:documentation>URL of a page for comments relating to the item.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="enclosure" type="tEnclosure" minOccurs="0"> <xs:annotation> <xs:documentation>Describes a media object that is attached to the item.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="guid" type="tGuid" minOccurs="0"> <xs:annotation> <xs:documentation>guid or permalink URL for this entry</xs:documentation> </xs:annotation> </xs:element> <xs:element name="pubDate" type="tRfc822FormatDate" minOccurs="0"> <xs:annotation> <xs:documentation>Indicates when the item was published.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="source" type="tSource" minOccurs="0"> <xs:annotation> <xs:documentation>The RSS channel that the item came from.</xs:documentation> </xs:annotation> </xs:element> <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation>Extensibility element.</xs:documentation> </xs:annotation> </xs:any> </xs:choice> </xs:sequence> <xs:anyAttribute namespace="##any" /> </xs:complexType> <xs:complexType name="tRssChannel"> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element name="title" type="xs:string"> <xs:annotation> <xs:documentation>The name of the channel. It's how people refer to your service. If you have an HTML website that contains the same information as your RSS file, the title of your channel should be the same as the title of your website.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="link" type="xs:anyURI"> <xs:annotation> <xs:documentation>The URL to the HTML website corresponding to the channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="description" type="xs:string"> <xs:annotation> <xs:documentation>Phrase or sentence describing the channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="language" type="xs:language" minOccurs="0"> <xs:annotation> <xs:documentation>The language the channel is written in. This allows aggregators to group all Italian language sites, for example, on a single page. A list of allowable values for this element, as provided by Netscape, is here. You may also use values defined by the W3C.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="copyright" type="xs:string" minOccurs="0"> <xs:annotation> <xs:documentation>Copyright notice for content in the channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="managingEditor" type="tEmailAddress" minOccurs="0"> <xs:annotation> <xs:documentation>Email address for person responsible for editorial content.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="webMaster" type="tEmailAddress" minOccurs="0"> <xs:annotation> <xs:documentation>Email address for person responsible for technical issues relating to channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="pubDate" type="tRfc822FormatDate" minOccurs="0"> <xs:annotation> <xs:documentation>The publication date for the content in the channel. All date-times in RSS conform to the Date and Time Specification of RFC 822, with the exception that the year may be expressed with two characters or four characters (four preferred).</xs:documentation> </xs:annotation> </xs:element> <xs:element name="lastBuildDate" type="tRfc822FormatDate" minOccurs="0"> <xs:annotation> <xs:documentation>The last time the content of the channel changed.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="category" type="tCategory" minOccurs="0"> <xs:annotation> <xs:documentation>Specify one or more categories that the channel belongs to.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="generator" type="xs:string" minOccurs="0"> <xs:annotation> <xs:documentation>A string indicating the program used to generate the channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="docs" type="xs:anyURI" minOccurs="0"> <xs:annotation> <xs:documentation>A URL that points to the documentation for the format used in the RSS file. It's probably a pointer to this page. It's for people who might stumble across an RSS file on a Web server 25 years from now and wonder what it is.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="cloud" type="tCloud" minOccurs="0"> <xs:annotation> <xs:documentation>Allows processes to register with a cloud to be notified of updates to the channel, implementing a lightweight publish-subscribe protocol for RSS feeds.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="ttl" type="xs:nonNegativeInteger" minOccurs="0"> <xs:annotation> <xs:documentation>ttl stands for time to live. It's a number of minutes that indicates how long a channel can be cached before refreshing from the source.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="image" type="tImage" minOccurs="0"> <xs:annotation> <xs:documentation>Specifies a GIF, JPEG or PNG image that can be displayed with the channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="textInput" type="tTextInput" minOccurs="0"> <xs:annotation> <xs:documentation>Specifies a text input box that can be displayed with the channel.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="skipHours" type="tSkipHoursList" minOccurs="0"> <xs:annotation> <xs:documentation>A hint for aggregators telling them which hours they can skip.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="skipDays" type="tSkipDaysList" minOccurs="0"> <xs:annotation> <xs:documentation>A hint for aggregators telling them which days they can skip.</xs:documentation> </xs:annotation> </xs:element> <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation>Extensibility element.</xs:documentation> </xs:annotation> </xs:any> </xs:choice> <xs:element name="item" type="tRssItem" maxOccurs="unbounded" /> <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation>Extensibility element.</xs:documentation> </xs:annotation> </xs:any> </xs:sequence> <xs:anyAttribute namespace="##any" /> </xs:complexType> <xs:simpleType name="tSkipHour"> <xs:annotation> <xs:documentation>A time in GMT when aggregators should not request the channel data. The hour beginning at midnight is hour zero.</xs:documentation> </xs:annotation> <xs:restriction base="xs:nonNegativeInteger"> <xs:minInclusive value="0" /> <xs:maxInclusive value="23" /> </xs:restriction> </xs:simpleType> <xs:complexType name="tSkipHoursList"> <xs:sequence> <xs:element name="hour" type="tSkipHour" minOccurs="0" maxOccurs="24" /> </xs:sequence> </xs:complexType> <xs:simpleType name="tSkipDay"> <xs:annotation> <xs:documentation>A day when aggregators should not request the channel data.</xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:enumeration value="Monday" /> <xs:enumeration value="Tuesday" /> <xs:enumeration value="Wednesday" /> <xs:enumeration value="Thursday" /> <xs:enumeration value="Friday" /> <xs:enumer... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:12
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Web.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Web.Tests Added Files: Adapdev.Web.Tests.csproj Log Message: --- NEW FILE: Adapdev.Web.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{5174127E-DD36-4C32-AB42-9ADD34260BB2}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Web.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Web.Tests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "Adapdev.Web" Project = "{49455A1D-1BBB-4356-AB83-E5690726C681}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
From: Sean M. <int...@us...> - 2005-11-16 07:02:12
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Windows.Forms.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Windows.Forms.Tests Added Files: Adapdev.Windows.Forms.Tests.csproj SmartTreeViewTest.cs Log Message: --- NEW FILE: Adapdev.Windows.Forms.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{D51D807A-D70C-445A-B1D9-062D61463AB7}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Windows.Forms.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Windows.Forms.Tests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "Adapdev.Windows.Forms" Project = "{0BE602B6-D67E-414E-B852-A2AC61305E8E}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "System.Windows.Forms" AssemblyName = "System.Windows.Forms" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Windows.Forms.dll" /> <Reference Name = "System.Drawing" AssemblyName = "System.Drawing" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Drawing.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SmartTreeViewTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: SmartTreeViewTest.cs --- using System; using System.Windows.Forms; using NUnit.Framework; using Adapdev.Windows.Forms; namespace Adapdev.Windows.Forms.Tests { using System.Drawing; /// <summary> /// Summary description for SmartTreeViewTest. /// </summary> /// [TestFixture] public class SmartTreeViewTest { SmartTreeView tree = null; [SetUp] public void BuildTree() { tree = new SmartTreeView(); TreeNode root = new TreeNode("Root"); tree.Nodes.Add(root); TreeNode node1 = new TreeNode("Node1"); TreeNode child1 = new TreeNode("Child1"); TreeNode child2 = new TreeNode("Child2"); node1.Nodes.Add(child1); node1.Nodes.Add(child2); TreeNode node2 = new TreeNode("Node2"); TreeNode child3 = new TreeNode("Child3"); TreeNode child4 = new TreeNode("Child4"); node2.Nodes.Add(child3); node2.Nodes.Add(child4); root.Nodes.Add(node1); root.Nodes.Add(node2); /* * Structure: * Root * Node1 * Child1 * Child2 * Node2 * Child3 * Child4 **/ } [Test] public void CheckParents() { // Make sure all nodes are at the proper state Assert.IsTrue(this.GetChild1().Checked == false, "Child1 should not be checked."); Assert.IsTrue(this.GetNode1().Checked == false, "Node1 should not be checked."); Assert.IsTrue(this.GetRoot().Checked == false, "Root should not be checked."); // Check the child, which should check all parents this.GetChild1().Checked = true; Assert.IsTrue(this.GetNode1().Checked, "Node1 should be checked."); Assert.IsTrue(this.GetRoot().Checked, "Root should be checked."); // Uncheck the child...parents should remain checked this.GetChild1().Checked = false; Assert.IsTrue(this.GetNode1().Checked, "Node1 should be checked."); Assert.IsTrue(this.GetRoot().Checked, "Root should be checked."); } [Test] public void CheckChildren() { // Make sure all nodes are at the proper state Assert.IsTrue(this.GetChild1().Checked == false, "Child1 should not be checked."); Assert.IsTrue(this.GetNode1().Checked == false, "Node1 should not be checked."); Assert.IsTrue(this.GetRoot().Checked == false, "Root should not be checked."); // Check the root node this.GetRoot().Checked = true; // All child nodes should be checked Assert.IsTrue(this.GetRoot().Checked, "Root should be checked."); Assert.IsTrue(this.GetNode1().Checked, "Node1 should be checked."); Assert.IsTrue(this.GetNode2().Checked, "Node2 should be checked."); Assert.IsTrue(this.GetChild1().Checked, "Child1 should be checked."); Assert.IsTrue(this.GetChild2().Checked, "Child2 should be checked."); Assert.IsTrue(this.GetChild3().Checked, "Child3 should be checked."); Assert.IsTrue(this.GetChild4().Checked, "Child4 should be checked."); // Uncheck the root node this.GetRoot().Checked = false; // All child nodes should be unchecked Assert.IsFalse(this.GetRoot().Checked, "Root should not be checked."); Assert.IsFalse(this.GetNode1().Checked, "Node1 should not be checked."); Assert.IsFalse(this.GetNode2().Checked, "Node2 should not be checked."); Assert.IsFalse(this.GetChild1().Checked, "Child1 should not be checked."); Assert.IsFalse(this.GetChild2().Checked, "Child2 should not be checked."); Assert.IsFalse(this.GetChild3().Checked, "Child3 should not be checked."); Assert.IsFalse(this.GetChild4().Checked, "Child4 should not be checked."); } [Test] public void CheckColor() { // IMPORTANT - need to set the root node checked value // Test fails otherwise, since the Color comes up // as Color.Empty this.GetRoot().Checked = false; // Node1 should be unchecked and light gray Assert.AreEqual(Color.LightGray, this.GetNode1().ForeColor, "Node1 unchecked color is incorrect."); // Root should be unchecked and light gray Assert.AreEqual(Color.LightGray, this.GetRoot().ForeColor, "Root unchecked color is incorrect."); this.GetNode1().Checked = true; // Node1 should be checked and black Assert.AreEqual(Color.Black, this.GetNode1().ForeColor); // Root should be checked and black Assert.AreEqual(Color.Black, this.GetRoot().ForeColor); } [Test] public void ValidateStructure() { Assert.AreEqual("Root", this.GetRoot().Text); Assert.AreEqual("Node1", this.GetNode1().Text); Assert.AreEqual("Node2", this.GetNode2().Text); Assert.AreEqual("Child1", this.GetChild1().Text); Assert.AreEqual("Child2", this.GetChild2().Text); Assert.AreEqual("Child3", this.GetChild3().Text); Assert.AreEqual("Child4", this.GetChild4().Text); } [Test] public void GetUniqueNodeName() { Assert.AreEqual("Root", tree.GetUniqueNodeName(this.GetRoot())); Assert.AreEqual("Node1Root", tree.GetUniqueNodeName(this.GetNode1())); Assert.AreEqual("Child1Node1Root", tree.GetUniqueNodeName(this.GetChild1())); } [Test] public void GetState() { this.tree.StateChanged += new StateChangedEventHandler(tree_StateChanged); ; this.GetRoot().Checked = false; this.GetNode1().Checked = false; Assert.IsTrue(this.GetNode1().Checked == false, "Node1 should not be checked initially"); // Check it - checked state should be saved this.GetNode1().Checked = true; Assert.IsTrue(tree.GetState(this.GetNode1()), "State wasn't saved for Node1"); string node1a = tree.GetUniqueNodeName(this.GetNode1()); // Remove it this.GetNode2().Remove(); this.GetNode1().Remove(); // Readd it this.GetRoot().Nodes.Add("Node1"); this.GetRoot().Nodes.Add("Node2"); string node2a = tree.GetUniqueNodeName(this.GetNode1()); Assert.AreEqual(node1a, node2a, "Nodes should be the same for state monitoring."); Assert.IsFalse(this.GetNode1().Checked, "Node1 should not be checked after being added"); Assert.IsFalse(this.GetNode2().Checked, "Node2 should not be checked before LoadState."); Assert.IsTrue(tree.HasState(this.GetNode1()), "State no longer exists for Node1"); Assert.IsTrue(tree.GetState(this.GetNode1()), "State should still be true."); // Load the state this.tree.LoadState(); Assert.IsTrue(this.GetNode1().Checked == true, "Node1 should be checked."); Assert.IsTrue(this.GetNode2().Checked == false, "Node1 should not be checked after LoadState."); // Clear the state and reload this.tree.ClearState(); this.GetNode1().Checked = false; this.tree.LoadState(); Assert.IsFalse(this.GetNode1().Checked == true, "Node1 should not be checked since state was cleared."); } #region Utility Methods private TreeNode GetRoot() { return tree.Nodes[0]; } private TreeNode GetNode1() { return this.GetRoot().Nodes[0]; } private TreeNode GetNode2() { return this.GetRoot().Nodes[1]; } private TreeNode GetChild1() { return this.GetNode1().Nodes[0]; } private TreeNode GetChild2() { return this.GetNode1().Nodes[1]; } private TreeNode GetChild3() { return this.GetNode2().Nodes[0]; } private TreeNode GetChild4() { return this.GetNode2().Nodes[1]; } #endregion private void tree_StateChanged(TreeNode node, bool state) { //Console.WriteLine("{0} changed to {1}", node.Text, state); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:12
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Tests/Cryptography In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Tests/Cryptography Added Files: CryptoTest.cs Log Message: --- NEW FILE: CryptoTest.cs --- using System; using System.Text; using Adapdev.Cryptography; using NUnit.Framework; namespace Adapdev.Cryptography.Tests { /// <summary> /// Summary description for Encryptor. /// </summary> /// [TestFixture] public class CryptoTest { private string _text = "This is the text to encrypt"; // Des private string _password8 = "password"; // Rijndael / TripleDes private string _password16 = "password12345678"; // Des / TripleDes private string _vector8 = "init vec"; // Rijndael private string _vector16 = "init vec is big."; [Test] public void EncryptDecryptDes() { this.EncryptDecrypt(this._password8, this._vector8, EncryptionAlgorithm.Des); } [Test] public void EncryptDecryptTripleDes() { this.EncryptDecrypt(this._password16, this._vector8, EncryptionAlgorithm.TripleDes); } [Test] public void EncryptDecryptRijndael() { this.EncryptDecrypt(this._password16, this._vector16, EncryptionAlgorithm.Rijndael); } [Test] public void EncryptDecryptDesDefault() { this.EncryptDecrypt(EncryptionAlgorithm.Des); } [Test] public void EncryptDecryptTripleDefault() { this.EncryptDecrypt(EncryptionAlgorithm.TripleDes); } [Test] public void EncryptDecryptRijndaelDefault() { this.EncryptDecrypt(EncryptionAlgorithm.Rijndael); } private void EncryptDecrypt(string key, string vector, EncryptionAlgorithm algorithm) { Console.WriteLine("Processing " + algorithm.ToString()); // Get the encrypted value byte[] cipherText = Crypto.Encrypt(this._text, key, vector, algorithm); // Display it //Console.WriteLine("Encrypted: " + Encoding.ASCII.GetString(cipherText)); // Decrypt string plainText = Crypto.Decrypt(cipherText, key, vector, algorithm); // Display it Console.WriteLine("Decrypted: " + plainText); // Decrypted value should be same as original Assert.AreEqual(this._text, plainText, "Incorrect value decrypted"); } private void EncryptDecrypt(EncryptionAlgorithm algorithm) { Console.WriteLine("Processing " + algorithm.ToString()); // Get the encrypted value using the built in key and vector byte[] cipherText = Crypto.Encrypt(this._text, algorithm); // Display it //Console.WriteLine("Encrypted: " + Encoding.ASCII.GetString(cipherText)); // Get the decrypted value using the built in key and vector string plainText = Crypto.Decrypt(cipherText, algorithm); // Display it Console.WriteLine("Decrypted: " + plainText); // Decrypted value should be same as original Assert.AreEqual(this._text, plainText, "Incorrect value decrypted"); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Parser/Node In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Parser/Node Added Files: ASTAddNode.cs ASTAndNode.cs ASTAssignment.cs ASTBlock.cs ASTComment.cs ASTDirective.cs ASTDivNode.cs ASTEQNode.cs ASTElseIfStatement.cs ASTElseStatement.cs ASTEscape.cs ASTEscapedDirective.cs ASTExpression.cs ASTFalse.cs ASTGENode.cs ASTGTNode.cs ASTIdentifier.cs ASTIfStatement.cs ASTIncludeStatement.cs ASTIntegerRange.cs ASTLENode.cs ASTLTNode.cs ASTMethod.cs ASTModNode.cs ASTMulNode.cs ASTNENode.cs ASTNotNode.cs ASTNumberLiteral.cs ASTObjectArray.cs ASTOrNode.cs ASTParameters.cs ASTReference.cs ASTSetDirective.cs ASTStringLiteral.cs ASTSubtractNode.cs ASTText.cs ASTTrue.cs ASTVariable.cs ASTWord.cs ASTprocess.cs AbstractExecutor.cs BooleanPropertyExecutor.cs GetExecutor.cs INode.cs NodeUtils.cs ParserVisitor.cs PropertyExecutor.cs SimpleNode.cs Log Message: --- NEW FILE: ASTTrue.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTTrue : SimpleNode { //UPGRADE_NOTE: Field value was renamed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1029"' private static Boolean value_Renamed_Field = true; public ASTTrue(int id) : base(id) { } public ASTTrue(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { return true; } public override Object value_Renamed(InternalContextAdapter context) { return value_Renamed_Field; } } } --- NEW FILE: ASTObjectArray.cs --- namespace NVelocity.Runtime.Parser.Node { /* Generated By:JJTree: Do not edit this line. ASTObjectArray.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Collections; using NVelocity.Context; public class ASTObjectArray : SimpleNode { public ASTObjectArray(int id) : base(id) { } public ASTObjectArray(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override Object value_Renamed(InternalContextAdapter context) { int size = jjtGetNumChildren(); ArrayList objectArray = new ArrayList(); for (int i = 0; i < size; i++) { objectArray.Add(jjtGetChild(i).value_Renamed(context)); } return objectArray; } } } --- NEW FILE: ASTGENode.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTGENode : SimpleNode { public ASTGENode(int id) : base(id) { } public ASTGENode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { /* * get the two args */ Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of '>=' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * if not an Integer, not much we can do either */ if (!(left is Int32) || !(right is Int32)) { rsvc.error((!(left is Int32) ? "Left" : "Right") + " side of '>=' operation is not a valid type. " + " It is a " + (!(left is Int32) ? left.GetType() : right.GetType()) + ". Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } return ((Int32) left) >= ((Int32) right); } } } --- NEW FILE: ASTGTNode.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTGTNode : SimpleNode { public ASTGTNode(int id) : base(id) { } public ASTGTNode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { /* * get the two args */ Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of '>' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * if not an Integer, not much we can do either */ if (!(left is Int32) || !(right is Int32)) { rsvc.error((!(left is Int32) ? "Left" : "Right") + " side of '>' operation is not a valid type. " + " It is a " + (!(left is Int32) ? left.GetType() : right.GetType()) + ". Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } return ((Int32) left) > ((Int32) right); } } } --- NEW FILE: AbstractExecutor.cs --- namespace NVelocity.Runtime.Parser.Node { using System; using System.Reflection; using NVelocity.Context; /// <summary> Abstract class that is used to execute an arbitrary /// method that is in introspected. This is the superclass /// for the GetExecutor and PropertyExecutor. /// </summary> public abstract class AbstractExecutor { protected internal RuntimeServices rsvc = null; /// <summary> Method to be executed. /// </summary> protected internal MethodInfo method = null; protected internal PropertyInfo property = null; /// <summary> Execute method against context. /// </summary> public abstract Object execute(Object o, InternalContextAdapter context); /// <summary> Tell whether the executor is alive by looking /// at the value of the method. /// </summary> public virtual bool isAlive() { return (method != null || property != null); } } } --- NEW FILE: ASTAndNode.cs --- namespace NVelocity.Runtime.Parser.Node { /* Generated By:JJTree: Do not edit this line. ASTAndNode.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; /// <summary> Please look at the Parser.jjt file which is /// what controls the generation of this class. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ASTAndNode.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ASTAndNode : SimpleNode { public ASTAndNode(int id) : base(id) { } public ASTAndNode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /// <summary> Returns the value of the expression. /// Since the value of the expression is simply the boolean /// result of evaluate(), lets return that. /// </summary> public override Object value_Renamed(InternalContextAdapter context) { return evaluate(context); } /// <summary> logical and : /// null && right = false /// left && null = false /// null && null = false /// </summary> public override bool evaluate(InternalContextAdapter context) { INode left = jjtGetChild(0); INode right = jjtGetChild(1); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side of '&&' operation is null." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * short circuit the test. Don't eval the RHS if the LHS is false */ if (left.evaluate(context)) { if (right.evaluate(context)) { return true; } } return false; } } } --- NEW FILE: ASTEscapedDirective.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; /// <summary> This class is responsible for handling EscapedDirectives /// in VTL. /// /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ASTEscapedDirective.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ASTEscapedDirective : SimpleNode { public ASTEscapedDirective(int id) : base(id) { } public ASTEscapedDirective(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool render(InternalContextAdapter context, TextWriter writer) { writer.Write(FirstToken.image); return true; } } } --- NEW FILE: ASTMulNode.cs --- namespace NVelocity.Runtime.Parser.Node { /* Generated By:JJTree: Do not edit this line. ASTMulNode.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; /// <summary> Handles integer multiplication /// * /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ASTMulNode.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// </version> public class ASTMulNode : SimpleNode { public ASTMulNode(int id) : base(id) { } public ASTMulNode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /// <summary> computes the product of the two args. Returns null if either arg is null /// or if either arg is not an integer /// </summary> public override Object value_Renamed(InternalContextAdapter context) { /* * get the two args */ Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * if either is null, lets log and bail */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of multiplication operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return null; } /* * if not an Integer, not much we can do either */ if (!(left is Int32) || !(right is Int32)) { rsvc.error((!(left is Int32) ? "Left" : "Right") + " side of multiplication operation is not a valid type. " + "Currently only integers (1,2,3...) and Integer type is supported. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return null; } return ((Int32) left)*((Int32) right); } } } --- NEW FILE: NodeUtils.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Text; using Context = Context.IContext; /// <summary> Utilities for dealing with the AST node structure. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: NodeUtils.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class NodeUtils { /// <summary> Collect all the <SPECIAL_TOKEN>s that /// are carried along with a token. Special /// tokens do not participate in parsing but /// can still trigger certain lexical actions. /// In some cases you may want to retrieve these /// special tokens, this is simply a way to /// extract them. /// </summary> public static String specialText(Token t) { String specialText = ""; if (t.specialToken == null || t.specialToken.image.StartsWith("##")) return specialText; Token tmp_t = t.specialToken; while (tmp_t.specialToken != null) { tmp_t = tmp_t.specialToken; } while (tmp_t != null) { String st = tmp_t.image; StringBuilder sb = new StringBuilder(); for (int i = 0; i < st.Length; i++) { char c = st[i]; if (c == '#' || c == '$') { sb.Append(c); } /* * more dreaded MORE hack :) * * looking for ("\\")*"$" sequences */ if (c == '\\') { bool ok = true; bool term = false; int j = i; for (ok = true; ok && j < st.Length; j++) { char cc = st[j]; if (cc == '\\') { /* * if we see a \, keep going */ continue; } else if (cc == '$') { /* * a $ ends it correctly */ term = true; ok = false; } else { /* * nah... */ ok = false; } } if (term) { String foo = st.Substring(i, (j) - (i)); sb.Append(foo); i = j; } } } specialText += sb.ToString(); tmp_t = tmp_t.next; } return specialText; } /// <summary> complete node literal /// * /// </summary> public static String tokenLiteral(Token t) { return specialText(t) + t.image; } /// <summary> Utility method to interpolate context variables /// into string literals. So that the following will /// work: /// * /// #set $name = "candy" /// $image.getURI("${name}.jpg") /// * /// And the string literal argument will /// be transformed into "candy.jpg" before /// the method is executed. /// </summary> public static String interpolate(String argStr, Context vars) { StringBuilder argBuf = new StringBuilder(); for (int cIdx = 0; cIdx < argStr.Length; ) { char ch = argStr[cIdx]; switch (ch) { case '$': StringBuilder nameBuf = new StringBuilder(); for (++cIdx; cIdx < argStr.Length; ++cIdx) { ch = argStr[cIdx]; if (ch == '_' || ch == '-' || Char.IsLetterOrDigit(ch)) nameBuf.Append(ch); else if (ch == '{' || ch == '}') continue; else break; } if (nameBuf.Length > 0) { Object value_Renamed = vars.Get(nameBuf.ToString()); if (value_Renamed == null) argBuf.Append("$").Append(nameBuf.ToString()); else { //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' argBuf.Append(value_Renamed.ToString()); } } break; default: argBuf.Append(ch); ++cIdx; break; } } return argBuf.ToString(); } } } --- NEW FILE: ASTWord.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; public class ASTWord : SimpleNode { public ASTWord(int id) : base(id) { } public ASTWord(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } } } --- NEW FILE: ASTStringLiteral.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.IO; using NVelocity.Context; /// <summary> ASTStringLiteral support. Will interpolate! /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: ASTStringLiteral.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class ASTStringLiteral : SimpleNode { /* cache the value of the interpolation switch */ private bool interpolate = true; private SimpleNode nodeTree = null; private String image = ""; private String interpolateimage = ""; public ASTStringLiteral(int id) : base(id) { } public ASTStringLiteral(Parser p, int id) : base(p, id) { } /// <summary> init : we don't have to do much. Init the tree (there /// shouldn't be one) and then see if interpolation is turned on. /// </summary> public override Object init(InternalContextAdapter context, Object data) { /* * simple habit... we prollie don't have an AST beneath us */ base.init(context, data); /* * the stringlit is set at template parse time, so we can * do this here for now. if things change and we can somehow * create stringlits at runtime, this must * move to the runtime execution path * * so, only if interpolation is turned on AND it starts * with a " AND it has a directive or reference, then we * can interpolate. Otherwise, don't bother. */ interpolate = rsvc.getBoolean(RuntimeConstants_Fields.INTERPOLATE_STRINGLITERALS, true) && FirstToken.image.StartsWith("\"") && ((FirstToken.image.IndexOf((Char) '$') != - 1) || (FirstToken.image.IndexOf((Char) '#') != - 1)); /* * get the contents of the string, minus the '/" at each end */ image = FirstToken.image.Substring(1, (FirstToken.image.Length - 1) - (1)); /* * tack a space on the end (dreaded <MORE> kludge) */ interpolateimage = image + " "; if (interpolate) { /* * now parse and init the nodeTree */ //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(interpolateimage); /* * it's possible to not have an initialization context - or we don't * want to trust the caller - so have a fallback value if so * * Also, do *not* dump the VM namespace for this template */ nodeTree = rsvc.parse(br, (context != null) ? context.CurrentTemplateName : "StringLiteral", false); /* * init with context. It won't modify anything */ nodeTree.init(context, rsvc); } return data; } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /// <summary> renders the value of the string literal /// If the properties allow, and the string literal contains a $ or a # /// the literal is rendered against the context /// Otherwise, the stringlit is returned. /// </summary> public override Object value_Renamed(InternalContextAdapter context) { if (interpolate) { try { /* * now render against the real context */ TextWriter writer = new StringWriter(); nodeTree.render(context, writer); /* * and return the result as a String */ String ret = writer.ToString(); /* * remove the space from the end (dreaded <MORE> kludge) */ return ret.Substring(0, (ret.Length - 1) - (0)); } catch (Exception e) { /* * eh. If anything wrong, just punt * and output the literal */ rsvc.error("Error in interpolating string literal : " + e); } } /* * ok, either not allowed to interpolate, there wasn't * a ref or directive, or we failed, so * just output the literal */ return image; } } } --- NEW FILE: ASTNENode.cs --- namespace NVelocity.Runtime.Parser.Node { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; public class ASTNENode : SimpleNode { public ASTNENode(int id) : base(id) { } public ASTNENode(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. * /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override bool evaluate(InternalContextAdapter context) { Object left = jjtGetChild(0).value_Renamed(context); Object right = jjtGetChild(1).value_Renamed(context); /* * null check */ if (left == null || right == null) { rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal() + ") of '!=' operation has null value." + " Operation not possible. " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "]"); return false; } /* * check to see if they are the same class. I don't think this is slower * as I don't think that getClass() results in object creation, and we can * extend == to handle all classes */ if (left.GetType().Equals(right.GetType())) { return !(left.Equals(right)); } else { rsvc.error("Error in evaluation of != expression." + " Both arguments must be of the same Class." + " Currently left = " + left.GetType() + ", right = " + right.GetType() + ". " + context.CurrentTemplateName + " [line " + Line + ", column " + Column + "] (ASTEQNode)"); return false; } } } } --- NEW FILE: ASTReference.cs --- namespace NVelocity.Runtime.Parser.Node { using System; using System.Collections; using System.IO; using System.Reflection; using System.Text; using NVelocity.App.Events; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Exception; /// <summary> /// This class is responsible for handling the references in /// VTL ($foo). /// /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:Chr...@dl...">Christoph Reck</a></author> /// <author> <a href="mailto:kjo...@tr...>Kent Johnson</a></author> /// <version> $Id: ASTReference.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ </version> public class ASTReference : SimpleNode { public virtual String RootString { get { return rootString; } } private String Root { get { Token t = FirstToken; /* * we have a special case where something like * $(\\)*!, where the user want's to see something * like $!blargh in the output, but the ! prevents it from showing. * I think that at this point, this isn't a reference. */ /* so, see if we have "\\!" */ int slashbang = t.image.IndexOf("\\!"); if (slashbang != - 1) { /* * lets do all the work here. I would argue that if this occurrs, it's * not a reference at all, so preceeding \ characters in front of the $ * are just schmoo. So we just do the escape processing trick (even | odd) * and move on. This kind of breaks the rule pattern of $ and # but '!' really * tosses a wrench into things. */ /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.Length; i = t.image.IndexOf((Char) '$'); if (i == - 1) { /* yikes! */ rsvc.error("ASTReference.getRoot() : internal error : no $ found for slashbang."); computableReference = false; nullString = t.image; return nullString; } while (i < len && t.image[i] != '\\') { i++; } /* ok, i is the first \ char */ int start = i; int count = 0; while (i < len && t.image[i++] == '\\') { count++; } /* * now construct the output string. We really don't care about leading * slashes as this is not a reference. It's quasi-schmoo */ nullString = t.image.Substring(0, (start) - (0)); // prefix up to the first nullString += t.image.Substring(start, (start + count - 1) - (start)); // get the slashes nullString += t.image.Substring(start + count); // and the rest, including the /* * this isn't a valid reference, so lets short circuit the value and set calcs */ computableReference = false; return nullString; } /* * we need to see if this reference is escaped. if so * we will clean off the leading \'s and let the * regular behavior determine if we should output this * as \$foo or $foo later on in render(). Lazyness.. */ escaped = false; if (t.image.StartsWith("\\")) { /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.Length; while (i < len && t.image[i] == '\\') { i++; } if ((i%2) != 0) escaped = true; if (i > 0) escPrefix = t.image.Substring(0, (i/2) - (0)); t.image = t.image.Substring(i); } /* * Look for preceeding stuff like '#' and '$' * and snip it off, except for the * last $ */ int loc1 = t.image.LastIndexOf((Char) '$'); /* * if we have extra stuff, loc > 0 * ex. '#$foo' so attach that to * the prefix. */ if (loc1 > 0) { morePrefix = morePrefix + t.image.Substring(0, (loc1) - (0)); t.image = t.image.Substring(loc1); } /* * Now it should be clean. Get the literal in case this reference * isn't backed by the context at runtime, and then figure out what * we are working with. */ nullString = literal(); if (t.image.StartsWith("$!")) { referenceType = QUIET_REFERENCE; /* * only if we aren't escaped do we want to null the output */ if (!escaped) nullString = ""; if (t.image.StartsWith("$!{")) { /* * ex : $!{provider.Title} */ return t.next.image; } else { /* * ex : $!provider.Title */ return t.image.Substring(2); } } else if (t.image.Equals("${")) { /* * ex : ${provider.Title} */ referenceType = FORMAL_REFERENCE; return t.next.image; } else if (t.image.StartsWith("$")) { /* * just nip off the '$' so we have * the root */ referenceType = NORMAL_REFERENCE; return t.image.Substring(1); } else { /* * this is a 'RUNT', which can happen in certain circumstances where * the parser is fooled into believeing that an IDENTIFIER is a real * reference. Another 'dreaded' MORE hack :). */ referenceType = RUNT; return t.image; } } } public virtual String Literal { set { /* * do only once */ if (this.literal_Renamed_Field == null) this.literal_Renamed_Field = value; } } /* Reference types */ private const int NORMAL_REFERENCE = 1; private const int FORMAL_REFERENCE = 2; private const int QUIET_REFERENCE = 3; private const int RUNT = 4; private int referenceType; private String nullString; private String rootString; private bool escaped = false; private bool computableReference = true; private String escPrefix = ""; private String morePrefix = ""; private String identifier = ""; //UPGRADE_NOTE: Field literal was renamed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1029"' private String literal_Renamed_Field = null; private int numChildren = 0; public ASTReference(int id) : base(id) { } public ASTReference(Parser p, int id) : base(p, id) { } /// <summary>Accept the visitor. /// </summary> public override Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public override Object init(InternalContextAdapter context, Object data) { /* * init our children */ base.init(context, data); /* * the only thing we can do in init() is getRoot() * as that is template based, not context based, * so it's thread- and context-safe */ rootString = Root; numChildren = jjtGetNumChildren(); /* * and if appropriate... */ if (numChildren > 0) { identifier = jjtGetChild(numChildren - 1).FirstToken.image; } return data; } /// <summary> Returns the 'root string', the reference key /// </summary> /// <summary> gets an Object that 'is' the value of the reference /// * /// </summary> /// <param name="o"> unused Object parameter /// </param> /// <param name="context">context used to generate value /// /// </param> public override Object execute(Object o, InternalContextAdapter context) { if (referenceType == RUNT) return null; /* * get the root object from the context */ Object result = getVariableValue(context, rootString); if (result == null) { return null; } /* * Iteratively work 'down' (it's flat...) the reference * to get the value, but check to make sure that * every result along the path is valid. For example: * * $hashtable.Customer.Name * * The $hashtable may be valid, but there is no key * 'Customer' in the hashtable so we want to stop * when we find a null value and return the null * so the error gets logged. */ try { for (int i = 0; i < numChildren; i++) { result = jjtGetChild(i).execute(result, context); if (result == null) { return null; } } return result; } catch (MethodInvocationException mie) { /* * someone tossed their cookies */ rsvc.error("Method " + mie.MethodName + " threw exception for reference $" + rootString + " in template " + context.CurrentTemplateName + " at " + " [" + this.Line + "," + this.Column + "]"); mie.ReferenceName = rootString; throw mie; } } /// <summary> gets the value of the reference and outputs it to the /// writer. /// * /// </summary> /// <param name="context"> context of data to use in getting value /// </param> /// <param name="writer"> writer to render to /// /// </param> public override bool render(InternalContextAdapter context, TextWriter writer) { if (referenceType == RUNT) { writer.Write(rootString); return true; } Object value_Renamed = execute(null, context); /* * if this reference is escaped (\$foo) then we want to do one of two things : * 1) if this is a reference in the context, then we want to print $foo * 2) if not, then \$foo (its considered shmoo, not VTL) */ if (escaped) { if (value_Renamed == null) { writer.Write(escPrefix); writer.Write("\\"); writer.Write(nullString); } else { writer.Write(escPrefix); writer.Write(nullString); } return true; } /* * the normal processing * * if we have an event cartridge, get a new value object */ EventCartridge ec = context.EventCartridge; if (ec != null) { value_Renamed = ec.referenceInsert(nullString, value_Renamed); } /* * if value is null... */ if (value_Renamed == null) { /* * write prefix twice, because it's shmoo, so the \ don't escape each other... */ writer.Write(escPrefix); writer.Write(escPrefix); writer.Write(morePrefix); writer.Write(nullString); if (referenceType != QUIET_REFERENCE && rsvc.getBoolean(RuntimeConstants_Fields.RUNTIME_LOG_REFERENCE_LOG_INVALID, true)) { rsvc.warn(new ReferenceException("reference : template = " + context.CurrentTemplateN... [truncated message content] |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime Added Files: RuntimeConstants.cs RuntimeInstance.cs RuntimeServices.cs RuntimeSingleton.cs VelocimacroFactory.cs VelocimacroManager.cs Log Message: --- NEW FILE: RuntimeConstants.cs --- namespace NVelocity.Runtime { using System; /// <summary> /// This class defines the keys that are used in the /// velocity.properties file so that they can be referenced as a constant /// within Java code. /// </summary> /// <author> <a href="mailto:jo...@la...">Jon S. Stevens</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> public struct RuntimeConstants_Fields { public const String RUNTIME_LOG = "runtime.log"; public const String RUNTIME_LOG_LOGSYSTEM = "runtime.log.logsystem"; public const String RUNTIME_LOG_LOGSYSTEM_CLASS = "runtime.log.logsystem.class"; public const String RUNTIME_LOG_ERROR_STACKTRACE = "runtime.log.error.stacktrace"; public const String RUNTIME_LOG_WARN_STACKTRACE = "runtime.log.warn.stacktrace"; public const String RUNTIME_LOG_INFO_STACKTRACE = "runtime.log.info.stacktrace"; public const String RUNTIME_LOG_REFERENCE_LOG_INVALID = "runtime.log.invalid.references"; public const String DEBUG_PREFIX = " [debug] "; public const String INFO_PREFIX = " [info] "; public const String WARN_PREFIX = " [warn] "; public const String ERROR_PREFIX = " [error] "; public const String UNKNOWN_PREFIX = " [unknown] "; public const String LOGSYSTEM_LOG4NET_CATEGORY = "runtime.log.logsystem.log4net.category"; public const String LOGSYSTEM_LOG4NET_PATTERN = "runtime.log.logsystem.log4net.pattern"; public const String LOGSYSTEM_LOG4NET_FILE_SIZE = "runtime.log.logsystem.log4net.file.size"; public const String LOGSYSTEM_LOG4NET_FILE_BACKUPS = "runtime.log.logsystem.log4net.file.backups"; public const String LOGSYSTEM_LOG4NET_SYSLOGD_HOST = "runtime.log.logsystem.log4net.syslogd.host"; public const String LOGSYSTEM_LOG4NET_SYSLOGD_FACILITY = "runtime.log.logsystem.log4net.syslogd.facility"; public const String LOGSYSTEM_LOG4NET_REMOTE_HOST = "runtime.log.logsystem.log4net.remote.host"; public const String LOGSYSTEM_LOG4NET_REMOTE_PORT = "runtime.log.logsystem.log4net.remote.port"; public const String LOGSYSTEM_LOG4NET_EMAIL_SERVER = "runtime.log.logsystem.log4net.email.server"; public const String LOGSYSTEM_LOG4NET_EMAIL_FROM = "runtime.log.logsystem.log4net.email.from"; public const String LOGSYSTEM_LOG4NET_EMAIL_TO = "runtime.log.logsystem.log4net.email.to"; public const String LOGSYSTEM_LOG4NET_EMAIL_SUBJECT = "runtime.log.logsystem.log4net.email.subject"; public const String LOGSYSTEM_LOG4NET_EMAIL_BUFFER_SIZE = "runtime.log.logsystem.log4net.email.buffer.size"; public const String COUNTER_NAME = "directive.foreach.counter.name"; public const String COUNTER_INITIAL_VALUE = "directive.foreach.counter.initial.value"; public const String ERRORMSG_START = "directive.include.output.errormsg.start"; public const String ERRORMSG_END = "directive.include.output.errormsg.end"; public const String PARSE_DIRECTIVE_MAXDEPTH = "directive.parse.max.depth"; public const String RESOURCE_MANAGER_CLASS = "resource.manager.class"; public const String RESOURCE_MANAGER_CACHE_CLASS = "resource.manager.cache.class"; public const String RESOURCE_MANAGER_LOGWHENFOUND = "resource.manager.logwhenfound"; public const String RESOURCE_LOADER = "resource.loader"; public const String FILE_RESOURCE_LOADER_PATH = "file.resource.loader.path"; public const String FILE_RESOURCE_LOADER_CACHE = "file.resource.loader.cache"; public const String VM_LIBRARY = "velocimacro.library"; public const String VM_LIBRARY_AUTORELOAD = "velocimacro.library.autoreload"; public const String VM_PERM_ALLOW_INLINE = "velocimacro.permissions.allow.inline"; public const String VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL = "velocimacro.permissions.allow.inline.to.replace.global"; public const String VM_PERM_INLINE_LOCAL = "velocimacro.permissions.allow.inline.local.scope"; public const String VM_MESSAGES_ON = "velocimacro.messages.on"; public const String VM_CONTEXT_LOCALSCOPE = "velocimacro.context.localscope"; public const String INTERPOLATE_STRINGLITERALS = "runtime.interpolate.string.literals"; public const String INPUT_ENCODING = "input.encoding"; public const String OUTPUT_ENCODING = "output.encoding"; public const String ENCODING_DEFAULT = "ISO-8859-1"; public const String DEFAULT_RUNTIME_PROPERTIES = "nvelocity.properties"; public const String DEFAULT_RUNTIME_DIRECTIVES = "directive.properties"; public const int NUMBER_OF_PARSERS = 20; public const String PARSER_POOL_SIZE = "parser.pool.size"; } public interface RuntimeConstants { /* * ---------------------------------------------------------------------- * These are public constants that are used as handles for the * properties that can be specified in your typical * nvelocity.properties file. * ---------------------------------------------------------------------- */ /* * ---------------------------------------------------------------------- * L O G G I N G C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// /// <summary> Location of the velocity log file. /// </summary> /// <summary> externally provided logger /// </summary> /// <summary> class of log system to use /// </summary> /// /// <summary> Stack trace output for error messages. /// </summary> /// /// <summary> Stack trace output for warning messages. /// </summary> /// /// <summary> Stack trace output for info messages. /// </summary> /// <summary> Logging of invalid references. /// </summary> /// <summary> Log message prefixes /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /// <summary> Log4Net configuration /// </summary> /* * ---------------------------------------------------------------------- * D I R E C T I V E C O N F I G U R A T I O N * ---------------------------------------------------------------------- * Directive properties are of the form: * * directive.<directive-name>.<property> * ---------------------------------------------------------------------- */ /// /// <summary> Initial counter value in #foreach directives. /// </summary> /// /// <summary> Initial counter value in #foreach directives. /// </summary> /// <summary> Starting tag for error messages triggered by passing /// a parameter not allowed in the #include directive. Only /// string literals, and references are allowed. /// </summary> /// <summary> Ending tag for error messages triggered by passing /// a parameter not allowed in the #include directive. Only /// string literals, and references are allowed. /// </summary> /// <summary> Maximum recursion depth allowed for the #parse directive. /// </summary> /* * ---------------------------------------------------------------------- * R E S O U R C E M A N A G E R C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /* * ---------------------------------------------------------------------- * R E S O U R C E L O A D E R C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// <summary> controls if the finding of a resource is logged /// </summary> /// <summary> Key used to retrieve the names of the resource loaders /// to be used. In a properties file they may appear as /// the following: /// * /// resource.loader = file,classpath /// </summary> /// <summary> The public handle for setting a path in /// the FileResourceLoader. /// </summary> /// <summary> The public handle for turning the caching on in the /// FileResourceLoader. /// </summary> /* * ---------------------------------------------------------------------- * V E L O C I M A C R O C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// /// <summary> Name of local Velocimacro library template. /// </summary> /// /// <summary> switch for autoloading library-sourced VMs (for development) /// </summary> /// /// <summary> boolean (true/false) default true : allow /// inline (in-template) macro definitions /// </summary> /// <summary> boolean (true/false) default false : allow inline /// (in-template) macro definitions to replace existing /// </summary> /// /// <summary> Switch for forcing inline macros to be local : default false. /// </summary> /// /// <summary> Switch for VM blather : default true. /// </summary> /// /// <summary> switch for local context in VM : default false /// </summary> /* * ---------------------------------------------------------------------- * G E N E R A L R U N T I M E C O N F I G U R A T I O N * ---------------------------------------------------------------------- */ /// <summary> Switch for the interpolation facility for string literals /// </summary> /// /// <summary> The character encoding for the templates. Used by the parser in /// processing the input streams. /// </summary> /// <summary> Encoding for the output stream. Currently used by Anakia and /// VelocityServlet /// </summary> /* * ---------------------------------------------------------------------- * These constants are used internally by the Velocity runtime i.e. * the constansts listed below are strictly used in the Runtime * class itself. * ---------------------------------------------------------------------- */ /// /// <summary> Default Runtime properties. /// </summary> /// /// <summary> Default Runtime properties /// </summary> /// <summary> Number of parsers to create /// </summary> } } --- NEW FILE: RuntimeSingleton.cs --- namespace NVelocity.Runtime { using System; using System.IO; using Commons.Collections; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> This is the Runtime system for Velocity. It is the /// single access point for all functionality in Velocity. /// It adheres to the mediator pattern and is the only /// structure that developers need to be familiar with /// in order to get Velocity to perform. /// * /// The Runtime will also cooperate with external /// systems like Turbine. Runtime properties can /// set and then the Runtime is initialized. /// * /// Turbine for example knows where the templates /// are to be loaded from, and where the velocity /// log file should be placed. /// * /// So in the case of Velocity cooperating with Turbine /// the code might look something like the following: /// * /// <pre> /// Runtime.setProperty(Runtime.FILE_RESOURCE_LOADER_PATH, templatePath); /// Runtime.setProperty(Runtime.RUNTIME_LOG, pathToVelocityLog); /// Runtime.init(); /// </pre> /// * /// <pre> /// ----------------------------------------------------------------------- /// N O T E S O N R U N T I M E I N I T I A L I Z A T I O N /// ----------------------------------------------------------------------- /// Runtime.init() /// /// If Runtime.init() is called by itself the Runtime will /// initialize with a set of default values. /// ----------------------------------------------------------------------- /// Runtime.init(String/Properties) /// * /// In this case the default velocity properties are layed down /// first to provide a solid base, then any properties provided /// in the given properties object will override the corresponding /// default property. /// ----------------------------------------------------------------------- /// </pre> /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:jl...@ho...">Jeff Bowden</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magusson Jr.</a> /// </author> /// <version> $Id: RuntimeSingleton.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class RuntimeSingleton : RuntimeConstants { public static RuntimeServices RuntimeServices { get { return (RuntimeServices) ri; } } public static ExtendedProperties Configuration { get { return ri.Configuration; } set { ri.Configuration = value; } } public static Introspector Introspector { get { return ri.Introspector; } } public static RuntimeInstance RuntimeInstance { get { return ri; } } private static RuntimeInstance ri = new RuntimeInstance(); /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>ResourceManager</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ public static void init() { lock (typeof (RuntimeSingleton)) { ri.init(); } } /// <summary> Allows an external system to set a property in /// the Velocity Runtime. /// * /// </summary> /// <param name="String">property key /// </param> /// <param name="String">property value /// /// </param> public static void setProperty(String key, Object value_Renamed) { ri.setProperty(key, value_Renamed); } /// <summary> Allow an external system to set an ExtendedProperties /// object to use. This is useful where the external /// system also uses the ExtendedProperties class and /// the velocity configuration is a subset of /// parent application's configuration. This is /// the case with Turbine. /// * /// </summary> /// <param name="ExtendedProperties">configuration /// /// </param> /// <summary> Add a property to the configuration. If it already /// exists then the value stated here will be added /// to the configuration entry. For example, if /// * /// resource.loader = file /// * /// is already present in the configuration and you /// * /// addProperty("resource.loader", "classpath") /// * /// Then you will end up with a Vector like the /// following: /// * /// ["file", "classpath"] /// * /// </summary> /// <param name="String">key /// </param> /// <param name="String">value /// /// </param> public static void addProperty(String key, Object value_Renamed) { ri.addProperty(key, value_Renamed); } /// <summary> Clear the values pertaining to a particular /// property. /// * /// </summary> /// <param name="String">key of property to clear /// /// </param> public static void clearProperty(String key) { ri.clearProperty(key); } /// <summary> Allows an external caller to get a property. The calling /// routine is required to know the type, as this routine /// will return an Object, as that is what properties can be. /// * /// </summary> /// <param name="key">property to return /// /// </param> public static Object getProperty(String key) { return ri.getProperty(key); } /// <summary> Initialize the Velocity Runtime with a Properties /// object. /// * /// </summary> /// <param name="">Properties /// /// </param> public static void init(ExtendedProperties p) { ri.init(p); } /// <summary> Initialize the Velocity Runtime with the name of /// ExtendedProperties object. /// * /// </summary> /// <param name="">Properties /// /// </param> public static void init(String configurationFile) { ri.init(configurationFile); } /// <summary> Returns a JavaCC generated Parser. /// * /// </summary> /// <returns>Parser javacc generated parser /// /// </returns> private static Parser.Parser createNewParser() { return ri.createNewParser(); } /// <summary> Parse the input and return the root of /// AST node structure. /// <br><br> /// In the event that it runs out of parsers in the /// pool, it will create and let them be GC'd /// dynamically, logging that it has to do that. This /// is considered an exceptional condition. It is /// expected that the user will set the /// PARSER_POOL_SIZE property appropriately for their /// application. We will revisit this. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// /// </param> public static SimpleNode parse(TextReader reader, String templateName) { return ri.parse(reader, templateName); } /// <summary> Parse the input and return the root of the AST node structure. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// </param> /// <param name="dumpNamespace">flag to dump the Velocimacro namespace for this template /// /// </param> public static SimpleNode parse(TextReader reader, String templateName, bool dumpNamespace) { return ri.parse(reader, templateName, dumpNamespace); } /// <summary> Returns a <code>Template</code> from the resource manager. /// This method assumes that the character encoding of the /// template is set by the <code>input.encoding</code> /// property. The default is "ISO-8859-1" /// * /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> public static Template getTemplate(String name) { return ri.getTemplate(name); } /// <summary> Returns a <code>Template</code> from the resource manager /// * /// </summary> /// <param name="name">The name of the desired template. /// </param> /// <param name="encoding">Character encoding of the template /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> public static Template getTemplate(String name, String encoding) { return ri.getTemplate(name, encoding); } /// <summary> Returns a static content resource from the /// resource manager. Uses the current value /// if INPUT_ENCODING as the character encoding. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> public static ContentResource getContent(String name) { return ri.getContent(name); } /// <summary> Returns a static content resource from the /// resource manager. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <param name="encoding">Character encoding to use /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> public static ContentResource getContent(String name, String encoding) { return ri.getContent(name, encoding); } /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> public static String getLoaderNameForResource(String resourceName) { return ri.getLoaderNameForResource(resourceName); } /// <summary> Log a warning message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void warn(Object message) { ri.warn(message); } /// /// <summary> Log an info message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void info(Object message) { ri.info(message); } /// <summary> Log an error message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void error(Object message) { ri.error(message); } /// <summary> Log a debug message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> public static void debug(Object message) { ri.debug(message); } /// <summary> String property accessor method with default to hide the /// configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="String">defaultValue default value to return if key not /// found in resource manager. /// </param> /// <returns>String value of key or default /// /// </returns> public static String getString(String key, String defaultValue) { return ri.getString(key, defaultValue); } /// <summary> Returns the appropriate VelocimacroProxy object if strVMname /// is a valid current Velocimacro. /// * /// </summary> /// <param name="String">vmName Name of velocimacro requested /// </param> /// <returns>String VelocimacroProxy /// /// </returns> public static Directive.Directive getVelocimacro(String vmName, String templateName) { return ri.getVelocimacro(vmName, templateName); } /// <summary> Adds a new Velocimacro. Usually called by Macro only while parsing. /// * /// </summary> /// <param name="String">name Name of velocimacro /// </param> /// <param name="String">macro String form of macro body /// </param> /// <param name="String">argArray Array of strings, containing the /// #macro() arguments. the 0th is the name. /// </param> /// <returns>boolean True if added, false if rejected for some /// reason (either parameters or permission settings) /// /// </returns> public static bool addVelocimacro(String name, String macro, String[] argArray, String sourceTemplate) { return ri.addVelocimacro(name, macro, argArray, sourceTemplate); } /// <summary> Checks to see if a VM exists /// * /// </summary> /// <param name="name"> Name of velocimacro /// </param> /// <returns>boolean True if VM by that name exists, false if not /// /// </returns> public static bool isVelocimacro(String vmName, String templateName) { return ri.isVelocimacro(vmName, templateName); } /// <summary> tells the vmFactory to dump the specified namespace. This is to support /// clearing the VM list when in inline-VM-local-scope mode /// </summary> public static bool dumpVMNamespace(String namespace_Renamed) { return ri.dumpVMNamespace(namespace_Renamed); } /* -------------------------------------------------------------------- * R U N T I M E A C C E S S O R M E T H O D S * -------------------------------------------------------------------- * These are the getXXX() methods that are a simple wrapper * around the configuration object. This is an attempt * to make a the Velocity Runtime the single access point * for all things Velocity, and allow the Runtime to * adhere as closely as possible the the Mediator pattern * which is the ultimate goal. * -------------------------------------------------------------------- */ /// <summary> String property accessor method to hide the configuration implementation /// </summary> /// <param name="key"> property key /// </param> /// <returns> value of key or null /// /// </returns> public static String getString(String key) { return ri.getString(key); } /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="String">key property key /// </param> /// <returns>int value /// /// </returns> public static int getInt(String key) { return ri.getInt(key); } /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="key"> property key /// </param> /// <param name="int">default value /// </param> /// <returns>int value /// /// </returns> public static int getInt(String key, int defaultValue) { return ri.getInt(key, defaultValue); } /// <summary> Boolean property accessor method to hide the configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="boolean">default default value if property not found /// </param> /// <returns>boolean value of key or default value /// /// </returns> public static bool getBoolean(String key, bool def) { return ri.getBoolean(key, def); } /// <summary> Return the velocity runtime configuration object. /// * /// </summary> /// <returns>ExtendedProperties configuration object which houses /// the velocity runtime properties. /// /// </returns> /// <summary> Return the Introspector for this RuntimeInstance /// * /// </summary> /// <returns>Introspector object for this runtime instance /// /// </returns> /// <summary> returns the RuntimeInstance object for this singleton /// For internal use only :) /// * /// </summary> /// <returns>RuntimeInstance the RuntimeInstance used by this Singleton /// instance /// /// </returns> } } --- NEW FILE: VelocimacroFactory.cs --- namespace NVelocity.Runtime { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using System.Collections; using NVelocity.Runtime.Directive; /// <summary> VelocimacroFactory.java /// * /// manages the set of VMs in a running Velocity engine. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VelocimacroFactory.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class VelocimacroFactory { private bool TemplateLocalInline { get { return templateLocal; } set { templateLocal = value; } } private bool AddMacroPermission { set { bool b = addNewAllowed; addNewAllowed = value; // TODO: looks like original code must have returned the value that was replaced //return b; } } private bool ReplacementPermission { set { bool b = replaceAllowed; replaceAllowed = value; // TODO: looks like original code must have returned the value that was replaced //return b; } } private bool Blather { get { return blather; } set { blather = value; } } private bool Autoload { get { return autoReloadLibrary; } set { autoReloadLibrary = value; } } /// <summary> runtime services for this instance /// </summary> private RuntimeServices rsvc = null; /// <summary> VMManager : deal with namespace management /// and actually keeps all the VM definitions /// </summary> private VelocimacroManager vmManager = null; /// <summary> determines if replacement of global VMs are allowed /// controlled by VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL /// </summary> private bool replaceAllowed = false; /// <summary> controls if new VMs can be added. Set by /// VM_PERM_ALLOW_INLINE Note the assumption that only /// through inline defs can this happen. /// additions through autoloaded VMs is allowed /// </summary> private bool addNewAllowed = true; /// <summary> sets if template-local namespace in used /// </summary> private bool templateLocal = false; /// <summary> controls log output /// </summary> private bool blather = false; /// <summary> determines if the libraries are auto-loaded /// when they change /// </summary> private bool autoReloadLibrary = false; /// <summary> vector of the library names /// </summary> private ArrayList macroLibVec = null; /// <summary> map of the library Template objects /// used for reload determination /// </summary> private Hashtable libModMap; /// <summary> CTOR : requires a runtime services from now /// on /// </summary> public VelocimacroFactory(RuntimeServices rs) { this.rsvc = rs; /* * we always access in a synchronized(), so we * can use an unsynchronized hashmap */ libModMap = new Hashtable(); vmManager = new VelocimacroManager(rsvc); } /// <summary> initialize the factory - setup all permissions /// load all global libraries. /// </summary> public virtual void initVelocimacro() { /* * maybe I'm just paranoid... */ lock (this) { /* * allow replacements while we add the libraries, if exist */ ReplacementPermission = true; Blather = true; logVMMessageInfo("Velocimacro : initialization starting."); /* * add all library macros to the global namespace */ vmManager.NamespaceUsage = false; /* * now, if there is a global or local libraries specified, use them. * All we have to do is get the template. The template will be parsed; * VM's are added during the parse phase */ Object libfiles = rsvc.getProperty(RuntimeConstants_Fields.VM_LIBRARY); if (libfiles != null) { if (libfiles is ArrayList) { macroLibVec = (ArrayList) libfiles; } else if (libfiles is String) { macroLibVec = new ArrayList(); macroLibVec.Add(libfiles); } for (int i = 0; i < macroLibVec.Count; i++) { String lib = (String) macroLibVec[i]; /* * only if it's a non-empty string do we bother */ if (lib != null && !lib.Equals("")) { /* * let the VMManager know that the following is coming * from libraries - need to know for auto-load */ vmManager.RegisterFromLib = true; logVMMessageInfo("Velocimacro : adding VMs from " + "VM library template : " + lib); try { Template template = rsvc.getTemplate(lib); /* * save the template. This depends on the assumption * that the Template object won't change - currently * this is how the Resource manager works */ Twonk twonk = new Twonk(this); twonk.template = template; twonk.modificationTime = template.LastModified; libModMap[lib] = twonk; } catch (System.Exception e) { logVMMessageInfo("Velocimacro : error using VM " + "library template " + lib + " : " + e); } logVMMessageInfo("Velocimacro : VM library template " + "macro registration complete."); vmManager.RegisterFromLib = false; } } } /* * now, the permissions */ /* * allowinline : anything after this will be an inline macro, I think * there is the question if a #include is an inline, and I think so * * default = true */ AddMacroPermission = true; if (!rsvc.getBoolean(RuntimeConstants_Fields.VM_PERM_ALLOW_INLINE, true)) { AddMacroPermission = false; logVMMessageInfo("Velocimacro : allowInline = false : VMs can not " + "be defined inline in templates"); } else { logVMMessageInfo("Velocimacro : allowInline = true : VMs can be " + "defined inline in templates"); } /* * allowInlineToReplaceGlobal : allows an inline VM , if allowed at all, * to replace an existing global VM * * default = false */ ReplacementPermission = false; if (rsvc.getBoolean(RuntimeConstants_Fields.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, false)) { ReplacementPermission = true; logVMMessageInfo("Velocimacro : allowInlineToOverride = true : VMs " + "defined inline may replace previous VM definitions"); } else { logVMMessageInfo("Velocimacro : allowInlineToOverride = false : VMs " + "defined inline may NOT replace previous VM definitions"); } /* * now turn on namespace handling as far as permissions allow in the * manager, and also set it here for gating purposes */ vmManager.NamespaceUsage = true; /* * template-local inline VM mode : default is off */ TemplateLocalInline = rsvc.getBoolean(RuntimeConstants_Fields.VM_PERM_INLINE_LOCAL, false); if (TemplateLocalInline) { logVMMessageInfo("Velocimacro : allowInlineLocal = true : VMs " + "defined inline will be local to their defining template only."); } else { logVMMessageInfo("Velocimacro : allowInlineLocal = false : VMs " + "defined inline will be global in scope if allowed."); } vmManager.TemplateLocalInlineVM = TemplateLocalInline; /* * general message switch. default is on */ Blather = rsvc.getBoolean(RuntimeConstants_Fields.VM_MESSAGES_ON, true); if (Blather) { logVMMessageInfo("Velocimacro : messages on : VM system " + "will output logging messages"); } else { logVMMessageInfo("Velocimacro : messages off : VM system will be quiet"); } /* * autoload VM libraries */ Autoload = rsvc.getBoolean(RuntimeConstants_Fields.VM_LIBRARY_AUTORELOAD, false); if (Autoload) { logVMMessageInfo("Velocimacro : autoload on : VM system " + "will automatically reload global library macros"); } else { logVMMessageInfo("Velocimacro : autoload off : VM system " + "will not automatically reload global library macros"); } rsvc.info("Velocimacro : initialization complete."); } return; } /// <summary> adds a macro to the factory. /// </summary> public virtual bool addVelocimacro(String name, String macroBody, String[] argArray, String sourceTemplate) { /* * maybe we should throw an exception, maybe just tell * the caller like this... * * I hate this : maybe exceptions are in order here... */ if (name == null || macroBody == null || argArray == null || sourceTemplate == null) { logVMMessageWarn("Velocimacro : VM addition rejected : " + "programmer error : arg null"); return false; } /* * see if the current ruleset allows this addition */ if (!canAddVelocimacro(name, sourceTemplate)) { return false; } /* * seems like all is good. Lets do it. */ lock (this) { vmManager.addVM(name, macroBody, argArray, sourceTemplate); } /* * if we are to blather, blather... */ if (blather) { String s = "#" + argArray[0]; s += "("; for (int i = 1; i < argArray.Length; i++) { s += " "; s += argArray[i]; } s += " ) : source = "; s += sourceTemplate; logVMMessageInfo("Velocimacro : added new VM : " + s); } return true; } /// <summary> determines if a given macro/namespace (name, source) combo is allowed /// to be added /// * /// </summary> /// <param name="name">Name of VM to add /// </param> /// <param name="sourceTemplate">Source template that contains the defintion of the VM /// </param> /// <returns>true if it is allowed to be added, false otherwise /// /// </returns> private bool canAddVelocimacro(String name, String sourceTemplate) { /* * short circuit and do it if autoloader is on, and the * template is one of the library templates */ if (Autoload) { /* * see if this is a library template */ for (int i = 0; i < macroLibVec.Count; i++) { String lib = (String) macroLibVec[i]; if (lib.Equals(sourceTemplate)) { return true; } } } /* * maybe the rules should be in manager? I dunno. It's to manage * the namespace issues first, are we allowed to add VMs at all? * This trumps all. */ if (!addNewAllowed) { logVMMessageWarn("Velocimacro : VM addition rejected : " + name + " : inline VMs not allowed."); return false; } /* * are they local in scope? Then it is ok to add. */ if (!templateLocal) { /* * otherwise, if we have it already in global namespace, and they can't replace * since local templates are not allowed, the global namespace is implied. * remember, we don't know anything about namespace managment here, so lets * note do anything fancy like trying to give it the global namespace here * * so if we have it, and we aren't allowed to replace, bail */ if (isVelocimacro(name, sourceTemplate) && !replaceAllowed) { logVMMessageWarn("Velocimacro : VM addition rejected : " + name + " : inline not allowed to replace existing VM"); return false; } } return true; } /// <summary> localization of the logging logic /// </summary> private void logVMMessageInfo(String s) { if (blather) rsvc.info(s); } /// <summary> localization of the logging logic /// </summary> private void logVMMessageWarn(String s) { if (blather) rsvc.warn(s); } /// <summary> Tells the world if a given directive string is a Velocimacro /// </summary> public virtual bool isVelocimacro(String vm, String sourceTemplate) { lock (this) { /* * first we check the locals to see if we have * a local definition for this template */ if (vmManager.get(vm, sourceTemplate) != null) return true; } return false; } /// <summary> actual factory : creates a Directive that will /// behave correctly wrt getting the framework to /// dig out the correct # of args /// </summary> public virtual Directive.Directive getVelocimacro(String vmName, String sourceTemplate) { VelocimacroProxy vp = null; lock (this) { /* * don't ask - do */ vp = vmManager.get(vmName, sourceTemplate); /* * if this exists, and autoload is on, we need to check * where this VM came from */ if (vp != null && Autoload) { /* * see if this VM came from a library. Need to pass sourceTemplate * in the event namespaces are set, as it could be masked by local */ String lib = vmManager.getLibraryName(vmName, sourceTemplate); if (lib != null) { try { /* * get the template from our map */ Twonk tw = (Twonk) libModMap[lib]; if (tw != null) { Template template = tw.template; /* * now, compare the last modified time of the resource * with the last modified time of the template * if the file has changed, then reload. Otherwise, we should * be ok. */ long tt = tw.modificationTime; long ft = template.ResourceLoader.getLastModified(template); if (ft > tt) { logVMMessageInfo("Velocimacro : autoload reload for VMs from " + "VM library template : " + lib); /* * when there are VMs in a library that invoke each other, * there are calls into getVelocimacro() from the init() * process of the VM directive. To stop the infinite loop * we save the current time reported by the resource loader * and then be honest when the reload is complete */ tw.modificationTime = ft; template = rsvc.getTemplate(lib); /* * and now we be honest */ tw.template = template; tw.modificationTime = template.LastModified; /* * note that we don't need to put this twonk back * into the map, as we can just use the same reference * and this block is synchronized */ } } } catch (System.Exception e) { logVMMessageInfo("Velocimacro : error using VM " + "library template " + lib + " : " + e); } /* * and get again */ vp = vmManager.get(vmName, sourceTemplate); } } } return vp; } /// <summary> tells the vmManager to dump the specified namespace /// </summary> public virtual bool dumpVMNamespace(String namespace_Renamed) { return vmManager.dumpNamespace(namespace_Renamed); } /// <summary> sets permission to have VMs local in scope to their declaring template /// note that this is really taken care of in the VMManager class, but /// we need it here for gating purposes in addVM /// eventually, I will slide this all into the manager, maybe. /// </summary> /// <summary> sets the permission to add new macros /// </summary> /// <summary> sets the permission for allowing addMacro() calls to /// replace existing VM's /// </summary> /// <summary> set output message mode /// </summary> /// <summary> get output message mode /// </summary> /// <summary> set the switch for automatic reloading of /// global library-based VMs /// </summary> /// <summary> get the switch for automatic reloading of /// global library-based VMs /// </summary> /// <summary> small continer class to hold the duple /// of a template and modification time. /// We keep the modification time so we can /// 'override' it on a reload to prevent /// recursive reload due to inter-calling /// VMs in a library /// </summary> //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'Twonk' to access its enclosing instance. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1019"' private class Twonk { public Twonk(VelocimacroFactory enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(VelocimacroFactory enclosingInstance) { this.enclosingInstance = enclosingInstance; } private VelocimacroFactory enclosingInstance; public VelocimacroFactory Enclosing_Instance { get { return enclosingInstance; } } public Template template; public long modificationTime; } } } --- NEW FILE: RuntimeServices.cs --- namespace NVelocity.Runtime { using System; using System.IO; using Commons.Collections; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> Interface for internal runtime services that are needed by the /// various components w/in Velocity. This was taken from the old /// Runtime singleton, and anything not necessary was removed. /// /// Currently implemented by RuntimeInstance. /// </summary> public interface RuntimeServices { ExtendedProperties Configuration { get; set; } Introspector Introspector { get; } /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>ResourceManager</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ void init(); /// <summary> Allows an external system to set a property in /// the Velocity Runtime. /// * /// </summary> /// <param name="String">property key /// </param> /// <param name="String">property value /// /// </param> void setProperty(String key, Object value_Renamed); /// <summary> Allow an external system to set an ExtendedProperties /// object to use. This is useful where the external /// system also uses the ExtendedProperties class and /// the velocity configuration is a subset of /// parent application's configuration. This is /// the case with Turbine. /// * /// </summary> /// <param name="ExtendedProperties">configuration /// /// </param> /// <summary> Add a property to the configuration. If it already /// exists then the value stated here will be added /// to the configuration entry. For example, if /// * /// resource.loader = file /// * /// is already present in the configuration and you /// * /// addProperty("resource.loader", "classpath") /// * /// Then you will end up with a Vector like the /// following: /// * /// ["file", "classpath"] /// * /// </summary> /// <param name="String">key /// </param> /// <param name="String">value /// /// </param> void addProperty(String key, Object value_Renamed); /// <summary> Clear the values pertaining to a particular /// property. /// * /// </summary> /// <param name="String">key of property to clear /// /// </param> void clearProperty(String key); /// <summary> Allows an external caller to get a property. The calling /// routine is required to know the type, as this routine /// will return an Object, as that is what properties can be. /// * /// </summary> /// <param name="key">property to return /// /// </param> Object getProperty(String key); /// <summary> Initialize the Velocity Runtime with a Properties /// object. /// * /// </summary> /// <param name="">Properties /// /// </param> // TODO //void init(System.Configuration.AppSettingsReader p); /// <summary> Initialize the Velocity Runtime with the name of /// ExtendedProperties object. /// * /// </summary> /// <param name="">Properties /// /// </param> void init(String configurationFile); /// <summary> Parse the input and return the root of /// AST node structure. /// <br><br> /// In the event that it runs out of parsers in the /// pool, it will create and let them be GC'd /// dynamically, logging that it has to do that. This /// is considered an exceptional condition. It is /// expected that the user will set the /// PARSER_POOL_SIZE property appropriately for their /// application. We will revisit this. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// /// </param> SimpleNode parse(TextReader reader, String templateName); /// <summary> Parse the input and return the root of the AST node structure. /// * /// </summary> /// <param name="InputStream">inputstream retrieved by a resource loader /// </param> /// <param name="String">name of the template being parsed /// </param> /// <param name="dumpNamespace">flag to dump the Velocimacro namespace for this template /// /// </param> SimpleNode parse(TextReader reader, String templateName, bool dumpNamespace); /// <summary> Returns a <code>Template</code> from the resource manager. /// This method assumes that the character encoding of the /// template is set by the <code>input.encoding</code> /// property. The default is "ISO-8859-1" /// * /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> Template getTemplate(String name); /// <summary> Returns a <code>Template</code> from the resource manager /// * /// </summary> /// <param name="name">The name of the desired template. /// </param> /// <param name="encoding">Character encoding of the template /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// /// </returns> Template getTemplate(String name, String encoding); /// <summary> Returns a static content resource from the /// resource manager. Uses the current value /// if INPUT_ENCODING as the character encoding. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> ContentResource getContent(String name); /// <summary> Returns a static content resource from the /// resource manager. /// * /// </summary> /// <param name="name">Name of content resource to get /// </param> /// <param name="encoding">Character encoding to use /// </param> /// <returns>parsed ContentResource object ready for use /// @throws ResourceNotFoundException if template not found /// from any available source. /// /// </returns> ContentResource getContent(String name, String encoding); /// <summary> Determines is a template exists, and returns name of the loader that /// provides it. This is a slightly less hokey way to support /// the Velocity.templateExists() utility method, which was broken /// when per-template encoding was introduced. We can revisit this. /// * /// </summary> /// <param name="resourceName">Name of template or content resource /// </param> /// <returns>class name of loader than can provide it /// /// </returns> String getLoaderNameForResource(String resourceName); /// <summary> Log a warning message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void warn(Object message); /// /// <summary> Log an info message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void info(Object message); /// <summary> Log an error message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void error(Object message); /// <summary> Log a debug message. /// * /// </summary> /// <param name="Object">message to log /// /// </param> void debug(Object message); /// <summary> String property accessor method with default to hide the /// configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="String">defaultValue default value to return if key not /// found in resource manager. /// </param> /// <returns>String value of key or default /// /// </returns> String getString(String key, String defaultValue); /// <summary> Returns the appropriate VelocimacroProxy object if strVMname /// is a valid current Velocimacro. /// * /// </summary> /// <param name="String">vmName Name of velocimacro requested /// </param> /// <returns>String VelocimacroProxy /// /// </returns> Directive.Directive getVelocimacro(String vmName, String templateName); /// <summary> Adds a new Velocimacro. Usually called by Macro only while parsing. /// * /// </summary> /// <param name="String">name Name of velocimacro /// </param> /// <param name="String">macro String form of macro body /// </param> /// <param name="String">argArray Array of strings, containing the /// #macro() arguments. the 0th is the name. /// </param> /// <returns>boolean True if added, false if rejected for some /// reason (either parameters or permission settings) /// /// </returns> bool addVelocimacro(String name, String macro, String[] argArray, String sourceTemplate); /// <summary> Checks to see if a VM exists /// * /// </summary> /// <param name="name"> Name of velocimacro /// </param> /// <returns>boolean True if VM by that name exists, false if not /// /// </returns> bool isVelocimacro(String vmName, String templateName); /// <summary> tells the vmFactory to dump the specified namespace. This is to support /// clearing the VM list when in inline-VM-local-scope mode /// </summary> bool dumpVMNamespace(String namespace_Renamed); /// <summary> String property accessor method to hide the configuration implementation /// </summary> /// <param name="key"> property key /// </param> /// <returns> value of key or null /// /// </returns> String getString(String key); /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="String">key property key /// </param> /// <returns>int value /// /// </returns> int getInt(String key); /// <summary> Int property accessor method to hide the configuration implementation. /// * /// </summary> /// <param name="key"> property key /// </param> /// <param name="int">default value /// </param> /// <returns>int value /// /// </returns> int getInt(String key, int defaultValue); /// <summary> Boolean property accessor method to hide the configuration implementation. /// /// </summary> /// <param name="String">key property key /// </param> /// <param name="boolean">default default value if property not found /// </param> /// <returns>boolean value of key or default value /// /// </returns> bool getBoolean(String key, bool def); /// <summary> Return the velocity runtime configuration object. /// * /// </summary> /// <returns>ExtendedProperties configuration object which houses /// the velocity runtime properties. /// /// </returns> /* * Return this instance's Introspector */ /* * Return the specified applcation attribute */ Object getApplicationAttribute(Object key); } } --- NEW FILE: RuntimeInstance.cs --- namespace NVelocity.Runtime { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using NVelocity.Runtime.Resource.Loader; using NVelocity.Util; using NVelocity.Util.Introspection; /// <summary> This is the Runtime system for Velocity. It is the /// single access point for all functionality in Velocity. /// It adheres to the mediator pattern and is the only /// structure that developers need to be familiar with /// in order to get Velocity to perform. /// * /// The Runtime will also cooperate with external [...1021 lines suppressed...] /// <summary> Return the velocity runtime configuration object. /// * /// </summary> /// <returns>ExtendedProperties configuration object which houses /// the velocity runtime properties. /// /// </returns> /// <summary> Return the Introspector for this instance /// </summary> public virtual Object getApplicationAttribute(Object key) { return applicationAttributes[key]; } public virtual Object setApplicationAttribute(Object key, Object o) { return applicationAttributes[key] = o; } } } --- NEW FILE: VelocimacroManager.cs --- namespace NVelocity.Runtime { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER C... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:11
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Web/Html/XPath In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Web/Html/XPath Added Files: Header.cs HtmlAttribute.cs HtmlDocument.cs HtmlEntity.cs HtmlNode.cs HtmlNodeNavigator.cs HtmlWeb.cs MixedCodeDocument.cs ParseReader.cs crc32.cs readme.txt tools.cs Log Message: --- NEW FILE: HtmlWeb.cs --- // HtmlAgilityPack V1.0 - Simon Mourier <si...@mi...> using System; using System.IO; using System.Net; using System.Xml; using System.Xml.Serialization; using System.Xml.Xsl; using Microsoft.Win32; namespace Adapdev.Web.Html.XPath { /// <summary> /// A utility class to get HTML document from HTTP. /// </summary> public class HtmlWeb { /// <summary> /// Represents the method that will handle the PreRequest event. /// </summary> public delegate bool PreRequestHandler(HttpWebRequest request); /// <summary> /// Represents the method that will handle the PostResponse event. /// </summary> public delegate void PostResponseHandler(HttpWebRequest request, HttpWebResponse response); /// <summary> /// Represents the method that will handle the PreHandleDocument event. /// </summary> public delegate void PreHandleDocumentHandler(HtmlDocument document); private int _streamBufferSize = 1024; private string _cachePath; private bool _usingCache; private bool _fromCache; private bool _cacheOnly; private bool _useCookies; private int _requestDuration; private bool _autoDetectEncoding = true; private HttpStatusCode _statusCode = HttpStatusCode.OK; private Uri _responseUri; /// <summary> /// Occurs before an HTTP request is executed. /// </summary> public PreRequestHandler PreRequest; /// <summary> /// Occurs after an HTTP request has been executed. /// </summary> public PostResponseHandler PostResponse; /// <summary> /// Occurs before an HTML document is handled. /// </summary> public PreHandleDocumentHandler PreHandleDocument; /// <summary> /// Creates an instance of an HtmlWeb class. /// </summary> public HtmlWeb() { } /// <summary> /// Gets an HTML document from an Internet resource and saves it to the specified file. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="path">The location of the file where you want to save the document.</param> public void Get(string url, string path) { Get(url, path, "GET"); } /// <summary> /// Gets an HTML document from an Internet resource and saves it to the specified file. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="path">The location of the file where you want to save the document.</param> /// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param> public void Get(string url, string path, string method) { Uri uri = new Uri(url); if ((uri.Scheme == Uri.UriSchemeHttps) || (uri.Scheme == Uri.UriSchemeHttp)) { Get(uri, method, path, null); } else { throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'."); } } /// <summary> /// Gets an HTML document from an Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <returns>A new HTML document.</returns> public HtmlDocument Load(string url) { return Load(url, "GET"); } /// <summary> /// Loads an HTML document from an Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param> /// <returns>A new HTML document.</returns> public HtmlDocument Load(string url, string method) { Uri uri = new Uri(url); HtmlDocument doc; if ((uri.Scheme == Uri.UriSchemeHttps) || (uri.Scheme == Uri.UriSchemeHttp)) { doc = LoadUrl(uri, method); } else { if (uri.Scheme == Uri.UriSchemeFile) { doc = new HtmlDocument(); doc.OptionAutoCloseOnEnd = false; doc.OptionAutoCloseOnEnd = true; doc.DetectEncodingAndLoad(url, _autoDetectEncoding); } else { throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'."); } } if (PreHandleDocument != null) { PreHandleDocument(doc); } return doc; } private bool IsCacheHtmlContent(string path) { string ct = GetContentTypeForExtension(Path.GetExtension(path), null); return IsHtmlContent(ct); } private bool IsHtmlContent(string contentType) { return contentType.ToLower().StartsWith("text/html"); } private string GetCacheHeadersPath(Uri uri) { //return Path.Combine(GetCachePath(uri), ".h.xml"); return GetCachePath(uri) + ".h.xml"; } /// <summary> /// Gets the cache file path for a specified url. /// </summary> /// <param name="uri">The url fo which to retrieve the cache path. May not be null.</param> /// <returns>The cache file path.</returns> public string GetCachePath(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (!UsingCache) { throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first."); } string cachePath; if (uri.AbsolutePath == "/") { cachePath = Path.Combine(_cachePath, ".htm"); } else { cachePath = Path.Combine(_cachePath, (uri.Host + uri.AbsolutePath).Replace('/', '\\')); } return cachePath; } /// <summary> /// Gets a value indicating if the last document was retrieved from the cache. /// </summary> public bool FromCache { get { return _fromCache; } } /// <summary> /// Gets the URI of the Internet resource that actually responded to the request. /// </summary> public Uri ResponseUri { get { return _responseUri; } } /// <summary> /// Gets or Sets a value indicating whether to get document only from the cache. /// If this is set to true and document is not found in the cache, nothing will be loaded. /// </summary> public bool CacheOnly { get { return _cacheOnly; } set { if ((value) && !UsingCache) { throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first."); } _cacheOnly = value; } } /// <summary> /// Gets or Sets a value indicating if cookies will be stored. /// </summary> public bool UseCookies { get { return _useCookies; } set { _useCookies = value; } } /// <summary> /// Gets the last request duration in milliseconds. /// </summary> public int RequestDuration { get { return _requestDuration; } } /// <summary> /// Gets or Sets a value indicating if document encoding must be automatically detected. /// </summary> public bool AutoDetectEncoding { get { return _autoDetectEncoding; } set { _autoDetectEncoding = value; } } /// <summary> /// Gets the last request status. /// </summary> public HttpStatusCode StatusCode { get { return _statusCode; } } /// <summary> /// Gets or Sets the size of the buffer used for memory operations. /// </summary> public int StreamBufferSize { get { return _streamBufferSize; } set { if (_streamBufferSize <= 0) { throw new ArgumentException("Size must be greater than zero."); } _streamBufferSize = value; } } private HtmlDocument LoadUrl(Uri uri, string method) { HtmlDocument doc = new HtmlDocument(); doc.OptionAutoCloseOnEnd = false; doc.OptionFixNestedTags = true; _statusCode = Get(uri, method, null, doc); if (_statusCode == HttpStatusCode.NotModified) { // read cached encoding doc.DetectEncodingAndLoad(GetCachePath(uri)); } return doc; } private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc) { string cachePath = null; HttpWebRequest req; bool oldFile = false; req = WebRequest.Create(uri) as HttpWebRequest; req.Method = method; _fromCache = false; _requestDuration = 0; int tc = Environment.TickCount; if (UsingCache) { cachePath = GetCachePath(req.RequestUri); if (File.Exists(cachePath)) { req.IfModifiedSince = File.GetLastAccessTime(cachePath); oldFile = true; } } if (_cacheOnly) { if (!File.Exists(cachePath)) { throw new HtmlWebException("File was not found at cache path: '" + cachePath + "'"); } if (path != null) { IOLibrary.CopyAlways(cachePath, path); // touch the file File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } _fromCache = true; return HttpStatusCode.NotModified; } if (_useCookies) { req.CookieContainer = new CookieContainer(); } if (PreRequest != null) { // allow our user to change the request at will if (!PreRequest(req)) { return HttpStatusCode.ResetContent; } // dump cookie // if (_useCookies) // { // foreach(Cookie cookie in req.CookieContainer.GetCookies(req.RequestUri)) // { // HtmlLibrary.Trace("Cookie " + cookie.Name + "=" + cookie.Value + " path=" + cookie.Path + " domain=" + cookie.Domain); // } // } } HttpWebResponse resp; try { resp = req.GetResponse() as HttpWebResponse; } catch (WebException we) { _requestDuration = Environment.TickCount - tc; resp = (HttpWebResponse)we.Response; if (resp == null) { if (oldFile) { if (path != null) { IOLibrary.CopyAlways(cachePath, path); // touch the file File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } return HttpStatusCode.NotModified; } throw; } } catch(Exception) { _requestDuration = Environment.TickCount - tc; throw; } // allow our user to get some info from the response if (PostResponse != null) { PostResponse(req, resp); } _requestDuration = Environment.TickCount - tc; _responseUri = resp.ResponseUri; bool html = IsHtmlContent(resp.ContentType); System.Text.Encoding respenc; if ((resp.ContentEncoding != null) && (resp.ContentEncoding.Length>0)) { respenc = System.Text.Encoding.GetEncoding(resp.ContentEncoding); } else { respenc = null; } if (resp.StatusCode == HttpStatusCode.NotModified) { if (UsingCache) { _fromCache = true; if (path != null) { IOLibrary.CopyAlways(cachePath, path); // touch the file File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } return resp.StatusCode; } else { // this should *never* happen... throw new HtmlWebException("Server has send a NotModifed code, without cache enabled."); } } Stream s = resp.GetResponseStream(); if (s != null) { if (UsingCache) { // NOTE: LastModified does not contain milliseconds, so we remove them to the file SaveStream(s, cachePath, RemoveMilliseconds(resp.LastModified), _streamBufferSize); // save headers SaveCacheHeaders(req.RequestUri, resp); if (path != null) { // copy and touch the file IOLibrary.CopyAlways(cachePath, path); File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } } else { // try to work in-memory if ((doc != null) && (html)) { if (respenc != null) { doc.Load(s,respenc); } else { doc.Load(s); } } } resp.Close(); } return resp.StatusCode; } private string GetCacheHeader(Uri requestUri, string name, string def) { // note: some headers are collection (ex: www-authenticate) // we don't handle that here XmlDocument doc = new XmlDocument(); doc.Load(GetCacheHeadersPath(requestUri)); XmlNode node = doc.SelectSingleNode("//h[translate(@n, 'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='" + name.ToUpper() + "']"); if (node == null) { return def; } // attribute should exist return node.Attributes[name].Value; } private void SaveCacheHeaders(Uri requestUri, HttpWebResponse resp) { // we cache the original headers aside the cached document. string file = GetCacheHeadersPath(requestUri); XmlDocument doc = new XmlDocument(); doc.LoadXml("<c></c>"); XmlNode cache = doc.FirstChild; foreach(string header in resp.Headers) { XmlNode entry = doc.CreateElement("h"); XmlAttribute att = doc.CreateAttribute("n"); att.Value = header; entry.Attributes.Append(att); att = doc.CreateAttribute("v"); att.Value = resp.Headers[header]; entry.Attributes.Append(att); cache.AppendChild(entry); } doc.Save(file); } private static long SaveStream(Stream stream, string path, DateTime touchDate, int streamBufferSize) { FilePreparePath(path); FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryReader br = null; BinaryWriter bw = null; long len; try { br = new BinaryReader(stream); bw = new BinaryWriter(fs); len = 0; byte[] buffer; do { buffer = br.ReadBytes(streamBufferSize); len += buffer.Length; if (buffer.Length>0) { bw.Write(buffer); } } while (buffer.Length>0); } finally { if (br != null) { br.Close(); } if (bw != null) { bw.Flush(); bw.Close(); } if (fs != null) { fs.Close(); } } File.SetLastWriteTime(path, touchDate); return len; } private static void FilePreparePath(string target) { if (File.Exists(target)) { FileAttributes atts = File.GetAttributes(target); File.SetAttributes(target, atts & ~FileAttributes.ReadOnly); } else { string dir = Path.GetDirectoryName(target); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } } private static DateTime RemoveMilliseconds(DateTime t) { return new DateTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second, 0); } /// <summary> /// Gets the path extension for a given MIME content type. /// </summary> /// <param name="contentType">The input MIME content type.</param> /// <param name="def">The default path extension to return if any error occurs.</param> /// <returns>The MIME content type's path extension.</returns> public static string GetExtensionForContentType(string contentType, string def) { if ((contentType == null) || (contentType.Length == 0)) { return def; } string ext; try { RegistryKey reg = Registry.ClassesRoot; reg = reg.OpenSubKey(@"MIME\Database\Content Type\" + contentType, false); ext = (string)reg.GetValue("Extension", def); } catch(Exception) { ext = def; } return ext; } /// <summary> /// Gets the MIME content type for a given path extension. /// </summary> /// <param name="extension">The input path extension.</param> /// <param name="def">The default content type to return if any error occurs.</param> /// <returns>The path extention's MIME content type.</returns> public static string GetContentTypeForExtension(string extension, string def) { if ((extension == null) || (extension.Length == 0)) { return def; } string contentType; try { RegistryKey reg = Registry.ClassesRoot; reg = reg.OpenSubKey(extension, false); contentType = (string)reg.GetValue("", def); } catch(Exception) { contentType = def; } return contentType; } /// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> public void LoadHtmlAsXml(string htmlUrl, XmlTextWriter writer) { HtmlDocument doc = Load(htmlUrl); doc.Save(writer); } /// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer) { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, null); } /// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp". May not be null.</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param> public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer, string xmlPath) { if (htmlUrl == null) { throw new ArgumentNullException("htmlUrl"); } HtmlDocument doc = Load(htmlUrl); if (xmlPath != null) { XmlTextWriter w = new XmlTextWriter(xmlPath, doc.Encoding); doc.Save(w); w.Close(); } if (xsltArgs == null) { xsltArgs = new XsltArgumentList(); } // add some useful variables to the xslt doc xsltArgs.AddParam("url", "", htmlUrl); xsltArgs.AddParam("requestDuration", "", RequestDuration); xsltArgs.AddParam("fromCache", "", FromCache); XslTransform xslt = new XslTransform(); xslt.Load(xsltUrl); xslt.Transform(doc, xsltArgs, writer, null); } /// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="type">The requested type.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string url, Type type) { return CreateInstance(url, null, null, type); } /// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="type">The requested type.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type) { return CreateInstance(htmlUrl, xsltUrl, xsltArgs, type, null); } /// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="type">The requested type.</param> /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type, string xmlPath) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); if (xsltUrl == null) { LoadHtmlAsXml(htmlUrl, writer); } else { if (xmlPath == null) { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer); } else { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath); } } writer.Flush(); StringReader sr = new StringReader(sw.ToString()); XmlTextReader reader = new XmlTextReader(sr); XmlSerializer serializer = new XmlSerializer(type); object o = null; try { o = serializer.Deserialize(reader); } catch(InvalidOperationException ex) { throw new Exception(ex.ToString() + ", --- xml:" + sw.ToString()); } return o; } /// <summary> /// Gets or Sets the cache path. If null, no caching mechanism will be used. /// </summary> public string CachePath { get { return _cachePath; } set { _cachePath = value; } } /// <summary> /// Gets or Sets a value indicating whether the caching mechanisms should be used or not. /// </summary> public bool UsingCache { get { if (_cachePath == null) { return false; } return _usingCache; } set { if ((value) && (_cachePath == null)) { throw new HtmlWebException("You need to define a CachePath first."); } _usingCache = value; } } } /// <summary> /// Represents an exception thrown by the HtmlWeb utility class. /// </summary> public class HtmlWebException: Exception { /// <summary> /// Creates an instance of the HtmlWebException. /// </summary> /// <param name="message">The exception's message.</param> public HtmlWebException(string message) :base(message) { } } } --- NEW FILE: HtmlNodeNavigator.cs --- // HtmlAgilityPack V1.0 - Simon Mourier <si...@mi...> using System; using System.Diagnostics; using System.Collections.Specialized; using System.IO; using System.Text; using System.Xml; using System.Xml.XPath; namespace Adapdev.Web.Html.XPath { internal class HtmlNameTable: XmlNameTable { private NameTable _nametable = new NameTable(); internal HtmlNameTable() { } internal string GetOrAdd(string array) { string s = Get(array); if (s == null) { return Add(array); } return s; } public override string Add(string array) { return _nametable.Add(array); } public override string Get(string array) { return _nametable.Get(array); } public override string Get(char[] array, int offset, int length) { return _nametable.Get(array, offset, length); } public override string Add(char[] array, int offset, int length) { return _nametable.Add(array, offset, length); } } /// <summary> /// Represents an HTML navigator on an HTML document seen as a data store. /// </summary> public class HtmlNodeNavigator: XPathNavigator { private HtmlDocument _doc = new HtmlDocument(); private HtmlNode _currentnode; private int _attindex; private HtmlNameTable _nametable = new HtmlNameTable(); internal bool Trace = false; internal HtmlNodeNavigator() { Reset(); } private void Reset() { InternalTrace(null); _currentnode = _doc.DocumentNode; _attindex = -1; } [Conditional("TRACE")] internal void InternalTrace(object Value) { if (!Trace) { return; } string name = null; StackFrame sf = new StackFrame(1, true); name = sf.GetMethod().Name; string nodename; if (_currentnode == null) { nodename = "(null)"; } else { nodename = _currentnode.Name; } string nodevalue; if (_currentnode == null) { nodevalue = "(null)"; } else { switch(_currentnode.NodeType) { case HtmlNodeType.Comment: nodevalue = ((HtmlCommentNode)_currentnode).Comment; break; case HtmlNodeType.Document: nodevalue = ""; break; case HtmlNodeType.Text: nodevalue = ((HtmlTextNode)_currentnode).Text; break; default: nodevalue = _currentnode.CloneNode(false).OuterHtml; break; } } System.Diagnostics.Trace.WriteLine("oid=" + GetHashCode() + ",n=" + nodename + ",a=" + _attindex + "," + ",v=" + nodevalue + "," + Value, "N!"+ name); } internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode) { if (currentNode == null) { throw new ArgumentNullException("currentNode"); } if (currentNode.OwnerDocument != doc) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } InternalTrace(null); _doc = doc; Reset(); _currentnode = currentNode; } private HtmlNodeNavigator(HtmlNodeNavigator nav) { if (nav == null) { throw new ArgumentNullException("nav"); } InternalTrace(null); _doc = nav._doc; _currentnode = nav._currentnode; _attindex = nav._attindex; _nametable = nav._nametable; // REVIEW: should we do this? } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public HtmlNodeNavigator(Stream stream) { _doc.Load(stream); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding) { _doc.Load(stream, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public HtmlNodeNavigator(TextReader reader) { _doc.Load(reader); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public HtmlNodeNavigator(string path) { _doc.Load(path); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(string path, Encoding encoding) { _doc.Load(path, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } /// <summary> /// Gets the name of the current HTML node without the namespace prefix. /// </summary> public override string LocalName { get { if (_attindex != -1) { InternalTrace("att>" + _currentnode.Attributes[_attindex].Name); return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name); } else { InternalTrace("node>" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } } /// <summary> /// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string NamespaceURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the qualified name of the current node. /// </summary> public override string Name { get { InternalTrace(">" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } /// <summary> /// Gets the prefix associated with the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string Prefix { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the type of the current node. /// </summary> public override XPathNodeType NodeType { get { switch(_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + XPathNodeType.Comment); return XPathNodeType.Comment; case HtmlNodeType.Document: InternalTrace(">" + XPathNodeType.Root); return XPathNodeType.Root; case HtmlNodeType.Text: InternalTrace(">" + XPathNodeType.Text); return XPathNodeType.Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + XPathNodeType.Attribute); return XPathNodeType.Attribute; } InternalTrace(">" + XPathNodeType.Element); return XPathNodeType.Element; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the text value of the current node. /// </summary> public override string Value { get { InternalTrace("nt=" + _currentnode.NodeType); switch(_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + ((HtmlCommentNode)_currentnode).Comment); return ((HtmlCommentNode)_currentnode).Comment; case HtmlNodeType.Document: InternalTrace(">"); return ""; case HtmlNodeType.Text: InternalTrace(">" + ((HtmlTextNode)_currentnode).Text); return ((HtmlTextNode)_currentnode).Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + _currentnode.Attributes[_attindex].Value); return _currentnode.Attributes[_attindex].Value; } return _currentnode.InnerText; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the base URI for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string BaseURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the xml:lang scope for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string XmlLang { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets a value indicating whether the current node is an empty element. /// </summary> public override bool IsEmptyElement { get { InternalTrace(">" + !HasChildren); // REVIEW: is this ok? return !HasChildren; } } /// <summary> /// Gets the XmlNameTable associated with this implementation. /// </summary> public override XmlNameTable NameTable { get { InternalTrace(null); return _nametable; } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasAttributes { get { InternalTrace(">" + (_currentnode.Attributes.Count>0)); return (_currentnode.Attributes.Count>0); } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasChildren { get { InternalTrace(">" + (_currentnode.ChildNodes.Count>0)); return (_currentnode.ChildNodes.Count>0); } } /// <summary> /// Moves to the next sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns> public override bool MoveToNext() { if (_currentnode.NextSibling == null) { InternalTrace(">false"); return false; } InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml); InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml); _currentnode = _currentnode.NextSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the previous sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToPrevious() { if (_currentnode.PreviousSibling == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.PreviousSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToFirst() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } if (_currentnode.ParentNode.FirstChild == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode.FirstChild; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first child of the current node. /// </summary> /// <returns>true if there is a first child node, otherwise false.</returns> public override bool MoveToFirstChild() { if (!_currentnode.HasChildNodes) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ChildNodes[0]; InternalTrace(">true"); return true; } /// <summary> /// Moves to the parent of the current node. /// </summary> /// <returns>true if there is a parent node, otherwise false.</returns> public override bool MoveToParent() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode; InternalTrace(">true"); return true; } /// <summary> /// Moves to the root node to which the current node belongs. /// </summary> public override void MoveToRoot() { _currentnode = _doc.DocumentNode; InternalTrace(null); } /// <summary> /// Moves to the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param> /// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveTo(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false (nav is not an HtmlNodeNavigator)"); return false; } InternalTrace("moveto oid=" + nav.GetHashCode() + ", n:" + nav._currentnode.Name + ", a:" + nav._attindex); if (nav._doc == _doc) { _currentnode = nav._currentnode; _attindex = nav._attindex; InternalTrace(">true"); return true; } // we don't know how to handle that InternalTrace(">false (???)"); return false; } /// <summary> /// Moves to the node that has an attribute of type ID whose value matches the specified string. /// </summary> /// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param> /// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveToId(string id) { InternalTrace("id=" + id); HtmlNode node = _doc.GetElementbyId(id); if (node == null) { InternalTrace(">false"); return false; } _currentnode = node; InternalTrace(">true"); return true; } /// <summary> /// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator that you want to compare against.</param> /// <returns>true if the two navigators have the same position, otherwise, false.</returns> public override bool IsSamePosition(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false"); return false; } InternalTrace(">" + (nav._currentnode == _currentnode)); return (nav._currentnode == _currentnode); } /// <summary> /// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator. /// </summary> /// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns> public override XPathNavigator Clone() { InternalTrace(null); return new HtmlNodeNavigator(this); } /// <summary> /// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns> public override string GetAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); HtmlAttribute att = _currentnode.Attributes[localName]; if (att == null) { InternalTrace(">null"); return null; } InternalTrace(">" + att.Value); return att.Value; } /// <summary> /// Moves to the HTML attribute with matching LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns> public override bool MoveToAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); int index = _currentnode.Attributes.GetAttributeIndex(localName); if (index == -1) { InternalTrace(">false"); return false; } _attindex = index; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first HTML attribute. /// </summary> /// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns> public override bool MoveToFirstAttribute() { if (!HasAttributes) { InternalTrace(">false"); return false; } _attindex = 0; InternalTrace(">true"); return true; } /// <summary> /// Moves to the next HTML attribute. /// </summary> /// <returns></returns> public override bool MoveToNextAttribute() { InternalTrace(null); if (_attindex>=(_currentnode.Attributes.Count-1)) { InternalTrace(">false"); return false; } _attindex++; InternalTrace(">true"); return true; } /// <summary> /// Returns the value of the namespace node corresponding to the specified local name. /// Always returns string.Empty for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns> public override string GetNamespace(string name) { InternalTrace("name=" + name); return string.Empty; } /// <summary> /// Moves the XPathNavigator to the namespace node with the specified local name. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNamespace(string name) { InternalTrace("name=" + name); return false; } /// <summary> /// Moves the XPathNavigator to the first namespace node of the current element. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Moves the XPathNavigator to the next namespace node. /// Always returns falsefor the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Gets the current HTML node. /// </summary> public HtmlNode CurrentNode { get { return _currentnode; } } /// <summary> /// Gets the current HTML document. /// </summary> public HtmlDocument CurrentDocument { get { return _doc; } } } } --- NEW FILE: HtmlNode.cs --- // HtmlAgilityPack V1.0 - Simon Mourier <si...@mi...> using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.XPath; namespace Adapdev.Web.Html.XPath { /// <summary> /// Flags that describe the behavior of an Element node. /// </summary> public enum HtmlElementFlag { /// <summary> /// The node is a CDATA node. /// </summary> CData = 1, [...2220 lines suppressed...] /// Gets or Sets the comment text of the node. /// </summary> public string Comment { get { if (_comment == null) { return base.InnerHtml; } return _comment; } set { _comment = value; } } } } --- NEW FILE: HtmlAttribute.cs --- // HtmlAgilityPack V1.0 - Simon Mourier <si...@mi...> using System; using System.Collections; namespace Adapdev.Web.Html.XPath { /// <summary> /// Represents an HTML attribute. /// </summary> public class HtmlAttribute: IComparable { internal int _line = 0; internal int _lineposition = 0; internal int _streamposition = 0; internal int _namestartindex = 0; internal int _namelength = 0; internal int _valuestartindex = 0; internal int _valuelength = 0; internal HtmlDocument _ownerdocument; // attribute can exists without a node internal HtmlNode _ownernode; internal string _name; internal string _value; internal HtmlAttribute(HtmlDocument ownerdocument) { _ownerdocument = ownerdocument; } /// <summary> /// Creates a duplicate of this attribute. /// </summary> /// <returns>The cloned attribute.</returns> public HtmlAttribute Clone() { HtmlAttribute att = new HtmlAttribute(_ownerdocument); att.Name = Name; att.Value = Value; return att; } /// <summary> /// Compares the current instance with another attribute. Comparison is based on attributes' name. /// </summary> /// <param name="obj">An attribute to compare with this instance.</param> /// <returns>A 32-bit signed integer that indicates the relative order of the names comparison.</returns> public int CompareTo(object obj) { HtmlAttribute att = obj as HtmlAttribute; if (att == null) { throw new ArgumentException("obj"); } return Name.CompareTo(att.Name); } internal string XmlName { get { return HtmlDocument.GetXmlName(Name); } } internal string XmlValue { get { return Value; } } /// <summary> /// Gets the qualified name of the attribute. /// </summary> public string Name { get { if (_name == null) { _name = _ownerdocument._text.Substring(_namestartindex, _namelength).ToLower(); } return _name; } set { if (value == null) { throw new ArgumentNullException("value"); } _name = value.ToLower(); if (_ownernode != null) { _ownernode._innerchanged = true; _ownernode._outerchanged = true; } } } /// <summary> /// Gets or sets the value of the attribute. /// </summary> public string Value { get { if (_value == null) { _value = _ownerdocument._text.Substring(_valuestartindex, _valuelength); } return _value; } set { _value = value; if (_ownernode != null) { _ownernode._innerchanged = true; _ownernode._outerchanged = true; } } } /// <summary> /// Gets the line number of this attribute in the document. /// </summary> public int Line { get { return _line; } } /// <summary> /// Gets the column number of this attribute in the document. /// </summary> public int LinePosition { get { return _lineposition; } } /// <summary> /// Gets the stream position of this attribute in the document, relative to the start of the document. /// </summary> public int StreamPosition { get { return _streamposition; } } /// <summary> /// Gets the HTML node to which this attribute belongs. /// </summary> public HtmlNode OwnerNode { get { return _ownernode; } } /// <summary> /// Gets the HTML document to which this attribute belongs. /// </summary> public HtmlDocument OwnerDocument { get { return _ownerdocument; } } } /// <summary> /// Represents a combined list and collection of HTML nodes. /// </summary> public class HtmlAttributeCollection: IEnumerable { internal Hashtable _hashitems = new Hashtable(); private ArrayList _items = new ArrayList(); private HtmlNode _ownernode; internal HtmlAttributeCollection(HtmlNode ownernode) { _ownernode = ownernode; } /// <summary> /// Inserts the specified attribute as the last attribute in the collection. /// </summary> /// <param name="newAttribute">The attribute to insert. May not be null.</param> /// <returns>The appended attribute.</returns> public HtmlAttribute Append(HtmlAttribute newAttribute) { if (newAttribute == null) { throw new ArgumentNullException("newAttribute"); } _hashitems[newAttribute.Name] = newAttribute; newAttribute._ownernode = _ownernode; _items.Add(newAttribute); _ownernode._innerchanged = true; _ownernode._outerchanged = true; return newAttribute; } /// <summary> /// Creates and inserts a new attribute as the last attribute in the collection. /// </summary> /// <param name="name">The name of the attribute to insert.</param> /// <returns>The appended attribute.</returns> public HtmlAttribute Append(string name) { HtmlAttribute att = _ownernode._ownerdocument.CreateAttribute(name); return Append(att); } /// <summary> /// Creates and inserts a new attribute as the last attribute in the collection. /// </summary> /// <param name="name">The name of the attribute to insert.</param> /// <param name="value">The value of the attribute to insert.</param> /// <returns>The appended attribute.</returns> public HtmlAttribute Append(string name, string value) { HtmlAttribute att = _ownernode._ownerdocument.CreateAttribute(name, value); return Append(att); } /// <summary> /// Inserts the specified attribute as the first node in the collection. /// </summary> /// <param name="newAttribute">The attribute to insert. May not be null.</param> /// <returns>The prepended attribute.</returns> public HtmlAttribute Prepend(HtmlAttribute newAttribute) { if (newAttribute == null) { throw new ArgumentNullException("newAttribute"); } _hashitems[newAttribute.Name] = newAttribute; newAttribute._ownernode = _ownernode; _items.Insert(0, newAttribute); _ownernode._innerchanged = true; _ownernode._outerchanged = true; return newAttribute; } /// <summary> /// Removes the attribute at the specified index. /// </summary> /// <param name="index">The index of the attribute to remove.</param> public void RemoveAt(int index) { HtmlAttribute att = (HtmlAttribute)_items[index]; _hashitems.Remove(att.Name); _items.RemoveAt(index); _ownernode._innerchanged = true; _ownernode._outerchanged = true; } /// <summary> /// Removes a given attribute from the list. /// </summary> /// <param name="attribute">The attribute to remove. May not be null.</param> public void Remove(HtmlAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } int index = GetAttributeIndex(attribute); if (index == -1) { throw new IndexOutOfRangeException(); } RemoveAt(index); } /// <summary> /// Removes an attribute from the list, using its name. If there are more than one attributes with this name, they will all be removed. /// </summary> /// <param name="name">The attribute's name. May not be null.</param> public void Remove(string name) { if (name == null) { throw new ArgumentNullException("name"); } string lname = name.ToLower(); for(int i=0;i<_items.Count;i++) { HtmlAttribute att = (HtmlAttribute)_items[i]; if (att.Name == lname) { RemoveAt(i); } } } /// <summary> /// Remove all attributes in the list. /// </summary> public void RemoveAll() { _hashitems.Clear(); _items.Clear(); _ownernode._innerchanged = true; _ownernode._outerchanged = true; } /// <summary> /// Gets the number of elements actually contained in the list. /// </summary> public int Count { get { return _items.Count; } } internal int GetAttributeIndex(HtmlAttribute attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } for(int i=0;i<_items.Count;i++) { if (((HtmlAttribute)_items[i])==attribute) return i; } return -1; } internal int GetAttributeIndex(string name) { if (name == null) { throw new ArgumentNullException("name"); } string lname = name.ToLower(); for(int i=0;i<_items.Count;i++) { if (((HtmlAttribute)_items[i]).Name==lname) return i; } return -1; } /// <summary> /// Gets a given attribute from the list using its name. /// </summary> public HtmlAttribute this[string name] { get { if (name == null) { throw new ArgumentNullException("name"); } return _hashitems[name.ToLower()] as HtmlAttribute; } } /// <summary> /// Gets the attribute at the specified index. /// </summary> public HtmlAttribute this[int index] { get { return _items[index] as HtmlAttribute; } } internal void Clear() { _hashitems.Clear(); _items.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the list. /// </summary> /// <returns>An IEnumerator for the entire list.</returns> public HtmlAttributeEnumerator GetEnumerator() { return new HtmlAttributeEnumerator(_items); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Represents an enumerator that can iterate through the list. /// </summary> public class HtmlAttributeEnumerator: IEnumerator { int _index; ArrayList _items; internal HtmlAttributeEnumerator(ArrayList items) { _items = items; _index = -1; } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> public void Reset() { _index = -1; } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns>true if the enumerator was successfully advanced to the next element, false if the enumerator has passed the end of the collection.</returns> public bool MoveNext() { _index++; return (_index<_items.Count); } /// <summary> /// Gets the current element in the collection. /// </summary> public HtmlAttribute Current { get { return (HtmlAttribute)(_items[_index]); } } /// <summary> /// Gets the current element in the collection. /// </summary> object IEnumerator.Current { get { return (Current); } } } } } --- NEW FILE: HtmlDocument.cs --- // HtmlAgilityPack V1.0 - Simon Mourier <si...@mi...> using System; using System.IO; using System.Text; using System.Diagnostics; using System.Collections; using System.Text.RegularExpressions; using System.Xml; using System.Xml.XPath; namespace Adapdev.Web.Html.XPath { /// <summary> /// Represents the type of parsing error. /// </summary> public enum HtmlParseErrorCode { /// <summary> /// A tag was not closed. [...2040 lines suppressed...] } internal class EncodingFoundException: Exception { private Encoding _encoding; internal EncodingFoundException(Encoding encoding) { _encoding = encoding; } internal Encoding Encoding { get { return _encoding; } } } } --- NEW FILE: HtmlEntity.cs --- // HtmlAgilityPack V1.0 - Simon Mourier <si...@mi...> using System; using System.Collections; using System.Text; namespace Adapdev.Web.Html.XPath { /// <summary> /// A utility class to replace special characters by entities and vice-versa. /// Follows HTML 4.0 specification found at http://www.w3.org/TR/html4/sgml/entities.html /// </summary> public class HtmlEntity { private static Hashtable _entityName; private static Hashtable _entityValue; private static readonly int _maxEntitySize; private HtmlEntity() { } static HtmlEntity() { _entityName = new Hashtable(); _entityValue = new Hashtable(); #region Entities Definition _entityValue.Add("nbsp", 160); // no-break space = non-breaking space, U+00A0 ISOnum _entityName.Add(160, "nbsp"); _entityValue.Add("iexcl", 161); // inverted exclamation mark, U+00A1 ISOnum _entityName.Add(161, "iexcl"); _entityValue.Add("cent", 162); // cent sign, U+00A2 ISOnum _entityName.Add(162, "cent"); _entityValue.Add("pound", 163); // pound sign, U+00A3 ISOnum _entityName.Add(163, "pound"); _entityValue.Add("curren", 164); // currency sign, U+00A4 ISOnum _entityName.Add(164, "curren"); _entityValue.Add("yen", 165); // yen sign = yuan sign, U+00A5 ISOnum _entityName.Add(165, "yen"); _entityValue.Add("brvbar", 166); // broken bar = broken vertical bar, U+00A6 ISOnum _entityName.Add(166, "brvbar"); _entityValue.Add("sect", 167); // section sign, U+00A7 ISOnum _entityName.Add(167, "sect"); _entityValue.Add("uml", 168); // diaeresis = spacing diaeresis, U+00A8 ISOdia _entityName.Add(168, "uml"); _entityValue.Add("copy", 169); // copyright sign, U+00A9 ISOnum _entityName.Add(169, "copy"); _entityValue.Add("ordf", 170); // feminine ordinal indicator, U+00AA ISOnum _entityName.Add(170, "ordf"); _entityValue.Add("laquo", 171); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum _entityName.Add(171, "laquo"); _entityValue.Add("not", 172); // not sign, U+00AC ISOnum _entityName.Add(172, "not"); _entityValue.Add("shy", 173); // soft hyphen = discretionary hyphen, U+00AD ISOnum _entityName.Add(173, "shy"); _entityValue.Add("reg", 174); // registered sign = registered trade mark sign, U+00AE ISOnum _entityName.Add(174, "reg"); _entityValue.Add("macr", 175); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia _entityName.Add(175, "macr"); _entityValue.Add("deg", 176); // degree sign, U+00B0 ISOnum _entityName.Add(176, "deg"); _entityValue.Add("plusmn", 177); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum _entityName.Add(177, "plusmn"); _entityValue.Add("sup2", 178); // superscript two = superscript digit two = squared, U+00B2 ISOnum _entityName.Add(178, "sup2"); _entityValue.Add("sup3", 179); // superscript three = superscript digit three = cubed, U+00B3 ISOnum _entityName.Add(179, "sup3"); _entityValue.Add("acute", 180); // acute accent = spacing acute, U+00B4 ISOdia _entityName.Add(180, "acute"); _entityValue.Add("micro", 181); // micro sign, U+00B5 ISOnum _entityName.Add(181, "micro"); _entityValue.Add("para", 1... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:11
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Visitor In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Visitor Added Files: BaseVisitor.cs NodeViewMode.cs VMReferenceMungeVisitor.cs Log Message: --- NEW FILE: NodeViewMode.cs --- namespace NVelocity.Runtime.Visitor { using System; using System.Text; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> This class is simply a visitor implementation /// that traverses the AST, produced by the Velocity /// parsing process, and creates a visual structure /// of the AST. This is primarily used for /// debugging, but it useful for documentation /// as well. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: NodeViewMode.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class NodeViewMode : BaseVisitor { private int indent = 0; private bool showTokens = true; /// <summary>Indent child nodes to help visually identify /// the structure of the AST. /// </summary> private String indentString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.Append(" "); } return sb.ToString(); } /// <summary> Display the type of nodes and optionally the /// first token. /// </summary> private Object showNode(INode node, Object data) { String tokens = ""; String special = ""; Token t; if (showTokens) { t = node.FirstToken; if (t.specialToken != null && !t.specialToken.image.StartsWith("##")) special = t.specialToken.image; tokens = " -> " + special + t.image; } Console.Out.WriteLine(indentString() + node + tokens); ++indent; data = node.childrenAccept(this, data); --indent; return data; } /// <summary>Display a SimpleNode /// </summary> public override Object visit(SimpleNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTprocess node /// </summary> public override Object visit(ASTprocess node, Object data) { return showNode(node, data); } /// <summary>Display an ASTExpression node /// </summary> public override Object visit(ASTExpression node, Object data) { return showNode(node, data); } /// <summary>Display an ASTAssignment node ( = ) /// </summary> public override Object visit(ASTAssignment node, Object data) { return showNode(node, data); } /// <summary>Display an ASTOrNode ( || ) /// </summary> public override Object visit(ASTOrNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTAndNode ( && ) /// </summary> public override Object visit(ASTAndNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTEQNode ( == ) /// </summary> public override Object visit(ASTEQNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTNENode ( != ) /// </summary> public override Object visit(ASTNENode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTLTNode ( < ) /// </summary> public override Object visit(ASTLTNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTGTNode ( > ) /// </summary> public override Object visit(ASTGTNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTLENode ( <= ) /// </summary> public override Object visit(ASTLENode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTGENode ( >= ) /// </summary> public override Object visit(ASTGENode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTAddNode ( + ) /// </summary> public override Object visit(ASTAddNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTSubtractNode ( - ) /// </summary> public override Object visit(ASTSubtractNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTMulNode ( * ) /// </summary> public override Object visit(ASTMulNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTDivNode ( / ) /// </summary> public override Object visit(ASTDivNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTModNode ( % ) /// </summary> public override Object visit(ASTModNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTNotNode ( ! ) /// </summary> public override Object visit(ASTNotNode node, Object data) { return showNode(node, data); } /// <summary>Display an ASTNumberLiteral node /// </summary> public override Object visit(ASTNumberLiteral node, Object data) { return showNode(node, data); } /// <summary>Display an ASTStringLiteral node /// </summary> public override Object visit(ASTStringLiteral node, Object data) { return showNode(node, data); } /// <summary>Display an ASTIdentifier node /// </summary> public override Object visit(ASTIdentifier node, Object data) { return showNode(node, data); } /// <summary>Display an ASTMethod node /// </summary> public override Object visit(ASTMethod node, Object data) { return showNode(node, data); } /// <summary>Display an ASTReference node /// </summary> public override Object visit(ASTReference node, Object data) { return showNode(node, data); } /// <summary>Display an ASTTrue node /// </summary> public override Object visit(ASTTrue node, Object data) { return showNode(node, data); } /// <summary>Display an ASTFalse node /// </summary> public override Object visit(ASTFalse node, Object data) { return showNode(node, data); } /// <summary>Display an ASTBlock node /// </summary> public override Object visit(ASTBlock node, Object data) { return showNode(node, data); } /// <summary>Display an ASTText node /// </summary> public override Object visit(ASTText node, Object data) { return showNode(node, data); } /// <summary>Display an ASTIfStatement node /// </summary> public override Object visit(ASTIfStatement node, Object data) { return showNode(node, data); } /// <summary>Display an ASTElseStatement node /// </summary> public override Object visit(ASTElseStatement node, Object data) { return showNode(node, data); } /// <summary>Display an ASTElseIfStatement node /// </summary> public override Object visit(ASTElseIfStatement node, Object data) { return showNode(node, data); } public override Object visit(ASTObjectArray node, Object data) { return showNode(node, data); } public override Object visit(ASTDirective node, Object data) { return showNode(node, data); } public override Object visit(ASTWord node, Object data) { return showNode(node, data); } public override Object visit(ASTSetDirective node, Object data) { return showNode(node, data); } } } --- NEW FILE: VMReferenceMungeVisitor.cs --- namespace NVelocity.Runtime.Visitor { using System; using System.Collections; using NVelocity.Runtime.Parser.Node; /// <summary> /// This class is a visitor used by the VM proxy to change the /// literal representation of a reference in a VM. The reason is /// to preserve the 'render literal if null' behavior w/o making /// the VMProxy stuff more complicated than it is already. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: VMReferenceMungeVisitor.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $</version> public class VMReferenceMungeVisitor : BaseVisitor { /// <summary> /// Map containing VM arg to instance-use reference /// Passed in with CTOR /// </summary> private Hashtable argmap = null; /// <summary> /// CTOR - takes a map of args to reference /// </summary> public VMReferenceMungeVisitor(Hashtable map) { argmap = map; } /// <summary> /// Visitor method - if the literal is right, will /// set the literal in the ASTReference node /// </summary> /// <param name="node">ASTReference to work on</param> /// <param name="data">Object to pass down from caller</param> public override Object visit(ASTReference node, Object data) { /* * see if there is an override value for this * reference */ String override_Renamed = (String) argmap[node.literal().Substring(1)]; /* * if so, set in the node */ if (override_Renamed != null) { node.Literal = override_Renamed; } /* * feed the children... */ data = node.childrenAccept(this, data); return data; } } } --- NEW FILE: BaseVisitor.cs --- namespace NVelocity.Runtime.Visitor { using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; /// <summary> This is the base class for all visitors. /// For each AST node, this class will provide /// a bare-bones method for traversal. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: BaseVisitor.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public abstract class BaseVisitor : ParserVisitor { public virtual StreamWriter Writer { set { this.writer = value; } } public virtual InternalContextAdapter Context { set { this.context = value; } } /// <summary>Context used during traversal /// </summary> protected internal InternalContextAdapter context; /// <summary>Writer used as the output sink /// </summary> protected internal StreamWriter writer; public virtual Object visit(SimpleNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTprocess node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTExpression node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTAssignment node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTOrNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTAndNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTEQNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTNENode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTLTNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTGTNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTLENode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTGENode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTAddNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTSubtractNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTMulNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTDivNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTModNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTNotNode node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTNumberLiteral node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTStringLiteral node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTIdentifier node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTMethod node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTReference node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTTrue node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTFalse node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTBlock node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTText node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTIfStatement node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTElseStatement node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTElseIfStatement node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTComment node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTObjectArray node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTWord node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTSetDirective node, Object data) { data = node.childrenAccept(this, data); return data; } public virtual Object visit(ASTDirective node, Object data) { data = node.childrenAccept(this, data); return data; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:11
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.Tests Added Files: Adapdev.UnitTest.Tests.csproj AssemblyInfo.cs Class1.cs TestTypeTest.cs Log Message: --- NEW FILE: Adapdev.UnitTest.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{7DC72EED-57C5-43A3-AB03-D456816A6F1A}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.UnitTest.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.UnitTest.Tests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev.UnitTest" Project = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Class1.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: Class1.cs --- using System; namespace Adapdev.UnitTest.Tests { /// <summary> /// Summary description for Class1. /// </summary> public class Class1 { public Class1() { // // TODO: Add constructor logic here // } } } --- NEW FILE: TestTypeTest.cs --- using System; using NUnit.Framework; using Adapdev.UnitTest; namespace Adapdev.UnitTest.Tests { /// <summary> /// Summary description for TestType. /// </summary> /// [TestFixture] public class TestTypeTest { [Test] public void MultipleTestTypes() { TestType tt = TestType.Unit | TestType.Web; Assert.IsTrue((tt & TestType.Unit) > 0, "Should be a unit test."); Assert.IsTrue((tt & TestType.Web) > 0, "Should be a web test."); Assert.IsFalse((tt & TestType.WebUserInterface) > 0, "Should not be a web UI test."); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:10
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Exception In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Exception Added Files: NodeException.cs ReferenceException.cs Log Message: --- NEW FILE: NodeException.cs --- namespace NVelocity.Runtime.Exception { using System; using NVelocity.Runtime.Parser.Node; public class NodeException : Exception { public NodeException(String exceptionMessage, INode node) : base(exceptionMessage + ": " + node.literal() + " [line " + node.Line + ",column " + node.Column + "]") { } } } --- NEW FILE: ReferenceException.cs --- namespace NVelocity.Runtime.Exception { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Runtime.Parser.Node; /// <summary> Exception thrown when a bad reference is found. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ReferenceException.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ /// /// </version> public class ReferenceException : Exception { public ReferenceException(String exceptionMessage, INode node) : base(exceptionMessage + " [line " + node.Line + ",column " + node.Column + "] : " + node.literal() + " is not a valid reference.") { } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:09
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Web/Html In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Web/Html Added Files: HtmlAttribute.cs HtmlComment.cs HtmlDocument.cs HtmlDomainTreeParser.cs HtmlElement.cs HtmlElementClose.cs HtmlHelper.cs HtmlLinearParser.cs HtmlNode.cs HtmlParser.cs HtmlScript.cs HtmlStyleSheet.cs HtmlText.cs SgmlComment.cs Log Message: --- NEW FILE: HtmlParser.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.Text; using System.Web; namespace Adapdev.Web.Html { /// <summary> /// This class is thrown when there is an error parsing the HTML. /// </summary> public class HtmlParserException: Exception { private int mLineNumber; public HtmlParserException(string message,int lineNumber) : base( message ) { mLineNumber = lineNumber; } public override String Message { get { return base.Message + " at line " + mLineNumber; } } } /// <summary> /// This is the base class of any HtmlParser you wish to implement. It handles /// the tag extraction and decoding for you. NB. This class is NOT thread-safe. You /// should not attempt to parse two files at the same time using the same instance /// of a parser. /// </summary> public abstract class HtmlParser { private const int END_OF_FILE = -1; private int mLineNumber; private bool mIgnoreErrors; /// <summary> /// Default constructor only exposed to make inheritence easier. /// </summary> public HtmlParser() { mIgnoreErrors = false; } /// <summary> /// This will parse the given HTML string. /// </summary> /// <param name="htmlString">The sequence of HTML tags to parse</param> /// <returns>The document representing the HTML</returns> public HtmlDocument Parse(String htmlString) { return Parse( new StringReader( htmlString ) ); } /// <summary> /// Implement this method if you want to handle text nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnText(HtmlDocument document,HtmlText htmlText) { } /// <summary> /// Implement this method if you want to handle script nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnScript(HtmlDocument document,HtmlScript scriptSource) { } /// <summary> /// Implement this method if you want to handle stylesheet nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnStyleSheet(HtmlDocument document,HtmlStyleSheet styleSheetSource) { } /// <summary> /// Implement this method if you want to handle open-tag nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnElementOpen(HtmlDocument document,HtmlElement element) { } /// <summary> /// Implement this method if you want to handle close-tag nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnElementClose(HtmlDocument document,HtmlElementClose element) { } /// <summary> /// Implement this method if you want to handle HTML comment nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnComment(HtmlDocument document,HtmlComment comment) { } /// <summary> /// Implement this method if you want to handle SGML comment nodes. /// </summary> /// <param name="document">The destination document</param> /// <param name="htmlText">The node that has been read</param> protected virtual void OnSgmlComment(HtmlDocument document,HtmlComment comment) { } /// <summary> /// The current line number. A parse is taken to start at line one. /// </summary> protected int LineNumber { get { return mLineNumber; } } /// <summary> /// If you choose to ignore errors, no exceptions will be thrown; errors will be silently ignored. /// </summary> public bool IgnoreErrors { get { return mIgnoreErrors; } set { mIgnoreErrors = value; } } /// <summary> /// This will parse the contents of the reader (a stream, for example) /// </summary> /// <param name="reader">The reader from which to read the HTML</param> /// <returns>The resultant document</returns> public HtmlDocument Parse(TextReader reader) { mLineNumber = 1; HtmlDocument document = new HtmlDocument(); int inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; while( inChar != END_OF_FILE ) { if( inChar == '<' ) { HtmlNode node = null; inChar = ParseTag( document , reader , ref node , inChar ); if( node is HtmlElementClose ) { OnElementClose( document , (HtmlElementClose) node ); } else if( node is HtmlElement ) { HtmlElement element = (HtmlElement) node; OnElementOpen( document , element ); if( "SCRIPT".Equals( element.Name.ToUpper() ) && ! element.IsClosed ) { bool ignoreSingleQuotes = true; /* * TODO: Is VBScript the only fella that uses single quotes in a manner other than to quote things...? if( element.Attributes[ "VBSCRIPT" ] == null ) { ignoreSingleQuotes = true; } */ String script = ""; inChar = ExtractScript( reader , ref script , inChar , ignoreSingleQuotes ); OnScript( document , new HtmlScript( script ) ); OnElementClose( document , new HtmlElementClose( element.Name ) ); } else if( "STYLE".Equals( element.Name.ToUpper() ) && ! element.IsClosed ) { String style = ""; inChar = ExtractStyle( reader , ref style , inChar ); OnStyleSheet( document , new HtmlStyleSheet( style ) ); OnElementClose( document , new HtmlElementClose( element.Name ) ); } } else if( node != null ) { if( node is HtmlComment ) { OnComment( document , (HtmlComment) node ); } } } else { HtmlNode node = null; inChar = ParseText( reader , ref node , inChar ); OnText( document , (HtmlText) node ); } } return document; } #region Node extraction private int ParseText(TextReader reader,ref HtmlNode outputNode,int inChar) { StringBuilder input = new StringBuilder(); input.Append( (char) inChar ); inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; while( inChar != END_OF_FILE ) { if( inChar == '<' ) { break; } else { input.Append( (char) inChar ); } inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } outputNode = new HtmlText( HttpUtility.HtmlDecode( input.ToString() ) ); return inChar; } private int ParseTag(HtmlDocument document,TextReader reader,ref HtmlNode outputNode,int inChar) { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; if( inChar == '!' ) { // This a comment string text = ""; inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; if( inChar == '-' ) { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; if( inChar == '-' ) { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; // Extract HTML comment inChar = ExtractComment( reader , ref text , inChar ); outputNode = new HtmlComment( text ); } else { // Extract SGML comment (probably a DOCTYPE) inChar = ExtractSGMLComment( reader , ref text , inChar ); if( text.Length >= 7 && "DOCTYPE".Equals( text.Substring( 0 , 7 ).ToUpper() ) ) { // We record DOCTYPE with the document (and not as a comment) document.DocumentType = text.Substring( 7 ).Trim(); } else { outputNode = new SgmlComment( text ); } } } else { // Extract SGML comment (probably a DOCTYPE) inChar = ExtractSGMLComment( reader , ref text , inChar ); if( text.Length >= 7 && "DOCTYPE".Equals( text.Substring( 0 , 7 ).ToUpper() ) ) { // We record DOCTYPE with the document (and not as a comment) document.DocumentType = text.Substring( 7 ).Trim(); } else { outputNode = new SgmlComment( text ); } } } else { // This is a tag inChar = SkipWhitespace( reader , inChar ); String name = ""; if( inChar == '/' ) { // This is a close element tag inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; inChar = SkipWhitespace( reader , inChar ); if( inChar != END_OF_FILE ) { inChar = ExtractName( reader , ref name , inChar ); } inChar = SkipWhitespace( reader , inChar ); if( inChar != '>' ) { if( ! IgnoreErrors ) { throw new HtmlParserException( "Tag not properly closed \"" + name + "\"" , mLineNumber ); } } else { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } outputNode = new HtmlElementClose( HttpUtility.HtmlDecode( name ) ); } else if( inChar != END_OF_FILE ) { // This is an open element tag inChar = ExtractName( reader , ref name , inChar ); inChar = SkipWhitespace( reader , inChar ); HtmlElement element = new HtmlElement( HttpUtility.HtmlDecode( name ) ); String attrName = ""; String attrValue = ""; while( inChar != END_OF_FILE && inChar != '>' ) { // Read each attribute attributes inChar = SkipWhitespace( reader , inChar ); inChar = ExtractName( reader , ref attrName , inChar ); inChar = SkipWhitespace( reader , inChar ); if( inChar == '=' ) { // Attribute has a value inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; inChar = SkipWhitespace( reader , inChar ); bool isClosedWithSlash = false; inChar = ExtractValue( reader , ref attrValue , inChar , ref isClosedWithSlash ); inChar = SkipWhitespace( reader , inChar ); element.Attributes.Add( new HtmlAttribute( HttpUtility.HtmlDecode( attrName ) , HttpUtility.HtmlDecode( attrValue ) ) ); element.IsClosedWithSlash = isClosedWithSlash; } else if( inChar == '/' ) { // Special examination of "/>" tag terminator inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; if( inChar == '>' ) { element.IsClosedWithSlash = true; } } else { // Null attribute value inChar = SkipWhitespace( reader , inChar ); element.Attributes.Add( new HtmlAttribute( HttpUtility.HtmlDecode( attrName ) , null ) ); } } if( inChar != '>' ) { if( ! IgnoreErrors ) { throw new HtmlParserException( "Tag not closed \"" + name + "\"" , mLineNumber); } } else { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } outputNode = element; } } return inChar; } #endregion private int SkipWhitespace(TextReader reader,int inChar) { while( char.IsWhiteSpace( (char) inChar ) ) { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } return inChar; } #region Extraction routines private int ExtractScript(TextReader reader,ref string text,int inChar,bool ignoreSingleQuotes) { return ExtractUntil( reader , "</SCRIPT>" , ref text , inChar , "Script not closed" , true , ignoreSingleQuotes ); } private int ExtractStyle(TextReader reader,ref string text,int inChar) { return ExtractUntil( reader , "</STYLE>" , ref text , inChar , "Style not closed" , true , false ); } private int ExtractUntil(TextReader reader,String terminatorText,ref string text,int inChar,string failMessage,bool respectQuotationMarks,bool ignoreSingleQuotes) { StringBuilder comment = new StringBuilder(); char[] terms = terminatorText.ToUpper().ToCharArray(); char[] cTemp = new char [ terms.Length ]; cTemp[ cTemp.Length - 1 ] = (char) inChar; bool inDoubleQuotes = false; bool inSingleQuotes = false; if( inChar == '\"' ) inDoubleQuotes = true; if( inChar == '\'' ) inSingleQuotes = true; while( inChar != END_OF_FILE ) { if( ignoreSingleQuotes ) inSingleQuotes = false; int i = 0; if( ! ( inSingleQuotes | inDoubleQuotes ) ) { for( i = 0 ; i < terms.Length ; i++ ) { if( terms[i] != char.ToUpper( cTemp[i] ) ) break; } } if( i == terms.Length ) break; comment.Append( (char) inChar ); if( ! ( inSingleQuotes | inDoubleQuotes ) ) { for( i = 0 ; i < cTemp.Length - 1 ; i++ ) { cTemp[ i ] = cTemp[ i + 1]; } } else { for( i = 0 ; i < cTemp.Length - 1 ; i++ ) { cTemp[ i ] = '\0'; } } cTemp[ cTemp.Length - 1 ] = (char) inChar; int oldChar = inChar; inChar = reader.Read(); if( inChar == '\"' && ! inSingleQuotes && ! ( oldChar == '\\' ) ) inDoubleQuotes = !inDoubleQuotes; if( inChar == '\'' && ! inDoubleQuotes && ! ( oldChar == '\\' ) ) inSingleQuotes = !inSingleQuotes; if( inChar == '\n' ) mLineNumber++; } text = comment.ToString(); if( text.Length >= terminatorText.Length && text.Substring( text.Length - terminatorText.Length ).ToUpper().Equals( terminatorText.ToUpper() ) ) { text = text.Substring( 0 , text.Length - terminatorText.Length ); } else { if( ! IgnoreErrors ) { throw new HtmlParserException( failMessage , mLineNumber ); } } return inChar; } private int ExtractComment(TextReader reader,ref String text,int inChar) { StringBuilder comment = new StringBuilder(); int c1=0,c2=0; while( inChar != END_OF_FILE ) { if( c1 == '-' && c2 == '-' && inChar == '>' ) { break; } comment.Append( (char) inChar ); c1 = c2; c2 = inChar; inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } if( comment.Length > 2 ) { text = comment.ToString().Substring( 0 , comment.Length - 2 ); } else { text = ""; } if( inChar == '>' ) { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } else { if( ! IgnoreErrors ) { throw new HtmlParserException( "Comment not closed" , mLineNumber ); } } return inChar; } private int ExtractSGMLComment(TextReader reader,ref String text,int inChar) { StringBuilder comment = new StringBuilder(); bool inQuotes = false; while( inChar != END_OF_FILE ) { if( inChar == '>' && ! inQuotes ) { break; } if( inChar == '\"' ) { inQuotes = ! inQuotes; } comment.Append( (char) inChar ); inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } if( inChar == '>' ) { inChar = reader.Read(); } else { if( ! IgnoreErrors ) { throw new HtmlParserException( "Comment not closed" , mLineNumber ); } } text = comment.ToString(); return inChar; } private int ExtractName(TextReader reader,ref String name,int inChar) { StringBuilder nameBuffer = new StringBuilder(); while( ! ( char.IsWhiteSpace( (char) inChar ) ) && inChar != END_OF_FILE && inChar != '=' && inChar != '>' /*&& inChar != '<'*/ && inChar != '/' ) { nameBuffer.Append( (char) inChar ); inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } name = nameBuffer.ToString(); return inChar; } private int ExtractValue(TextReader reader,ref String value,int inChar,ref bool isClosedWithSlash) { StringBuilder valueBuffer = new StringBuilder(); if( inChar == '\"' || inChar == '\'' ) { int terminatorChar = inChar; inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; while( inChar != END_OF_FILE && inChar != terminatorChar ) { valueBuffer.Append( (char) inChar ); inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } if( inChar == terminatorChar ) { inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } else { if( ! IgnoreErrors ) { throw new HtmlParserException( "String not terminated" , mLineNumber ); } } } else { int lastInChar = 0; while( ! char.IsWhiteSpace( (char) inChar ) && inChar != END_OF_FILE && inChar != '>' ) { valueBuffer.Append( (char) inChar ); lastInChar = inChar; inChar = reader.Read(); if( inChar == '\n' ) mLineNumber++; } if( lastInChar == '/' && inChar == '>' ) { valueBuffer.Remove( valueBuffer.Length - 1 , 1 ); isClosedWithSlash = true; } } value = valueBuffer.ToString(); return inChar; } #endregion } } --- NEW FILE: HtmlComment.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.ComponentModel; namespace Adapdev.Web.Html { /// <summary> /// This represents a HTML comment. If the input document contained an SGML-style /// comment (but wasn't a DOCTYPE), it is treated as if it were a regular HTML-style /// comment. i.e. <! comment > is treated the same as <!-- comment -->. /// All comments are output in HTML/XML using the second format. /// </summary> public class HtmlComment: HtmlNode { private string mText; /// <summary> /// Creates a new comment with the given text. /// </summary> /// <param name="text">The comment text</param> public HtmlComment(string text) { mText = text; } /// <summary> /// This will write this comment out in HTML format. Be sure that the /// comment text does not contain comments itself as no encoding is /// performed here. /// </summary> /// <param name="writer">The writer on which to write this comment</param> public override void WriteHTML(TextWriter writer) { writer.Write( "<!--" ); writer.Write( mText ); writer.Write( "-->" ); } /// <summary> /// This will write this comment out in XML format. Be sure that the /// comment text does not contain comments itself as no encoding is /// performed here. /// </summary> /// <param name="writer">The writer on which to write this comment</param> public override void WriteXML(TextWriter writer) { writer.Write( "<!--" ); writer.Write( mText ); writer.Write( "-->" ); } /// <summary> /// Get or set the textual contents of the comment. /// </summary> [ Category("General"), Description("The comment") ] public string Text { get { return mText; } set { mText = value; } } /// <summary> /// This makes a duplicate of this comment. /// </summary> /// <returns>A duplicate of this comment</returns> public override object Clone() { return new HtmlComment( mText ); } } } --- NEW FILE: HtmlElement.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.Text; using System.Collections; using System.ComponentModel; using System.Web; namespace Adapdev.Web.Html { /// <summary> /// This represents an element within the document. /// </summary> public class HtmlElement: HtmlNode { private HtmlNodeCollection mNodes; private HtmlAttributeCollection mAttributes; private string mName; private bool mIsClosedWithSlash; private bool mIsClosedWithTag; private bool mAllowNoClose; /// <summary> /// Creates a new empty element with the given name. /// </summary> /// <param name="name">The name of the element</param> public HtmlElement(string name) { mNodes = new HtmlNodeCollection( this ); mAttributes = new HtmlAttributeCollection(); mName = name; mIsClosedWithSlash = false; mIsClosedWithTag = false; } /// <summary> /// Creates a new empty element with the given name. /// </summary> /// <param name="name">The name of the element</param> /// <param name="allowNoClosingTag">Some tags do not need to be closed at all, under those circumstances, set this to true</param> public HtmlElement(string name,bool allowNoClosingTag) { mNodes = new HtmlNodeCollection( this ); mAttributes = new HtmlAttributeCollection(); mName = name; mIsClosedWithSlash = false; mIsClosedWithTag = false; mAllowNoClose = allowNoClosingTag; } /// <summary> /// This will write this element (and any child-nodes) in HTML format. /// </summary> /// <param name="writer">The writer on which to write the element</param> public override void WriteHTML(TextWriter writer) { writer.Write( "<" ); writer.Write( Name ); if( Attributes.Count > 0 ) { foreach( HtmlAttribute attribute in Attributes ) { writer.Write( " " ); attribute.WriteHTML( writer ); } } writer.Write( ">" ); foreach( HtmlNode node in this.Nodes ) { node.WriteHTML( writer ); } if( this.Nodes.Count > 0 || ! HtmlHelper.ElementDoesNotRequireClosing( Name ) ) { writer.Write( "</" ); writer.Write( Name ); writer.Write( ">" ); } } /// <summary> /// This will write this element (and any child-nodes) in XML format. /// </summary> /// <param name="writer">The writer on which to write the element</param> public override void WriteXML(TextWriter writer) { writer.Write( "<" ); writer.Write( Name.ToLower() ); if( Attributes.Count > 0 ) { foreach( HtmlAttribute attribute in Attributes ) { writer.Write( " " ); attribute.WriteXML( writer ); } } if( Nodes.Count == 0 ) { writer.Write( "/>" ); } else { writer.Write( ">" ); foreach( HtmlNode node in this.Nodes ) { node.WriteXML( writer ); } writer.Write( "</" ); writer.Write( Name.ToLower() ); writer.Write( ">" ); } } /// <summary> /// Get or set the name of the element. /// </summary> [ Category("General"), Description("The name of the element") ] public string Name { get { return mName; } set { mName = value; } } /// <summary> /// This will return all the nodes (in order) that this element contains. /// </summary> [ Category("Navigation"), Description("All the child nodes of this element") ] public HtmlNodeCollection Nodes { get { return mNodes; } } /// <summary> /// This will return the collection of attribute values for this element. /// </summary> [ Category("General"), Description("The attributes of this element") ] public HtmlAttributeCollection Attributes { get { return mAttributes; } } /// <summary> /// This is an internal property used by the domain tree parser to determine /// how this element is eventually closed (if at all). /// </summary> internal bool IsClosedWithSlash { get { return mIsClosedWithSlash; } set { mIsClosedWithSlash = value; } } /// <summary> /// This is an internal property used by the domain tree parser to determine /// how this element is eventually closed (if at all). /// </summary> internal bool IsClosedWithTag { get { return mIsClosedWithTag; } set { mIsClosedWithTag = value; } } /// <summary> /// This is an internal property used by the domain tree parser to determine /// how this element is eventually closed (if at all). /// </summary> internal bool IsClosed { get { return ( mNodes.Count > 0 ) || mIsClosedWithSlash || mIsClosedWithTag; } } /// <summary> /// This will return the HTML to represent this element. /// </summary> /// <returns></returns> public override string ToString() { StringBuilder output = new StringBuilder(); output.Append( "<" ); output.Append( Name ); if( Attributes.Count > 0 ) { foreach( HtmlAttribute attribute in Attributes ) { output.Append( " " ); output.Append( attribute.ToString() ); } } if( this.IsClosedWithSlash ) { output.Append( "/" ); } output.Append( ">" ); return output.ToString(); } /// <summary> /// This makes a deep copy of this element. /// </summary> /// <returns>A copy of this element</returns> public override object Clone() { HtmlElement clonedElement = new HtmlElement( mName ); clonedElement.mNodes = (HtmlNodeCollection) mNodes.Clone(); clonedElement.mAttributes = (HtmlAttributeCollection) mAttributes.Clone(); clonedElement.mIsClosedWithSlash = mIsClosedWithSlash; clonedElement.mIsClosedWithTag = mIsClosedWithTag; return clonedElement; } /// <summary> /// Return the HTML contained within this node - useful if you know /// it's just text. /// </summary> [ Category("General"), Description("The HTML contents of this element") ] public string InnerHTML { get { StringWriter stringWriter = new StringWriter(); Nodes.WriteHTML( stringWriter ); return stringWriter.ToString(); } } /// <summary> /// Return the HTML contained within this node - useful if you know /// it's just text. /// </summary> [ Category("General"), Description("The HTML contents of this element") ] public string InnerText { get { StringWriter stringWriter = new StringWriter(); HtmlNodeCollection textNodes = Nodes.FindAllText( false ); foreach( HtmlNode node in textNodes ) { stringWriter.Write( node.ToString() ); } return stringWriter.ToString(); } } } /// <summary> /// This is a collection of elements - you should not directly modify this collection /// (use the HtmlElement.Nodes property instead). The implementation of this class /// will change in the future. /// </summary> public class HtmlElementCollection: HtmlNodeCollection { /// <summary> /// This creates a new empty collection in which to store nodes. /// </summary> internal HtmlElementCollection() : base( null ) { } /// <summary> /// This is only ever used internally, and is for maintaining the parent/child /// relationships. /// </summary> /// <param name="parent">The owner of this collection</param> internal HtmlElementCollection(HtmlElement parent) : base( parent ) { } /// <summary> /// Get or set the element at the given index /// </summary> public new HtmlElement this [int index] { get { return (HtmlElement) base[ index ]; } set { base[ index ] = value; } } } } --- NEW FILE: HtmlNode.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.Collections; using System.ComponentModel; namespace Adapdev.Web.Html { /// <summary> /// This abstract object represents an object that can appear in an HTML document. /// </summary> public abstract class HtmlNode: ICloneable { protected HtmlElement mParent; /// <summary> /// This constructor is only ever used by the child classes. /// </summary> protected HtmlNode() { } /// <summary> /// Write this node in HTML format /// </summary> /// <param name="writer"></param> public abstract void WriteHTML(TextWriter writer); /// <summary> /// Write this node in XML format /// </summary> /// <param name="writer"></param> public abstract void WriteXML(TextWriter writer); /// <summary> /// The HTML used to build the document tree from this node. /// </summary> [ Category("General"), Description("The HTML representation of the document tree from this point") ] public string HTML { get { StringWriter stringWriter = new StringWriter(); WriteHTML( stringWriter ); return stringWriter.ToString(); } } /// <summary> /// The XML used to build the document tree from this node. /// </summary> [ Category("General"), Description("The XML representation of the document tree from this point") ] public string XML { get { StringWriter stringWriter = new StringWriter(); WriteXML( stringWriter ); return stringWriter.ToString(); } } /// <summary> /// This will return the next sibling node. If this is the last one, it will return null. /// </summary> [ Category("Navigation"), Description("The next sibling node") ] public HtmlNode Next { get { if( Index == -1 ) { return null; } else { if( Parent.Nodes.Count > Index + 1 ) { return Parent.Nodes[ Index + 1 ]; } else { return null; } } } } /// <summary> /// This will return the previous sibling node. If this is the first one, it will return null. /// </summary> [ Category("Navigation"), Description("The previous sibling node") ] public HtmlNode Previous { get { if( Index == -1 ) { return null; } else { if( Index > 0 ) { return Parent.Nodes[ Index - 1 ]; } else { return null; } } } } /// <summary> /// This will return the first child node. If there are no children, this /// will return null. /// </summary> [ Category("Navigation"), Description("The first child of this node") ] public HtmlNode FirstChild { get { if( this is HtmlElement ) { if( ((HtmlElement)this).Nodes.Count == 0 ) { return null; } else { return ((HtmlElement)this).Nodes[ 0 ]; } } else { return null; } } } /// <summary> /// This will return the last child node. If there are no children, this /// will return null. /// </summary> [ Category("Navigation"), Description("The last child of this node") ] public HtmlNode LastChild { get { if( this is HtmlElement ) { if( ((HtmlElement)this).Nodes.Count == 0 ) { return null; } else { return ((HtmlElement)this).Nodes[ ((HtmlElement)this).Nodes.Count - 1 ]; } } else { return null; } } } /// <summary> /// This will return the index position within the parent's nodes that this one resides. /// If this is not in a collection, this will return -1. /// </summary> [ Category("Navigation"), Description("The zero-based index of this node in the parent's nodes collection") ] public int Index { get { if( mParent == null ) { return -1; } else { return mParent.Nodes.IndexOf( this ); } } } /// <summary> /// This will return the parent of this node, or null if there is none. /// </summary> [ Category("Navigation"), Description("The parent node of this one") ] public HtmlElement Parent { get { return mParent; } } /// <summary> /// This internal function is used to maintain the parent/child relationships. /// </summary> /// <param name="parent"></param> internal void SetParent(HtmlElement parent) { mParent = parent; } /// <summary> /// This will return true if this is root node (ie. has no parent) /// </summary> [ Category("Navigation"), Description("Is this node a root node?") ] public bool IsRoot { get { return mParent == null; } } /// <summary> /// This will return true if this is a child node (has a parent). /// </summary> [ Category("Navigation"), Description("Is this node a child of another?") ] public bool IsChild { get { return mParent != null; } } /// <summary> /// Does this node have any children? If this node is anything other than an /// HtmlElement, this will return false. /// </summary> [ Category("Navigation"), Description("Does this node have any children?") ] public bool IsParent { get { if( this is HtmlElement ) { return ((HtmlElement)this).Nodes.Count > 0; } else { return false; } } } /// <summary> /// This will return true if the node passed is a descendent of this node. /// </summary> /// <param name="node">The node that might be the parent or grandparent (etc.)</param> /// <returns>True if this node is a descendent of the one passed in.</returns> [ Category("Relationships") ] public bool IsDescendentOf(HtmlNode node) { HtmlNode parent = mParent; while( parent != null ) { if( parent == node ) { return true; } parent = parent.Parent; } return false; } /// <summary> /// This will return true if the node passed is one of the children or grandchildren of this node. /// </summary> /// <param name="node">The node that might be a child.</param> /// <returns>True if this node is an ancestor of the one specified.</returns> [ Category("Relationships") ] public bool IsAncestorOf(HtmlNode node) { return node.IsDescendentOf( this ); } /// <summary> /// This will return the ancstor that is common to this node and the one specified. /// </summary> /// <param name="node">The possible node that is relative</param> /// <returns>The common ancestor, or null if there is none</returns> [ Category("Relationships") ] public HtmlNode GetCommonAncestor(HtmlNode node) { HtmlNode thisParent = this; while( thisParent != null ) { HtmlNode thatParent = node; while( thatParent != null ) { if( thisParent == thatParent ) { return thisParent; } thatParent = thatParent.Parent; } thisParent = thisParent.Parent; } return null; } /// <summary> /// This will remove this node and all child nodes from the tree. If this /// is a root node, this operation will do nothing. /// </summary> [ Category("General") ] public void Remove() { if( mParent != null ) { mParent.Nodes.RemoveAt( this.Index ); } } /// <summary> /// This will take a deep copy of this node collection /// </summary> /// <returns></returns> public abstract object Clone(); /// <summary> /// Create a document fragment from this node. /// </summary> /// <returns>A new document from this node</returns> public HtmlDocument CreateDocumentFragment() { HtmlNodeCollection collection = new HtmlNodeCollection(); collection.Add( (HtmlNode) this.Clone() ); HtmlDocument fragment = new HtmlDocument( collection ); return fragment; } } /// <summary> /// This represents a collection of nodes (i.e. a portion of a document) /// </summary> public class HtmlNodeCollection: CollectionBase,ICloneable { private HtmlElement mParent; /// <summary> /// This creates a new empty collection in which to store nodes. /// </summary> public HtmlNodeCollection() { mParent = null; } /// <summary> /// This is only ever used internally, and is for maintaining the parent/child /// relationships. /// </summary> /// <param name="parent">The owner of this collection</param> internal HtmlNodeCollection(HtmlElement parent) { mParent = parent; } /// <summary> /// This will add the node to the end of this collection. /// </summary> /// <param name="node">The node to add</param> /// <returns>The zero-based index of where the node was added</returns> public virtual int Add(HtmlNode node) { if( mParent != null ) node.SetParent( mParent ); return base.InnerList.Add( node ); } /// <summary> /// This will add a collection of nodes to the end of this collection. /// </summary> /// <param name="nodes">The collection of nodes to add</param> public void Add(HtmlNodeCollection nodes) { foreach(HtmlNode node in nodes) { if( mParent != null ) node.SetParent( mParent ); base.InnerList.Add( node ); } } /// <summary> /// Insert a node at the given index. /// </summary> /// <param name="index">The index at which to insert</param> /// <param name="node">The node to insert</param> public void Insert(int index,HtmlNode node) { if( mParent != null ) node.SetParent( mParent ); base.InnerList.Insert( index , node ); } /// <summary> /// Get or set the node at the given index /// </summary> public HtmlNode this [int index] { get { return (HtmlNode) base.InnerList[ index ]; } set { if( mParent != null ) value.SetParent( mParent); base.InnerList[ index ] = value; } } /// <summary> /// Get the element that owns this collection. If this collection is not /// contained in an element, this will return null. /// </summary> public HtmlElement Parent { get { return mParent; } } /// <summary> /// The zero-based index of the node within this collection. /// </summary> /// <param name="node">The node to find</param> /// <returns>The index of the node (or -1 if it was not found)</returns> public int IndexOf(HtmlNode node) { return base.InnerList.IndexOf( node ); } /// <summary> /// This will search though this collection of nodes for all elements with the /// specified name. If you want to search the subnodes recursively, you should /// pass True as the parameter in searchChildren. This search is guaranteed to /// return nodes in the order in which they are found in the document. /// </summary> /// <param name="name">The name of the element to find</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindByName(string name) { return FindByName( name , true ); } /// <summary> /// This will search though this collection of nodes for all elements with the /// specified name. If you want to search the subnodes recursively, you should /// pass True as the parameter in searchChildren. This search is guaranteed to /// return nodes in the order in which they are found in the document. /// </summary> /// <param name="name">The name of the element to find</param> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindByName(string name,bool searchChildren) { HtmlElementCollection results = new HtmlElementCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { if( ( (HtmlElement)node ).Name.ToLower().Equals( name.ToLower() ) ) { results.Add( node ); } if( searchChildren ) { foreach( HtmlNode matchedChild in ( (HtmlElement)node ).Nodes.FindByName( name , searchChildren ) ) { results.Add( matchedChild ); } } } } return results; } /// <summary> /// This will search though this collection of nodes for all elements with the an /// attribute with the given name. /// </summary> /// <param name="name">The name of the attribute to find</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindByAttributeName(string attributeName) { return FindByAttributeName( attributeName , true ); } /// <summary> /// This will search though this collection of nodes for all elements with the an /// attribute with the given name. /// </summary> /// <param name="name">The name of the attribute to find</param> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindByAttributeName(string attributeName,bool searchChildren) { HtmlElementCollection results = new HtmlElementCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { foreach( HtmlAttribute attribute in ((HtmlElement)node).Attributes ) { if( attribute.Name.ToLower().Equals( attributeName.ToLower() ) ) { results.Add( node ); break; } } if( searchChildren ) { foreach( HtmlNode matchedChild in ( (HtmlElement)node ).Nodes.FindByAttributeName( attributeName , searchChildren ) ) { results.Add( matchedChild ); } } } } return results; } /// <summary> /// This will search though this collection of nodes for all elements with the an /// attribute with the given name, and the attribute has the specified value. /// </summary> /// <param name="attributeName">The name of the attribute to find</param> /// <param name="attributeValue">The value of the attribute to find</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindByAttributeNameValue(string attributeName,string attributeValue) { return FindByAttributeNameValue( attributeName , attributeValue , true ); } /// <summary> /// This will search though this collection of nodes for all elements with the an /// attribute with the given name, and the attribute has the specified value. /// </summary> /// <param name="attributeName">The name of the attribute to find</param> /// <param name="attributeValue">The value of the attribute to find</param> /// <param name="searchChildren">Flag indicating that all child nodes should also be recursed</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindByAttributeNameValue(string attributeName,string attributeValue,bool searchChildren) { HtmlElementCollection results = new HtmlElementCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { foreach( HtmlAttribute attribute in ((HtmlElement)node).Attributes ) { if( attribute.Name.ToLower().Equals( attributeName.ToLower() ) ) { if( attribute.Value.ToLower().Equals( attributeValue.ToLower() ) ) { results.Add( node ); } break; } } if( searchChildren ) { foreach( HtmlNode matchedChild in ( (HtmlElement)node ).Nodes.FindByAttributeNameValue( attributeName , attributeValue , searchChildren ) ) { results.Add( matchedChild ); } } } } return results; } /// <summary> /// This will take a deep copy of this node collection /// </summary> /// <returns></returns> public object Clone() { HtmlNodeCollection clonedCollection = new HtmlNodeCollection(); foreach(HtmlNode node in this) { clonedCollection.Add( (HtmlNode) node.Clone() ); } return clonedCollection; } /// <summary> /// Write the HTML /// </summary> /// <param name="writer"></param> public void WriteHTML(TextWriter writer) { foreach( HtmlNode node in this ) { node.WriteHTML( writer ); } } /// <summary> /// Write the XML /// </summary> /// <param name="writer"></param> public void WriteXML(TextWriter writer) { foreach( HtmlNode node in this ) { node.WriteXML( writer ); } } /// <summary> /// Get the HTML requred to render these nodes. /// </summary> [ Category("General"), Description("The HTML required to render these nodes") ] public string HTML { get { StringWriter stringWriter = new StringWriter(); WriteHTML( stringWriter ); return stringWriter.ToString(); } } /// <summary> /// Get the XML requred to render these nodes. /// </summary> [ Category("General"), Description("The XML required to render these nodes") ] public string XML { get { StringWriter stringWriter = new StringWriter(); WriteXML( stringWriter ); return stringWriter.ToString(); } } /// <summary> /// This will search through this collection of nodes and will return all the /// HtmlScript objects. /// </summary> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlNodeCollection FindAllScripts(bool searchChildren) { HtmlNodeCollection results = new HtmlNodeCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { if( searchChildren ) { results.Add( ( (HtmlElement) node ).Nodes.FindAllScripts( searchChildren ) ); } } else if( node is HtmlScript ) { results.Add( node ); } } return results; } /// <summary> /// This will search through this collection of nodes and will return all the /// HtmlComment objects. /// </summary> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlNodeCollection FindAllComments(bool searchChildren) { HtmlNodeCollection results = new HtmlNodeCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { if( searchChildren ) { results.Add( ( (HtmlElement) node ).Nodes.FindAllComments( searchChildren ) ); } } else if( node is HtmlComment ) { results.Add( node ); } } return results; } /// <summary> /// This will search through this collection of nodes and will return all the /// HtmlStyleSheet objects. /// </summary> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlNodeCollection FindAllStyleSheets(bool searchChildren) { HtmlNodeCollection results = new HtmlNodeCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { if( searchChildren ) { results.Add( ( (HtmlElement) node ).Nodes.FindAllStyleSheets( searchChildren ) ); } } else if( node is HtmlStyleSheet ) { results.Add( node ); } } return results; } /// <summary> /// This will search through this collection of nodes and will return all the /// HtmlText objects. /// </summary> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlNodeCollection FindAllText(bool searchChildren) { HtmlNodeCollection results = new HtmlNodeCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { if( searchChildren ) { results.Add( ( (HtmlElement) node ).Nodes.FindAllText( searchChildren ) ); } } else if( node is HtmlText ) { results.Add( node ); } } return results; } /// <summary> /// This will search through this collection of nodes and will return all the /// HtmlText objects. /// </summary> /// <param name="searchChildren">True if you want to search sub-nodes, False to /// only search this collection.</param> /// <returns>A collection of all the nodes that macth.</returns> public HtmlElementCollection FindAllElements(bool searchChildren) { HtmlElementCollection results = new HtmlElementCollection(null); foreach( HtmlNode node in base.List ) { if( node is HtmlElement ) { results.Add( node ); if( searchChildren ) { results.Add( ( (HtmlElement) node ).Nodes.FindAllElements( searchChildren ) ); } } } return results; } /// <summary> /// Create a document fragment from these nodes. /// </summary> /// <returns>A new document with these nodes</returns> public HtmlDocument CreateDocumentFragment() { HtmlDocument fragment = new HtmlDocument( (HtmlNodeCollection) this.Clone() ); return fragment; } } } --- NEW FILE: HtmlStyleSheet.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.ComponentModel; namespace Adapdev.Web.Html { /// <summary> /// Summary description for HtmlStyle. /// </summary> public class HtmlStyleSheet: HtmlNode { private string mText; public HtmlStyleSheet(string styleSheetSource) { mText = styleSheetSource; } public override void WriteHTML(TextWriter writer) { writer.Write( mText ); } public override void WriteXML(TextWriter writer) { writer.Write( "<![CDATA[" ); writer.Write( mText ); writer.Write( "]]>" ); } /// <summary> /// Set or get the stylesheet definition /// </summary> [ Category("General"), Description("The definition of the stylesheet") ] public string Text { get { return mText; } set { mText = value; } } public override object Clone() { return new HtmlStyleSheet( mText ); } } } --- NEW FILE: HtmlDocument.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.Text; using System.ComponentModel; namespace Adapdev.Web.Html { /// <summary> /// This object represents an HTML document. This can be used to represent /// a complete document or just a fragment of a document. /// </summary> public class HtmlDocument { private HtmlNodeCollection mNodes; private string mDocumentType; /// <summary> /// Creates a new empty document. /// </summary> public HtmlDocument() { mNodes = new HtmlNodeCollection(); mDocumentType = null; } /// <summary> /// Used to create instances of document fragments. The nodes that are /// added should be cloned from the original document. /// </summary> /// <param name="nodes">The nodes to copy into this new fragment</param> internal HtmlDocument(HtmlNodeCollection nodes) { mNodes = (HtmlNodeCollection) nodes; } /// <summary> /// This will return all the root nodes of the document. In a complete /// document, this is just a collection containing the HTML element. /// </summary> public HtmlNodeCollection Nodes { get { return mNodes; } } /// <summary> /// The DOCTYPE for this document. If no DOCTYPE is specified, this value /// is null. Similarly, assigning null to this will indicate that this document /// has no type. /// </summary> public string DocumentType { get { return mDocumentType; } set { mDocumentType = value; } } /// <summary> /// Write this entire document in HTML format. /// </summary> /// <param name="writer">The writer to write on</param> public void WriteHTML(TextWriter writer) { if( DocumentType != null ) { writer.Write( "<!DOCTYPE " ); writer.Write( DocumentType ); writer.Write( ">" ); } Nodes.WriteHTML( writer ); } /// <summary> /// Write this entire document in XML format. /// </summary> /// <param name="writer">The writer to write on</param> public void WriteXML(TextWriter writer) { if( DocumentType != null ) { writer.Write( "<!DOCTYPE " ); writer.Write( DocumentType ); writer.Write( ">" ); } Nodes.WriteXML( writer ); } /// <summary> /// The HTML used to build the document tree from this node. /// </summary> [ Category("General"), Description("The HTML representation of the document tree from this point") ] public string HTML { get { StringWriter stringWriter = new StringWriter(); WriteHTML( stringWriter ); return stringWriter.ToString(); } } /// <summary> /// The XML used to build the document tree from this node. /// </summary> [ Category("General"), Description("The XML representation of the document tree from this point") ] public string XML { get { StringWriter stringWriter = new StringWriter(); WriteXML( stringWriter ); return stringWriter.ToString(); } } } } --- NEW FILE: HtmlHelper.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.Collections.Specialized; namespace Adapdev.Web.Html { /// <summary> /// Internal helper class for HTML processing /// </summary> internal class HtmlHelper { private static StringCollection mOpenEndedTags; /// <summary> /// This is a singleton, so perform initialisation here /// </summary> static HtmlHelper() { mOpenEndedTags = new StringCollection(); // This lot is taken from the HTML4 spec mOpenEndedTags.Add( "area" ); mOpenEndedTags.Add( "base" ); mOpenEndedTags.Add( "basefont" ); mOpenEndedTags.Add( "br" ); mOpenEndedTags.Add( "col" ); mOpenEndedTags.Add( "frame" ); mOpenEndedTags.Add( "hr" ); mOpenEndedTags.Add( "img" ); mOpenEndedTags.Add( "input" ); mOpenEndedTags.Add( "isindex" ); mOpenEndedTags.Add( "link" ); mOpenEndedTags.Add( "meta" ); mOpenEndedTags.Add( "param" ); } /// <summary> /// Returns true if the named element should not be closed in HTML. /// </summary> /// <param name="elementName">The name of the element</param> /// <returns>True if the element should not be closed</returns> internal static bool ElementDoesNotRequireClosing(string elementName) { return mOpenEndedTags.Contains( elementName.ToLower() ); } } } --- NEW FILE: HtmlText.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.ComponentModel; using System.Web; namespace Adapdev.Web.Html { /// <summary> /// Summary description for HtmlText. /// </summary> public class HtmlText: HtmlNode { protected string mText; public HtmlText(string text) { mText = text; } public override void WriteHTML(TextWriter writer) { HttpUtility.HtmlEncode( mText , writer ); } public override void WriteXML(TextWriter writer) { HttpUtility.HtmlEncode( mText , writer ); } /// <summary> /// Retrieves the text directly. /// </summary> /// <returns></returns> public override string ToString() { return mText; } /// <summary> /// Set or get the text /// </summary> [ Category("General"), Description("The text contained in the node") ] public string Text { get { return mText; } set { mText = value; } } public override object Clone() { return new HtmlText( mText ); } } } --- NEW FILE: SgmlComment.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.ComponentModel; namespace Adapdev.Web.Html { /// <summary> /// Summary description for SgmlComment. /// </summary> public class SgmlComment: HtmlComment { public SgmlComment(string text) : base( text ) { } public override void WriteHTML(TextWriter writer) { writer.Write( "<!" ); writer.Write( Text ); writer.Write( ">" ); } public override void WriteXML(TextWriter writer) { writer.Write( "<!" ); writer.Write( Text ); writer.Write( ">" ); } /// <summary> /// This makes a duplicate of this comment. /// </summary> /// <returns>A duplicate of this comment</returns> public override object Clone() { return new SgmlComment( Text ); } } } --- NEW FILE: HtmlScript.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; using System.IO; using System.ComponentModel; namespace Adapdev.Web.Html { /// <summary> /// Summary description for HtmlScript. /// </summary> public class HtmlScript: HtmlNode { private string mText; public HtmlScript(string source) { mText = source; } public override void WriteHTML(TextWriter writer) { writer.Write( mText ); } public override void WriteXML(TextWriter writer) { writer.Write( "<![CDATA[" ); writer.Write( mText ); writer.Write( "]]>" ); } /// <summary> /// Set or get the source code /// </summary> [ Category("General"), Description("The source code of the script") ] public string Text { get { return mText; } set { mText = value; } } public override object Clone() { return new HtmlScript( mText ); } } } --- NEW FILE: HtmlDomainTreeParser.cs --- // Copyright Andy Powney 2004. http://powney.demon.co.uk/milhtml.html // Originally published under the GNU Public License. Included in this // library under the Apache License 2.0 with permission from Andy. using System; namespace Adapdev.Web.Html { /// <summary> /// This parser will build a domain tree of the document that is being /// parsed. The various navigation functionality within the other objects /// in this library depend on this being used. /// </summary> public class HtmlDomainTreeParser: HtmlParser { private bool mIgnoreUnbalancedClosing; private bool mIgnoreEmptyTextNodes; /// <summary> /// This will create a new domain tree parser. /// </summary> public HtmlDomainTreeParser() { mIgnoreUnbalancedClosing = false; mIgnoreEmptyTextNodes = false; } /// <summary> /// This will create a new domain tree parser. /// </summary> public HtmlDomainTreeParser(bool ignoreUnbalancedClosing) { mIgnoreUnbalancedClosing = ignoreUnbalancedClosing; mIgnoreEmptyTextNodes = false; } /// <summary> /// This will create a new domain tree parser. /// </summary> public HtmlDomainTreeParser(bool ignoreUnbalancedClosing,bool ignoreEmptyTextNodes) { mIgnoreUnbalancedClosing = ignoreUnbalancedClosing; mIgnoreEmptyTextNodes = ignoreEmptyTextNodes; } /// <summary> /// Setting this flag will cause the parser to ignore unbalanced close tags. /// On many webpages, you will discover that close tags don't necessarily /// tally up with open tags. FORM-tags are notorious for this. /// </summary> public bool IgnoreUnbalancedClosing { get { return mIgnoreUnbalancedClosing; } set { mIgnoreUnbalancedClosing = value; } } /// <summary> /// Setting this flag will cause the parser to ignore text nodes that contain purely /// whitespace. /// </summary> public bool IgnoreEmptyTextNodes { get { return mIgnoreEmptyTextNodes; } set { mIgnoreEmptyTextNodes = value; } } /// <summary> /// This is called by the base parser when a piece of text has been read. /// </summary> /// <param name="document">The document being built</param> /// <param name="htmlText">The text that has been read</param> protected override void OnText(HtmlDocument document,HtmlText htmlText) { if( IgnoreEmptyTextNodes ) { if( htmlText.Text.Trim().Length > 0 ) { document.Nodes.Add( htmlText ); } } else { document.Nodes.Add( htmlText ); } } /// <summary> /// This is called by the base parser when a piece of script has been read. /// </summary> /// <param name="document">The document being built</param> /// <param name="scriptSource">The script source code that has been read</param> prote... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:09
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Context In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Context Added Files: AbstractContext.cs IContext.cs InternalContextAdapter.cs InternalContextAdapterImpl.cs InternalContextBase.cs InternalEventContext.cs InternalHousekeepingContext.cs InternalWrapperContext.cs VMContext.cs Log Message: --- NEW FILE: InternalEventContext.cs --- namespace NVelocity.Context { using NVelocity.App.Events; /// <summary> /// Interface for event support. Note that this is a public internal /// interface, as it is something that will be accessed from outside /// of the .context package. /// </summary> public interface InternalEventContext { EventCartridge EventCartridge { get; } EventCartridge AttachEventCartridge(EventCartridge ec); } } --- NEW FILE: InternalContextBase.cs --- namespace NVelocity.Context { using System; using System.Collections; using NVelocity.App.Events; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> class to encapsulate the 'stuff' for internal operation of velocity. /// We use the context as a thread-safe storage : we take advantage of the /// fact that it's a visitor of sorts to all nodes (that matter) of the /// AST during init() and render(). /// Currently, it carries the template name for namespace /// support, as well as node-local context data introspection caching. /// * /// Note that this is not a public class. It is for package access only to /// keep application code from accessing the internals, as AbstractContext /// is derived from this. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: InternalContextBase.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> [Serializable] public class InternalContextBase : InternalHousekeepingContext, InternalEventContext { //, System.Runtime.Serialization.ISerializable { public InternalContextBase() { InitBlock(); } private void InitBlock() { introspectionCache = new Hashtable(33); templateNameStack = new Stack(); } public virtual String CurrentTemplateName { get { if ((templateNameStack.Count == 0)) return "<undef>"; else return (String) templateNameStack.Peek(); } } public virtual Object[] TemplateNameStack { get { return templateNameStack.ToArray(); } } public virtual Resource CurrentResource { get { return currentResource; } set { currentResource = value; } } public virtual EventCartridge EventCartridge { get { return eventCartridge; } } /// <summary> cache for node/context specific introspection information /// </summary> //UPGRADE_NOTE: The initialization of 'introspectionCache' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Hashtable introspectionCache; /// <summary> Template name stack. The stack top contains the current template name. /// </summary> //UPGRADE_NOTE: The initialization of 'templateNameStack' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Stack templateNameStack; /// <summary> EventCartridge we are to carry. Set by application /// </summary> private EventCartridge eventCartridge = null; /// <summary> Current resource - used for carrying encoding and other /// information down into the rendering process /// </summary> private Resource currentResource = null; /// <summary> set the current template name on top of stack /// * /// </summary> /// <param name="s">current template name /// /// </param> public virtual void PushCurrentTemplateName(String s) { Object temp_object; temp_object = s; Object generatedAux = temp_object; templateNameStack.Push(temp_object); return; } /// <summary> remove the current template name from stack /// </summary> public virtual void PopCurrentTemplateName() { templateNameStack.Pop(); return; } /// <summary> get the current template name /// * /// </summary> /// <returns>String current template name /// /// </returns> /// <summary> get the current template name stack /// * /// </summary> /// <returns>Object[] with the template name stack contents. /// /// </returns> /// <seealso cref=" IntrospectionCacheData) /// object if exists for the key /// * /// "/> /// <param name="key"> key to find in cache /// </param> /// <returns>cache object /// /// </returns> public virtual IntrospectionCacheData ICacheGet(Object key) { return (IntrospectionCacheData) introspectionCache[key]; } /// <seealso cref=" IntrospectionCacheData) /// element in the cache for specified key /// * /// "/> /// <param name="key"> key /// </param> /// <param name="o"> IntrospectionCacheData object to place in cache /// /// </param> public virtual void ICachePut(Object key, IntrospectionCacheData o) { introspectionCache[key] = o; } public virtual EventCartridge AttachEventCartridge(EventCartridge ec) { EventCartridge temp = eventCartridge; eventCartridge = ec; return temp; } } } --- NEW FILE: InternalWrapperContext.cs --- namespace NVelocity.Context { /// <summary> /// interface for internal context wrapping functionality /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: InternalWrapperContext.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ </version> public interface InternalWrapperContext { /// <summary> /// returns the wrapped user context /// </summary> IContext InternalUserContext { get; } /// <summary> /// returns the base full context impl /// </summary> InternalContextAdapter BaseContext { get; } } } --- NEW FILE: AbstractContext.cs --- namespace NVelocity.Context { using System; /// <summary> This class is the abstract base class for all conventional /// Velocity Context implementations. Simply extend this class /// and implement the abstract routines that access your preferred /// storage method. /// * /// Takes care of context chaining. /// * /// Also handles / enforces policy on null keys and values : /// * /// <ul> /// <li> Null keys and values are accepted and basically dropped. /// <li> If you place an object into the context with a null key, it /// will be ignored and logged. /// <li> If you try to place a null into the context with any key, it /// will be dropped and logged. /// </ul> /// * /// The default implementation of this for application use is /// org.apache.velocity.VelocityContext. /// * /// All thanks to Fedor for the chaining idea. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:fed...@ho...">Fedor Karpelevitch</a> /// </author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: AbstractContext.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> [Serializable] public abstract class AbstractContext : InternalContextBase, IContext { //, System.Runtime.Serialization.ISerializable public virtual Object[] Keys { get { return InternalGetKeys(); } } public virtual IContext ChainedContext { get { return innerContext; } } /// <summary> the chained Context if any /// </summary> private IContext innerContext = null; /// /// <summary> Implement to return a value from the context storage. /// <br><br> /// The implementation of this method is required for proper /// operation of a Context implementation in general /// Velocity use. /// /// </summary> /// <param name="key">key whose associated value is to be returned /// </param> /// <returns>object stored in the context /// /// </returns> public abstract Object InternalGet(String key); /// /// <summary> Implement to put a value into the context storage. /// <br><br> /// The implementation of this method is required for /// proper operation of a Context implementation in /// general Velocity use. /// * /// </summary> /// <param name="key">key with which to associate the value /// </param> /// <param name="value">value to be associated with the key /// </param> /// <returns>previously stored value if exists, or null /// /// </returns> public abstract Object InternalPut(String key, Object value_Renamed); /// /// <summary> Implement to determine if a key is in the storage. /// <br><br> /// Currently, this method is not used internally by /// the Velocity core. /// * /// </summary> /// <param name="key">key to test for existance /// </param> /// <returns>true if found, false if not /// /// </returns> public abstract bool InternalContainsKey(Object key); /// /// <summary> Implement to return an object array of key /// strings from your storage. /// <br><br> /// Currently, this method is not used internally by /// the Velocity core. /// * /// </summary> /// <returns>array of keys /// /// </returns> public abstract Object[] InternalGetKeys(); /// /// <summary> I mplement to remove an item from your storage. /// <br><br> /// Currently, this method is not used internally by /// the Velocity core. /// * /// </summary> /// <param name="key">key to remove /// </param> /// <returns>object removed if exists, else null /// /// </returns> public abstract Object InternalRemove(Object key); /// <summary> default CTOR /// </summary> public AbstractContext() { } /// <summary> Chaining constructor accepts a Context argument. /// It will relay get() operations into this Context /// in the even the 'local' get() returns null. /// /// </summary> /// <param name="inner">context to be chained /// /// </param> public AbstractContext(IContext inner) { innerContext = inner; /* * now, do a 'forward pull' of event cartridge so * it's accessable, bringing to the top level. */ if (innerContext is InternalEventContext) { AttachEventCartridge(((InternalEventContext) innerContext).EventCartridge); } } /// <summary> Adds a name/value pair to the context. /// /// </summary> /// <param name="key"> The name to key the provided value with. /// </param> /// <param name="value">The corresponding value. /// </param> /// <returns>Object that was replaced in the the Context if /// applicable or null if not. /// /// </returns> public virtual Object Put(String key, Object value_Renamed) { /* * don't even continue if key or value is null */ if (key == null) { return null; } else if (value_Renamed == null) { return null; } return InternalPut(key, value_Renamed); } /// <summary> Gets the value corresponding to the provided key from the context. /// * /// Supports the chaining context mechanism. If the 'local' context /// doesn't have the value, we try to get it from the chained context. /// * /// </summary> /// <param name="key">The name of the desired value. /// </param> /// <returns> The value corresponding to the provided key or null if /// the key param is null. /// /// </returns> public virtual Object Get(String key) { /* * punt if key is null */ if (key == null) { return null; } /* * get the object for this key. If null, and we are chaining another Context * call the get() on it. */ Object o = InternalGet(key); if (o == null && innerContext != null) { o = innerContext.Get(key); } return o; } /// <summary> Indicates whether the specified key is in the context. Provided for /// debugging purposes. /// * /// </summary> /// <param name="key">The key to look for. /// </param> /// <returns>true if the key is in the context, false if not. /// /// </returns> public virtual bool ContainsKey(Object key) { if (key == null) { return false; } return InternalContainsKey(key); } /// <summary> Get all the keys for the values in the context /// </summary> /// <returns>Object[] of keys in the Context. Does not return /// keys in chained context. /// /// </returns> /// <summary> Removes the value associated with the specified key from the context. /// * /// </summary> /// <param name="key">The name of the value to remove. /// </param> /// <returns> The value that the key was mapped to, or <code>null</code> /// if unmapped. /// /// </returns> public virtual Object Remove(Object key) { if (key == null) { return null; } return InternalRemove(key); } /// <summary> returns innerContext if one is chained /// * /// </summary> /// <returns>Context if chained, <code>null</code> if not /// /// </returns> } } --- NEW FILE: InternalContextAdapterImpl.cs --- namespace NVelocity.Context { using System; using NVelocity.App.Events; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> This adapter class is the container for all context types for internal /// use. The AST now uses this class rather than the app-level Context /// interface to allow flexibility in the future. /// * /// Currently, we have two context interfaces which must be supported : /// <ul> /// <li> Context : used for application/template data access /// <li> InternalHousekeepingContext : used for internal housekeeping and caching /// <li> InternalWrapperContext : used for getting root cache context and other /// such. /// <li> InternalEventContext : for event handling. /// </ul> /// * /// This class implements the two interfaces to ensure that all methods are /// supported. When adding to the interfaces, or adding more context /// functionality, the interface is the primary definition, so alter that first /// and then all classes as necessary. As of this writing, this would be /// the only class affected by changes to InternalContext /// * /// This class ensures that an InternalContextBase is available for internal /// use. If an application constructs their own Context-implementing /// object w/o subclassing AbstractContext, it may be that support for /// InternalContext is not available. Therefore, InternalContextAdapter will /// create an InternalContextBase if necessary for this support. Note that /// if this is necessary, internal information such as node-cache data will be /// lost from use to use of the context. This may or may not be important, /// depending upon application. /// /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: InternalContextAdapterImpl.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> //TODO: class was sealed public class InternalContextAdapterImpl : InternalContextAdapter { public virtual String CurrentTemplateName { get { return icb.CurrentTemplateName; } } public virtual Object[] TemplateNameStack { get { return icb.TemplateNameStack; } } public virtual Resource CurrentResource { get { return icb.CurrentResource; } set { icb.CurrentResource = value; } } public virtual Object[] Keys { get { return context.Keys; } } public virtual IContext InternalUserContext { get { return context; } } public virtual InternalContextAdapter BaseContext { get { return this; } } public virtual EventCartridge EventCartridge { get { if (iec != null) { return iec.EventCartridge; } return null; } } /// /// <summary> the user data Context that we are wrapping /// </summary> internal IContext context = null; /// /// <summary> the ICB we are wrapping. We may need to make one /// if the user data context implementation doesn't /// support one. The default AbstractContext-derived /// VelocityContext does, and it's recommended that /// people derive new contexts from AbstractContext /// rather than piecing things together /// </summary> internal InternalHousekeepingContext icb = null; /// <summary> The InternalEventContext that we are wrapping. If /// the context passed to us doesn't support it, no /// biggie. We don't make it for them - since its a /// user context thing, nothing gained by making one /// for them now /// </summary> internal InternalEventContext iec = null; /// <summary> CTOR takes a Context and wraps it, delegating all 'data' calls /// to it. /// /// For support of internal contexts, it will create an InternalContextBase /// if need be. /// </summary> public InternalContextAdapterImpl(IContext c) { context = c; if (!(c is InternalHousekeepingContext)) { icb = new InternalContextBase(); } else { icb = (InternalHousekeepingContext) context; } if (c is InternalEventContext) { iec = (InternalEventContext) context; } } /* --- InternalHousekeepingContext interface methods --- */ public void PushCurrentTemplateName(String s) { icb.PushCurrentTemplateName(s); } public void PopCurrentTemplateName() { icb.PopCurrentTemplateName(); } public IntrospectionCacheData ICacheGet(Object key) { return icb.ICacheGet(key); } public void ICachePut(Object key, IntrospectionCacheData o) { icb.ICachePut(key, o); } /* --- Context interface methods --- */ public Object Put(String key, Object value_Renamed) { return context.Put(key, value_Renamed); } public Object Get(String key) { return context.Get(key); } public bool ContainsKey(Object key) { return context.ContainsKey(key); } public Object Remove(Object key) { return context.Remove(key); } /* ---- InternalWrapperContext --- */ /// <summary> returns the user data context that /// we are wrapping /// </summary> /// <summary> Returns the base context that we are /// wrapping. Here, its this, but for other thing /// like VM related context contortions, it can /// be something else /// </summary> /* ----- InternalEventContext ---- */ public EventCartridge AttachEventCartridge(EventCartridge ec) { if (iec != null) { return iec.AttachEventCartridge(ec); } return null; } } } --- NEW FILE: VMContext.cs --- namespace NVelocity.Context { using System; using System.Collections; using NVelocity.App.Events; using NVelocity.Runtime; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> This is a special, internal-use-only context implementation to be /// used for the new Velocimacro implementation. /// * /// The main distinguishing feature is the management of the VMProxyArg objects /// in the put() and get() methods. /// * /// Further, this context also supports the 'VM local context' mode, where /// any get() or put() of references that aren't args to the VM are considered /// local to the vm, protecting the global context. /// /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VMContext.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> public class VMContext : InternalContextAdapter { private void InitBlock() { vmproxyhash = new Hashtable(); localcontext = new Hashtable(); } public virtual IContext InternalUserContext { get { return innerContext.InternalUserContext; } } public virtual InternalContextAdapter BaseContext { get { return innerContext.BaseContext; } } public virtual Object[] Keys { get { // TODO //return vmproxyhash.keySet().toArray(); throw new NotImplementedException(); } } public virtual String CurrentTemplateName { get { return innerContext.CurrentTemplateName; } } public virtual Object[] TemplateNameStack { get { return innerContext.TemplateNameStack; } } public virtual EventCartridge EventCartridge { get { return innerContext.EventCartridge; } } public virtual Resource CurrentResource { get { return innerContext.CurrentResource; } set { innerContext.CurrentResource = value; } } /// <summary>container for our VMProxy Objects /// </summary> //UPGRADE_NOTE: The initialization of 'vmproxyhash' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal Hashtable vmproxyhash; /// <summary>container for any local or constant VMProxy items /// </summary> //UPGRADE_NOTE: The initialization of 'localcontext' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal Hashtable localcontext; /// <summary>the base context store. This is the 'global' context /// </summary> internal InternalContextAdapter innerContext = null; /// <summary>context that we are wrapping /// </summary> internal InternalContextAdapter wrappedContext = null; /// <summary>support for local context scope feature, where all references are local /// </summary> private bool localcontextscope = false; /// <summary> CTOR, wraps an ICA /// </summary> public VMContext(InternalContextAdapter inner, RuntimeServices rsvc) { InitBlock(); localcontextscope = rsvc.getBoolean(RuntimeConstants_Fields.VM_CONTEXT_LOCALSCOPE, false); wrappedContext = inner; innerContext = inner.BaseContext; } /// <summary> return the inner / user context /// </summary> /// <summary> Used to put VMProxyArgs into this context. It separates /// the VMProxyArgs into constant and non-constant types /// pulling out the value of the constant types so they can /// be modified w/o damaging the VMProxyArg, and leaving the /// dynamic ones, as they modify context rather than their own /// state /// </summary> /// <param name="vmpa">VMProxyArg to add /// /// </param> public virtual void AddVMProxyArg(VMProxyArg vmpa) { /* * ask if it's a constant : if so, get the value and put into the * local context, otherwise, put the vmpa in our vmproxyhash */ String key = vmpa.ContextReference; if (vmpa.isConstant()) { localcontext[key] = vmpa.getObject(wrappedContext); } else { vmproxyhash[key] = vmpa; } } /// <summary> Impl of the Context.put() method. /// * /// </summary> /// <param name="key">name of item to set /// </param> /// <param name="value">object to set to key /// </param> /// <returns>old stored object /// /// </returns> public virtual Object Put(String key, Object value_Renamed) { /* * first see if this is a vmpa */ VMProxyArg vmpa = (VMProxyArg) vmproxyhash[key]; if (vmpa != null) { return vmpa.setObject(wrappedContext, value_Renamed); } else { if (localcontextscope) { /* * if we have localcontextscope mode, then just * put in the local context */ return localcontext[key] = value_Renamed; } else { /* * ok, how about the local context? */ if (localcontext.ContainsKey(key)) { return localcontext[key] = value_Renamed; } else { /* * otherwise, let them push it into the 'global' context */ return innerContext.Put(key, value_Renamed); } } } } /// <summary> Impl of the Context.gut() method. /// * /// </summary> /// <param name="key">name of item to get /// </param> /// <returns> stored object or null /// /// </returns> public virtual Object Get(String key) { /* * first, see if it's a VMPA */ Object o = null; VMProxyArg vmpa = (VMProxyArg) vmproxyhash[key]; if (vmpa != null) { o = vmpa.getObject(wrappedContext); } else { if (localcontextscope) { /* * if we have localcontextscope mode, then just * put in the local context */ o = localcontext[key]; } else { /* * try the local context */ o = localcontext[key]; if (o == null) { /* * last chance */ o = innerContext.Get(key); } } } return o; } /// <summary> not yet impl /// </summary> public virtual bool ContainsKey(Object key) { return false; } /// <summary> impl badly /// </summary> /// <summary> impl badly /// </summary> public virtual Object Remove(Object key) { Object o = vmproxyhash[key]; vmproxyhash.Remove(key); return o; } public virtual void PushCurrentTemplateName(String s) { innerContext.PushCurrentTemplateName(s); } public virtual void PopCurrentTemplateName() { innerContext.PopCurrentTemplateName(); } public virtual IntrospectionCacheData ICacheGet(Object key) { return innerContext.ICacheGet(key); } public virtual void ICachePut(Object key, IntrospectionCacheData o) { innerContext.ICachePut(key, o); } public virtual EventCartridge AttachEventCartridge(EventCartridge ec) { return innerContext.AttachEventCartridge(ec); } } } --- NEW FILE: InternalContextAdapter.cs --- namespace NVelocity.Context { /// <summary> interface to bring all necessary internal and user contexts together. /// this is what the AST expects to deal with. If anything new comes /// along, add it here. /// * /// I will rename soon :) /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: InternalContextAdapter.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> public interface InternalContextAdapter : InternalHousekeepingContext, IContext, InternalWrapperContext, InternalEventContext { } } --- NEW FILE: InternalHousekeepingContext.cs --- namespace NVelocity.Context { using System; using NVelocity.Runtime.Resource; using NVelocity.Util.Introspection; /// <summary> /// interface to encapsulate the 'stuff' for internal operation of velocity. /// We use the context as a thread-safe storage : we take advantage of the /// fact that it's a visitor of sorts to all nodes (that matter) of the /// AST during init() and render(). /// /// Currently, it carries the template name for namespace /// support, as well as node-local context data introspection caching. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:Chr...@dl...">Christoph Reck</a></author> /// <version> $Id: InternalHousekeepingContext.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $</version> public interface InternalHousekeepingContext { String CurrentTemplateName { get; } Object[] TemplateNameStack { get; } Resource CurrentResource { get; set; } /// <summary> /// set the current template name on top of stack /// </summary> /// <param name="s">current template name</param> void PushCurrentTemplateName(String s); /// <summary> /// remove the current template name from stack /// </summary> void PopCurrentTemplateName(); /// <summary> get the current template name /// * /// </summary> /// <returns>String current template name /// /// </returns> /// <summary> Returns the template name stack in form of an array. /// * /// </summary> /// <returns>Object[] with the template name stack contents. /// /// </returns> /// <seealso cref=" IntrospectionCacheData) /// object if exists for the key /// * /// "/> /// <param name="key"> key to find in cache /// </param> /// <returns>cache object /// /// </returns> IntrospectionCacheData ICacheGet(Object key); /// <seealso cref=" IntrospectionCacheData) /// element in the cache for specified key /// * /// "/> /// <param name="key"> key /// </param> /// <param name="o"> IntrospectionCacheData object to place in cache /// /// </param> void ICachePut(Object key, IntrospectionCacheData o); /// <summary> /// temporary fix to enable #include() to figure out /// current encoding. /// </summary> } } --- NEW FILE: IContext.cs --- namespace NVelocity.Context { using System; /// <summary> /// Interface describing the application data context. This set of /// routines is used by the application to set and remove 'named' data /// object to pass them to the template engine to use when rendering /// a template. /// /// This is the same set of methods supported by the original Context /// class /// </summary> /// <seealso cref="NVelocity.Context.AbstractContext"/> /// <seealso cref="NVelocity.VelocityContext"/> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> public interface IContext { /// <summary> /// Adds a name/value pair to the context. /// </summary> /// <param name="key">The name to key the provided value with.</param> /// <param name="value">The corresponding value.</param> Object Put(String key, Object value); /// <summary> /// Gets the value corresponding to the provided key from the context. /// </summary> /// <param name="key">The name of the desired value.</param> /// <returns>The value corresponding to the provided key.</returns> Object Get(String key); /// <summary> /// Indicates whether the specified key is in the context. /// </summary> /// <param name="key">The key to look for.</param> /// <returns>Whether the key is in the context.</returns> Boolean ContainsKey(Object key); /// <summary> /// Get all the keys for the values in the context /// </summary> Object[] Keys { get; } /// <summary> /// Removes the value associated with the specified key from the context. /// </summary> /// <param name="key">The name of the value to remove.</param> /// <returns>The value that the key was mapped to, or <code>null</code> if unmapped.</returns> Object Remove(Object key); } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:09
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/IO In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/IO Added Files: VelocityWriter.cs Log Message: --- NEW FILE: VelocityWriter.cs --- //package org.apache.velocity.io; // // //import java.io.IOException; //import java.io.OutputStreamWriter; //import java.io.Writer; namespace NVelocity.IO { using System; using System.IO; using System.Text; /** * Implementation of a fast Writer. It was originally taken from JspWriter * and modified to have less syncronization going on. * * @author <a href="mailto:jv...@ap...">Jason van Zyl</a> * @author <a href="mailto:jo...@la...">Jon S. Stevens</a> * @author Anil K. Vijendran * @version $Id: VelocityWriter.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ */ // TODO: class was final and it appears that readonly and final are not the same thing - most of the methods were final as well public class VelocityWriter : TextWriter { /** * constant indicating that the Writer is not buffering output */ public static readonly int NO_BUFFER = 0; /** * constant indicating that the Writer is buffered and is using the * implementation default buffer size */ public static readonly int DEFAULT_BUFFER = -1; /** * constant indicating that the Writer is buffered and is unbounded; * this is used in BodyContent */ public static readonly int UNBOUNDED_BUFFER = -2; protected int bufferSize; protected Boolean autoFlush; private TextWriter writer; private char[] cb; private int nextChar; private static int defaultCharBufferSize = 8*1024; private Boolean flushed = false; /** * Create a buffered character-output stream that uses a default-sized * output buffer. * * @param response A Servlet Response */ public VelocityWriter(TextWriter writer) : this(writer, defaultCharBufferSize, true) { } /** * private constructor. */ private VelocityWriter(int bufferSize, Boolean autoFlush) { this.bufferSize = bufferSize; this.autoFlush = autoFlush; } /** * This method returns the size of the buffer used by the JspWriter. * * @return the size of the buffer in bytes, or 0 is unbuffered. */ public int getBufferSize() { return bufferSize; } /** * This method indicates whether the JspWriter is autoFlushing. * * @return if this JspWriter is auto flushing or throwing IOExceptions on * buffer overflow conditions */ public Boolean isAutoFlush() { return autoFlush; } /** * Create a new buffered character-output stream that uses an output * buffer of the given size. * * @param response A Servlet Response * @param sz Output-buffer size, a positive integer * * @exception IllegalArgumentException If sz is <= 0 */ public VelocityWriter(TextWriter writer, int sz, Boolean autoFlush) : this(sz, autoFlush) { if (sz < 0) throw new ArgumentOutOfRangeException("Buffer size <= 0"); this.writer = writer; cb = sz == 0 ? null : new char[sz]; nextChar = 0; } private void init(TextWriter writer, int sz, Boolean autoFlush) { this.writer = writer; if (sz > 0 && (cb == null || sz > cb.Length)) cb = new char[sz]; nextChar = 0; this.autoFlush = autoFlush; this.bufferSize = sz; } /** * Flush the output buffer to the underlying character stream, without * flushing the stream itself. This method is non-private only so that it * may be invoked by PrintStream. */ private void flushBuffer() { //throws IOException if (bufferSize == 0) return; flushed = true; if (nextChar == 0) return; writer.Write(cb, 0, nextChar); nextChar = 0; } /** * Discard the output buffer. */ public void clear() { nextChar = 0; } private void bufferOverflow() { // throws IOException throw new IOException("overflow"); } /** * Flush the stream. * */ public void flush() { // throws IOException flushBuffer(); if (writer != null) { writer.Flush(); } } /** * Close the stream. * */ public void close() { //throws IOException { if (writer == null) return; flush(); } /** * @return the number of bytes unused in the buffer */ public int getRemaining() { return bufferSize - nextChar; } /** * Write a single character. * */ public void write(int c) { //throws IOException { if (bufferSize == 0) { writer.Write(c); } else { if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); cb[nextChar++] = (char) c; } } /** * Our own little min method, to avoid loading java.lang.Math if we've run * out of file descriptors and we're trying to print a stack trace. */ private int min(int a, int b) { if (a < b) return a; return b; } /** * Write a portion of an array of characters. * * <p> Ordinarily this method stores characters from the given array into * this stream's buffer, flushing the buffer to the underlying stream as * needed. If the requested length is at least as large as the buffer, * however, then this method will flush the buffer and write the characters * directly to the underlying stream. Thus redundant * <code>DiscardableBufferedWriter</code>s will not copy data unnecessarily. * * @param cbuf A character array * @param off Offset from which to start reading characters * @param len Number of characters to write * */ public void write(char[] cbuf, int off, int len) { //throws IOException { if (bufferSize == 0) { writer.Write(cbuf, off, len); return; } if (len == 0) { return; } if (len >= bufferSize) { /* If the request length exceeds the size of the output buffer, flush the buffer and then write the data directly. In this way buffered streams will cascade harmlessly. */ if (autoFlush) flushBuffer(); else bufferOverflow(); writer.Write(cbuf, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); Array.Copy(cbuf, b, cb, nextChar, d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write an array of characters. This method cannot be inherited from the * Writer class because it must suppress I/O exceptions. */ public void write(char[] buf) { //throws IOException { write(buf, 0, buf.Length); } /** * Write a portion of a String. * * @param s String to be written * @param off Offset from which to start reading characters * @param len Number of characters to be written * */ public void write(String s, int off, int len) { //throws IOException { if (bufferSize == 0) { writer.Write(s, off, len); return; } int b = off, t = off + len; while (b < t) { int d = min(bufferSize - nextChar, t - b); Array.Copy(s.ToCharArray(), b, cb, nextChar, b + d); b += d; nextChar += d; if (nextChar >= bufferSize) if (autoFlush) flushBuffer(); else bufferOverflow(); } } /** * Write a string. This method cannot be inherited from the Writer class * because it must suppress I/O exceptions. */ public void write(String s) { //throws IOException { write(s, 0, s.Length); } /** * resets this class so that it can be reused * */ public void recycle(TextWriter writer) { this.writer = writer; flushed = false; clear(); } // needed to extend TextWriter public override Encoding Encoding { get { return writer.Encoding; } } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:09
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Defaults In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Defaults Added Files: directive.properties nvelocity.properties Log Message: --- NEW FILE: nvelocity.properties --- #---------------------------------------------------------------------------- # These are the default properties for the # NVelocity Runtime. These values are used when # Runtime.init() is called, and when Runtime.init(properties) # fails to find the specificed properties file. #---------------------------------------------------------------------------- #---------------------------------------------------------------------------- # R U N T I M E L O G #---------------------------------------------------------------------------- #---------------------------------------------------------------------------- # default LogSystem to use: default: SimpleLog4NetLogSystem #---------------------------------------------------------------------------- runtime.log.logsystem.class = NVelocity.Runtime.Log.SimpleLog4NetLogSystem #--------------------------------------------------------------------------- # This is the location of the NVelocity Runtime log. #---------------------------------------------------------------------------- runtime.log = nvelocity.log #---------------------------------------------------------------------------- # This controls if Runtime.error(), info() and warn() messages include the # whole stack trace. The last property controls whether invalid references # are logged. #---------------------------------------------------------------------------- runtime.log.error.stacktrace = false runtime.log.warn.stacktrace = false runtime.log.info.stacktrace = false runtime.log.invalid.reference = true #---------------------------------------------------------------------------- # Configuration for the Log4NetLogSystem. # You must define the runtime.log.logsystem.class property to be: # NVelocity.Runtime.Log.Log4NetLogSystem # # You must also include log4net dll files into your classpath. They are # included with the Velocity distribution in the build/lib directory. # # There are several different options that you can configure. # Uncomment the ones that you want and also define their settings. #---------------------------------------------------------------------------- #runtime.log.logsystem.log4net.pattern=%d - %m%n #runtime.log.logsystem.log4net.file.size=100000 #runtime.log.logsystem.log4net.file.backups=1 #runtime.log.logsystem.log4net.syslogd.host=my.syslog.server.com #runtime.log.logsystem.log4net.syslogd.facility=LOG_DAEMON #runtime.log.logsystem.log4net.remote.host=my.remote.server.com #runtime.log.logsystem.log4net.remote.port=1099 #runtime.log.logsystem.log4net.email.server=localhost #runtime.log.logsystem.log4net.email.from=root@localhost #runtime.log.logsystem.log4net.email.to=root@localhost #runtime.log.logsystem.log4net.email.subject=NVelocity Error Report #runtime.log.logsystem.log4net.email.buffer.size=512 #---------------------------------------------------------------------------- # T E M P L A T E E N C O D I N G #---------------------------------------------------------------------------- input.encoding=ISO-8859-1 output.encoding=ISO-8859-1 #---------------------------------------------------------------------------- # F O R E A C H P R O P E R T I E S #---------------------------------------------------------------------------- # These properties control how the counter is accessed in the #foreach # directive. By default the reference $velocityCount will be available # in the body of the #foreach directive. The default starting value # for this reference is 1. #---------------------------------------------------------------------------- directive.foreach.counter.name = velocityCount directive.foreach.counter.initial.value = 1 #---------------------------------------------------------------------------- # I N C L U D E P R O P E R T I E S #---------------------------------------------------------------------------- # These are the properties that governed the way #include'd content # is governed. #---------------------------------------------------------------------------- directive.include.output.errormsg.start = <!-- include error : directive.include.output.errormsg.end = see error log --> #---------------------------------------------------------------------------- # P A R S E P R O P E R T I E S #---------------------------------------------------------------------------- directive.parse.max.depth = 10 #---------------------------------------------------------------------------- # T E M P L A T E L O A D E R S #---------------------------------------------------------------------------- # # #---------------------------------------------------------------------------- resource.loader = file file.resource.loader.description = NVelocity File Resource Loader file.resource.loader.class = NVelocity.Runtime.Resource.Loader.FileResourceLoader file.resource.loader.path = . file.resource.loader.cache = false file.resource.loader.modificationCheckInterval = 2 #---------------------------------------------------------------------------- # VELOCIMACRO PROPERTIES #---------------------------------------------------------------------------- # global : name of default global library. It is expected to be in the regular # template path. You may remove it (either the file or this property) if # you wish with no harm. #---------------------------------------------------------------------------- velocimacro.library = VM_global_library.vm velocimacro.permissions.allow.inline = true velocimacro.permissions.allow.inline.to.replace.global = false velocimacro.permissions.allow.inline.local.scope = false velocimacro.context.localscope = false #---------------------------------------------------------------------------- # INTERPOLATION #---------------------------------------------------------------------------- # turn off and on interpolation of references and directives in string # literals. ON by default :) #---------------------------------------------------------------------------- runtime.interpolate.string.literals = true #---------------------------------------------------------------------------- # RESOURCE MANAGEMENT #---------------------------------------------------------------------------- # Allows alternative ResourceManager and ResourceCache implementations # to be plugged in. #---------------------------------------------------------------------------- resource.manager.class = NVelocity.Runtime.Resource.ResourceManagerImpl resource.manager.cache.class = NVelocity.Runtime.Resource.ResourceCacheImpl --- NEW FILE: directive.properties --- directive.1=NVelocity.Runtime.Directive.Foreach directive.2=NVelocity.Runtime.Directive.Include directive.3=NVelocity.Runtime.Directive.Parse directive.4=NVelocity.Runtime.Directive.Macro directive.5=NVelocity.Runtime.Directive.Literal |