Update programmatically image after Event with KNX.Net - c#

I'm creating a webapp to control some lights in my house. I can't understand why after firing the Event void, the image is not updating; while if i fire it from a button it is actually changing.
I have tried this so far, using KNX.Net libraries
...
public void Event(string address, string state)
{
if (address.Equals(CH03LightOnOffAddressStatus) || address.Equals(CH04LightOnOffAddressStatus))
{
System.Diagnostics.Debug.WriteLine("New Event: device " + address + " has status (" + state + ") --> " + _connection.FromDataPoint("9.001", state));
}
else if (
address.Equals(CH01LightOnOffAddressStatus) ||
address.Equals(CH02LightOnOffAddressStatus)
)
{
var data = string.Empty;
if (state.Length == 1)
{
data = ((byte)state[0]).ToString();
}
else
{
var bytes = new byte[state.Length];
for (var i = 0; i < state.Length; i++)
{
bytes[i] = Convert.ToByte(state[i]);
}
data = state.Aggregate(data, (current, t) => current + t.ToString());
}
System.Diagnostics.Debug.WriteLine("New Event: device " + address + " has status --> " + data);
condition = data;
nowAddress = address;
}
if (condition == "1")
{
Image1.ImageUrl = #"\Res\Call.png";
}
else
{
Image1.ImageUrl = #"\Res\Bomb.png";
}
}
...
While if i fire it like this, the image is changing indeed
...
private void CH01LightOn()
{
_connection.Action(CH01LightOnOffAddress, true);
Thread.Sleep(500);
if (condition == "1")
{
Image1.ImageUrl = #"\Res\Call.png";
}
else
{
Image1.ImageUrl = #"\Res\Bomb.png";
}
}
...
I just need the images to be changing after the event is fired.
Thank you in advance.

This is probably a threading issue. If the Event method is not called on the UI thread, you cannot access your WinForms controls directly, but have to use Control.Invoke.
To try this, replace Image1.ImageUrl = #"\Res\Call.png" by:
if (Image1.InvokeRequired)
{
Image1.Invoke((Action)(() => Image1.ImageUrl = #"\Res\Call.png"));
}
else
{
Image1.ImageUrl = #"\Res\Call.png"
}

Related

C#: Add a new check without affecting existing checks

I hope I can explain my scenario the best I can.
I have code that when the "Load" button is clicked, all file names (if any) located in a predefined network directory path, are loaded to a text-area.
Currently there can be .txt, .xml files.
Contents could look like:
first_file_found.xml
second_file_found.xml
third_file_found.txt
Also, in the code there is another function "isCoValid" that performs an additional validation of the contents of these files, based on return value (true/false) of this function, the "Process" button is enabled:
if (IsFlatFile(fileName) || IsXMLFile(fileName))
{
if (isCoValid(fileName))
{
btnProcess.Enabled = true;
}
else
{
btnProcess.Enabled = false;
break;
}
}
Now I have to add a .csv file type, but this file does not required to perform the isCoValid function.
The text-area contents now look like:
first_file_found.xml
second_file_found.xml
third_file_found.txt
fourht_file_found.csv
My request for help is to ask how can the check to find out if there is a CSV file can be done, and also controlling the enabling of the "Process" button, but still respect the existing check for .txt, and .xml and the validation of contents?
I might have xml and text files, that aren't valid, but I still need to be able to process the .csv. file.
I did change it like this:
if (IsFlatFile(fileName) || IsXMLFile(fileName))
{
if (isCoValid(fileName))
{
btnProcess.Enabled = true;
}
else
{
btnProcess.Enabled = false;
break;
}
}
if (IsCSVFile(fileName))
{
btnProcess.Enabled = true;
}
But I am sure this is not correct and I would like to ask for some help if possible.
I hope I explained my problem with some clarity and straightforwardness, if not, please let me know and I can try to provide more information.
Thank you,
Erasmo
Additional Code Requested
public bool IsFlatFile(string FileName)
bool ReturnValue = false;
if (FileName.ToUpper().Right(4) == ".TXT")
{
if ((FileName.Substring(0, 2).ToUpper() == "MN") ||
(FileName.Substring(0, 2).ToUpper() == "CH"))
{
ReturnValue = true;
}
}
return ReturnValue;
}
public bool IsXMLFile(string FileName)
bool ReturnValue = false;
if (FileName.ToUpper().Right(4) == ".XML")
{
if ((FileName.Substring(0, 2).ToUpper() == "TR") ||
(FileName.Substring(0, 2).ToUpper() == "SK"))
{
ReturnValue = true;
}
}
return ReturnValue;
}
protected bool isCoValid(string fName)
{
bool retCode = false;
Parameters parms;
var reader = new AppSettingsReader();
Application app = new Application();
Package package = null;
try
{
package = app.LoadPackage(packagePath + "ValidateContents.dtsx", null);
parms = package.Parameters;
parms["ID"].Value = "";
parms["ImportFileName"].Value = fName;
parms["UserID"].Value = userName;
DTSExecResult results = package.Execute();
if (results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in package.Errors)
{
retCode = false;
resultText = resultText + "DTSX Package Execution results: " + local_DtsError.Description.ToString() + Environment.NewLine;
}
}
else
{
resultText = resultText + "Successful Process Completion." + Environment.NewLine + Environment.NewLine;
string sqlStr = "SELECT TOP 1 * FROM Validation WHERE Type = 'VALCO' AND CAST(CreatedDate AS DATE) = CAST(GETDATE() AS DATE)";
DataTable dt = new DataTable();
dt = GetDataSet(sqlStr);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
if (row["Status"].ToString() == "Valid")
{
retCode = true;
resultText = "Output: Valid" + Environment.NewLine + "Press the 'Process' button to proceed.";
}
else
{
retCode = false;
resultText = "Output: " + row["Status"].ToString() + Environment.NewLine + "Validation Fail: " + row["Error"].ToString();
}
}
}
else
{
resultText = "Unable to read Validation Table for this file.";
retCode = false;
}
}
}
catch (Exception)
{
throw;
}
return retCode;
}
Your code will look like so:
if (IsFlatFile(fileName) || IsXMLFile(fileName) || IsCSVFile(fileName))
{
btnProcess.Enabled = isCoValid(fileName);
if (!btnProcess.Enabled) break;
}
public static bool IsCSVFile(string FileName) =>
Path.GetExtension(FileName).Equals(".csv", StringComparison.OrdinalIgnoreCase);
when you write your own IsCSVFile() method and update isCoValid() method to fit your needs.
Sorry, but I can't guess what happens inside classes that are used in isCoValid() method.

