Tag: .net

Entries for tag ".net", ordered from most recent. Entry count: 20.

Warning! Some information on this page is older than 3 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Pages: 1 2 3 >

14:32
Sun
26
Feb 2012

NoConsole - My C# Project

Some time ago I started a new personal project. It is called NoConsole. I uploaded it to SourceForge GitHub, with C# source code in Git repository, under GNU GPL. The idea (and name) comes from my aversion to console-based programs. I want to create a framework which enables easy development of GUI over command line tools.

Probably the most interesting part is C# scripting. .NET Framework includes C# compiler, so user doesn't have to install any development environment to be able to compile C# source code into managed EXE or DLL files. So if my program is coded in C#, there was no purpose in including any other scripting language. Scripts that control this program are just CS files. They are compiled into DLL-s on first use. They can execute arbitrary code, but the library shipped with NoConsole simplifies some some common tasks and enables integrating with host application:

The project is in early stage of development. Much can be added or changed. But I already use it to simplify some of the work I do, using my scripts I didn't share here.

Comments (1) | Tags: .net gui productions | Author: Adam Sawicki | Share

17:38
Sat
04
Feb 2012

Algorithms for Managing Tree Structure

What are the ways of storing a tree data structure in memory? I mean a tree with arbitrary number of child nodes. Probably first thing that comes to our minds - as high level programmers - is to dynamically allocate each node as object of some class that would store its data and a collection of pointers to its children. Opposite approach would be to store all nodes in some array - a continuous piece of memory, where each node would refer to other nodes by index or something. Third approach - something in between in terms of sophistication, as well as efficiency - is to have dynamically allocated nodes, but not to store a collection of all child nodes. It is a good idea to employ kind of linked list here. I'd like to describe such data structure and basic algorithms for manipulating it.

The idea is that each node stores - besides its data - 5 pointers (possibly null) to some other nodes: parent, previous sibling, next sibling, first child and last child. It could be seen as equivalent to doubly linked list. It has much more pointers that is needed to be able to traverse whole tree, but thanks to this you can traverse such tree in any order, as well as insert and remove nodes at any point, with best possible time complexity. A node with Parent == null is considered a tree root. Here is a picture of a single node and example tree:

Read full entry > | Comments (4) | Tags: algorithms .net | Author: Adam Sawicki | Share

19:31
Mon
23
Jan 2012

The Concept of Wait Cursor

When coding a GUI application, sometimes we have to conduct lengthy operation like loading or saving a file. It would be perfect if every such operation was done on separate, background thread while main thread - the one responsible for windowed interface - would show progress and allow to cancel the operation at any time. But multithreaded programming is hard, so some (not so critical and not so long) operations, like loading a configuration file, are usually done on the main thread, freezing the whole GUI. It's OK as long as the operation takes no longer than a fraction of second or several seconds - just like loading and parsing small configuration file, unless the file is located on a floppy disk :)

But it's good to show to the user that some operation is being performed so he doesn't get angry and terminate your application so quickly. Changing mouse cursor from "Normal" to "Wait" is useful here, so GUI libraries provide functionality for this.

In C#, we do it by setting Cursor property of a Form. Assuming we are inside a method of a Form:

Cursor = Cursors.WaitCursor;
// Lengthy process...
Cursor = Cursors.Default;

Just don't forget to restore default cursor no matter what's the result of the operation. try-finally section can be useful here to make the wait cursor "exception-safe". Good news is that if you wish to show a MessageBox informing user about an error that happened between setting the cursor to WaitCursor and restoring it, the cursor will change to Default automatically for the time the message window is shown.

It may be tempting to use Application.UseWaitCursor instead, but this method is worse. It requires to go back to main message loop before the cursor change takes effect, so if you set Application.UseWaitCursor = true; then do some time-consuming process inside same function and set Application.UseWaitCursor = false; at the end, user won't see changed cursor at all, whereas setting Cursor property of a form takes effect immediately.

