Results 1 to 7 of 7

Thread: Nooby to .Net

  1. #1
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default Nooby to .Net

    I think I would start a thread about useful classes in the .Net Framework. I say useful refering to classes that I would come across using and thus know how to use.

    Here is the first class XmlTextReader which is found in the System.Xml namespace and can be link here http://samples.gotdotnet.com/quickst...adXMLFile.aspx

    This class is useful for creating a settings file and easily read the setting in different programs. Talk about compatibility.

    I hope to soon go through the code on the site with my personal commentation.

    Home site http://samples.gotdotnet.com/quickstart/howto/
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  2. #2
    Join Date
    Oct 2004
    Posts
    4,814
    Rep Power
    24

    Default

    ThreadPool.

    Provides a pool of threads that can be used to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

    Reference

    The .Net ThreadPool is useful. But I created my own for customized situations and better performance.

  3. #3
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default XmlTextReader (cont)

    XML is a standard way of sharing data. It can be easily used when you choose to use it because you would be doing the same thing over and over. Say you saved some settings in an XML file and you want to load some of the settings for a particular module to run. The order, position, line, etc of how the settings were saved will be no problem with XML in my case.

    Take an XML file, settings.xml:
    Code:
    <?xml version="1.0" ?>
    <!-- This is a mysettings XML document -->
    <mysettings><!-- This is a root node-->
      <variable1 att1="12">value1</variable1>
      <variable3 att3="45">value3</variable3>
      <variable2 att2="23">value2</variable2>
    </mysettings>
    This code can let you view or load variables1, and variable2. (Scroll left and read through the comments):
    Code:
    XmlTextReader reader = null;
    
    try
    {  
        //Load the reader with the data file and ignore all white space nodes.         
        reader = new XmlTextReader(this.strFilename);
        reader.WhitespaceHandling = WhitespaceHandling.None;
    
        //Clear my display text box
        this.StatusDisplayBox.Text    =    "";
    
        /*
        Parse the file and check all element nodes for the variable we want
        */
        while (reader.Read())//Read all nodes. One node at a time is read and its properties are stored in the reader, eg reader.Name and reader.NodeType
        {
            if( reader.NodeType == XmlNodeType.Element )//Only interested in the element-type node
            {
                if(reader.Name == "variable1")//Find the element with the name variable1
                {
                    //Get the text in this element. The text is a text-type node in itself. It is val1
                    this.StatusDisplayBox.Text    +=    reader.ReadElementString("variable1") + "\n";
                }
                if(reader.Name == "variable2")
                {
                    //Get val2
                    this.StatusDisplayBox.Text    +=    reader.ReadElementString("variable2") + "\n";
                }
            }       
        }           
    }
    finally
    {
        if (reader!=null)
            reader.Close();
    }
    Some useful members of XmlTextReader are:
    Read, ReadElementString, MoveToNextAttribute, MoveToAttribute (similar to attributes of html tags)
    There are, of course, others.
    Last edited by crosswire; Jul 16, 2005 at 12:39 AM.
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  4. #4
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default OpenFileDialog

    Hey Leo, I read on the thread pool class, it was pretty interesting.
    I did some reading on thread management with .net before, but I did not actually went deep with the classes, until now.

    I will do some complicated classes now and then, mostly I will do some of the simplier classes until I get better experienced with the framework.

    Here is one that every techie probably know already, OpenFileDialog.

    Code:
        System.Windows.Forms.OpenFileDialog   OpenXMLFileDialog   =   new OpenFileDialog();
    
        //Set the file filter view to default to seeing only xml files, and the drop box filter to all files.
        OpenXMLFileDialog.Filter	=	"XML Files(*.xml)|*.xml|All Files (*.*)|*.*||";
    
        //Displays the common open file dialog that everyone knows
        OpenXMLFileDialog.ShowDialog();
    
        //After the dialog is closed, get the file that the user opened
        this.StatusDisplayBox.Text	=	OpenXMLFileDialog.FileName;
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  5. #5
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default

    Here is another simple class DataTable found in the System.Data namespace ie System.Data.DataTable.
    I use it to store data in a table form.

    Online Reference

    Online Example

    Somethings a table (DataTable) can do:
    • Create new rows (DataRow) which has the same column format as the table using DataTable.NewRow()
    • Add a new row using using DataTable.Rows.Add(DataRow) this is also overloaded
    • Add a new column using using DataTable.Columns.Add(DataColumn)
    • Set columns as primary keys
    • Select rows in the table that match a certain search or query using DataTable.Select(string filterExpression), yep overloaded


    Other things you can do with a DataTable
    • You can place a DataTable in a DataSet (more later on DataSet).
    • You can use the DataView associated with a DataTable to set the sorting, filtering, searching, editing, and navigation view of the table using Data.DefaultView.
    • You can bind a DataTable to a DataGrid (plenty ways to do this like using a DataSet referencing a specific DataTable)


    Code:
    	//Create a new table named Settings
    	this.tableSettings			=	new System.Data.DataTable("Settings");
    
    	//Create a column named "Name" for the table
    	DataColumn	columnName		=	new System.Data.DataColumn("Name", System.Type.GetType("System.String"));
    
    	//Set the column to be writable, even though it has this value by default
    	columnName.ReadOnly		=	false;
    
    	//Add the column "Name" to the table "Settings"
    	this.tableSettings.Columns.Add(columnName);
    
    	//Create another column named "Value" which stores 32 bit integers
    	DataColumn	columnValue		=	new System.Data.DataColumn("Value", System.Type.GetType("System.Int32"));
    
    	//Add the next column to the table
    	this.tableSettings.Columns.Add(columnValue);
    
    	//Set the first column "Name" as the primary key column for the table. This will allow only unique "Names" in the table
    	DataColumn[] columnsPrimaryKeys	=	new DataColumn[1];
    	columnsPrimaryKeys[0]			=	this.tableSettings.Columns["Name"];
    	this.tableSettings.PrimaryKey	=	columnsPrimaryKeys;
    
    	//Use the DataView property of the table to set the display of the table. Here I set the rows to odered by ascending names.
    	if(this.tableSettings.DefaultView != null)
    		//A DataView must be present, but in case the Framework changes, I check it first
    		this.tableSettings.DefaultView.Sort	=	"Name ASC";
    
    	//Bind the table to the DataGrid control which I had named SettingsView
    	this.SettingsView.SetDataBinding(tableSettings, "");
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  6. #6
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default DataTable Code

    Here is a C# program that you can use to try a DataTable class

    In this program, I used buttons and keyboard events to trigger variuos operation on the DataTable. There is one button to save a DataTable as an XML file (by saving the DataSet that contains the table). There is a DataGrid that let's you view and edit the table. I want to allow the user to undo up to 10 changes made in the DataTable, but that part is unfinished (not much was done). Also I wanted to selectively delete the first row in the table when it is in alphabeticall order. Any one can help me with these two problems? I am planning it out using what is available in the class such as the event triggers (DataTabele.RowChanged), and the rollback functions (DataTable.RejectChanges), plus any costum implemation I can think of to do this problem.

    Code:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    
    namespace NoobyDataTable
    {
    	/// <summary>
    	/// Summary description for Form1.
    	/// </summary>
    	public class Form1 : System.Windows.Forms.Form
    	{
    		private System.Windows.Forms.DataGrid SettingsView;
    		private System.Data.DataTable tableSettings;
    		private System.Windows.Forms.Button butSaveTable;
    		private System.Windows.Forms.TextBox textBoxTableName;
    		private System.Windows.Forms.Button butDeleteTop;
    		private System.Windows.Forms.Button butLoadDefaults;
    		private System.Windows.Forms.Button butSelectRow;
    		private System.Windows.Forms.Button butUndoLast;
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		private System.ComponentModel.Container components = null;
    
    		public Form1()
    		{
    			//
    			// Required for Windows Form Designer support
    			//
    			InitializeComponent();
    
    			//
    			// TODO: Add any constructor code after InitializeComponent call
    			//
    
    			/*
    			 *    Public Methods
    			 * DataTable.AcceptChanges
    			 * DataTable.RejectChanges
    			 * DataTable.Select
    			 * DataTable.NewRow
    			 * DataTable.DataSet
    			 * 
    			 *    Public Events:
    			 * DataTable.RowChanged
    			 * DataTable.RowDeleted
    			 * */
    
    			//Create a new table named Settings
    			this.tableSettings			=	new System.Data.DataTable("Settings");
    
    			//Create a column named "Name" for the table
    			DataColumn	columnName		=	new System.Data.DataColumn("Name", System.Type.GetType("System.String"));
    
    			//Set the column to be writable, even though it has this value by default
    			columnName.ReadOnly		=	false;
    
    			//Add the column "Name" to the table "Settings"
    			this.tableSettings.Columns.Add(columnName);
    
    			//Create another column named "Value" which stores 32 bit integers
    			DataColumn	columnValue		=	new System.Data.DataColumn("Value", System.Type.GetType("System.Int32"));
    
    			//Add the next column to the table
    			this.tableSettings.Columns.Add(columnValue);
    
    			//Set the first column "Name" as the primary key column for the table. This will allow only unique "Names" in the table
    			DataColumn[] columnsPrimaryKeys	=	new DataColumn[1];
    			columnsPrimaryKeys[0]			=	this.tableSettings.Columns["Name"];
    			this.tableSettings.PrimaryKey	=	columnsPrimaryKeys;
    
    			//Use the DataView property of the table to set the display of the table. Here I set the rows to odered by ascending names.
    			if(this.tableSettings.DefaultView != null)
    				//A DataView must be present, but in case the Framework changes, I check it first
    				this.tableSettings.DefaultView.Sort	=	"Name ASC";
    
    			//Bind the table to the DataGrid control which I had named SettingsView
    			this.SettingsView.SetDataBinding(tableSettings, "");
    
    
    			//I want the same event handler, implemented near bottom, for two similar events
    			this.tableSettings.RowChanged	+=	new DataRowChangeEventHandler( Row_Changed );
    			//this.tableSettings.RowDeleted	+=	new DataRowChangeEventHandler( Row_Changed );
    		}
    
    		/// <summary>
    		/// Clean up any resources being used.
    		/// </summary>
    		protected override void Dispose( bool disposing )
    		{
    			if( disposing )
    			{
    				if (components != null) 
    				{
    					components.Dispose();
    				}
    			}
    			base.Dispose( disposing );
    		}
    
    		#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.SettingsView = new System.Windows.Forms.DataGrid();
    			this.butSaveTable = new System.Windows.Forms.Button();
    			this.textBoxTableName = new System.Windows.Forms.TextBox();
    			this.butDeleteTop = new System.Windows.Forms.Button();
    			this.butLoadDefaults = new System.Windows.Forms.Button();
    			this.butSelectRow = new System.Windows.Forms.Button();
    			this.butUndoLast = new System.Windows.Forms.Button();
    			((System.ComponentModel.ISupportInitialize)(this.SettingsView)).BeginInit();
    			this.SuspendLayout();
    			// 
    			// SettingsView
    			// 
    			this.SettingsView.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
    				| System.Windows.Forms.AnchorStyles.Left) 
    				| System.Windows.Forms.AnchorStyles.Right);
    			this.SettingsView.BackgroundColor = System.Drawing.Color.LightGray;
    			this.SettingsView.DataMember = "";
    			this.SettingsView.HeaderForeColor = System.Drawing.SystemColors.ControlText;
    			this.SettingsView.Location = new System.Drawing.Point(16, 96);
    			this.SettingsView.Name = "SettingsView";
    			this.SettingsView.Size = new System.Drawing.Size(264, 264);
    			this.SettingsView.TabIndex = 0;
    			// 
    			// butSaveTable
    			// 
    			this.butSaveTable.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
    			this.butSaveTable.Location = new System.Drawing.Point(16, 376);
    			this.butSaveTable.Name = "butSaveTable";
    			this.butSaveTable.TabIndex = 1;
    			this.butSaveTable.Text = "Save Table";
    			this.butSaveTable.Click += new System.EventHandler(this.butSaveTable_Click);
    			// 
    			// textBoxTableName
    			// 
    			this.textBoxTableName.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
    				| System.Windows.Forms.AnchorStyles.Right);
    			this.textBoxTableName.Location = new System.Drawing.Point(104, 379);
    			this.textBoxTableName.Name = "textBoxTableName";
    			this.textBoxTableName.Size = new System.Drawing.Size(176, 20);
    			this.textBoxTableName.TabIndex = 2;
    			this.textBoxTableName.Text = "Settings";
    			this.textBoxTableName.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxTableName_KeyDown);
    			this.textBoxTableName.TextChanged += new System.EventHandler(this.textBoxTableName_TextChanged);
    			// 
    			// butDeleteTop
    			// 
    			this.butDeleteTop.Location = new System.Drawing.Point(28, 56);
    			this.butDeleteTop.Name = "butDeleteTop";
    			this.butDeleteTop.Size = new System.Drawing.Size(104, 24);
    			this.butDeleteTop.TabIndex = 3;
    			this.butDeleteTop.Text = "Delete Top Row";
    			this.butDeleteTop.Click += new System.EventHandler(this.butDeleteTop_Click);
    			// 
    			// butLoadDefaults
    			// 
    			this.butLoadDefaults.Location = new System.Drawing.Point(28, 16);
    			this.butLoadDefaults.Name = "butLoadDefaults";
    			this.butLoadDefaults.Size = new System.Drawing.Size(104, 24);
    			this.butLoadDefaults.TabIndex = 3;
    			this.butLoadDefaults.Text = "Load Default Row";
    			this.butLoadDefaults.Click += new System.EventHandler(this.butLoadDefaults_Click);
    			// 
    			// butSelectRow
    			// 
    			this.butSelectRow.Location = new System.Drawing.Point(164, 16);
    			this.butSelectRow.Name = "butSelectRow";
    			this.butSelectRow.Size = new System.Drawing.Size(104, 24);
    			this.butSelectRow.TabIndex = 3;
    			this.butSelectRow.Text = "Select \'Var\' Row";
    			this.butSelectRow.Click += new System.EventHandler(this.butSelectRow_Click);
    			// 
    			// butUndoLast
    			// 
    			this.butUndoLast.Location = new System.Drawing.Point(164, 56);
    			this.butUndoLast.Name = "butUndoLast";
    			this.butUndoLast.Size = new System.Drawing.Size(104, 24);
    			this.butUndoLast.TabIndex = 3;
    			this.butUndoLast.Text = "Undo Last Row";
    			this.butUndoLast.Click += new System.EventHandler(this.butUndoLast_Click);
    			// 
    			// Form1
    			// 
    			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    			this.ClientSize = new System.Drawing.Size(296, 413);
    			this.Controls.AddRange(new System.Windows.Forms.Control[] {
    																		  this.butDeleteTop,
    																		  this.textBoxTableName,
    																		  this.butSaveTable,
    																		  this.SettingsView,
    																		  this.butLoadDefaults,
    																		  this.butSelectRow,
    																		  this.butUndoLast});
    			this.Name = "Form1";
    			this.Text = "View a DataTable";
    			((System.ComponentModel.ISupportInitialize)(this.SettingsView)).EndInit();
    			this.ResumeLayout(false);
    
    		}
    		#endregion
    contiuned to next post
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

  7. #7
    Join Date
    Sep 2004
    Posts
    1,905
    Rep Power
    21

    Default

    Code:
    		/// <summary>
    		/// The main entry point for the application.
    		/// </summary>
    		[STAThread]
    		static void Main() 
    		{
    			Application.Run(new Form1());
    		}
    
    		private void textBoxTableName_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    		{
    			if(
    				(e.Control && ((e.KeyData & Keys.S) == Keys.S)) ||
    				((e.KeyData & Keys.Enter) == Keys.Enter)
    			  )
    			{
    					MessageBox.Show("Save Table");
    			}
    		}
    
    		private void textBoxTableName_TextChanged(object sender, System.EventArgs e)
    		{
    			this.tableSettings.TableName	=	this.textBoxTableName.Text;
    		}
    
    		private void butSaveTable_Click(object sender, System.EventArgs e)
    		{
    			System.Windows.Forms.SaveFileDialog		dialogSaveAsXML;
    			dialogSaveAsXML			=	new System.Windows.Forms.SaveFileDialog();
    			dialogSaveAsXML.Filter	=	"XML files (*.xml)|*.xml|All files (*.*)|*.*";
    			if(dialogSaveAsXML.ShowDialog() == DialogResult.OK)
    			{
    				//I need a Data set that contains this table, so see if the is such a dataset else create one
    				if(this.tableSettings.DataSet == null)
    				{
    					//There is no dataset which contains this table so I create one and make it contain this table
    					System.Data.DataSet		dsAllSettings	=	new System.Data.DataSet();
    					dsAllSettings.Tables.Add(this.tableSettings);
    					//"tableSettings.DataSet" now refers to the DataSet which contains this tableSettings
    				}
    				System.Xml.XmlDataDocument		xmldocSettings	=	new System.Xml.XmlDataDocument(this.tableSettings.DataSet);
    				xmldocSettings.Save(dialogSaveAsXML.FileName);
    			}
    
    
    		}
    
    		private void butDeleteTop_Click(object sender, System.EventArgs e)
    		{
    			if(this.tableSettings.Rows.Count > 0)
    			{
    				this.tableSettings.AcceptChanges();
    
    				this.tableSettings.Rows.RemoveAt(0);//this.tableSettings.Rows.Find(1)
    			}
    		}
    
    		private void butLoadDefaults_Click(object sender, System.EventArgs e)
    		{
    			//If the default variable is not loaded already
    			if(this.tableSettings.Rows.Find("Var1") == null)
    			{
    				this.tableSettings.AcceptChanges();
    
    				System.Data.DataRow		rowDefault;
    
    				rowDefault	=	this.tableSettings.NewRow();
    				rowDefault["Name"]	=	"Var1";
    				rowDefault["Value"]	=	123;
    
    				this.tableSettings.Rows.Add(rowDefault);
    			}
    		}
    
    		private void butSelectRow_Click(object sender, System.EventArgs e)
    		{
    			DataRow[] drFoundRows =	this.tableSettings.Select("Name LIKE 'Var*'");
    
    			String	strDisplayRows	=	"";
    
    			foreach(DataRow drFoundCount in drFoundRows)
    			{
    				strDisplayRows	+=	drFoundCount["Name"].ToString() + "\t" + drFoundCount["Value"].ToString();
    			}
    			MessageBox.Show(drFoundRows.Length + " rows contain 'Var'\n" + strDisplayRows);
    			
    		}
    		private void Row_Changed( object sender, DataRowChangeEventArgs e )
    		{
    			//((DataTable)sender).AcceptChanges();
    			//tableSettings.AcceptChanges();
    			MessageBox.Show("Row Chandged");
    		}
    
    		private void butUndoLast_Click(object sender, System.EventArgs e)
    		{
    			this.tableSettings.RejectChanges();
    		}
    	}
    }
    Let's act on what we agree on now, and argue later on what we don't.
    Black men leave Barbeque alone if Barbeque don't trouble you

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •