Reflection For Information On Constants

How can one get the names of all the constants in a given type?

How can one get the values of all the constants in a given type?

See below.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;

namespace Test.Abcd.Common.Core
{
	/// <summary>
	/// This provides generic services for Reflection.
	/// </summary>
	public static class ReflectionHelper
	{
		#region HelperMethods

		/// <summary>
		/// This returns FieldInfo for constants in a given type.
		/// </summary>
		/// <param name="targetType">This is the type to use.</param>
		/// <returns>This is an array of FieldInfo objects.</returns>
		/// <remarks>
		/// Note that this code was refactored from code found on 20091201 at the following link...
		/// http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx
		/// </remarks>
		public static FieldInfo[] GetConstantFieldInfoArray(System.Type targetType)
		{
			//The "BindingFlags.Public" gets all public fields.
			//The "BindingFlags.Static" gets all static fields.
			//The "BindingFlags.FlattenHierarchy" gets fields from all base types.
			FieldInfo[] myFields = targetType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

			ArrayList myConstants = new ArrayList();

			//Go through the list and only pick out the constants.
			foreach (FieldInfo myFieldInfoTemp in myFields)
			{
				// IsLiteral determines if its value is written at compile time and not changeable.
				// IsInitOnly determine if the field can be set in the body of the constructor.
				// For C#, a field with the readonly keyword would have IsLiteral=true and IsInitOnly=true. 
				// For C#, a const field would have IsLiteral=true and IsInitOnly=false.
				if ((myFieldInfoTemp.IsLiteral) && (!myFieldInfoTemp.IsInitOnly))
				{
					myConstants.Add(myFieldInfoTemp);
				}
			}

			// Return an array of FieldInfos
			return (FieldInfo[])myConstants.ToArray(typeof(FieldInfo));
		}

		/// <summary>
		/// This will get the values of all the constants in the given type.
		/// </summary>
		/// <param name="targetType">This is the type to use.</param>
		/// <param name="convertToLowercase">This is a flag indicating if the values should be converted to lowercase or not.</param>
		/// <param name="trimWhitespace">This is a flag indicating if the values should be whitespace-trimmed or not.</param>
		/// <returns>This a collection of the values.</returns>
		/// <remarks>
		/// Note this will only work if the underlying type for the constants is "string".
		/// </remarks>
		public static StringCollection GetConstantValueStringCollection(System.Type targetType, bool convertToLowercase, bool trimWhitespace)
		{
			StringCollection myCollection = null;

			FieldInfo[] myFieldInfoArray = Team.Framework.Common.Core.ReflectionHelper.GetConstantFieldInfoArray(targetType);
			string myValueStringTemp = "";
			object myValueObjectTemp = null;
			int myLoopIndex = 0;
			myCollection = new StringCollection();

			foreach (FieldInfo myFieldInfoTemp in myFieldInfoArray)
			{
				myValueObjectTemp = null;
				myValueStringTemp = "";

				if (myFieldInfoTemp == null)
				{
					throw new System.ApplicationException("The current object, myFieldInfoTemp, is null.");
				}

				myValueObjectTemp = myFieldInfoTemp.GetValue(null);
				Debug.WriteLine("myLoopIndex='" + myLoopIndex.ToString() + "'");

				if (myValueObjectTemp == null)
				{
					myValueStringTemp = "";
					Debug.WriteLine("myValueObjectTemp == null");
					Debug.WriteLine("myValueStringTemp='" + myValueStringTemp + "'");
				}
				else
				{
					myValueStringTemp = myValueObjectTemp.ToString();

					if (convertToLowercase)
					{
						myValueStringTemp = myValueStringTemp.ToLower();
					}

					if (trimWhitespace)
					{
						myValueStringTemp = myValueStringTemp.Trim();
					}
					
					Debug.WriteLine("myValueObjectTemp != null");
					Debug.WriteLine("myValueStringTemp='" + myValueStringTemp + "'");
				}

				myCollection.Add(myValueStringTemp);
				myLoopIndex = myLoopIndex + 1;
			}

			return myCollection;
		}

