вторник, 19 августа 2014 г.

C# данные для TreeView из базы данных

private void LoadTree()
{
    DataTable tbl = new DataTable();


    tbl = oraConnector.ExecQuery("select account_id, parent, 
                                  type, name from account");

    //Use a DataSet to manage the data
    DataSet ds = new DataSet();
    ds.Tables.Add(tbl);

    //add a relationship
    ds.Relations.Add("rsParentChild",  
                     ds.Tables[0].Columns["account_id"],  
                     ds.Tables[0].Columns["parent"]);

    foreach (DataRow dr in tbl.Rows)
    {
        if (dr["parent"] == DBNull.Value)
        {
            TreeNode root = new TreeNode(dr["name"].ToString());
            root.Tag = dr["type"].ToString();
            treeView.Nodes.Add(root);
            PopulateTree(dr, root);
        }
    }

    // treeView.ExpandAll();
}

public void PopulateTree(DataRow dr, TreeNode pNode)
{

    foreach (DataRow row in dr.GetChildRows("rsParentChild"))
    {
        TreeNode cChild = new TreeNode(row["NAME"].ToString());
        cChild.Tag = row["TYPE"].ToString();
        pNode.Nodes.Add(cChild);

        //Recursively build the tree
        PopulateTree(row, cChild);
    }
}

понедельник, 18 августа 2014 г.

C# Capturing keyboard activity of another application with the Raw Input API

Источник (source): http://www.news2news.com/vfp/?example=572&ver=vcs&PHPSESSID=3D014ff%3D

using System;
using System.Windows.Forms;
using RawInputHook.DeviceManager;
 
namespace RawInputHook.WinForm
{
    public partial class RawInputMonitorForm : Form
    {
        public RawInputMonitorForm()
        {
            InitializeComponent();
 
            RawInputDeviceManager mgr = new RawInputDeviceManager();
            mgr.RawInputEvent += new RawInputEventHandler(OnRawInputEvent);
 
            mgr.AddKeyboardDevice(this.Handle);
            mgr.RegisterDevices();
 
            Application.AddMessageFilter(mgr);
        }
 
        void OnRawInputEvent(object sender, RawInputEventArgs e)
        {
            if (e.asciiCode != 0)
            {
                switch (e.asciiCode)
                {
                    case 13:
                        textBox1.Text += "\r\n";
                        break;
                    default:
                        textBox1.Text += (char)e.asciiCode;
                        break;
                }
            }
        }
 
    }
}

 
// ======================================
 
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
namespace RawInputHook.DeviceManager
{
     public delegate void RawInputEventHandler(
        object sender, RawInputEventArgs e);
 
    public class RawInputDeviceManager : IMessageFilter
    {
        const int WM_INPUT = 0x00ff;
        public event RawInputEventHandler RawInputEvent;
        List < RAWINPUTDEVICE > devices = new List < RAWINPUTDEVICE > ();
 
        public void AddKeyboardDevice(IntPtr windowHandle)
        {
            AddDevice(1, 6, 0x100, windowHandle);
        }
 
        void AddDevice(ushort usagePage, ushort usage,
            Int32 flags, IntPtr windowHandle)
        {
            devices.Add(new RAWINPUTDEVICE(usagePage, usage,
                flags, windowHandle));
        }
 
        public bool RegisterDevices()
        {
            if (devices.Count == 0) return false;
 
            RAWINPUTDEVICE[] d = devices.ToArray();
            bool result = RegisterRawInputDevices(d, devices.Count,
                Marshal.SizeOf(typeof(RAWINPUTDEVICE)));
 
            return result;
        }
 
        void ProcessRawInput(IntPtr hRawInput)
        {
            RAWINPUT pData = new RAWINPUT();
            int pcbSize = Marshal.SizeOf(typeof(RAWINPUT));
 
            int result = GetRawInputData(hRawInput,
                RawInputCommand.Input, out pData,
                ref pcbSize, Marshal.SizeOf(typeof(RAWINPUTHEADER)));
 
            if (result != -1)
            {
                if (pData.Header.Type == RawInputType.Keyboard)
                {
                    if ((pData.Keyboard.Flags == 0) || 
                        (pData.Keyboard.Flags == 2))
                    {
                        int asciiCode = VKeyToChar(
                            pData.Keyboard.VirtualKey,
                            pData.Keyboard.MakeCode);
 
                        RawInputEvent(this, 
                            new RawInputEventArgs(pData, asciiCode));
                    }
                }
            }
        }
 
        int VKeyToChar(int virtKey, int scanCode)
        {
            int asciiCode = 0;
            byte[] kbdState = new byte[256];
            GetKeyboardState(kbdState);
            ToAscii(virtKey, scanCode, kbdState, ref asciiCode, 0);
            return asciiCode;
        }
 
        #region IMessageFilter Members
 
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == WM_INPUT)
            {
                if (m.WParam != (IntPtr)0) //the app is on background
                {
                    if (RawInputEvent != null) //event implemented
                    {
                        ProcessRawInput(m.LParam);
                        return true; //stop the message
                    }
                }
            }
            return false; //allow the message to continue
        }
 
        #endregion
 
        [DllImport("user32.dll")]
        static extern bool RegisterRawInputDevices(
            [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] 
            RAWINPUTDEVICE[] pRawInputDevices,
            int uiNumDevices, int cbSize);
 
        [DllImport("user32.dll")]
        static extern int GetRawInputData(IntPtr hRawInput,
            RawInputCommand uiCommand, out RAWINPUT pData,
            ref int pcbSize, int cbSizeHeader);
 
        [DllImport("user32.dll")]
        static extern int GetKeyboardState(byte[] lpKeyState);
 
        [DllImport("user32.dll")]
        static extern int MapVirtualKey(int uCode, int uMapType);
 
        [DllImport("user32.dll")]
        static extern int ToAscii(int uVirtKey, int uScanCode,
            byte[] lpKeyState, ref int lpChar, int uFlags);
    }
 
    public class RawInputEventArgs : EventArgs
    {
        public RAWINPUT rawInput;
        public int asciiCode = 0;
        public RawInputEventArgs(RAWINPUT rawInput, int asciiCode)
        {
            this.rawInput = rawInput;
            this.asciiCode = asciiCode;
        }
    }
 
    [StructLayout(LayoutKind.Sequential)]
    struct RAWINPUTDEVICE
    {
        public ushort UsagePage;
        public ushort Usage;
        public Int32 Flags;
        public IntPtr WindowHandle;
        public RAWINPUTDEVICE(ushort usagePage, ushort usage,
            Int32 flags, IntPtr windowHandle)
        {
            UsagePage = usagePage;
            Usage = usage;
            Flags = flags;
            WindowHandle = windowHandle;
        }
    }
 
    [StructLayout(LayoutKind.Explicit)]
    public struct RAWINPUT
    {
        [FieldOffset(0)]
        public RAWINPUTHEADER Header;
        [FieldOffset(16)]
        public RAWKEYBOARD Keyboard;
        //mouse and HID parts omitted
    }
 
    [StructLayout(LayoutKind.Sequential)]
    public struct RAWINPUTHEADER
    {
        public RawInputType Type;
        public int Size;
        public IntPtr Device;
        public IntPtr wParam;
    }
 
    [StructLayout(LayoutKind.Sequential)]
    public struct RAWKEYBOARD
    {
        public ushort MakeCode;
        public ushort Flags;
        public ushort Reserved;
        public ushort VirtualKey;
        public int Message;
        public int ExtraInformation;
    }
 
    public enum RawInputType
    {
        Mouse = 0,
        Keyboard = 1,
        HID = 2
    }
 
    enum RawInputCommand
    {
        Input = 0x10000003,
        Header = 0x10000005
    }
}