wxWidgets library makes it easy to change cursor to "busy" - as they call it - and restore it at the end of C++ scope by creating an object of class wxBusyCursor on the stack. It will change cursor in its constructor and automatically restore it in destructor of the object.

{
    wxBusyCursor busyCursor;
    // Lengthy process...
}

MFC library also has such class. It is called CWaitCursor.

If you know the way to show wait cursor in other GUI libraries, post it in a comment.

Comments (0) | Tags: wxwidgets .net mfc gui | Author: Adam Sawicki | Share

23:00
Wed
04
Jan 2012

Fast, Heuristic Disk Search

In March 2007 I've written an algorithm which I called "Fast, heuristic disk search" and published it in my article Szybkie, heurystyczne przeszukiwanie dysku (in Polish) on codeguru.pl. Today I went back to it, improved it a bit and I think it is a good opportunity to present it once again, this time in English :)

The problem is about searching hard disk, looking for a file or directory with particular name. Naive approach, which is used by file searching functions in programs like Total Commander, uses depth-first search, so it enters C:\, then C:\Program Files, then C:\Program Files\Adobe etc., spending lots of time in places where it probably won't find the file we are looking for.

Game developers know that searching algorithm can be significantly improved by using some heuristics that will drive algorithm towards (probably) right direction. We do it in A* pathfinding. Does a similar principle could be used also when searching for a file?

My particular problem was configuring a program with path to a console tool, let's say fxc.exe shader compiler from DirectX SDK. We could present a textbox where user has to enter path to this tool. We could also make "Browse" button with an open file dialog to simplify locating it. But wouldn't be great if program tried to locate it automatically on first run? Some installed programs store path in a registry key, but if it doesn't, we have no idea where could it be if we don't look for it among files and directories on hard disk.

My algorithm tries to locate given file or directory in given time limit by searching all given directories and their subdirectories. The improvement I propose here is inteligent management of the order in which we process these directories.

The algorithm uses two collections: a queue of directories to process and a set of already visisted directories. Here is the code in C#:

Read full entry > | Comments (0) | Tags: algorithms .net | Author: Adam Sawicki | Share

22:46
Thu
01
Dec 2011

C++/CLI Tutorial

I finished and present my latest production - a tutorial for C++/CLI programming language. C++/CLI is an extension to C++ made by Microsoft and available in Visual Studio / Visual C++ IDE. At the same time it is one of the languages of .NET platform, next to C# or VB.NET. With it you can freely mix native and managed code, which gives extraordinary power in some applications. I've been using this language in my previous job and now I want to share this piece of knowledge. Here is the PDF document and ZIP archive with sample source code:

Comments (1) | Tags: teaching productions .net c++ | Author: Adam Sawicki | Share

20:49
Fri
18
Feb 2011

Naprawiacz nazw plików - My Little Tool

Here I publish a small C# program that I developed for some specific needs of my father, but some of you may also find useful. It recursively searches selected directory for files and subdirectiores which names are too long or contain some non-ANSI characters, especially Russian cyryclic or Polish diacritic letters. It then presents the list and lets you manually rename or delete selected items, as well as automatically rename all selected items to convert these special letters to their English transcription.

This program can be useful if you collect some ebooks or other documents and need to store, pack or catalog these files in some way that doesn't like long names or nonstandard characters. The whole GUI is in Polish. The program requires .NET Framework 4. Source code in C# is attached. I think this code can be good entry point to write other similar programs that look for files and directories that meet some specific criteria.