Looping and appending text to StringBuilder issue

I have a small issue when trying to append text from a loop into a stringbuilder, after trying a few things out, i think i'm on the right track with this.
Code:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
// STRING VALUE IT SO WE CAN REUSE //
string action = e.Argument as string;
// CONNECTION //
if (action == "wraith_create_project")
{
// STRING BUILDER //
StringBuilder sb = new StringBuilder();
// VARS //
var articleSource = "";
// INVOKE - AVOID CROSS THREAD ERRORS //
Invoke(new MethodInvoker(() => { articleSource = comboBoxArticleSources.Text; }));
// TRY/CATCH //
try
{
// INVOKE - AVOID CROSS THREAD ERRORS //
Invoke(new MethodInvoker(() => { listBoxMain.Items.Add("[" + DateTime.Now + "] Creating project ... " + txtBoxProjectName.Text); }));
// ARTICLE SOURCE //
if (articleSource == "Internal Article Builder")
{
// VARS/CONSTANTS //
var separator = Environment.NewLine;
const string gsaSeparator = "\x01";
// WHICH SPINNER TO USE //
if (chkBoxInternalSpinner.Checked) {
// LOOP //
var title = "";
var body = "";
var hash = "";
//var gsaArticleInfo = "";
for (int x = 0; x <= 5; x++ ) {
// EVERY LOOP REQUESTS AN ARTICLE //
var requestArticles = Helpers.getArticleTitleAndBodyInternalSpinner("https://www.wraithseo.com/api.php?articleBuilder=1&q=" + txtBoxScrapeKeyword.Text.Replace(" ", "_"));
title = Helpers.internalSpinner(requestArticles.Item1); // SEND TO INTERNAL SPINNER FOR SPINNING ...
body = Helpers.internalSpinner(requestArticles.Item2); // SEND TO INTERNAL SPINNER FOR SPINNING ...
hash = To32BitFnv1aHash(body).ToString("X8");
Invoke(new MethodInvoker(() =>
{
listBoxMain.Items.Add("[" + DateTime.Now + "] Returned article ... " + requestArticles.Item1);
listBoxMain.Items.Add("[" + DateTime.Now + "] Spun the article ... " + title);
}));
// ENCODE WITH THE GSA SEPERATOR BETWEEN EACH FIELD //
var gsaArticleInfo = title + gsaSeparator + "%first_paragraph-article%" + gsaSeparator + body + gsaSeparator + hash;
// ADD TO THE RICHTEXTBOX ALL FIELDS FROM ABOVE //
var richTextBoxText = string.Join(separator, gsaArticleInfo);
// APPEND FIELDS TO THE STRINGBUILDER //
sb.Append(richTextBoxText);
}
// INVOKE - AVOID CROSS THREAD ERRORS //
Invoke(new MethodInvoker(() => { richTxtBoxArticle.Text = sb.ToString(); }));
}
} else if (articleSource == "") {
// RESERVED FOR ADDITIONAL SOURCES //
}
} catch (Exception ex) {
Helpers.returnMessage(ex.ToString());
}
}
}
What i'm doing here is sending a request to my server which is returning an article sized bunch of text, i'm then spinning that text and trying to display it in a richTextBox, i noticed that instead of adding each article to the richTextBox it was being overwritten by the same article, i thought by using the stringbuilder to append the article to it on each loop i could then display it outside the loop but it always seems to overwrite, instead of adding 5 articles (which is the max i have set for tetsing)
Any help would be appreciated.
Updated Code:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string action = e.Argument as string;
if (action == "wraith_create_project")
{
StringBuilder sb = new StringBuilder();
var separator = Environment.NewLine;
const string gsaSeparator = "\x01";
var articleSource = "";
var title = "";
var body = "";
var hash = "";
var gsaArticleInfo = "";
var richTextBoxText = "";
// TEST //
List<string> gsaStuff = new List<string>();
// TEST //
Invoke(new MethodInvoker(() => { articleSource = comboBoxArticleSources.Text; }));
try
{
Invoke(new MethodInvoker(() => { listBoxMain.Items.Add("[" + DateTime.Now + "] Creating project ... " + txtBoxProjectName.Text); }));
if (articleSource == "Internal Article Builder")
{
if (chkBoxInternalSpinner.Checked) {
for (int x = 0; x <= 5; x++ ) {
// EVERY LOOP REQUESTS AN ARTICLE WHICH IS RETURNED AT RAND() //
var requestArticles = Helpers.getArticleTitleAndBodyInternalSpinner("https://www.wraithseo.com/api.php?articleBuilder=1&q=" + txtBoxScrapeKeyword.Text.Replace(" ", "_"));
title = Helpers.internalSpinner(requestArticles.Item1); // SEND TO INTERNAL SPINNER FOR SPINNING ...
body = Helpers.internalSpinner(requestArticles.Item2); // SEND TO INTERNAL SPINNER FOR SPINNING ...
hash = To32BitFnv1aHash(body).ToString("X8");
Invoke(new MethodInvoker(() =>
{
listBoxMain.Items.Add("[" + DateTime.Now + "] Returned article ... " + requestArticles.Item1);
listBoxMain.Items.Add("[" + DateTime.Now + "] Spun the article ... " + title);
}));
// ENCODE WITH THE GSA SEPERATOR BETWEEN EACH FIELD //
gsaArticleInfo = title + gsaSeparator + "%first_paragraph-article%" + gsaSeparator + body + gsaSeparator + hash;
// ADD TO THE RICHTEXTBOX ALL FIELDS FROM ABOVE //
richTextBoxText = string.Join(separator, gsaArticleInfo);
// APPEND FIELDS TO THE STRINGBUILDER //
sb.Append(string.Join(separator, gsaArticleInfo));
gsaStuff.Add(richTextBoxText);
// INVOKE - AVOID CROSS THREAD ERRORS //
Invoke(new MethodInvoker(() => { richTxtBoxArticle.AppendText(richTextBoxText); }));
Invoke(new MethodInvoker(() => { richTxtBoxArticle.Lines = gsaStuff.ToArray(); }));
} // End for loop.
Invoke(new MethodInvoker(() => { richTxtBoxArticle.Lines = gsaStuff.ToArray(); }));
//Helpers.returnMessage("SB Contents: > " + sb.ToString());
} // End checkbox.
} else if (articleSource == "") {
// RESERVED FOR ADDITIONAL SOURCES //
}
} catch (Exception ex) {
Helpers.returnMessage(ex.ToString());
}
}
}
This is happening because you're calling onto the UI thread from another thread REALLY QUICKLY. The textbox simply can't keep up.
The solution here is to use the BackgroundWorker.ReportProgress method, and pass the strings back out of your worker to your UI thread. You'd handle the ProgressChanged event of the worker from your Form, and update your controls within there instead.
Hope that helps you out.