вторник, 12 августа 2014 г.

C# перетаскивание формы за другой компонент

1. Подключаем пространство имен:

using System.Runtime.InteropServices;

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;


2. Импортируем необходимые библиотеки:

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

3. Пишем обработчик на компонент, за который планируем перетаскивать форму:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

пятница, 8 августа 2014 г.

C# модем и sms

Класс для декодирования sms-сообщения:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ManagmentSerialPort.Framework.SMS
{
    class SMSDecoder

    {

        Hashtable htAbc;

        public SMSDecoder()
        {
            htAbc = new Hashtable();
            htAbc.Add("0410", "А"); htAbc.Add("0411", "Б");
            htAbc.Add("0412", "В"); htAbc.Add("0413", "Г");
            htAbc.Add("0414", "Д"); htAbc.Add("0415", "Е");
            htAbc.Add("00A8", "Ё"); htAbc.Add("0416", "Ж");
            htAbc.Add("0417", "З"); htAbc.Add("0418", "И");
            htAbc.Add("0419", "Й"); htAbc.Add("041A", "К");
            htAbc.Add("041B", "Л"); htAbc.Add("041C", "М"); 
            htAbc.Add("041D", "Н"); htAbc.Add("041E", "О");
            htAbc.Add("041F", "П"); htAbc.Add("0420", "Р"); 
            htAbc.Add("0421", "С"); htAbc.Add("0422", "Т");
            htAbc.Add("0423", "У"); htAbc.Add("0424", "Ф"); 
            htAbc.Add("0425", "Х"); htAbc.Add("0426", "Ц");
            htAbc.Add("0427", "Ч"); htAbc.Add("0428", "Ш"); 
            htAbc.Add("0429", "Щ"); htAbc.Add("042C", "Ь");
            htAbc.Add("042A", "Ъ"); htAbc.Add("042D", "Э"); 
            htAbc.Add("042E", "Ю"); htAbc.Add("042F", "Я");
            htAbc.Add("0430", "а"); htAbc.Add("0431", "б"); 
            htAbc.Add("0432", "в"); htAbc.Add("0433", "г");
            htAbc.Add("0434", "д"); htAbc.Add("0435", "е"); 
            htAbc.Add("00B8", "ё"); htAbc.Add("0436", "ж");
            htAbc.Add("0437", "з"); htAbc.Add("0438", "и"); 
            htAbc.Add("0439", "й"); htAbc.Add("043A", "к");
            htAbc.Add("043B", "л"); htAbc.Add("043C", "м"); 
            htAbc.Add("043D", "н"); htAbc.Add("043E", "о");
            htAbc.Add("043F", "п"); htAbc.Add("0440", "р"); 
            htAbc.Add("0441", "с"); htAbc.Add("0442", "т"); 
            htAbc.Add("0443", "у"); htAbc.Add("0444", "ф"); 
            htAbc.Add("0445", "х"); htAbc.Add("0446", "ц");
            htAbc.Add("0447", "ч"); htAbc.Add("0448", "ш"); 
            htAbc.Add("0449", "щ"); htAbc.Add("044D", "э");
            htAbc.Add("044E", "ю"); htAbc.Add("044F", "я"); 
            htAbc.Add("0041", "A"); htAbc.Add("0042", "B"); 
            htAbc.Add("0043", "C"); htAbc.Add("0044", "D"); 
            htAbc.Add("0045", "E"); htAbc.Add("0046", "F");
            htAbc.Add("0047", "G"); htAbc.Add("0048", "H"); 
            htAbc.Add("0049", "I"); htAbc.Add("004A", "J");
            htAbc.Add("004B", "K"); htAbc.Add("004C", "L"); 
            htAbc.Add("004D", "M"); htAbc.Add("004E", "N");
            htAbc.Add("004F", "O"); htAbc.Add("0050", "P"); 
            htAbc.Add("0051", "Q"); htAbc.Add("0052", "R");
            htAbc.Add("0053", "S"); htAbc.Add("0054", "T"); 
            htAbc.Add("0055", "U"); htAbc.Add("0056", "V");
            htAbc.Add("0057", "W"); htAbc.Add("0058", "X"); 
            htAbc.Add("0059", "Y"); htAbc.Add("005A", "Z");
            htAbc.Add("0061", "a"); htAbc.Add("0062", "b"); 
            htAbc.Add("0063", "c"); htAbc.Add("0064", "d");
            htAbc.Add("0065", "e"); htAbc.Add("0066", "f"); 
            htAbc.Add("0067", "g"); htAbc.Add("0068", "h");
            htAbc.Add("0069", "i"); htAbc.Add("006A", "j"); 
            htAbc.Add("006B", "k"); htAbc.Add("006C", "l");
            htAbc.Add("006D", "m"); htAbc.Add("006E", "n"); 
            htAbc.Add("006F", "o"); htAbc.Add("0070", "p");
            htAbc.Add("0071", "q"); htAbc.Add("0072", "r"); 
            htAbc.Add("0073", "s"); htAbc.Add("0074", "t");
            htAbc.Add("0075", "u"); htAbc.Add("0076", "v"); 
            htAbc.Add("0077", "w"); htAbc.Add("0078", "x");
            htAbc.Add("0079", "y"); htAbc.Add("007A", "z"); 
            htAbc.Add("0030", "0"); htAbc.Add("0031", "1");
            htAbc.Add("0032", "2"); htAbc.Add("0033", "3"); 
            htAbc.Add("0034", "4"); htAbc.Add("0035", "5");
            htAbc.Add("0036", "6"); htAbc.Add("0037", "7"); 
            htAbc.Add("0038", "8"); htAbc.Add("0039", "9");
            htAbc.Add("0027", "'"); htAbc.Add("002D", "-"); 
            htAbc.Add("002A", "*"); htAbc.Add("0020", " ");
            htAbc.Add("003A", ":"); htAbc.Add("003B", ";"); 
            htAbc.Add("0029", ")"); htAbc.Add("0028", "(");
            htAbc.Add("002E", "."); htAbc.Add("002C", ","); 
            htAbc.Add("0021", "!"); htAbc.Add("003D", "=");
            htAbc.Add("005F", "_"); htAbc.Add("044C", "ь"); 
            htAbc.Add("002B", "+");
        }

        public string DecodeMessage(string sMessage)
        {

            string str = "";
            int n = 4;
            List<string> lst = new List<string>();

            for (int i = 0; i < sMessage.Length; i += n)
            {
                lst.Add(sMessage.Substring(i, n));
            }

            foreach (string code in lst) {
                str += GetCharByCode(code);
            }
            return str;
        }

        private string GetCharByCode(string code)
        {

            string retVal = "";
            try
            {
                retVal = htAbc[code].ToString();
            } catch (Exception ex) {
                // System.Windows.Forms.MessageBox.Show("Отсутствует сопоставление для кода " + code);
                return "?";
            }
            return retVal;
        }
    }
}


