CS2-C# Code Search

CS2 is capable of indexing source code files (at the moment only C# code can be parsed) and searching among them with various parameters, like class, property and method names, as well as full-text queries.

The main user interface for interacting with the search engine is an ASP.NET website built for version 2.0 of the .NET framework .

Download CS2 Search Engine

[Via dotnetkicks.com]

Displaying large amount of data in DataGridView

DataGridView supports the special mode (Virtual Mode). The basic idea is that inside the control not stored any data.
In given below example of the primitive electronic table, the data stored in the hashtable.The electronic table has a large amount of cells. In this example the number of cells equals to 100000 lines * 100 columns = 10000000. Also the programm save and loads changed cells on the disk

Note: The SerializableDictionary can be found here

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.IO; 
using System.Text; 
using System.Windows.Forms; 
using System.Xml.Serialization; 
namespace Devintelligence.Example { 
    public partial class Form1 : Form 
    { 
        #region Fields  
        public SerializableDictionary<string, int> data = new SerializableDictionary<string, int>(); 
        private Font systemFont; 
        private XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary<string, int>)); 
        #endregion  
        public Form1() 
        { 
            InitializeComponent(); 
        } 
        private void Form1_Load(object sender, EventArgs e) 
        { 
            if (File.Exists(FilePath)) 
            { 
                // load from file & desirialize  
                using (FileStream filestream = File.OpenRead(FilePath)) 
                { 
                    data = serializer.Deserialize(filestream) as SerializableDictionary<string, int>; 
                } 
            } 
            ((ISupportInitialize)dataGridView1).BeginInit(); 
            dataGridView1.VirtualMode = true; 
            dataGridView1.CellValueNeeded += new DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded); 
            dataGridView1.CellValuePushed += new DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed); 
            // create columns  
            for (int i = 0; i < 100 ; i++) 
            { 
                string name = string.Format("{0}", i); 
                dataGridView1.Columns.Add(name, name); 
            } 
            dataGridView1.RowCount = 100000; 
            systemFont = new Font(dataGridView1.Font,FontStyle.Bold); 
            ((ISupportInitialize)dataGridView1).EndInit(); 
        } 
        /// <summary>  
        /// Calculates the unique hash key based on row and column indexes. 
        /// </summary>  
        /// <param name="rowIndex">Index of the row.</param>  
        /// <param name="columnIndex">Index of the column.</param>  
        /// <returns></returns>  
        private static string CalculateKey(int rowIndex, int columnIndex) 
        { 
            return string.Format("{0}_{1}", rowIndex, columnIndex); 
        } 
        /// <summary>  
        /// Handles the CellValuePushed event of the dataGridView1 control. 
        /// </summary>  
        /// <param name="sender">The source of the event.</param>  
        /// <param name="e">The <see cref="T:System.Windows.Forms.DataGridViewCellValueEventArgs"/> 
        /// instance containing the event data.</param>  
        void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e) 
        { 
            data[CalculateKey(e.RowIndex, e.ColumnIndex)] = Convert.ToInt32(e.Value); 
            // mark changed cells  
            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.LightPink; 
            dataGridView1[e.ColumnIndex, e.RowIndex].Style.Font = systemFont; 
        } 
        /// <summary>  
        /// Handles the CellValueNeeded event of the dataGridView1 control. 
        /// </summary>  
        /// <param name="sender">The source of the event.</param>  
        /// <param name="e">The <see cref="T:System.Windows.Forms.DataGridViewCellValueEventArgs"/>  
        /// instance containing the event data.</param>  
        void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) 
        { 
            int value; 
            if (data.TryGetValue(CalculateKey(e.RowIndex, e.ColumnIndex), out value)) 
            { 
                e.Value = value; 
                // mark changed cells  
                dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.LightPink; 
                dataGridView1[e.ColumnIndex, e.RowIndex].Style.Font = systemFont; 
            } 
            else  
            { 
                e.Value = e.ColumnIndex*e.RowIndex; 
            } 
        } 
        
        private static string FilePath 
        { 
            get  
            { 
                // the data file will be saved in file named data.xml  
                return Path.Combine(Application.StartupPath, "data.xml"); 
            } 
        } 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
        { 
            // serialize & save entered data  
            using (FileStream filestream = File.Open(FilePath, FileMode.Create)) 
            { 
                serializer.Serialize(filestream, data); 
            } 
        } 
    } 
}

Validating properties in a PropertyGrid control

The easiest way to validate a certain property is using the PropertyValueChanged event.The code bellow shows how to limit the valid range of Age property to be 1-150