Download:
Naprawiacz_nazw_plikow_bin.zip (EXE file)
Naprawiacz_nazw_plikow_src.zip (C# source code)

Now the Polish version:

Chciałbym opublikować mały program w C#, który napisałem dla specyficznych potrzeb mojego taty, ale może okazać się przydatny także innym. Program rekurencyjnie przeszukuje wskazany katalog w poszukiwaniu plików i podkatalogów, których nazwy są zbyt długie lub zawierają znaki spoza zakresu ANSI, szczególnie cyrylicę i polskie znaki diakrytyczne. Następnie prezentuje listę, na której można ręcznie zmieniać nazwy i usuwać wybrane elementy, a także automatycznie zmienić nazwy wszystkich zaznaczonych elementów konwertując te zestawy liter na ich transkrypcje po angielsku.

Ten program może się przydać, jeśli zbierasz ebooki czy inne dokumenty, a chcesz je zapisywać, pakować czy katalogować za pomocą takich programów, które nie radzą sobie ze zbyt długimi nazwami albo niestandardowymi znakami. Interfejs programu jest w języku polskim. Program wymaga zainstalowanego .NET Framework 4. Do archiwum dołączam kod źródłowy w C#. Myślę, że ten kod może być dobrym punktem wyjścia do pisania innych podobnych programów, które wyszukują pliki i katalogi spełniające podane kryteria.

Comments (0) | Tags: .net tools | Author: Adam Sawicki | Share

19:22
Fri
07
Jan 2011

Process Class Deadlocks on Long Lines when Redirecting Output

To run a console process programatically from your program and capture its output is very difficult to do right. There are so many possible problems! Not only you have to pass correct command line parameters and escape them if they contain special characters like space, care about working directory and maybe even environmental variables. You must also handle different possible behavior of the program. For example, it can freeze indefinitely, so you better do some timeout when waiting for it to exit. It may ask for additional console input and wait for it. It may print some information on both of its outputs - "standard output" and "standard error". They are all asynchronous and you better capture these data because if a buffer fills up, the program will hang waiting until you consume this output to allow it to post more. You also have to read these buffers to the end after program exited because there may still be some bytes remaining.

I do it in C# and I was hoping I already did it all right... Until today. I wanted to run "mysqldump" and capture its output to store a MySQL database table in memory and then import it on another machine. But when exporting a table with large binary data in its BLOB fields, my program hung. My code was like this:

using System.Text;
using System.Diagnostics;
using System.Threading;

class ConsoleCommand
{
  public void Execute(string fileName, string arguments, int timeout, string standardInputData)
  {
    using (Process process = new Process())
    {
      process.StartInfo.FileName = fileName;
      process.StartInfo.Arguments = arguments;
      process.StartInfo.RedirectStandardInput = true;
      process.StartInfo.RedirectStandardOutput = true;
      process.StartInfo.RedirectStandardError = true;
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.CreateNoWindow = true;
      process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
      process.ErrorDataReceived += new DataReceivedEventHandler(StandardErrorHandler);
      process.Start();
 
      process.BeginOutputReadLine();
      process.BeginErrorReadLine();
 
      if (standardInputData != null)
      {
        process.StandardInput.Write(standardInputData);
        process.StandardInput.Close();
      }
 
      if (!process.WaitForExit(timeout))
        throw new Exception("Process execution timeout.");
      m_StandardOutputEvent.WaitOne();
      m_StandardErrorEvent.WaitOne();
 
      m_ExitCode = process.ExitCode;
    }
  }

  public int ExitCode { get { return m_ExitCode; } }
  public string StandardOutputData { get { return m_StandardOutputData.ToString(); } }
  public string StandardErrorData { get { return m_StandardErrorData.ToString(); } }

  private void StandardOutputHandler(object process, DataReceivedEventArgs e)
  {
    if (e.Data == null)
      m_StandardOutputEvent.Set();
    else
      m_StandardOutputData.AppendLine(e.Data);
  }

  private void StandardErrorHandler(object process, DataReceivedEventArgs e)
  {
    if (e.Data == null)
      m_StandardErrorEvent.Set();
    else
      m_StandardErrorData.AppendLine(e.Data);
  }

  private int m_ExitCode;
  private StringBuilder m_StandardOutputData = new StringBuilder();
  private StringBuilder m_StandardErrorData = new StringBuilder();
  private ManualResetEvent m_StandardOutputEvent = new ManualResetEvent(false);
  private ManualResetEvent m_StandardErrorEvent = new ManualResetEvent(false);
}

I couldn't find any solution on the Internet. That's why I write about it here - maybe some day someone (you?) who has same problem finds this article on Google. I know it must have something in common with binary data on the output, so I coded a small program that printed all possible ASCII characters. It worked. So there was not the problem with characters codes, but with the length of the data. The delegate associated with OutputDataReceived and ErrorDataReceived is designed to handle text lines. I suppose there is an internal buffer somewhere inside .NET that splits the text into lines. If there is a lot of data (more than 1 MB) in a single line (binary data without end-of-line character), the buffer fills up, neither OutputDataReceived delegate is called, nor the console program is able to print more output and everything just deadlocks :(

The only solution I know at the moment is not to use these OutputDataReceived and ErrorDataReceived events, but to poll for output data synchronously like this:

class ConsoleCommand
{
  public void Execute(string fileName, string arguments, int timeout, string standardInputData)
  {
    using (Process process = new Process())
    {
      process.StartInfo.FileName = fileName;
      process.StartInfo.Arguments = arguments;
      process.StartInfo.RedirectStandardInput = true;
      process.StartInfo.RedirectStandardOutput = true;
      process.StartInfo.RedirectStandardError = true;
      process.StartInfo.UseShellExecute = false;
      process.StartInfo.CreateNoWindow = true;
      process.Start();

      if (standardInputData != null)
      {
        process.StandardInput.Write(standardInputData);
        process.StandardInput.Close();
      }

      DateTime end_time = DateTime.Now + TimeSpan.FromMilliseconds((double)timeout);
      bool process_exit = false, output_end = false, error_end = false;
      for (;;)
      {
        if (!output_end)
        {
          if (process.StandardOutput.EndOfStream)
            output_end = true;
          else
            m_StandardOutputData.Append(process.StandardOutput.ReadToEnd());
        }

        if (!error_end)
        {
          if (process.StandardError.EndOfStream)
            error_end = true;
          else
            m_StandardErrorData.Append(process.StandardError.ReadToEnd());
        }

        if (!process_exit)
          process_exit = process.WaitForExit(0);

        if (DateTime.Now > end_time)
        {
          process.Close();
          throw new Exception("Process execution timeout.");
        }

        if (process_exit && output_end && error_end)
          break;

        System.Threading.Thread.Yield();
      }

      m_ExitCode = process.ExitCode;
    }
  }

  public int ExitCode { get { return m_ExitCode; } }
  public string StandardOutputData { get { return m_StandardOutputData.ToString(); } }
  public string StandardErrorData { get { return m_StandardErrorData.ToString(); } }

  private int m_ExitCode;
  private StringBuilder m_StandardOutputData = new StringBuilder();
  private StringBuilder m_StandardErrorData = new StringBuilder();
}

Comments (2) | Tags: .net | Author: Adam Sawicki | Share

20:59
Mon
05
Jul 2010

Color Names in .NET - CheatSheet

Some color values used in computer science have their names, like "Red" (#FF0000) or "Navy" (#000080). You probably know them if you've written anything in HTML. But there are more of them than just several most popular ones, made of values 0x00, 0x80 and 0xFF. I've prepared (or rather, to be honest, copied from MSDN Library) a table of color names available in .NET standard library, as static variables in System.Drawing.Color, System.Drawing.Pens and System.Drawing.Brushes classes. Here is my "Color Names in .NET" CheatSheet:

Color_Names_in_DotNet.pdf
Color_Names_in_DotNet.odt

Comments (2) | Tags: rendering graphics .net | Author: Adam Sawicki | Share

Pages: 1 2 3 >

STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2017 Adam Sawicki
Copyright © 2004-2017 Adam Sawicki