Archive for the Category code

 
 

A simple way to run C# code from bat file

I read an interested article demonstrated how to run a bat file with embedded C# code. I repost this example here, because the original post is written in Russian. Despite the fact that there are other more powerful solutions and frameworks to achieve the same goal (e.g. Powershell) – I think the way presented by the author, is very useful for different scenarios.


/*
@echo off && cls
set WinDirNet=%WinDir%\Microsoft.NET\Framework
IF EXIST "%WinDirNet%\v2.0.50727\csc.exe" set csc="%WinDirNet%\v2.0.50727\csc.exe"
IF EXIST "%WinDirNet%\v3.5\csc.exe" set csc="%WinDirNet%\v3.5\csc.exe"
IF EXIST "%WinDirNet%\v4.0.30319\csc.exe" set csc="%WinDirNet%\v4.0.30319\csc.exe"
%csc% /nologo /out:"%~0.exe" %0
"%~0.exe"
del "%~0.exe"
exit
*/

class HelloWorld
{

    static void Main()
    {
        System.Console.WriteLine("Hello, World!\r\nI am at " + System.Environment.Version);
        System.Console.ReadLine();
    }
}

Sorting System.Collections.Generic.List<T>

This post shows the sorting technique using anonymous delegate that can be implemented in any custom type generic list based on the selected property.For sorting any custom type the class must implement the System.IComparable interface. Now let me assume you have a Person class and if you want to sort the list of person objects then you must implement System.IComparable interface and write the logic of how our person object is to be sorted in the CompareTo method

using System;

namespace ConsoleApplication1
{
    class Person : IComparable
    {
        public Person(string firstName, int age)
        {
            FirstName = firstName;
            Age = age;
        }

        public string FirstName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }

        // sorting in ascending order      

        #region IComparable Members

        public int CompareTo(object obj)
        {
            var person = (Person) obj;
            return FirstName.CompareTo(person);
        }

        #endregion
    }
}

But you can simplify the sorting just by using the anonymous delegate as shown bellow and you don’t need to implement IComparable interface

var persons = new List<Person>
                    {
                        new Person("Tom", 30),
                        new Person("Harry", 55)
                    };
// sort in ascending order
persons.Sort(delegate(Person person0, Person person1)
                    {
                        return person0.FirstName.CompareTo(person1.FirstName);
                    });
// sort in descending order
persons.Sort(delegate(Person person0, Person person1)
                    {
                        return person1.FirstName.CompareTo(person0.FirstName);
                    });

Technorati tags: generic, c#, code

Sending the LINQ To SQL log to log4net

DataContext Log Property can be used to print generated SQL query or command in the console window as shown below:

db.Log = Console.Out;

If you want to print the SQL query in DebugView or VS Output window you may use DebugWriter class(by Kris Vandermotten) .The usage of the class is pretty simple …

db.Log = new DebugWriter();

I wrote a small class that help you redirect DataContext messages to log4net .I’ve changed the DebugWriter and call it Log4NetWriter . The usage is still simple

db.Log = new Log4NetWriter(this.GetType());

As result you get formatted log4net messages that can be send to any log4net appender .

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using log4net;
using log4net.Core;
using log4net.Repository.Hierarchy;
 
namespace Devintelligence.Data
{
 
 
    public class Log4NetWriter : TextWriter
    {
 
        /// <summary>
        /// Initializes a new instance of the <see cref="Log4NetWriter"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        public Log4NetWriter(Type type):this(type,Level.Debug)
        {
        }
 
 
        /// <summary>
        /// Initializes a new instance of the <see cref="Log4NetWriter"/> class.
        /// </summary>
        /// <param name="type">The logger source type.</param>
        /// <param name="level">The log4net log level.</param>
        public Log4NetWriter(Type type, Level level)
        {
            logSrcType = type;
            this.level = level;
            open = true;
        }
 
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="T:System.IO.TextWriter"/> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            open = false;
            base.Dispose(disposing);
        }
 
