Wednesday, June 30, 2010

Other approaches to create single instance

http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application
http://rrelyea.spaces.live.com/blog/cns!167AD7A5AB58D5FE!1834.entry

Making your WPF application single instance

I used the ideas in this article. However, when bringing my
application to the top, I used my own methods. Below is the link to
the article, and the code that I used.
http://sanity-free.org/143/csharp_dotnet_single_instance_application.html

However, I used the following:
In my Startup.cs file I did the following:

static Mutex mutex = new Mutex(true,
"{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
[STAThread]
public static void Main()
{
try
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
MyApp app = new MyApp
app.InitializeComponent();
app.Run();
mutex.ReleaseMutex();
}
else
{
// send our Win32 message to make the currently
running instance
// jump on top of all the other windows
NativeMethods.BringTMForeGround();
}
}
catch (Exception e)
{//Catch all un-handle exception from the application

}
}

And in my NativeMethods.cs I did the following:
[DllImport("User32", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName, string
lpWindowName);

[DllImport("User32", EntryPoint = "BringWindowToTop")]
public static extern bool BringWindowToTop(IntPtr wHandle);

[DllImport("User32", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr wHandle);

[DllImport("User32", EntryPoint = "SetFocus")]
public static extern bool SetFocus(IntPtr wHandle);

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

public static void BringTMForeGround()
{
try
{
bool ret = false;
IntPtr hWnd = NativeMethods.FindWindow(null, "Title of
Application Window"); // Get Window of App2

if (hWnd == IntPtr.Zero)
{
FindWindowLike.Window[] list = FindWindowLike.Find(0, "Title
of Application Window", "");
if (list.Length >= 1)
hWnd = (IntPtr)list[0].Handle;
}
if (hWnd != IntPtr.Zero) // Check if App2 exists
{
ret = NativeMethods.SetForegroundWindow(hWnd);
ret = NativeMethods.ShowWindow(hWnd, 9);
ret = NativeMethods.BringWindowToTop(hWnd);
//ret = SetFocus(hWnd);
}
}
catch (Exception)
{
}
}


The function FindWinowLike was another class and this is whats in it:
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;

namespace MyAppNamespace
{
public class FindWindowLike
{

public class Window
{
public string Title;
public string Class;
public int Handle;
}

[DllImport("user32")]
private static extern int GetWindow(int hwnd, int wCmd);

[DllImport("user32")]
private static extern int GetDesktopWindow();

[DllImport("user32", EntryPoint = "GetWindowLongA")]
private static extern int GetWindowLong(int hwnd, int nIndex);

[DllImport("user32")]
private static extern int GetParent(int hwnd);

[DllImport("user32", EntryPoint = "GetClassNameA")]
private static extern int GetClassName(
int hWnd, [Out] StringBuilder lpClassName, int nMaxCount);

[DllImport("user32", EntryPoint = "GetWindowTextA")]
private static extern int GetWindowText(
int hWnd, [Out] StringBuilder lpString, int nMaxCount);

private const int GWL_ID = (-12);
private const int GW_HWNDNEXT = 2;
private const int GW_CHILD = 5;

public static Window[] Find(int hwndStart, string findText, string
findClassName)
{

ArrayList windows = DoSearch(hwndStart, findText, findClassName);

return (Window[])windows.ToArray(typeof(Window));

} //Find


private static ArrayList DoSearch(int hwndStart, string findText,
string findClassName)
{

ArrayList list = new ArrayList();

if (hwndStart == 0)
hwndStart = GetDesktopWindow();

int hwnd = GetWindow(hwndStart, GW_CHILD);

while (hwnd != 0)
{

// Recursively search for child windows.
list.AddRange(DoSearch(hwnd, findText, findClassName));

StringBuilder text = new StringBuilder(255);
int rtn = GetWindowText(hwnd, text, 255);
string windowText = text.ToString();
windowText = windowText.Substring(0, rtn);

StringBuilder cls = new StringBuilder(255);
rtn = GetClassName(hwnd, cls, 255);
string className = cls.ToString();
className = className.Substring(0, rtn);

if (GetParent(hwnd) != 0)
rtn = GetWindowLong(hwnd, GWL_ID);

if (windowText.Length > 0 && windowText.StartsWith(findText) &&
(className.Length == 0 || className.StartsWith(findClassName)))
{
Window currentWindow = new Window();

currentWindow.Title = windowText;
currentWindow.Class = className;
currentWindow.Handle = hwnd;

list.Add(currentWindow);
}

hwnd = GetWindow(hwnd, GW_HWNDNEXT);

}

return list;

} //DoSearch

} //Class

}

Monday, June 28, 2010

What is in the bitmap header

from - http://local.wasp.uwa.edu.au/~pbourke/dataformats/bmp/

Header

The header consists of the following fields. Note that we are assuming
short int of 2 bytes, int of 4 bytes, and long int of 8 bytes. Further
we are assuming byte ordering as for typical (Intel) machines. The
header is 14 bytes in length.

typedef struct {
unsigned short int type; /* Magic identifier */
unsigned int size; /* File size in bytes */
unsigned short int reserved1, reserved2;
unsigned int offset; /* Offset to image data, bytes */
} HEADER;

The useful fields in this structure are the type field (should be
'BM') which is a simple check that this is likely to be a legitimate
BMP file, and the offset field which gives the number of bytes before
the actual pixel data (this is relative to the start of the file).
Note that this struct is not a multiple of 4 bytes for those
machines/compilers that might assume this, these machines will
generally pad this struct by 2 bytes to 16 which will unalign the
future fread() calls - be warned.
Information

The image info data that follows is 40 bytes in length, it is
described in the struct given below. The fields of most interest below
are the image width and height, the number of bits per pixel (should
be 1, 4, 8 or 24), the number of planes (assumed to be 1 here), and
the compression type (assumed to be 0 here).

typedef struct {
unsigned int size; /* Header size in bytes */
int width,height; /* Width and height of image */
unsigned short int planes; /* Number of colour planes */
unsigned short int bits; /* Bits per pixel */
unsigned int compression; /* Compression type */
unsigned int imagesize; /* Image size in bytes */
int xresolution,yresolution; /* Pixels per meter */
unsigned int ncolours; /* Number of colours */
unsigned int importantcolours; /* Important colours */
} INFOHEADER;

The compression types supported by BMP are listed below :

* 0 - no compression
* 1 - 8 bit run length encoding
* 2 - 4 bit run length encoding
* 3 - RGB bitmap with mask

Only type 0 (no compression will be discussed here.

How to find the image format of an image in C#

from stackoverflow -
http://stackoverflow.com/questions/1397512/find-image-format-using-bitmap-object-in-c
using(Image img = Image.FromFile(@"C:\path\to\img.jpg"))
{
if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
// ...
}
}

Proper way to rethrow an exception in c#

just do "throw;" don't do "throw ex" or something like that.

Monday, June 14, 2010

How to get a specific version or get a specific label from TFS to a different location

Create a new workspace and specify that workspace to have a different location

Unhandled exception in BackgroundWorker

I was using the BackgroundWorker in WPF and had an unhandled exception
there and needed a better way to deal with this error. This is how I
did it:
I used the RunWorkerCompleted event. In this event, if the e.Error !=
null, I set a string value ErrorMessage to the message, and I call a
function ErrorOccurred which then raises an event that my calling
application caught. Below is my code:

My main Class

This code is just put together and probably won't work, but should
give you the general idea. This is my Window that calls the
background worker. I have two events, Finished and Error. If the
Error occurs, I do something, if its finishes successfully I do
something else.
public partial class MainWindow : Window
{
private DoWork Worker = new DoWork();

public MainWindow()
{
InitializeComponent();
Worker.Finished += new FinishedEventHandler(Worker_Finished);
Worker.Error += new ErrorEventHandler(Worker_Error);
}

void Worker_Finished(object sender, EventArgs e, List<Response> rList)
{
//do something when finished
}
void Worker_Error(object sender, EventArgs e, string errorMessage)
{
//do something if error
}

private void btnWork_ItemClick(object sender, ClickEventArgs e)
{
if (!Worker.IsBusy())
{
Worker.DoWork();
}
}
}

This is my Worker class

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

namespace MyNamespace
{
// A delegate type for hooking up when the backgroundworker is
finished. It returns the Response object
public delegate void FinishedEventHandler(object sender, EventArgs
e, List<Something> rList);
public delegate void ErrorEventHandler(object sender, EventArgs e,
string errorMessage);

public class DoWork
{

public BackgroundWorker worker;
List<Response> ResponseList;// = new List<Response>();
string ErrorMessage;


// An event that clients can use to be notified whenever the
// elements Backgroundworker is finished
public event FinishedEventHandler Finished;
public event ErrorEventHandler Error;

protected virtual void WorkCompleted(EventArgs e)
{
if (Finished != null)
Finished(this, e, ResponseList);
}

protected virtual void ErrorOccurred(EventArgs e)
{
if (Error != null)
Error(this, e, ErrorMessage);
}

/// <summary>
/// Main calls are
/// IsBusy, DoWork and CancelWork. It has a event called
FinishedEventHandler
/// that is raised when the work is completed
/// </summary>
public CheckResponse()
{
// Create a Background Worker
worker = new BackgroundWorker();

// Enable support for cancellation
worker.WorkerSupportsCancellation = true;
worker.DoWork +=
new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}

/// <summary>
/// when the work is completed return anobject and set r to its value
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void worker_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
ErrorMessage = "An error occurred. " + e.Error.Message;
ErrorOccurred(EventArgs.Empty);
}
else
{
ResponseList = (List<Response>)e.Result;
WorkCompleted(EventArgs.Empty);
}
}
/// <summary>
/// </summary>
/// <param name="sender"><param>
/// <param name="e"></param>
private void worker_DoWork(
object sender, DoWorkEventArgs e)
{
try
{
e.Result = Some call that returns a List
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

/// <summary>
/// Returns the status of the Backgroundworker. if its busy or not
/// </summary>
/// <returns></returns>
public bool IsBusy()
{
return worker.IsBusy;
}
/// <summary>
/// Can be called to cancel a backgroundworker
/// </summary>
public void CancelWork()
{
worker.CancelAsync();
}
/// <summary>
/// If the backgroundworker is not busy it starts the worker.
/// </summary>
public void DoWork()
{
if (!worker.IsBusy)
{
worker.RunWorkerAsync();
}
}
}
}