dotFusion.net

Today I’ll show you not only one, but two interesting things.
I’ll show you how to run an application from your C# program as a different user (for example Administrator). And I’ll also show you how to mask the password a user enters in your console application.
 

A more illustrative primer of what I mean you can see on the screen captures below:

 
Running a program as different user (Administrator) from C#
(running a program as Administrator from C#)
 
Password masking in C# console application.
(password mask in C# a program)

 
Source code:

using System;
using System.Security;
using System.ComponentModel;
using System.IO;
using System.Collections.Generic;
using System.Text;
 
namespace RunAsDifferentUser
{
    class Program
    {
        static SecureString getSecureString(String pass)
        {
            SecureString password = new SecureString();
            foreach (Char c in pass)
                password.AppendChar(c);
 
            return password;
        }
 
        /* This function is to mask our 
         * password input in the console
         */
        public static string ReadPassword() {
            Stack<string> pass = new Stack<string>();
 
            for (ConsoleKeyInfo consKeyInfo = Console.ReadKey(true);
              consKeyInfo.Key != ConsoleKey.Enter; consKeyInfo = Console.ReadKey(true))
            {
                if (consKeyInfo.Key == ConsoleKey.Backspace)
                {
                    try
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        Console.Write(" ");
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        pass.Pop();
                    }
                    catch (InvalidOperationException ex)
                    {
                        /* Nothing to delete, go back to previous position */
                        Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop);
                    }
                }
                else {
                    Console.Write("*");
                    pass.Push(consKeyInfo.KeyChar.ToString());
                }
            }
            String[] password = pass.ToArray();
            Array.Reverse(password);
            return string.Join(string.Empty, password);
        }
 
 
 
        static void Main(String[] args)
        {
            String domain = null;
            String user = "Administrator";
 
            Console.Write("Enter your administrator password: ");
            SecureString password = getSecureString(ReadPassword());
 
            String filename = "regedit.exe";
 
            try
            {
                System.Diagnostics.Process.Start(filename, user, password, domain);
                Console.WriteLine("\nOur program is being succesfully run! Exiting.");
            }
            catch (Win32Exception ex)
            {
                Console.Error.WriteLine("\n{0}. Exiting.", ex.Message.ToString());
            }
        }
    }
}

 
Download this Source Code (MS Visual C# 2005 Express Edition Project)

Please note that if you want to try this example you have to know the Administrator password on your computer. If your administrator account is being renamed you’ll have to change the “user” string to the new name.

Multi-platform .INI files in C#

Posted on: January 29th, 2009.
Category: C#

Here is a new way of reading and writing .ini files in C#.
 

It’s an alternative INI file parser written by me. It uses Regex and Collections. I’m only posting a part of the source code because it is too long. But if you scroll a little bit you can download the full source with a Demo project included.
 

Please redistribute and modify under the terms of GNU LGPL v3.0.

 
Source code:

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
 
namespace MPIniReadWrite
{
    class MultiplatformIni
    {
        private String iniFilePath;
        public String IniPath
        {
            get { return iniFilePath; }
        }
        private static Char decSep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.ToCharArray()[0];
        private static Regex keyValRegex = new Regex(
          @"((\s)*(?<Key>([^\=^\n]+))[\s^\n]*\=(\s)*(?<Value>([^\n]+(\n){0,1})))",
            RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | 
            RegexOptions.CultureInvariant
        );
        private static Regex secRegex = new Regex(
          @"(\[)*(?<Section>([^\]^\n]+))(\])" ,
          RegexOptions.Compiled | RegexOptions.CultureInvariant
        );
 
        private ArrayList newValues = new ArrayList();
        struct sectKeyVal
        {
            public String section, key, value;
            public sectKeyVal(String section, String key, String value)
            {
                this.section = section;
                this.key = key;
                this.value = value;
            }
        }
 
        public MultiplatformIni(String iniFilePath)
        {
            this.iniFilePath = iniFilePath;
        }
        ~MultiplatformIni()
        {
            Flush();
        }
// Source code truncated...

 
Download the full source code and an example (Visual C# 2005 Express Project)

I’ve compiled this using .NET framework 2.0 and Mono 2.2 with no problem. Have fun! :)

INI files manipulation using C#

Posted on: January 26th, 2009.
Category: C#

This time I’m going to present you the Windows way of Reading and Writing .INI files using C#.
 

This is far from the best way of doing this, because it works only when your executable is being run on Windows (this code uses kernel32.dll functions). Here is the base INI Read/Write class code:

 
Here’s the nuberings remover source:

using System;
using System.Runtime.InteropServices;
using System.Text;
 
namespace IniReadWrite
{
    class IniFile
    {
        [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,
          string key, string value, string iniFilePath);
        [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section,
          string key, string defValue, StringBuilder retValue, int size, string iniFilePath);
 
        private const int valueLength = 255; // Maximum length of value
        private String iniPath; // The path of our .ini file
 
        public IniFile(String iniFilePath)
        {
            iniPath = iniFilePath;
        }
 
        public void WriteString(String section, String key, String value)
        {
            WritePrivateProfileString(section, key, value, iniPath);
        }
        public void WriteInt(String section, String key, int value)
        {
            WriteString(section, key, value.ToString());
        }
        public void WriteDouble(String section, String key, Double value)
        {
            WriteString(section, key, value.ToString());
        }
 
        public String ReadString(String section, String key, String defValue)
        {
            StringBuilder tmp = new StringBuilder(valueLength);
            int i = GetPrivateProfileString(section, key, defValue, tmp, valueLength, iniPath);
 
            return tmp.ToString();
        }
        public int ReadInt(String section, String key, int defValue)
        {
            return Int32.Parse(ReadString(section, key, defValue.ToString()));
        }
        public Double ReadDouble(String section, String key, Double defValue)
        {
            return Double.Parse(ReadString(section, key, defValue.ToString()));
        }
    }
}

 
Download this code and an example (Visual C# 2005 Express Edition Project)

I will soon be posting a version of this code that doesn’t need kernel32.dll and should work cross-platform even when compiled for Linux (using Mono).

Source code numbering remover

Posted on: January 20th, 2009.
Category: C#

I’ve been copying a lot of source code from different sites recently. But when I copy the source code it is being pasted with numberings in front of every line.
 

So I wrote this program to remove all the numbers before each line of source code.

 
Here’s the nuberings remover source:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace RemFirstNums
{
    class Program
    {
        static void RemStartSymbols(ref String input, bool firstSpacesRemoved)
        {
            String numbers = "0123456789";
            CharEnumerator charEnum = numbers.GetEnumerator();
            bool foundMore = false, tmp = false;
 
            if (!firstSpacesRemoved)
                while (input.StartsWith(" ") || input.StartsWith("\\s+"))
                    input = input.Substring(1, input.Length - 1);
 
            while (charEnum.MoveNext())
                while (tmp = input.StartsWith(charEnum.Current.ToString()))
                {
                    foundMore = foundMore || tmp;
                    input = input.Substring(1, input.Length - 1);
                }
            if (foundMore)
                RemStartSymbols(ref input, true);
        }
        static void Main(String[] args)
        {
            TextReader TextRead = null;
            TextWriter TextWrite = null;
 
            Console.WriteLine("NumberingRemover for C# 0.1");
            Console.WriteLine("Written by Iskren Slavov");
            Console.WriteLine("Copyright (C) 2009");
 
            Console.Write("\nThis computer software must be ");
            Console.Write("redistributed and edited under the terms of GNU GPL v2. ");
            Console.Write("For more information about licensing read LICENSE.TXT\n\n");
 
            try
            {
                if ((args[0].Trim() != null) && (args[1].Trim() != null))
                {
                    String workStr = "";
                    TextRead = new StreamReader(args[0]);
                    TextWrite = new StreamWriter(args[1]);
 
                    Console.Write("=========================\nConverting... ");
                    while ((workStr = TextRead.ReadLine()) != null)
                    {
                        RemStartSymbols(ref workStr, false);
                        TextWrite.WriteLine(workStr);
                    }
                    Console.WriteLine("All done!\n=========================");
                }
 
                TextRead.Close();
                TextWrite.Close();
            }
            catch (IOException ex)
            {
                Console.Error.WriteLine("{0}", ex.Message);
                Console.WriteLine("\nPress any key to exit . . .");
                Console.ReadKey();
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("==================");
                Console.WriteLine("Description: Removes leading numbers from source code.");
                Console.WriteLine("Usage: NumberingRemover.exe <input-file.txt> <output-file.txt>");
                Console.WriteLine("==================");
                Console.WriteLine("\nPress any key to exit . . .");
                Console.ReadKey();
            }
        }
    }
}

 
Download the source code and binaries (MS Visual C# Express edition project)

I hope this little program will be helpful for you, developers. I’m thinking of a rewrite in C++, so stay tuned…

A Simple Morse Code Converter

Posted on: January 18th, 2009.
Category: C#

Hello everybody, yesterday I wrote for you a simple Morse code to Text & Text to Morse code converter.
 

It’s 100% Morse code compliant and it supports only numbers, letters and space.
As you may already know the official Morse code specification does not provide symbols for any special characters (?.!=+- for example). But if you are interested – write me a line and I may add some of them to the next version of the example program.

 

Source code:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace MorseCodeConverter
{
    class MorseCodeCore
    {
        private Char[] Letters = new Char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g',
          'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
          'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
          '9', ' '};
        private String[] MorseCode = new String[] {".-", "-...", "-.-.",
          "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", 
          "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", 
          "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", 
          "...--", "....-", ".....", "-....", "--...", "---..", "----.", " "};
 
        public String ConvertTextToMorse(String text)
        {
            text = text.ToLower();
            String result = "";
            int index = -1;
            for (int i = 0; i <= text.Length - 1; i++)
            {
                index = Array.IndexOf(Letters, text[i]);
                if (index != -1)
                    result += MorseCode[index] + " ";
            }
 
            return result;
        }
 
        public String ConvertMorseToText(String text)
        {
            text = "@" + text.Replace(" ", "@@") + "@";
            int index = -1;
            foreach (Char c in Letters)
            {
                index = Array.IndexOf(Letters, c);
                text = text.Replace("@" + MorseCode[index] + "@", "@" + c.ToString() + "@");
            }
 
            return text.Replace("@@@@", " ").Replace("@", "");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            MorseCodeCore Morse = new MorseCodeCore();
 
            Console.WriteLine("Converting from text to morse: ");
            String str = Morse.ConvertTextToMorse("string to convert to morse code") ;
            Console.WriteLine(str);
 
            Console.WriteLine("\nConverting from morse to text: ");
            str = Morse.ConvertMorseToText("... - .-. .. -. --.   - ---   -.-." + 
              " --- -. ...- . .-. -   -... .- -.-. -.-   - ---   - . -..- -");
            Console.WriteLine(str);
 
            Console.ReadKey();
        }
    }
}

 
Download the example Source Code (MS Visual C# Express Edition Project)

This is a really simple example. If you think of a more sophisticated one, you may send it to me, and I will publish it with your name and email/website…