суббота, 24 ноября 2012 г.

Stopwatch (время выполнения, мониторинг)


Измерить время выполнения можно так


using System.Diagnostics;  
...
...
...

Stopwatch sw = new Stopwatch();
  sw.Start();

... Измеряемый Код

  sw.Stop();
  MessageBox.Show(sw.Elapsed.Minutes + "Min " + sw.Elapsed.Seconds + "Sec " + sw.Elapsed.Milliseconds + "ms");

пятница, 23 ноября 2012 г.

Icon Size - Windows Forms Applications

Circumstance:Icon Version:
Control Box16x16x256
Taskbar16x16x256
Notify Icon32x32x256, shrunk down (see below)
Desktop Shortcut32x32x256 (Normal sized icons)
48x48x256 (Large sized icons)
Add/Remove Programs16x16x256
Folder Browse dialog16x16x256

CSV и DataTable


Создание и чтение CSV файла.

Первая строка в CSVфайле содержит имена столбцов и типы в формате
name1:String;name2:String;name3:Int32;name4:Decimal;name5:DateTime

Пример:
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
CSV.CreateFile(table, @"c:\test.csv");
DataTable dt = CSV.LoadFile(@"c:\test.csv");

--------------------------------------------------------------------------------------------------------
using System;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

public static class CSV
    {
        public static void CreateFile(DataTable dt, String strFilePath)
        {
            #region Export DataTable to CSV

            using (StreamWriter sw = new StreamWriter(strFilePath, false))
            {
                int iColCount = dt.Columns.Count;

                // First we will write the headers.
                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(String.Format(@"{0}:{1}", dt.Columns[i], dt.Columns[i].DataType.ToString().Replace(@"System.", "")));
                    if (i < iColCount - 1)
                    {
                        sw.Write(";");
                    }
                }
                sw.Write(sw.NewLine);

                // Now write all the rows.
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        else
                        {
                            sw.Write(@"");
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(";");
                        }
                    }
                    sw.Write(sw.NewLine);
                }
                sw.Close();
            }

            #endregion
        }


        public static DataTable LoadFile(String strFilePath)
        {
            if (!File.Exists(strFilePath))
            {
                return null;
            }

            #region Export CSV to DataTable

            DataTable dt = new DataTable();

            FileInfo f = new FileInfo(strFilePath);
            double readSize = 0;

            using (var sr = new StreamReader(strFilePath, System.Text.Encoding.ASCII))
            {
                String line;
                bool setColums = false;
                char[] splRow = new char[] { ';' };
                char[] splCol = new char[] { ':' };

                Int32 cols = 0;
                while (sr.Peek() >= 0)
                {
                    try
                    {
                        line = sr.ReadLine();
                        readSize += line.Length;

                        if (string.IsNullOrEmpty(line)) continue;
                        var values = line.Split(splRow, StringSplitOptions.None);

                        if (!setColums)
                        {
                            setColums = true;
                            cols = values.Length;
                            String colName;
                            Type colType;
                            for (int colNum = 0; colNum < cols; colNum++)
                            {
                                if (values[colNum].IndexOfAny(splCol) != -1)
                                {
                                    var v = values[colNum].Split(splCol);
                                    colName = v[0];
                                    colType = Type.GetType(@"System." + v[1], false, false);
                                    dt.Columns.Add(colName, colType != null ? colType : typeof(String));
                                }
                                else
                                {
                                    dt.Columns.Add(values[colNum]);
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                dt.Rows.Add(values);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message + "\n" + line);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }

            return dt;

            #endregion
        }
    }

Запуск одного экземпляра приложения

При своем запуске приложение пытается создать мьютекс с определенным именем. Если это удалось, то запускаемый экземпляр приложения является первым и пока единственным. В противном случае Mutex не позволит вновь запустить пока еще работающее приложение Поэтому, данный класс мы и используем в нашем случае:


using System;
using System.Windows.Forms;
using System.Threading;

namespace OneCopyOfApp
{
    static class Program
    {
        private static Mutex m_instance;
        private const string m_appName = "NameOfMyApp";

        [STAThread]
        static void Main()
        {
            bool tryCreateNewApp;
            m_instance = new Mutex(true, m_appName, 
                    out tryCreateNewApp);
            if (tryCreateNewApp)
            {
                Application.EnableVisualStyles();
                Application.
                  SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                return;
            }          
        }
    }
}



Есть второй, более безопасный в отношении атак способ. Основан он на библиотеках VB. Для начала добавьте ссылку на сборку Microsoft.VisualBasic.dll.
Для удобства вынести в начало проекта пространство имен Microsoft.VisualBasic.ApplicationServices. Ну а сам код следующий (обратите внимание каким образом мы вызываем метод Run())


using System;
using System.Windows.Forms;
using System.Threading;
using Microsoft.VisualBasic.ApplicationServices;

namespace OneCopyOfApp
{
    public class OneInstanceApp : 
        WindowsFormsApplicationBase
    {
        private SingleInstanceApplication()
        {
            base.IsSingleInstance = true;
        }

        public static void Run(Form form,
            StartupNextInstanceEventHandler startupHandler)
        {
            OneInstanceApp app = 
                new OneInstanceApp();
            app.MainForm = form;
            app.StartupNextInstance += startupHandler;
            app.Run(Environment.GetCommandLineArgs());
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            OneInstanceApp.Run(new Form1(),
                StartupNextInstanceHandler);
        }

        static void StartupNextInstanceHandler(
            object sender, StartupNextInstanceEventArgs e)
        {
            MessageBox.Show(e.CommandLine[0]);
        }
    }
}

Работа с Файлами

using System.IO;


Создание директории:

if (!System.IO.Directory.Exists(@"c:\MyDir\"))
{
        System.IO.Directory.CreateDirectory(@"c:\MyDir\");
 }
-----------------------------------------------------------------------------------------------------

Файлы в директории:


string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
// returns:
// "c:\MyDir\test1.BMP"
// "c:\MyDir\test2.jpg"

string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");

// returns:
// "c:\MyDir\test.BMP"


string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp", SearchOption.AllDirectories);

// returns:
// "c:\MyDir\test.BMP"
// "c:\MyDir\Friends\test3.BMP"

-------------------------------------------------------------------------------------------------------

вторник, 20 ноября 2012 г.

Практическое руководство. Объединение делегатов (многоадресные делегаты)


В этом примере описано создание множественных делегатов. Полезным свойством объектов delegate является возможность назначения нескольких объектов одному экземпляру делегата с помощью оператора +. Множественный делегат содержит список назначенных делегатов. При вызове множественный делегат вызывает делегаты из списка по порядку. Можно комбинировать только делегаты одного и того же типа.

Оператор - можно использовать для удаления делегатов-компонентов из множественного делегата.

using System;

// Define a custom delegate that has a string parameter and returns void.
delegate void CustomDel(string s);

class TestClass
{
    // Define two methods that have the same signature as CustomDel.
    static void Hello(string s)
    {
        System.Console.WriteLine("  Hello, {0}!", s);
    }

    static void Goodbye(string s)
    {
        System.Console.WriteLine("  Goodbye, {0}!", s);
    }

    static void Main()
    {
        // Declare instances of the custom delegate.
        CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;

        // In this example, you can omit the custom delegate if you
        // want to and use Action<string> instead.
        //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel;

        // Create the delegate object hiDel that references the
        // method Hello.
        hiDel = Hello;

        // Create the delegate object byeDel that references the
        // method Goodbye.
        byeDel = Goodbye;

        // The two delegates, hiDel and byeDel, are combined to
        // form multiDel.
        multiDel = hiDel + byeDel;

        // Remove hiDel from the multicast delegate, leaving byeDel,
        // which calls only the method Goodbye.
        multiMinusHiDel = multiDel - hiDel;

        Console.WriteLine("Invoking delegate hiDel:");
        hiDel("A");
        Console.WriteLine("Invoking delegate byeDel:");
        byeDel("B");
        Console.WriteLine("Invoking delegate multiDel:");
        multiDel("C");
        Console.WriteLine("Invoking delegate multiMinusHiDel:");
        multiMinusHiDel("D");
    }
}
/* Output:
Invoking delegate hiDel:
  Hello, A!
Invoking delegate byeDel:
  Goodbye, B!
Invoking delegate multiDel:
  Hello, C!
  Goodbye, C!
Invoking delegate multiMinusHiDel:
  Goodbye, D!
*/
</string></string>