Использование класса:

    ...
    SMSDecoder smsDecoder;

    smsDecoder = new Framework.SMS.SMSDecoder();

    MessageBox.Show(smsDecoder.DecodeMessage( "041D043E043C04350440002004320430044804350433043E0020043C043E04310438043B044C043D043E0433043E002004420435043B04350444043E043D04300020002B00370039003800390036003800320030003200330039"));
    ....

В выводимом сообщении мы получаем раскодированный текст "Номер вашего мобильного телефона +79896820239" 

воскресенье, 11 мая 2014 г.

BPWin русский текст на диаграмме

Друзья, создаем *.reg-файл, копируем в него текст приведенный ниже, перезагружаем компьютер и все.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes]
"Arial CE,238"="Arial,238"
"Arial CYR,204"="Arial,204"
"Arial Greek,161"="Arial,161"
"Arial TUR,162"="Arial,162"
"Courier New CE,238"="Courier New,238"
"Courier New CYR,204"="Courier New,204"
"Courier New Greek,161"="Courier New,161"
"Courier New TUR,162"="Courier New,162"
"Helv"="MS Sans Serif"
"Helvetica"="Arial"
"MS Shell Dlg 2"="Tahoma"
"Times"="Times New Roman,204"
"Times New Roman CE,238"="Times New Roman,238"
"Times New Roman CYR,204"="Times New Roman,204"
"Times New Roman Greek,161"="Times New Roman,161"
"Times New Roman TUR,162"="Times New Roman,162"
"Tms Rmn"="MS Serif"
"Arial Baltic,186"="Arial,186"
"Courier New Baltic,186"="Courier New,186"
"Times New Roman Baltic,186"="Times New Roman,186"
"System,0"="System,204"
"Fixedsys,0"="Fixedsys,204"
"Small Fonts,0"="Small Fonts,204"
"MS Serif,0"="MS Serif,204"
"MS Sans Serif,0"="MS Sans Serif,204"
"Courier,0"="Courier New,204"
"Arial Cyr,0"="Arial,204"
"Courier New Cyr,0"="Courier New,204"
"Times New Roman Cyr,0"="Times New Roman,204"
"Helv,0"="MS Sans Serif,204"
"Tms Rmn,0"="MS Serif,204"
"MS Shell Dlg"="Microsoft Sans Serif"
"Arial"="Arial,204"
"Courier New"="Courier New,204"
"Times New Roman"="Times New Roman,204"
"Arial,0"="Arial,204"
"Times New Roman,0"="Times New Roman,204"
"Courier New,0"="Courier New,204"
"Courier"="Courier,204"
"Times,0"="Times,204"