        /// <summary>
        /// Writes a character to the text stream.
        /// </summary>
        /// <param name="value">The character to write to the text stream.</param>
        /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter"/> is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        public override void Write(char value)
        {
            if (!open)
            {
                throw new ObjectDisposedException(null);
            }
            Log(value.ToString());
        }
 
        /// <summary>
        /// Writes a string to the text stream.
        /// </summary>
        /// <param name="value">The string to write.</param>
        /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter"/> is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        public override void Write(string value)
        {
            if (!open)
            {
                throw new ObjectDisposedException(null);
            }
            if (value != null)
            {
                Log(value);
            }
        }
 
        /// <summary>
        /// Writes a subarray of characters to the text stream.
        /// </summary>
        /// <param name="buffer">The character array to write data from.</param>
        /// <param name="index">Starting index in the buffer.</param>
        /// <param name="count">The number of characters to write.</param>
        /// <exception cref="T:System.ArgumentException">The buffer length minus <paramref name="index"/> is less than <paramref name="count"/>. </exception>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="buffer"/> parameter is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        ///     <paramref name="index"/> or <paramref name="count"/> is negative. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter"/> is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        public override void Write(char[] buffer, int index, int count)
        {
            if (!open)
            {
                throw new ObjectDisposedException(null);
            }
            if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count)
            {
                base.Write(buffer, index, count); // delegate throw exception to base class
            }
            Log( new string(buffer, index, count));
        }
 
        /// <summary>
        /// When overridden in a derived class, returns the <see cref="T:System.Text.Encoding"/> in which the output is written.
        /// </summary>
        /// <value></value>
        /// <returns>The Encoding in which the output is written.</returns>
        public override Encoding Encoding
        {
            get
            {
                if (encoding == null)
                {
                    encoding = new UnicodeEncoding(false, false);
                }
                return encoding;
            }
        }
 
 
        /// <summary>
        /// Writes a message to log4net 
        /// </summary>
        /// <param name="message"></param>
        private void Log( string message )
        {
            Hierarchy hierarchy = ((Hierarchy)LogManager.GetRepository());
            ILoggerFactory loggerFactory = ((Hierarchy)LogManager.GetRepository()).LoggerFactory;
            Logger logger = hierarchy.GetLogger(logSrcType.FullName, loggerFactory);
            logger.Log(level, message, null);
        }
 
 
        private bool open;
        private static UnicodeEncoding encoding;
        private readonly Level level;
        private Type logSrcType;
    }
}

 

Technorati Tags: ,,,

Shaped Windows in WPF

In previous versions of Microsoft .Net Framework, creating shaped windows was a time-consuming process that involved Win API calls.Not anymore – one of the modern  aspects of WPF is that you can make  non-rectangular windows in simple way.Creating shaped forms works in the following manner.First, you create an image, which, when we are finished, will act as your window.  Second, you change a XAML to make this image become the form.

  • Create a transparent image file that will be used to set the desired shape of the window.

shaped-form

  • Create a Windows Application(WPF) project and add the image control to it.Remember to make the window transparent as shown in code below
<Window x:Class="WindowsApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WindowsApplication1" Height="300" Width="300"
    AllowsTransparency="True"
    WindowStyle="None"
    Background="Transparent" 
    >
    <Grid>
    <Image  Name="image1" />
  </Grid>
</Window>

 

  • Add code that recreates the functionality that the title bar provided, such as moving the window and closing it.
using System;
using System.Windows.Input;
using System.Windows.Media.Imaging;
 
 
namespace WindowsApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : System.Windows.Window
{
    public Window1()
    {
        InitializeComponent();
 
        image1.Source = new BitmapImage(
 
            new Uri(@"C:\Documents and Settings\username\Desktop\Untitled.png"));
    }
 
 
    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);
        DragMove();
    }
 
 
 
    protected override void OnMouseRightButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseRightButtonDown(e);
 
        Close();
    }
 
}
}
 
Technorati Tags: WPF, XAML, dotnet

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); 
            } 
        } 
    } 
}


Page 1 of 512345