Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, November 4, 2008

Checking for Multiple Instances of a Windows Forms or Console Application

When running a windows application or console/batch application you may run into issues if you have multiple instances running on the same machine. The applications may cause contention when reading and writing to a file system or database. Depending on how you design your application, it may cause data loss.

To handle this, you can use the System.Diagnostics namespace to check for existing instances of the application. If an instance exists with a different process ID, kill the existing process.

Note: You can kill the existing instance instead using process.Kill();

// Grab the current process so you can pull it's name
Process currentProcess = Process.GetCurrentProcess();
// Get existing processes on the current machine with the same name
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process process in processes)
{
// Loop through and check for any instance with the same name
if (process.Id != currentProcess.Id)
{
MessageBox.Show("Application is already running");
Application.Exit();
return;
}
}

// This piece of code isn't necessarily required. When using Visual Studio, your windows
// app runs under [ApplicationNam].vshost. This checks for these processes as well.
processes = Process.GetProcessesByName(currentProcess.ProcessName.Replace(".vshost", ""));
foreach (Process process in processes)
{
if (process.Id != currentProcess.Id)
{
MessageBox.Show("Application is already running");
Application.Exit();
return;
}
}

Wednesday, October 15, 2008

Page does not contain a definition for 'Context'

I inherited a website this week and it wouln't build. In the past the website was built in debug mode and the files were moved out manually. It wouldn't built in release mode and it wouldn't allow for me to do a publish website. It received the error ... "does not contain a definition for context."

The web page had the following page definition:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage1.aspx.cs" Inherits="MyPage1" %>

Whereas, the codebehind for MyPage1 (MyPage1.aspx.cs) included the wrong class name. I updated the class name to correspond to the class name mentioned in the web page and it will now build in release mode.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MyPage2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
}