using System.Windows.Forms; 
namespace WindowsApplication1 
{ 
    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
            //init person object  
            Person person = new Person(); 
            person.FirstName = "George"; 
            person.Age = 33; 
            propertyGrid.SelectedObject = person; 
            propertyGrid.PropertyValueChanged+=  new PropertyValueChangedEventHandler( propertyGrid_PropertyValueChanged ); 
        } 
 
        private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) 
        { 
            if (e.ChangedItem.Label == "Age" && !IsAgeValid((int)e.ChangedItem.Value) ) 
            { 
                // the entered age value is wrong - show error message 
                e.ChangedItem.PropertyDescriptor.SetValue( propertyGrid.SelectedObject, e.OldValue); 
                MessageBox.Show("Wrong age", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
            } 
        } 
 
        ///<summary>
        /// Determines whether age is valid 
        /// </summary>  
        /// <param name="age">The age.</param>  
        /// <returns>  
        /// <c>true</c> if is age valid ; otherwise, <c>false</c>. 
        /// </returns>  
        private static bool IsAgeValid( int age ) 
        { 
            return ((age > 0) && (age < 150)); 
        } 
    } 
}

 

Technorati tags: propertygrid, dotnet, programming

Return the value for the specific attribute using XPathNodeIterator

I will use the following XML document in the example below.

<?xml version="1.0" encoding="utf-8" ?>
<users>
  <user FirstName="Tom" LastName="Adams" Age="23" />
  <user FirstName="Jhon" LastName="Brams" Age="17" />
  <user FirstName="Bill" LastName="Smith" Age="33" />
</users>

The code prints out all the user nodes of the users node that  have an age with a value greater than 17.

// Read the xml from resource file 
string xml = Resources.Users; 
using (StringReader sr = new StringReader(xml)) 
{ 
    XPathDocument document = new XPathDocument(sr); 
    XPathNavigator navigator = document.CreateNavigator(); 
    XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable); 
    //Selects all the user nodes of the users node that 
    // have an age with a value greater than 17  
    XPathNodeIterator it = navigator.Select("/users/user[@Age>17]"); 
    while (it.MoveNext()) 
    { 
        // access the atributes  
        string firstName = it.Current.GetAttribute("FirstName", ns.DefaultNamespace); 
        string lastName = it.Current.GetAttribute("LastName", ns.DefaultNamespace); 
        // Print out  
        Console.WriteLine( "{0} {1}", firstName, lastName ); 
    } 
}

C# String Library by Chad Finsterwald

Inspired by PHP String Functions that are missing in .Net.

Below is a list of the method names and descriptions in the string library.

  • Base64StringEncode: Base64 encodes a string.
  • Base64StringDecode: Decodes a Base64 string.
  • CaseInsenstiveReplace: A case insenstive replace function.
  • ReplaceFirst: Replaces the first occurence of a string with the replacement value. The Replace is case senstive. [The inclusion of this method and ReplaceLast was suggested by a reader's comment.]
  • ReplaceLast: Replaces the last occurence of a string with the replacement value. The replace is case senstive.
  • FilterWords: Removes all the words passed in the filter words parameters. The replace is NOT case sensitive.
  • HasWords: Checks the passed string to see if it contains any of the passed words. Not case-sensitive.
  • HtmlSpecialEntitiesEncode: A wrapper around HttpUtility.HtmlEncode.
  • HtmlSpecialEntitiesDecode: A wrapper around HttpUtility.HtmlDecode.
  • MD5String: MD5 encodes the passed string.
  • MD5VerifyString: Verifies a string against the passed MD5 hash.
  • PadLeftHtmlSpaces: Left pads the passed string using the HTML non-breaking space ( ) for the total number of spaces.
  • CaseInsenstiveReplace: Performs a case insenstive replace.
  • PadLeft: Left pads the passed string using the passed pad string for the total number of spaces. (It will not cut-off the pad even if it causes the string to exceed the total width.)
  • PadRightHtmlSpaces: Right pads the passed string using the HTML non-breaking space ( ) for the total number of spaces.
  • PadRight: Right pads the passed string using the passed pad string for the total number of spaces. (It will not cut-off the pad even if it causes the string to exceed the total width.)
  • RemoveNewLines: Removes the new line (\n) and carriage return (\r) symbols.
  • Reverse: Reverses the passed string.
  • SentenceCase: Converts a string to sentence case.
  • SpaceToNbsp: Converts all spaces to HTML non-breaking spaces.
  • StripTags: Removes all HTML tags from the passed string.
  • TitleCase: Converts a string to title case.
  • TrimIntraWords: Removes multiple spaces between words.
  • NewLineToBreak: Converts each new line (\n) and carriage return (\r) symbols to the HTML
    tag.
  • WordWrap: Wraps the passed string at the passed total number of characters (if cuttOff is true)or at the next whitespace (if cutOff is false). Uses the environment new linesymbol for the break text.

Technorati tags: string, php, dotnet, c#, library


Page 2 of 41234