вторник, 29 апреля 2014 г.

C# DataGridView. Объединение двух sql-запросов из SQLServer и Oracle в одну DataTable

Статья в первую очередь является подсказкой для меня, поэтому привожу пример конкретной ситуации.
Ситуация следующая, один набор данных на сервер работающем под управлением ПО "Пирамида 2000. Сервер", база данных MS SQL Server, второй набор данных находится на сервере под управлением ПО "КТС Энергомера 2.7", база данных Oracle.

Если в статье затрагиваю чей-то интерес, писать сюда: palem[dog]list[dot]ru.


string sqlP2kQuery = sqlGetP2kData;
string sqlKtsQuery = sqlGetKtsData;

DataTable tblP2k = dbManager.sqlConnector.ExecQuery(sqlP2kQuery);
DataTable tblKts = dbManager.oraConnector.ExecQuery(sqlKtsQuery);

DataTable resTable = dbManager.TablePlusTable(tblP2k, tblKts);

dgv1.DataSource = resTable;
dgv1.Update();



~~~ Запрос 1. К базе данных MS SQL Server (sqlGetP2kData)
if OBJECT_ID('tempdb..#telNumber', 'U') is not null
    drop table #telNumber

select
    STATIONID, 
    substring(CONNECTSTR, 4, 11) as TelNumber
