Monday, November 28, 2011

Myth Self Note 10: C# WPF - Update UI in other Thread


Problem:
1 - Error Message: "The calling thread cannot access this object because a different thread owns it"
2 - Can't add value or edit listbox while using thread

Search Key:
1 - listbox c# thread used cannot access

Solution:
Use "Dispatcher.Invoke"

'Myth' Example:
1- this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
//do something here
}));

Screenshot Example:
2 - call the function from the running thread
"Thread t = new Thread(startScan);
t.Start();"

private void startScan()
{
bla bla bla
ProgressChanged(filesPath);
bla bla bla
}

Help Link:

Thursday, November 10, 2011

Myth Self Note 9: C# WPF - Recursive Loop

Notes:
using recursive loop..

the different is, using
DirectoryInfo.GetFiles()
method, it will search all files in the particular directory then store in an array..then we will loop the array and scan/do function on each item in the array...

the purpose i'm doing the coding manually (recursive loop) is because everytime i encounter a file, i will scan/do some function on it...then store it in the array...(different from GetFiles)

here's my coding..

declare array mypath to store choosen path to be scan for files
private string[] mypath;

store all choosen path in the array
mypath = File.ReadAllLines("scanpath.scn");

this will call the function to search all files in the directory and subdirectory
searchFile();

the function searchFile, loop root directory that i choose in scanpath file just now.
private void searchFile()
{
for (int i = 0; i < mypath.Length ; i++)
{
DirectoryInfo myRoot = new DirectoryInfo(mypath[i]);
string[] myDir = Directory.GetDirectories(mypath[i]);

showFile(myRoot);
recursiveLoop(myDir);

}
}


the function showFile, show/add the list of files in the directory into a listview
private void showFile(DirectoryInfo myDir)
{
string myPath = "";
string myPath2 = "";

foreach (FileInfo file in myDir.GetFiles())
{
myPath = file.ToString();
myPath2 = myDir + "\\" + myPath;

lstScan.Items.Add(myPath2);
string result = doFunction(myPath2);
if (!result.Equals(string.Empty))
{
addIntoListView(myPath, result);
}
}
}

the function recursiveLoop, which will loop and search files in each subdirectory in the directory..and also subdirectory in the subdirectory..untill all files in the root directory and all its subdirectory'subdirectory and so on..
private void recursiveLoop(string[] subdir)
{
foreach (string s in subdir)
{
try
{

DirectoryInfo mySub = new DirectoryInfo(s);
string myPath = "";
string myPath2 = "";

foreach (FileInfo file in mySub.GetFiles())
{
myPath = file.ToString();
myPath2 = mySub + "\\" + myPath;

lstScan.Items.Add(myPath2);
string result = doFunction(myPath2);
if (!result.Equals(string.Empty))
{
addIntoListView(myPath, result);
}
}

string[] myDir = Directory.GetDirectories(s);
recursiveLoop(myDir);
}
catch (Exception c)
{
// Console.WriteLine("Error: " + c.Message);
}
}
}