		#endregion //HelperMethods
	}
}

HTH.

Thank you.

— Mark Kamoski

Advertisements

Simple RSS Control

This is a simple RSS control.

(To use this sample, one needs the code below plus a Linq-To-Sql data model with the given table in it.)

This is the User Control code-behind…

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;

/// <summary>
/// This control displays Rss content.
/// </summary>
/// <remarks>
/// The code in this control was refactored from the orginal found on 20091128 here...
/// http://code.msdn.microsoft.com/CreateRSSFeedVBNet/Release/ProjectReleases.aspx?ReleaseId=969
/// </remarks>
public partial class EasyControls_RssCreatorControl01 : System.Web.UI.UserControl
{
	#region HelperMethods

	public void DoPageLoad()
	{
		this.Response.Clear();
		this.Response.ContentType = "text/xml";
		var myDataContext = new Aggregator01DbDataContext();

		//Add a where clause here if desired.
		var myRssNewsRecords = from r in myDataContext.RssNewsRecord
							   select r;

		var myRssItemList = new List<System.Xml.Linq.XElement>();
		XElement myRssItemTemp = null;

		foreach (RssNewsRecord myRssNewsRecordTemp in myRssNewsRecords)
		{
			myRssItemTemp = new XElement(
				"item",
				new System.Xml.Linq.XElement("title", myRssNewsRecordTemp.Title),
				new System.Xml.Linq.XElement("link", myRssNewsRecordTemp.Link),
				new System.Xml.Linq.XElement("description", myRssNewsRecordTemp.Description),
				new System.Xml.Linq.XElement("pubDate", DateTime.Now.ToString("r"))
				);

			myRssItemList.Add(myRssItemTemp);
		}

		XDocument myRssResult = new XDocument();
		myRssResult.Declaration = new XDeclaration("1.0", "utf-8", "yes");

		XElement myNode1 = new XElement("rss", "");
		XAttribute myAttribute = new XAttribute("version", "2.0");
		myNode1.Add(myAttribute);

		XElement myNode2 = new XElement(
			"channel",
			new System.Xml.Linq.XElement("title", ConfigurationManager.AppSettings["rss_Title"]),
			new System.Xml.Linq.XElement("link", ConfigurationManager.AppSettings["rss_Link"]),
			new System.Xml.Linq.XElement("description", ConfigurationManager.AppSettings["rss_Description"]),
			new System.Xml.Linq.XElement("pubDate", DateTime.Now.ToString("r")),
			myRssItemList
			);

		myNode1.AddFirst(myNode2);
		myRssResult.AddFirst(myNode1);
		this.Response.Write(myRssResult.ToString());
		this.Response.End();
	}

	#endregion //HelperMethods

	#region HandlerMethods

	protected void Page_Load(object sender, EventArgs e)
	{
		this.DoPageLoad();
	}

	#endregion //HandlerMethods
}

This is the User Control code-infront…

<%@ control language="C#" autoeventwireup="true" codefile="RssCreatorControl01.ascx.cs" inherits="EasyControls_RssCreatorControl01" %>

This is the SQL schema…

