На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Модераторы: maxim84_
  
> различные примеры
    Небольшой примерчик работы с базами данных
    SimpleDB.rar (15K)
    В комплекте нет экзешников - это уж как-нибудь сами

    Для работы требуется MSSQL сервер с базой Northwind (но, я думаю, если переписать ConnectionString, то подойдёт любыя другая СУБД с поддержкой OleDB. Там используется только таблица Categories(CategoryID int, CategoryName nvarchar 15, DEscription ntext, Picture varbinary) )

    Комментарии только в примере на VB, но в примере на C# код полностью аналогичен.

    И главное - не забываёте про DataAdapter.Fill()!

    Это сообщение было перенесено сюда или объединено из темы "FAQ"
      Всем привет. Автор: kosten_spb*
      Q: Столкнулся со следующей проблемой – во время выполнения потока, который был запущен по нажатию кнопки на форме, необходимо получать данные из него.
      Поток запускался следующей функцией:
      ExpandedWrap disabled
         
        private void button1_Click(object sender, System.EventArgs e)
        {
          cr = new CCrawler(tbURL.Text);
          an = new CAnalyzer();
         
        //Добавляем обработчики событий потоков
         cr.OnHTMLLink += new CCrawler.HTMLLinkHandler(an.startAnalyze);
         an.OnScript += new CAnalyzer.ScriptHandler(getScript);
         
         a = new Thread(new ThreadStart(cr.startCrawler));
         a.Start();
         scriptCount = 0;
                
         sbpInfo.Text = "Выполняется поиск сценариев...";
        }

      A: Для корректной работы с контролом необходимы следующие действия:
      1. Объявление класса делегата
      ExpandedWrap disabled
         
         delegate void addNode(Scriptinfo si);

      2. Создание функции обратного вызова
      ExpandedWrap disabled
         
        void addNodeCallBack(Scriptinfo si)
        {
        //заполняем компонент TreeView - tvScriptList
         tvScriptList.BeginUpdate();
         tvScriptList.Nodes.Add(new TreeNode(si.ScriptName));
         tvScriptList.Nodes[scriptCount].Nodes.Add(new TreeNode("Параметры"));
         tvScriptList.Nodes[scriptCount].Nodes.Add(new TreeNode(si.ScriptMethod));
         foreach(String sp in si.ScriptParam)
         {
           tvScriptList.Nodes[scriptCount].Nodes[0].Nodes.Add(new TreeNode((string)sp));
         }
         tvScriptList.EndUpdate();
        }

      2. Вызов функции-обработчика события
      ExpandedWrap disabled
         
        public void getScript(object ob, CScriptArgs mySA)
        {
          String aaa = "";
          Scriptinfo si = mySA.Script;
          Console.Write(mySA.Script.ScriptName + "\n");
          aaa = si.ScriptName;
          //заполняем дерево ресурсов
          //выполняется если метод вызван из другого потока
          if(InvokeRequired)
          {
            addNode an = new addNode(addNodeCallBack);
            tvScriptList.Invoke(an, new Object [] {mySA.Script});
          }
          scriptCount++;
        }

      Данная методика подробно описана на здесь

      * все комментарии, по поводу работоспособности кода направлять ему и копию модераторам

      Эта тема была разделена из темы "FAQ"
        Примеры работы с процессами (System.Diagnostics.Process) от Gazon'a:
        1. Запуск процесса:
        ExpandedWrap disabled
           
          using System;
          using System.Diagnostics;
          using System.ComponentModel;
           
          namespace MyProcessSample
          {
              /// <summary>
              /// Shell for the sample.
              /// </summary>
              public class MyProcess
              {
                  // These are the Win32 error code for file not found or access denied.
                  const int ERROR_FILE_NOT_FOUND =2;
                  const int ERROR_ACCESS_DENIED = 5;
           
                  /// <summary>
                  /// Prints a file with a .doc extension.
                  /// </summary>
                  public void PrintDoc()
                  {
                      Process myProcess = new Process();
                      
                      try
                      {
                          // Get the path that stores user documents.
                          string myDocumentsPath =
                              Environment.GetFolderPath(Environment.SpecialFolder.Personal);
           
                          myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc";
                          myProcess.StartInfo.Verb = "Print";
                          myProcess.StartInfo.CreateNoWindow = true;
                          myProcess.Start();
                      }
                      catch (Win32Exception e)
                      {
                          if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
                          {
                              Console.WriteLine(e.Message + ". Check the path.");
                          }
           
                          else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
                          {
                              // Note that if your word processor might generate exceptions
                              // such as this, which are handled first.
                              Console.WriteLine(e.Message +
                                  ". You do not have permission to print this file.");
                          }
                      }
                  }
           
           
                  public static void Main()
                  {
                      MyProcess myProcess = new MyProcess();
                      myProcess.PrintDoc();
                  }
              }
          }

        2. Завершение процесса:
        ExpandedWrap disabled
           
          using System;
          using System.Diagnostics;
            class MyClass
              {
                  static void Main()
                  {
          //Используем статический метод Process.GetProcessesByName, для получения массива объектов
          //типа Process, каждый из которых связан с процессом, имя которого мы указали.
                      Process [] localByName = Process.GetProcessesByName("notepad");
          //Проходим по массиву процессов, и каждый завершаем.
                      foreach(Process tempProc in localByName)
                      {
                        tempProc.Kill();
                      }
                  }
              }

        3. Перечисление процессов:
        ExpandedWrap disabled
           
           //Get current process
                      Process currentProcess = Process.GetCurrentProcess();
           
                      
                      // Get all instances of Notepad running on the local
                      // computer.
                      Process [] localByName = Process.GetProcessesByName("notepad");
           
                      
                      // Get all instances of Notepad running on the specifiec
                      // computer.
                      // 1. Using the computer alias (do not precede with "\\").
                      Process [] remoteByName = Process.GetProcessesByName("notepad", "myComputer");
                      
                      // 2. Using an IP address to specify the machineName parameter.
                      Process [] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");
                      
                      
                      // Get all processes running on the local computer.
                      Process [] localAll = Process.GetProcesses();
           
                      
                      // Get all processes running on the remote computer.
                      Process [] remoteAll = Process.GetProcesses("myComputer");
           
                      
                      // Get a process on the local computer, using the process id.
                      Process localById = Process.GetProcessById(1234);
           
                      
                      // Get a process on a remote computer, using the process id.
                      Process remoteById = Process.GetProcessById(2345, "myComputer");
        0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
        0 пользователей:


        Рейтинг@Mail.ru
        [ Script execution time: 0,0222 ]   [ 15 queries used ]   [ Generated: 24.04.24, 12:00 GMT ]