c# фильтр datagridview


string namestr = "MyColumnName";
BindingSource.Filter = " name LIKE'" + namestr + "%'";

с# работа с API / c# work with API


Для использования в программе API-функций надо, во-первых, добавить постранство имен System.Runtime.InteropServices, во-вторых, добавить заголовок нужной API-функции и в-третьих, вызвать ее в нужном месте.

Код:

using System;
...
//Добавление пространства имен
using System.Runtime.InteropServices;
...
        //Добавление заголовка
[DllImport("user32.dll", EntryPoint="MessageBox")]
        public static extern int MessageBox(int hWnd,
        String strMessage, String strCaption, uint uiType);
...
private void button1_Click(object sender, System.EventArgs e)
        {
            //Вызов API-функции
            MessageBox(0, "Hello!", "Caption", 0);
        }
    ...

В указанном примере при нажатии на кнопку выскочит MessageBox (путем вызова соответствующей API-функции).

с# application settings MSDN


http://msdn.microsoft.com/ru-ru/library/wabtadw6.aspx пошаговое описание

http://msdn.microsoft.com/ru-ru/library/a65txexh.aspx сам мини кусок кода

Properties.Settings.Default.FirstUserSetting = "abc";
Properties.Settings.Default.Save();

C# connect to dbf

using System.Data.OleDb;