C# How to rename a file without using File.Move

I have a c# application that connects to a server, gets the datagrid, manipulates each row and then according to each updated row the new row gets uploaded to the server and one file per row gets renamed on the hdd.
The application works totally fine but i analyzed it with the profiler and realised that this line of code:
File.Move(symbolsOldPath, symbolsPath);
takes 80% of the time my application needs to complete its task.
I went through all the questions on StackOverflow and other questions out there if there is a different way for a better performance but i wasnt succesful. The only other way i found was implementing VB to use the Rename method, but as it calls the File.Move method it is no improvement. Do you guys know an alternative way with better performance?
Here is my code of the class that changes the data.
public DataTable ChangeData(DataTable unchangedData, string searchPathSymbols, string searchPathImages, ProgressBar pbForm)
{
pbtemp = pbForm;
int rowCount = unchangedData.Rows.Count;
foreach (DataRow row in unchangedData.Rows)
{
counter++;
if (counter == 10)
{
pbtemp.Value += counter;
counter = 0;
Application.DoEvents();
}
number = row[1].ToString();
symbolsPath = row[2].ToString();
symbolsPathCopy = symbolsPath;
imagesPath = row[3].ToString();
imagesPathCopy = imagesPath;
aliasSymbols = symbolsPath.Substring(0, symbolsPath.IndexOf('>') + 1);
if (symbolsPath == imagesPath)
{
if (aliasSymbols.Contains("Symbole"))
{
if (!string.IsNullOrEmpty(symbolsPath))
{
SymbolsChanger(searchPathSymbols, row);
row[3] = row[2];
}
}
else
{
if (!string.IsNullOrEmpty(imagesPath))
{
ImagesChanger(searchPathImages, row);
row[2] = row[3];
}
}
}
else
{
if (!string.IsNullOrEmpty(symbolsPath))
{
SymbolsChanger(searchPathSymbols, row);
}
if (!string.IsNullOrEmpty(imagesPath))
{
ImagesChanger(searchPathImages, row);
}
}
}
pbtemp.Value += (rowCount - pbtemp.Value);
return unchangedData;
}
private void SymbolsChanger(string searchPathSymbols, DataRow row)
{
string symbolsOldPath;
//Symbols
//Get and delete Alias and get filepath
int countAliasSymbolsIndex = symbolsPath.LastIndexOf('>') + 1;
symbolsPath = symbolsPath.Remove(0, countAliasSymbolsIndex);
symbolsOldPath = searchPathSymbols + "\\" + symbolsPath;
//Remove and replace numbers
int startSymbolsIndex = 0;
int endSymbolsIndex = symbolsPath.IndexOf('_') == -1 ? symbolsPath.LastIndexOf('.') : symbolsPath.IndexOf('_');
int countSymbolsIndex = endSymbolsIndex - startSymbolsIndex;
symbolsPath = symbolsPath.Remove(startSymbolsIndex, countSymbolsIndex);
string nameSymbols = number + symbolsPath;
symbolsPath = searchPathSymbols + "\\" + nameSymbols;
try
{
//Rename file
File.Move(symbolsOldPath, symbolsPath);
}
catch(FileNotFoundException)
{
try
{
File.Move(symbolsPath, symbolsPath);
}
catch (FileNotFoundException)
{
logArrayDataChange.Add(symbolsPathCopy);
}
}
row[2] = aliasSymbols + nameSymbols;
}
private void ImagesChanger(string searchPathImages, DataRow row)
{
string imagesOldPath;
//Images
//Get and delete Alias and get filepath
string aliasImage = imagesPath.Substring(0, imagesPath.IndexOf('>') + 1);
int countAliasImagesIndex = imagesPath.LastIndexOf('>') + 1;
imagesPath = imagesPath.Remove(0, countAliasImagesIndex);
imagesOldPath = imagesPath.StartsWith("\\") == true ? searchPathImages + imagesPath : searchPathImages + "\\" + imagesPath;
//Remove and replace numbers
int startImagesIndex = imagesPath.LastIndexOf("\\") == -1 ? 0 : imagesPath.LastIndexOf("\\");
int endImagesIndex = imagesPath.IndexOf('_') == -1 ? imagesPath.LastIndexOf('.') : imagesPath.IndexOf('_');
int countImagesIndex = endImagesIndex - startImagesIndex;
imagesPath = imagesPath.Remove(startImagesIndex + 1, countImagesIndex - 1);
int insertIndex = imagesPath.LastIndexOf("\\") == -1 ? 0 : imagesPath.LastIndexOf("\\");
string nameImages = imagesPath.Insert(insertIndex + 1, number);
imagesPath = searchPathImages + "\\" + nameImages;
try
{
//Rename file
File.Move(imagesOldPath, imagesPath);
}
catch (FileNotFoundException)
{
try
{
File.Move(imagesPath, imagesPath);
}
catch (FileNotFoundException)
{
logArrayDataChange.Add(imagesPathCopy);
}
}
row[3] = aliasImage + nameImages;
}
}
}
I would keep File.Move to do the job. Besides a little overhead (checks), File.Move uses only the native MoveFile Windows call to move the file:
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
[ResourceExposure(ResourceScope.Machine)]
internal static extern bool MoveFile(String src, String dst);
You can call that method yourself, but I doubt it will get any faster than that.
From the documentation it seems that move is already built to rename efficiently:
The MoveFile function will move (rename) either a file or a directory ...