USE [YOUR_DATABASE_NAME_GOES_HERE]
GO
/****** Object:  Table [dbo].[RssNewsRecord]    Script Date: 11/30/2009 14:32:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RssNewsRecord]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RssNewsRecord](
[Description] [varchar](1024) NOT NULL CONSTRAINT [DF_RssNewsRecord_Description]  DEFAULT (''),
[Link] [varchar](128) NOT NULL CONSTRAINT [DF_RssNewsRecord_Link]  DEFAULT (''),
[LiveDate] [datetime] NOT NULL CONSTRAINT [DF_RssNewsRecord_LiveDate]  DEFAULT (getdate()),
[ModifiedBy] [nvarchar](128) NOT NULL CONSTRAINT [DF_RssNewsRecord_ModifiedBy]  DEFAULT (''),
[ModifiedDateTime] [datetime] NOT NULL CONSTRAINT [DF_RssNewsRecord_ModifiedDateTime]  DEFAULT (getdate()),
[ModifiedTimestamp] [timestamp] NOT NULL,
[PkId] [uniqueidentifier] NOT NULL CONSTRAINT [DF_RssNewsRecord_Id]  DEFAULT (newid()),
[Title] [varchar](128) NOT NULL CONSTRAINT [DF_RssNewsRecord_Title]  DEFAULT (''),
CONSTRAINT [Pk_RssNewsRecord_PkId] PRIMARY KEY CLUSTERED
(
[PkId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
CONSTRAINT [Uk_RssNewsRecord_Title] UNIQUE NONCLUSTERED
(
[Title] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF

This is the consuming page code-behind…

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class RssCreatorControl01Test01 : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}
}

This is the consuming page code-infront…

<%@ page language="C#" autoeventwireup="true" codefile="RssCreatorControl01Test01.aspx.cs" inherits="RssCreatorControl01Test01" %>

<%@ register src="EasyControls/RssCreatorControl01.ascx" tagname="RssCreatorControl01" tagprefix="uc1" %>
<uc1:rsscreatorcontrol01 id="RssCreatorControl011" runat="server" />

Screen Scraper Code Sample 01

Screen Scraper Sample 01

Once I had to make a simple, one-page, basic, screen scraper sample.

The code is below.

This is the code-infront…

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Text;

public partial class ScreenScraperExample4 : System.Web.UI.Page
{
	#region MemberConstants

	public const string DefaultDateTimeFormat = "yyyy-MM-dd HH:mm:ss.fffffff tt zzz";
	public const int DefaultUrlLengthMin = 16;
	public const int DefaultStartTokenLengthMin = 1;
	public const int DefaultEndTokenLengthMin = 1;
	public const string DefaultUrl = @"http://www.Google.com";
	public const string DefaultStartToken = @"Web";
	public const string DefaultEndToken = @"News";

	#endregion //MemberConstants

	#region HelperMethods

	private string GetDataValue(string targetUrl, string targetTokenStart, string targetTokenEnd)
	{
		string myReturnValue = "";

		//Special thanks to the following link for starting point, etc,...
		//http://www.eggheadcafe.com/community/aspnet/2/10065129/parsing-datas-from-the-ht.aspx

		targetUrl = (targetUrl + "").Trim();

		if (targetUrl.Length < ScreenScraperExample4.DefaultUrlLengthMin)
		{
			throw new System.NotSupportedException(
				"URL must be greater-than-or-equal-to '" +
				ScreenScraperExample4.DefaultUrlLengthMin.ToString() + "'.");
		}

		targetTokenStart = (targetTokenStart + "").Trim();

		if (targetTokenStart.Length < ScreenScraperExample4.DefaultStartTokenLengthMin)
		{
			throw new System.NotSupportedException(
				"Start-token must be greater-than-or-equal-to '" +
				ScreenScraperExample4.DefaultStartTokenLengthMin.ToString() + "'.");
		}

		targetTokenEnd = (targetTokenEnd + "").Trim();

		if (targetTokenEnd.Length < ScreenScraperExample4.DefaultEndTokenLengthMin)
		{
			throw new System.NotSupportedException(
				"End-token must be greater-than-or-equal-to '" +
				ScreenScraperExample4.DefaultEndTokenLengthMin.ToString() + "'.");
		}

		//Get a Reader.
		StreamReader myReader = null;

		//Get the link.
		WebRequest myRequest = WebRequest.Create(targetUrl);

		//Get the HTML.
		WebResponse myResponse = myRequest.GetResponse();

		//Fill the Reader.
		myReader = new StreamReader(myResponse.GetResponseStream());

		//Get the content.
		string myContent = myReader.ReadToEnd();

		//Get the Regex.
		Regex myRegex =
			new Regex(targetTokenStart + "((.|\n)*?)" + targetTokenEnd, RegexOptions.IgnoreCase);

		//Run the Regex.
		Match myMatch = myRegex.Match(myContent);

		//Bam! We return the value from our Match, and we're in business. 
		myReturnValue = myMatch.Value + "";

		return myReturnValue;
	}

	private void ResetFormNow()
	{
		this.UrlTextBox.Text = ScreenScraperExample4.DefaultUrl;
		this.StartTokenTextBox.Text = ScreenScraperExample4.DefaultStartToken;
		this.EndTokenTextBox.Text = ScreenScraperExample4.DefaultEndToken;
		this.OutputTextBox.Text = "";
	}

	private void ClearFormNow()
	{
		this.UrlTextBox.Text = "";
		this.StartTokenTextBox.Text = "";
		this.EndTokenTextBox.Text = "";
		this.OutputTextBox.Text = "";
	}

	#endregion //HelperMethods

	#region HandlerMethods

	private void Page_Load(object sender, System.EventArgs e)
	{
		try
		{
			this.ResetButton.OnClientClick = @"return confirm('Discard data and reset?');";
			this.ClearButton.OnClientClick = @"return confirm('Discard data and clear?');";
			this.CancelButton.OnClientClick = @"return confirm('Discard data and exit?');";

			if (!this.IsPostBack)
			{
				this.ResetFormNow();
				this.StatusLabel.Text =
					DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
			}
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void TestInlineButton_Click(object sender, EventArgs e)
	{
		try
		{
			string myTargetUrl = this.UrlTextBox.Text;
			myTargetUrl = myTargetUrl + "";
			myTargetUrl = myTargetUrl.Trim();

			if (myTargetUrl.Length < ScreenScraperExample4.DefaultUrlLengthMin)
			{
				throw new System.NotSupportedException(
					"URL must be greater-than-or-equal-to '" +
					ScreenScraperExample4.DefaultUrlLengthMin.ToString() + "'.");
			}

			string myReturn =
				this.GetDataValue(myTargetUrl, this.StartTokenTextBox.Text, this.EndTokenTextBox.Text);

			this.OutputTextBox.Text = myReturn;

			this.StatusLabel.Text =
				DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void ResetButton_Click(object sender, EventArgs e)
	{
		try
		{
			this.ResetFormNow();

			this.StatusLabel.Text =
				DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void ClearButton_Click(object sender, EventArgs e)
	{
		try
		{
			this.ClearFormNow();

			this.StatusLabel.Text =
				DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void CancelButton_Click(object sender, EventArgs e)
	{
		try
		{
			this.Response.Redirect("Default.aspx");
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	#endregion //HandlerMethods
}

This is the code-behind…


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Text;

public partial class ScreenScraperExample4 : System.Web.UI.Page
{
	#region MemberConstants

	public const string DefaultDateTimeFormat = "yyyy-MM-dd HH:mm:ss.fffffff tt zzz";
	public const int DefaultUrlLengthMin = 16;
	public const int DefaultStartTokenLengthMin = 1;
	public const int DefaultEndTokenLengthMin = 1;
	public const string DefaultUrl = @"http://www.Google.com";
	public const string DefaultStartToken = @"Web";
	public const string DefaultEndToken = @"News";

	#endregion //MemberConstants

	#region HelperMethods

	private string GetDataValue(string targetUrl, string targetTokenStart, string targetTokenEnd)
	{
		string myReturnValue = "";

		targetUrl = (targetUrl + "").Trim();

		if (targetUrl.Length < ScreenScraperExample4.DefaultUrlLengthMin)
		{
			throw new System.NotSupportedException(
				"URL must be greater-than-or-equal-to '" + 
				ScreenScraperExample4.DefaultUrlLengthMin.ToString() + "'.");
		}

		targetTokenStart = (targetTokenStart + "").Trim();

		if (targetTokenStart.Length < ScreenScraperExample4.DefaultStartTokenLengthMin)
		{
			throw new System.NotSupportedException(
				"Start-token must be greater-than-or-equal-to '" + 
				ScreenScraperExample4.DefaultStartTokenLengthMin.ToString() + "'.");
		}

		targetTokenEnd = (targetTokenEnd + "").Trim();

		if (targetTokenEnd.Length < ScreenScraperExample4.DefaultEndTokenLengthMin)
		{
			throw new System.NotSupportedException(
				"End-token must be greater-than-or-equal-to '" + 
				ScreenScraperExample4.DefaultEndTokenLengthMin.ToString() + "'.");
		}

		//Get a Reader.
		StreamReader myReader = null;

		//Get the link.
		WebRequest myRequest = WebRequest.Create(targetUrl);

		//Get the HTML.
		WebResponse myResponse = myRequest.GetResponse();

		//Put the HTML into the Reader.
		myReader = new StreamReader(myResponse.GetResponseStream());

		//And dump the StreamReader into a string...
		string myContent = myReader.ReadToEnd();

		//Here we set up our Regular expression to snatch what's between the BEGIN and END comments. 
		Regex myRegex =
			new Regex(targetTokenStart + "((.|\n)*?)" + targetTokenEnd, RegexOptions.IgnoreCase);

		//Here we apply our regular expression to our string using the Match object. 
		Match myMatch = myRegex.Match(myContent);

		//Bam! We return the value from our Match, and we're in business. 
		myReturnValue = myMatch.Value + "";

		return myReturnValue;
	}

	private void ResetFormNow()
	{
		this.UrlTextBox.Text = ScreenScraperExample4.DefaultUrl;
		this.StartTokenTextBox.Text = ScreenScraperExample4.DefaultStartToken;
		this.EndTokenTextBox.Text = ScreenScraperExample4.DefaultEndToken;
		this.OutputTextBox.Text = "";
	}

	private void ClearFormNow()
	{
		this.UrlTextBox.Text = "";
		this.StartTokenTextBox.Text = "";
		this.EndTokenTextBox.Text = "";
		this.OutputTextBox.Text = "";
	}

	#endregion //HelperMethods

	#region HandlerMethods

	private void Page_Load(object sender, System.EventArgs e)
	{
		try
		{
			this.ResetButton.OnClientClick = @"return confirm('Discard data and reset?');";
			this.ClearButton.OnClientClick = @"return confirm('Discard data and clear?');";
			this.CancelButton.OnClientClick = @"return confirm('Discard data and exit?');";

			if (!this.IsPostBack)
			{
				this.ResetFormNow();
				this.StatusLabel.Text =
					DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
			}
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void TestInlineButton_Click(object sender, EventArgs e)
	{
		try
		{
			string myTargetUrl = this.UrlTextBox.Text;
			myTargetUrl = myTargetUrl + "";
			myTargetUrl = myTargetUrl.Trim();

			if (myTargetUrl.Length < ScreenScraperExample4.DefaultUrlLengthMin)
			{
				throw new System.NotSupportedException(
					"URL must be greater-than-or-equal-to '" +
					ScreenScraperExample4.DefaultUrlLengthMin.ToString() + "'.");
			}

			string myReturn = 
				this.GetDataValue(myTargetUrl, this.StartTokenTextBox.Text, this.EndTokenTextBox.Text);

			this.OutputTextBox.Text = myReturn;

			this.StatusLabel.Text =
				DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void ResetButton_Click(object sender, EventArgs e)
	{
		try
		{
			this.ResetFormNow();

			this.StatusLabel.Text =
				DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void ClearButton_Click(object sender, EventArgs e)
	{
		try
		{
			this.ClearFormNow();

			this.StatusLabel.Text =
				DateTime.Now.ToString(ScreenScraperExample4.DefaultDateTimeFormat) + ": Done.";
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	protected void CancelButton_Click(object sender, EventArgs e)
	{
		try
		{
			this.Response.Redirect("Default.aspx");
		}
		catch (Exception ex)
		{
			this.StatusLabel.Text = ex.ToString();
		}
	}

	#endregion //HandlerMethods
}