Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Miroslav Stampar http://mstampar.awardspace.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 53 total  RSS 

Compress/decompress byte array

 using System;
 using System.Collections.Generic;
 using System.IO.Compression;
 using System.IO;
 using System.Collections;

namespace Utilities
{
 class Compression
 {
        public static byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
            ds.Write(data, 0, data.Length);
            ds.Flush();
            ds.Close();
            return ms.ToArray();
        }
        public static byte[] Decompress(byte[] data)
        {
            const int BUFFER_SIZE = 256;
            byte[] tempArray = new byte[BUFFER_SIZE];
            List<byte[]> tempList = new List<byte[]>();
            int count = 0, length = 0;

            MemoryStream ms = new MemoryStream(data);
            DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress);

            while ((count = ds.Read(tempArray, 0, BUFFER_SIZE)) > 0)
            {
                if (count == BUFFER_SIZE)
                {
                    tempList.Add(tempArray);
                    tempArray = new byte[BUFFER_SIZE];
                }
                else
                {
                    byte[] temp = new byte[count];
                    Array.Copy(tempArray, 0, temp, 0, count);
                    tempList.Add(temp);
                }
                length += count;
            }

            byte[] retVal = new byte[length];

            count = 0;
            foreach (byte[] temp in tempList)
            {
                Array.Copy(temp, 0, retVal, count, temp.Length);
                count += temp.Length;
            }

            return retVal;
        }
 }
}

Sort generic list

public class Item
{
 public Item(string term, int freq)
 {
  _term = term;
  _freq = freq;
 }

 private string _term;
 public string Term
 {
  get { return _term; }
  set { _term = value; }
 }

  private int _freq;
  public int Freq
  {
   get { return _freq; }
   set { _freq = value; }
  }
 }

 public class ItemComparer:IComparer<Item>
 {
  #region IComparer<Item> Members

  public int Compare(Item x, Item y)
  {
   return y.Freq - x.Freq; //descending sort
   //return x.Freq - y.Freq; //ascending sort
  }

  #endregion
 }

static void Main()
{
 List<Item> items = new List<Item>();
 ....
 items.Sort(new ItemComparer());
}

OnApplicationIdle event

using System;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
   

public class HelloWorldForm : Form
{
    public HelloWorldForm()
    {
        Text = "Hello, WindowsForms!";
    }
}
   
public class ApplicationEventHandlerClass
{
    public void OnIdle(object sender, EventArgs e)
    {
        Console.WriteLine("The application is idle.");
    }
}
   
public class MainClass
{
    public static void Main()
    {
        HelloWorldForm FormObject = new HelloWorldForm();
        ApplicationEventHandlerClass AppEvents = new ApplicationEventHandlerClass();
   
        Application.Idle += new EventHandler(AppEvents.OnIdle);
        Application.Run(FormObject);
    }
}

OnApplicationExit event

using System;
using System.Threading;
using System.Reflection;
using System.Windows.Forms;
   

public class HelloWorldForm : Form
{
    public HelloWorldForm()
    {
        Text = "Hello, WindowsForms!";
    }
}
   
public class ApplicationEventHandlerClass
{
    public void OnApplicationExit(object sender, EventArgs e)
    {
        try
        {
            Console.WriteLine("The application is shutting down.");
        }
        catch(NotSupportedException)
        {
        }
    }
}
   
public class MainClass
{
    public static void Main()
    {
        HelloWorldForm FormObject = new HelloWorldForm();
        ApplicationEventHandlerClass AppEvents = new ApplicationEventHandlerClass();
   
        Application.ApplicationExit += new EventHandler(AppEvents.OnApplicationExit);
        Application.Run(FormObject);
    }
}

Reduce memory footprint of a .NET application

Don’t ask me anything. It just works :)

 try
{
Process process = Process.GetCurrentProcess();
process.MaxWorkingSet = loProcess.MaxWorkingSet;
process.Dispose();
}
catch { }


p.s. you can even make a timer that could run this piece of code periodically.

Get list of running processes

 Console.WriteLine("ID:\tProcess name:");
 Console.WriteLine("--\t------------");
 foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses())
  Console.WriteLine("{0}\t{1}", process.Id, process.ProcessName); 

Automatically send keys to other application

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace ConsoleApplicationTest
{
    class Program
    {
        [System.Runtime.InteropServices.DllImport("USER32.DLL", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [System.Runtime.InteropServices.DllImport("USER32.DLL", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        static void Main(string[] args)
        {
            Process calc = Process.Start("calc.exe");
            calc.WaitForInputIdle();

            IntPtr calculatorHandle = FindWindow(null, "Calculator");
            if (calculatorHandle == IntPtr.Zero)
            {
                Console.WriteLine("Calculator is not running.");
            }
            else
            {
                SetForegroundWindow(calculatorHandle);
                SendKeys.SendWait("13");
                SendKeys.SendWait("*");
                SendKeys.SendWait("13");
                SendKeys.SendWait("=");
            }
        }
    }
}

HTML Encoding/Decoding

 string temp = System.Web.HttpUtility.HtmlEncode("this is a test");
 temp2 = System.Web.HttpUtility.HtmlDecode(temp2);


p.s. first add reference to "System.Web"

DateTime to double and vice versa

 public static double ToDouble(DateTime what)
 {
  return BitConverter.ToDouble(BitConverter.GetBytes(what.Ticks), 0);
 }

 public static DateTime ToDateTime(double what)
 {
  return new DateTime(BitConverter.ToInt64(BitConverter.GetBytes(what), 0));
 }

Beep

        [DllImport("kernel32.dll")]
        public static extern bool Beep(int freq, int duration);

        static void Main(string[] args)
        {
            Beep(1000, 50);
        }
« Newer Snippets
Older Snippets »
Showing 1-10 of 53 total  RSS