c# application becomes unresponsive when loading an image

I'm creating a tool that reads information from a file and also displays an image extracted from said file as well. it reads the info just fine and everything but when it comes to displaying the image it freezes the program without an error. the program just becomes unresponsive. the debugger doesn't say anything either except after some time it will say the thread has exited with still no response from the program.
i need to rename some stuff as i don't want to get in trouble
Here's the code I'm using to extract and display the image:
try
{
global.meta.filetype = STFSRead.readString_C(0, 4);
textBox2.Text = global.meta.filetype;
textBox3.Text = STFSRead.detectType(global.meta.contype.ToString("X4"));
textBox4.Text = global.meta.metaversion.ToString();
textBox5.Text = global.meta.id1;
textBox6.Text = global.meta.version.ToString("X");
textBox7.Text = global.meta.version2.ToString("X");
textBox8.Text = global.meta.id2;
textBox9.Text = global.meta.id3;
textBox10.Text = global.meta.id4;
textBox11.Text = global.meta.id5;
textBox12.Text = global.meta.displayname;
textBox13.Text = global.meta.titlename;
textBox14.Text = STFSRead.detectSomeInfo(global.meta.aflag.ToString("X2"));
pictureBox1.Image = STFSRead.loadImage();
}
catch
{
throw new Exception("What did you do?\n All this is suppose to do is read a file, how did you screw that up?");
}
public static Image loadImage()
{
Exception failed = new Exception("LoadImage failed. Contact a developer");
string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/appname/cache/";
string imgname = global.meta.id.Replace(" ", "") + ".png";
if (Directory.Exists(#path))
{
if (File.Exists(#path + imgname))
{
using (Image img = Image.FromFile(#path + imgname))
{
return img;
}
throw failed;
}
else if (!File.Exists(#path + imgname))
{
if (extractData(imgname, 0x171A, 0x4000))
{
using (Image img = Image.FromFile(#path + imgname))
{
return img;
}
throw failed;
}
else
throw failed;
}
else
throw failed;
}
else if(!Directory.Exists(#path)){
Directory.CreateDirectory(#path);
if (File.Exists(#path + imgname))
{
using (Image img = Image.FromFile(#path + imgname))
{
return img;
}
throw failed;
}
else if (!File.Exists(#path+imgname))
{
if (extractData(imgname, 0x171A, 0x4000))
{
using (Image img = Image.FromFile(#path + imgname))
{
return img;
}
throw failed;
}
else
throw failed;
}
else
throw failed;
}
else
throw failed;
}
public static bool extractData(string filename, long startpos, long length)
{
string data = STFSRead.readString_A(startpos, length);
string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)+"/appname/cache/";
if (Directory.Exists(#path))
{
using (StreamWriter file = new StreamWriter(#path + filename))
{
file.Write(data);
file.Close();
}
}
else if (!Directory.Exists(#path))
{
Directory.CreateDirectory(#path);
using (StreamWriter file = new StreamWriter(#path + filename))
{
file.Write(data);
file.Close();
}
}
if (File.Exists(#path + filename))
return true;
else
throw new Exception("Couldn't extract file "+filename+" at location "+startpos+" with a length of "+length);
}
public static string readString_A(long startpos, long length)
{
string s = "";
for (long i = startpos; i < startpos + length; i = i++)
{
global.fs.Position = i;
byte[] buf = new byte[1];
global.fs.Read(buf, 0, 1);
if (buf[0] == 0x00) // Null symbol
{
}
else
{
char c = Convert.ToChar(buf[0]);
s += c;
}
}
if (s == "" || s == " ")
{
s = "";
}
return s;
}
I have checked my appdata folder and while the directory gets created, the image does not get created so i'm thinking its failing during extraction. and none of my exceptions get triggered either
Edit: about the exceptions.... i added all of them when the program started screwing up to see if it will trigger them and narrow down where the error might be. i don't want it to handle those exceptions. might not be the best way to do that but i am still learning c# so i don't expect it to be the best way. if there is a better way to do this then let me know.
I think your problem is here:
for (long i = startpos; i < startpos + length; i = i++)
It should be:
for (long i = startpos; i < startpos + length; i++)
i=i++ is not actually incremeting the variable
You can find why here: i = i++ doesn't increment i. Why?. Thanks to #RenniePet for the link.

Start Application only once (Mono)

I'm currently developing an mono application in c#, which I would like to start only once. I know, this can be achieved with mutex. But how can I bring the application to front using mono?
I tried getting the Process via
Process.GetProcessByName("AudioCuesheetEditor")
but couldn't access the MainWindowHandle.
How can I bring the running application to front?
Thanks for you answers.
EDIT:
Now I have been able to get the MainWindowHandle, but it's a IntPtr. How do I bring this handle to front? I tried
Window wRunning = new Window(handle);
wRunning.Present();
but that gave me an exception :(.
I have been able to fix it with a file system watcher:
FileSystemWatcher fswRunning = new FileSystemWatcher(Path.GetTempPath() + "AudioCuesheetEditor");
fswRunning.Filter = "*.txt";
fswRunning.Changed += delegate(object sender, FileSystemEventArgs e) {
log.debug("FileSystemWatcher called Changed");
if (pAudioCuesheetEditor != null)
{
log.debug("pAudioCuesheetEditor != null");
pAudioCuesheetEditor.getObjMainWindow().Present();
}
};
fswRunning.EnableRaisingEvents = true;
Boolean bAlreadyRunning = false;
Process[] arrPRunning = Process.GetProcesses();
foreach (Process pRunning in arrPRunning)
{
Boolean bCheckProcessMatch = false;
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
if (pRunning.HasExited == false)
{
log.debug("pRunning.ProcessName = " + pRunning.ProcessName + " pRunning.MainWindowTitle = " + pRunning.MainWindowTitle);
if (pRunning.ProcessName.ToLower().Contains("mono"))
{
for (int i = 0; i < pRunning.Modules.Count;i++)
{
if (pRunning.Modules[i].ModuleName.Contains("AudioCuesheetEditor"))
{
bCheckProcessMatch = true;
i = pRunning.Modules.Count;
}
}
}
}
}
else
{
log.debug("pRunning.ProcessName = " + pRunning.ProcessName);
if (pRunning.ProcessName == Process.GetCurrentProcess().ProcessName)
{
bCheckProcessMatch = true;
}
}
log.debug("bCheckProcessMatch == " + bCheckProcessMatch);
if ((pRunning.Id != Process.GetCurrentProcess().Id) && (bCheckProcessMatch == true))
{
log.info("Writing to file " + Path.GetTempPath() + "AudioCuesheetEditor" + Path.DirectorySeparatorChar + "message.txt");
File.WriteAllText(Path.GetTempPath() + "AudioCuesheetEditor" + Path.DirectorySeparatorChar + "message.txt","Present");
bAlreadyRunning = true;
}
}
log.debug("bAlreadyRunning = " + bAlreadyRunning);
if (bAlreadyRunning == false)
{
//Start Application
}
Using a FSW for this seems like very hacky.
I think the most elegant solution is using IPC.
In particular, I would use DBus. In fact, it's what Banshee uses to avoid multiple instances of it being created. So go ahead and check out our source code if you're interested.

Categories

Resources