...

            OleDbConnection _connection = new OleDbConnection();
            StringBuilder ConnectionString = new StringBuilder("");
            ConnectionString.Append(@"Provider=Microsoft.Jet.OLEDB.4.0;");
            ConnectionString.Append(@"Extended Properties=Paradox 5.x;");
            ConnectionString.Append(@"Data Source=D:\dbf;");
            _connection.ConnectionString = ConnectionString.ToString();
            try { _connection.Open(); }
            catch (Exception _e) { MessageBox.Show("Error openning database! " + _e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM kadr.db;", _connection);
            DataSet dsRetrievedData = new DataSet();
            da.Fill(dsRetrievedData);
            this.dataGridView1.DataSource = dsRetrievedData;
            this.dataGridView1.DataMember = dsRetrievedData.Tables[0].TableName;

С# запрос к базе / c# request to base

SqlCommand cmd = new SqlCommand("update table set bestOfTheBestField=@par where Na uslovie fantazii ne hvatilo");
cmd.Parameters.Add("@par", SqlDbType.Int).Value = (int)this.textBox.Text.Trim();
return cmd.ExecuteNonQuery();

дизасемблер для приложений .NET / Disassembler for .NET Applications


Приведенная ниже команда выводит метаданные и дизассемблированный код PE-файла MyHello.exe в стандартном графическом интерфейсе пользователя программы Ildasm.exe.
Копировать
ildasm myHello.exe
Копировать
ildasm myHello.exe

Приведенная ниже команда дизассемблирует файл MyFile.exe и сохраняет выходной текст для ассемблера MSIL в файле MyFile.il.
Копировать
ildasm MyFile.exe /output:MyFile.il
Копировать
ildasm MyFile.exe /output:MyFile.il

Приведенная ниже команда дизассемблирует файл MyFile.exe и выводит выходной текст для ассемблера MSIL на консоль.
Копировать
ildasm MyFile.exe /text
Копировать
ildasm MyFile.exe /text

Если файл MyApp.exe содержит внедренные управляемые и неуправляемые ресурсы, в результате выполнения следующей команды будет создано четыре файла: MyApp.il, MyApp.res, Icons.resources, и Message.resources.
Копировать
ildasm MyApp.exe /output:MyApp.il
Копировать
ildasm MyApp.exe /output:MyApp.il

Приведенная ниже команда дизассемблирует метод MyMethod класса MyClass в файле MyFile.exe и выводит результат в окно консоли.
Копировать
ildasm /item:MyClass::MyMethod MyFile.exe /text
Копировать
ildasm /item:MyClass::MyMethod MyFile.exe /text

В предыдущем примере допустимо наличие нескольких методов с именем MyMethod и различными подписями. Приведенная ниже команда дизассемблирует метод экземпляра MyMethod с типом возвращаемого значения void и типами параметров int32 и string.
Копировать
ildasm /item:"MyClass::MyMethod(instance void(int32,string)" MyFile.exe /text

c# универсальные шаблоны

// Declare the generic class.
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

c# Delete and copy files with replacing

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

C# how to copy all files in a folder

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace CopyDir
{
    class Program
    {
        static void Main(string[] args)
        {
            string FromDir = @"c:\source";
            string ToDir = @"c:\destination";
            if (!Directory.Exists(ToDir))
 
                Directory.CreateDirectory(ToDir);
 
            string[] Files;
            Files = Directory.GetFileSystemEntries(FromDir);
 
            for (int k = 0; k < Files.Length; k++)
            {
                string FromFile = Path.GetFileName(Files[k]);
 
                FileAttributes FileAttr = File.GetAttributes(Files[k]);
 
                if ((FileAttr & FileAttributes.Directory)== FileAttributes.Directory)
                    continue;
 
                Console.WriteLine(FromFile);
 
        string arrival = ToDir + "\\" + FromFile;
        File.Copy(Files[k], arrival, true);
                 
            }
            Console.ReadLine();
         }
    }
}

C# MySQL read and insert in BLOB field

//Save
//-----------------------------------
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;

conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();

string SQL;
UInt32 FileSize;
byte[] rawData;
FileStream fs;

conn.ConnectionString = "server=127.0.0.1;uid=root;" +
    "pwd=12345;database=test;";

try
{
    fs = new FileStream(@"c:\image.png", FileMode.Open, FileAccess.Read);
    FileSize = fs.Length;

    rawData = new byte[FileSize];
    fs.Read(rawData, 0, FileSize);
    fs.Close();

    conn.Open();

    SQL = "INSERT INTO file VALUES(NULL, @FileName, @FileSize, @File)";

    cmd.Connection = conn;
    cmd.CommandText = SQL;
    cmd.Parameters.AddWithValue("@FileName", strFileName);
    cmd.Parameters.AddWithValue("@FileSize", FileSize);
    cmd.Parameters.AddWithValue("@File", rawData);

    cmd.ExecuteNonQuery();

    MessageBox.Show("File Inserted into database successfully!",
        "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

    conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
    MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

//Read
//-------------------------------------------------------------------------

MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader myData;

conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();

string SQL;
UInt32 FileSize;
byte[] rawData;
FileStream fs;

conn.ConnectionString = "server=127.0.0.1;uid=root;" +
    "pwd=12345;database=test;";

SQL = "SELECT file_name, file_size, file FROM file";

try
{
    conn.Open();

    cmd.Connection = conn;
    cmd.CommandText = SQL;

    myData = cmd.ExecuteReader();

    if (! myData.HasRows)
        throw new Exception("There are no BLOBs to save");

    myData.Read();

    FileSize = myData.GetUInt32(myData.GetOrdinal("file_size"));
    rawData = new byte[FileSize];

    myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, FileSize);

    fs = new FileStream(@"C:\newfile.png", FileMode.OpenOrCreate, FileAccess.Write);
    fs.Write(rawData, 0, FileSize);
    fs.Close();

    MessageBox.Show("File successfully written to disk!",
        "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

    myData.Close();
    conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
    MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

c# How to work with ini files

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace sIniFile
{
    /// <summary>
    /// Descrizione di riepilogo per IniFileClass.
    /// </summary>
    public class IniFileClass
    {
        private String IniFile = "";
        
        // Importazione dei metodi dalle DLL di sistema
        [DllImport("kernel32")] private static extern long WritePrivateProfileInt(String Section, String Key, int Value, String FilePath);
        [DllImport("kernel32")] private static extern long WritePrivateProfileString(String Section, String Key, String Value, String FilePath);
        [DllImport("kernel32")] private static extern int GetPrivateProfileInt(String Section, String Key, int Default, String FilePath);
        [DllImport("kernel32")] private static extern int GetPrivateProfileString(String Section, String Key, String Default, StringBuilder retVal, int Size, String FilePath);

        public IniFileClass(String IniFile)
        {
            // Mi salvo il percorso del file INI
            this.IniFile = IniFile;
        }

        public String ReadString(String Section, String Key, String Default)
        {
            // Creo lo StringBuilder che conterra la stringa
            StringBuilder StrBu = new StringBuilder(255);
            // Provo a leggere il parametro richiesto
            GetPrivateProfileString(Section, Key, Default, StrBu, 255, IniFile);
            // Restituisco il parametro letto
            return StrBu.ToString();
        }

        public int ReadInt(String Section, String Key, int Default)
        {
            // Restituisco il valore del parametro letto
            return GetPrivateProfileInt(Section, Key, Default, IniFile); 
        }

        public void WriteString(String Section, String Key, String Value)
        {
            // Salvo il valore del parametro impostato
            WritePrivateProfileString(Section, Key, Value, IniFile);
        }

        public void WriteInt(String Section, String Key, int Value)
        {
            // Salvo il valore del parametro impostato
            WritePrivateProfileInt(Section, Key, Value, IniFile);
        }
    }
}

c# scroll panel with picturebox by dragging mouse


private Point _StartPoint;
void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left)
    _StartPoint = e.Location;
}
void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    Point changePoint = new Point(e.Location.X - _StartPoint.X, 
                                  e.Location.Y - _StartPoint.Y);
    panel1.AutoScrollPosition = new Point(-panel1.AutoScrollPosition.X - changePoint.X,
                                          -panel1.AutoScrollPosition.Y - changePoint.Y);
  }
}
A Meaning (Prod. By Joel Johnston) by Hi-Rez on Grooveshark