into
    #telNumber
from 
    ICMROUTES
where 
    VIRTPORT = 1 

if OBJECT_ID('tempdb..#const', 'U') is not null
    drop table tempdb..#const

select
  const.ITEMID,
    CAST(const.CONSTANTTEXT AS NUMERIC(38, 0)) as value
into
  tempdb..#const
from
  CONSTANTS as const
where
  const.CONSTANTTYPE = 8

if OBJECT_ID('tempdb..#values', 'U') is not null
    drop table #values

select
  *
into
    #values
from
  Piramida2000.dbo.DATA
where
  (Piramida2000.dbo.DATA.DATA_DATE = '28.04.2014')
    and
    (Piramida2000.dbo.DATA.PARNUMBER = 101)
    and
    (Piramida2000.dbo.DATA.ITEM = 2)

select
    convert(varchar(100), 'p2k') as SERVTYPE,
    convert(varchar(100), Folders.ID) as FOLDERID,
    convert(varchar(100), DEVICES.CODE) as DEVICECODE,
    convert(varchar(100), DEVICES.NAME) as OBJECTNAME,
    convert(varchar(100), 'CE303') as METERTYPE,
    convert(varchar(100), tempdb..#const.value) as SN,
    convert(varchar(100), dog.dog) as DOG,
    convert(varchar(100), #telNumber.TelNumber) as TELNUMBER,
    convert(varchar(100), '26.02.2014') as DATETIME,
    convert(varchar(100), 'A-') as ENTYPE,
    convert(varchar(100), Cast(tempdb..#values.VALUE0 as decimal(38, 3))) as KWTCH
from
    Piramida2000.dbo.DEVICES
join
  Piramida2000.dbo.FOLDERS on DEVICES.FOLDERID = FOLDERS.ID
left join
  tempdb..#values on DEVICES.CODE = #values.OBJECT
left join
  tempdb..#const on DEVICES.ID = #const.ITEMID
left join
  #telNumber on DEVICES.ID = #telNumber.STATIONID
left join
    dogovor as dog on (cast(#const.value as varchar(20)) = cast(dog.SN as varchar(20)))
    order by Devices.NAME



~~~ Запрос 2. К базе данных Oracle (sqlGetKtsData)
select 
  TO_CHAR('kts') SERVTYPE ,
  TO_CHAR(dsrobj.dcid) FOLDERID, 
  TO_CHAR(devs.devinc) DEVICECODE, 
  TO_CHAR(dsrobj.name) OBJECTNAME, 
  TO_CHAR('CE201') METERTYPE, 
  TO_CHAR(devs.sernum) SN,  
  TO_CHAR('') DOG,  
  TO_CHAR('') TELNUMBER, 
  '28.04.2014' datetime, 
  TO_CHAR('A-') EnType, 
  TO_CHAR(cdi.val, '9999.999') kWtCh 
from 
  devices devs 
join 
  dsrobj on (dsrobj.dcid = devs.dcid) and (dsrobj.objid = devs.objid)
left join 
  cdi on (cdi.devid = devs.devinc) and (cdi.tariffid = 0) and (cdi.reliable = 3) and (cdi.stamp = to_date('28.04.2014', 'DD.MM.YY'))

понедельник, 21 апреля 2014 г.

C# Drag and Drop файла на WinForm

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
    }

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);
    }
  }

Docker. Первые контейнеры

Источник:  php.dragomano.ru Структура каталогов: ~/develop/web/project/                  nginx/      - сервис web-сервера                php...