Archive for the Category tricks

 
 

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

Tag property without inheritance

Tag property is very often used to store a data associated with an object. The simple way to add support for Tag property is to create a base class with the Tag property .I don’t like this solution – the reason is simple .Sometimes I want to inherit from an existing class that doesn’t have the Tag property and I can’t change its source code .In WPF we have dependency properties that can help us in this case.

MyControl cnt = new MyControl();
cnt.SetValue(FrameworkElement.TagProperty, new Info() );

One problem – we still need to inherit from DependecyObject class.

The helper class below uses extension methods – to provide the tag functionality for your classes.

Of course, for better performance, you may change the dictionary(and methods) to be more type specific .

/// Implements tag functionality
static class TagHelper
{

    /// Adds the tag
    public static void AddTag(this object element, object tag)
    {
        if (!Tags.ContainsKey(element))
        {
            Tags.Add(element, tag);
        }
    }

    /// Removes the tag for the specified element.
    public static void RemoveTag(this object element )
    {
        Tags.Remove(element);
    }

    ///
    /// Clears the tags.
    ///
    public static void ClearTags()
    {
        Tags.Clear();
    }

    /// Gets the tag for the specified element.
    public static object Get(this object element)
    {
        object tag;
        Tags.TryGetValue(element, out tag);

        return tag;
    }

    private static readonly Dictionary<object, object> Tags = new Dictionary<object, object>();
}

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

Page 1 of 512345