How to use for loop instead of foreach loop in traversing GetProcessByName - c++-cli

I had been searching through the internet for getting all the processes of an application. And so far all the implementation of traversing it is by using foreach loop which I'm not familiar with. It works but I just can't rest easy for it working without me getting to understand it. So I'd like to ask if someone can show me how to implement such code using for loop.
System::Diagnostics::Process^ current = System::Diagnostics::Process::GetCurrentProcess();
for each (System::Diagnostics::Process^ process in System::Diagnostics::Process::GetProcessesByName(current->ProcessName))
if (process->Id != current->Id)
{
// process already exist
}
I'm using visual studio c++/clr btw, hence :: since it's not in c#.

GetProcessesByName returns a cli::array, so iterate using that and its length property.
cli::array<Process^>^ processes = Process::GetProcessesByName(current->ProcessName);
for (int i = 0; i < processes->Length; i++)
{
if (processes[i]->Id != current->Id)
{
// process already exist
}
}
That said, there might be a better way to do this.
It looks like you're trying to see if there's another copy of your application running, so that you can display an "App is already running, switch to that one instead" message to the user.
The problem is that the process name here is just the filename of your EXE, without the path or the "EXE" extension. Try renaming your application to "Notepad.exe", and run a couple copies of the Windows Notepad, and you'll see that they both show up in the GetProcessesByName result.
A better way to do this is to create a named Mutex, and check for its existence and/or lock status at startup.
Here's an answer that does just that. Prevent multiple instances of a given app in .NET? It is written in C#, but it can be translated to C++/CLI. The only notable thing about the translation is that it's using a C# using statement; in C++/CLI that would be the line Mutex mutex(false, "whatever string");, using C++/CLI's stack semantics.

Related

Lucene index files changing constantly even when there is no adding, updating, or deletion operations performed on it

I have noticed that, my lucene index segment files (file names) are always changing constantly, even when I am not performing any add, update, or delete operations. The only operations I am performing is reading and searching. So, my question is, does Lucene index segment files get updated internally somehow just from reading and searching operations?
I am using Lucene.Net v4.8 beta, if that matters. Thanks!
Here is an example of how I found this issue (I wanted to get the index size). Assuming a Lucene Index already exists, I used the following code to get the index size:
Example:
private long GetIndexSize()
{
var reader = GetDirectoryReader("validPath");
long size = 0;
foreach (var fileName in reader.Directory.ListAll())
{
size += reader.Directory.FileLength(fileName);
}
return size;
}
private DirectoryReader GetDirectoryReader(string path)
{
var directory = FSDirectory.Open(path);
var reader = DirectoryReader.Open(directory);
return reader;
}
The above method is called every 5 minutes. It works fine ~98% of the time. However, the other 2% of the time, I would get the error file not found in the foreach loop, and after debugging, I saw that the files in reader.Directory are changing in count. The index is updated at certain times by another service, but I can assure that no updates were made to the index anywhere near the times when this error occurs.
Since you have multiple processes writing/reading the same set of files, it is difficult to isolate what is happening. Lucene.NET does locking and exception handling to ensure operations can be synced up between processes, but if you read the files in the directory directly without doing any locking, you need to be prepared to deal with IOExceptions.
The solution depends on how up to date you need the index size to be:
If it is okay to be a bit out of date, I would suggest using DirectoryInfo.EnumerateFiles on the directory itself. This may be a bit more up to date than Directory.ListAll() because that method stores the file names in an array, which may go stale before the loop is done. But, you still need to catch FileNotFoundException and ignore it and possibly deal with other IOExceptions.
If you need the size to be absolutely up to date and plan to do an operation that requires the index to be that size, you need to open a write lock to prevent the files from changing while you get the value.
private long GetIndexSize()
{
// DirectoryReader is superfluous for this example. Also,
// using a MMapDirectory (which DirectoryReader.Open() may return)
// will use more RAM than simply using SimpleFSDirectory.
var directory = new SimpleFSDirectory("validPath");
long size = 0;
// NOTE: The lock will stay active until this is disposed,
// so if you have any follow-on actions to perform, the lock
// should be obtained before calling this method and disposed
// after you have completed all of your operations.
using Lock writeLock = directory.MakeLock(IndexWriter.WRITE_LOCK_NAME);
// Obtain exclusive write access to the directory
if (!writeLock.Obtain(/* optional timeout */))
{
// timeout failed, either throw an exception or retry...
}
foreach (var fileName in directory.ListAll())
{
size += directory.FileLength(fileName);
}
return size;
}
Of course, if you go that route, your IndexWriter may throw a LockObtainFailedException and you should be prepared to handle them during the write process.
However you deal with it, you need to be catching and handling exceptions because IO by its nature has many things that can go wrong. But exactly how you deal with it depends on what your priorities are.
Original Answer
If you have an IndexWriter instance open, Lucene.NET will run a background process to merge segments based on the MergePolicy being used. The default settings can be used with most applications.
However, the settings are configurable through the IndexWriterConfig.MergePolicy property. By default, it uses the TieredMergePolicy.
var config = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer)
{
MergePolicy = new TieredMergePolicy()
};
There are several properties on TieredMergePolicy that can be used to change the thresholds that it uses to merge.
Or, it can be changed to a different MergePolicy implementation. Lucene.NET comes with:
LogByteSizeMergePolicy
LogDocMergePolicy
NoMergePolicy
TieredMergePolicy
UpgradeIndexMergePolicy
SortingMergePolicy
The NoMergePolicy class can be used to disable merging entirely.
If your application never needs to add documents to the index (for example, if the index is built as part of the application deployment), it is also possible to use a IndexReader from a Directory instance directly, which does not do any background segment merges.
The merge scheduler can also be swapped and/or configured using the IndexWriterConfig.MergeScheduler property. By default, it uses the ConcurrentMergeScheduler.
var config = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer)
{
MergePolicy = new TieredMergePolicy(),
MergeScheduler = new ConcurrentMergeScheduler()
};
The merge schedulers that are included with Lucene.NET 4.8.0 are:
ConcurrentMergeScheduler
NoMergeScheduler
SerialMergeScheduler
The NoMergeScheduler class can be used to disable merging entirely. This has the same effect as using NoMergePolicy, but also prevents any scheduling code from being executed.

System.AccessViolationException: 'Attempted to read or write protected memory. (Making a wrapper for a c++ lib)

My constructor is as next
ScaperEngine::ScaperEngine(GrabberType grabberType, bool timing) {
switch (grabberType)
{
case GrabberType::DepthSenseGrabber:
this->interface = new pcl::DepthSenseGrabber("");
break;
default:
throw new std::exception("Grabber type wasn't chosen correctly");
break;
}
executionPipeline = new ExecutionPipeline();
executionPipeline->setTiming(timing);
}
And then I have some code like:
void ScaperEngine::StartPipeline()
{
IPCLNormalCalculator* normalCalculator = new PCLNormalCalculator(normalCalcMaxDepthChangeFactor, normalSmoothingSize);
executionPipeline->SetPCLNormalCalculator(normalCalculator);
The most strange thing is that the constructor is building executionPipeline in the right way putting its place in memory in 0x0000020ef385e830, but when my c# managed code calls StartPipeline the executionPipeline address changed to 0xcdcdcdcdcdcdcdcd and in Quick Watch the following text appears for its variables <Unable to read memory>.
Please anyone has a clue whats going on?
With many thanks.
The 0xcdcdcdcdcdcdcdcd you are seeing is a special feature of the Visual Studio debugger that represents uninitialized heap memory. A more comprehensive list of codes are available from this StackOverflow question. In brief, it seems as though your C# code is calling StartPipeline() on an invalid object. This could happen, for example, if the pointer is altered to point to a random location in heap memory. Make your C# code (and the runtime) is properly storing the pointer to the ScraperEngine object and not corrupting it along the way.

Get referring method in VB.net

I'm trying to get the referring method in vb.net.
e.g. I have 1 generic method (sendMail) that handle's emails, any other method can call this. I want sendMail to log an entry to the database when it sends an email. In this log i want the name of method that calls sendMail. I can do it by passing paramaters but I would like to know if sendMail can access the name of the method that calls it.
I found this article that works great in vs
Is it possible to get the referring method in VB.NET?
but unfortunately i'm working in a proprietary application and their IDE and the output I get from StackFrame is 'ExecuteAction at offset 1438 in file:line:column :0:0 '. I think it might be because the StackFrame used in example by Jon works in debug mode not release. (MSDN said something about debug mode but i'm not 100% sure here)
Is there another way of getting the calling method name?
Or am I using StackFrame incorrectly?
Cheers in advance.
dno
public string GetStackTrace()
{
StackTrace st = new StackTrace(true);
StackFrame[] frames = st.GetFrames();
return frames[1].GetMethod().Name.ToString();
}
give it a try:
this method will most likely return the name of its caller, with a few adjustment, you cant tweak it to nest back by increasing the index of the frames array.
good luck

WP7 fails to consume ASMX correctly ? Always get empty arrays?

I'm making a WP7 app, which is consuming an ASMX which I can't touch, nor adapt, since I'm not the creator, nor the provider, I'm just consuming it.
When I add the service reference to my WP7 solution (not mango - but it's the same behaviour in mango), I'll uncheck the "Reuse types in referenced assemblies" because I don't care about those.
Side Note: Even when I leave that checkbox checked it doesn't work either.
Then I add the following code to the constructor of a new WP7 page :
MobileWS.WebServiceSoapClient ws = new MobileWS.WebServiceSoapClient("WebServiceSoap", "http://www.somewhere.com/MobileService.asmx");
ws.getCountriesCompleted += new EventHandler<MobileWS.getCountriesCompletedEventArgs>(OnGetCountriesCompleted);
ws.getCountriesAsync("fr");
This goes out and fetches an array of Country objects ("fr" stands for "french", so it'll be "Etas Unis" instead of "United States")... at least that's the idea.
I even checked with Fiddler2 if it returned anything, and indeed, the ASMX responds with some XML that contains the countries.
Then my handler goes like this :
private void OnGetCountriesCompleted(object sender, MobileWS.getCountriesCompletedEventArgs e)
{
if (e.Cancelled == false && e.Error == null && e.Result != null)
{
List<MobileWS.Country> countries = e.Result.ToList<MobileWS.Country>();
CountriesListBox.ItemsSource = countries;
}
}
Unfortunatly the e.Result always returns an empty array of country objects (so non at all, but he knows there should be country objects in there, but there are 0 items in the array) !
Though, if I browse to : http://www.somewhere.com/MobileService.asmx I get the list when I invoke the getCountries function.
Even more strange, when I copy and past the exact same code in a WPF application it works like a charm, I get a filled array with 7 country objects in.
What's wrong ?
I'm refusing to parse the returned XML myself so far, but I'm feeling I will need to sooner or later because of this fail.
I'm pretty sure that the XML that is send back is correct, else the WPF application would have similar problems, no ?
So, looks like I'm doomed to parse it myself, then ?
I see a lot of examples on the web where they do that (parsing the XML result themselfs), so there must be a reason for that, and that reason is the one I describe above :).
Sounds like a serialization issue to me. And that's about all I can say, without knowing the service or how the used classes are written/generated.
Remember that Windows Phone have limited reflection abilities, and as such can only reflect on public/internal classes, and don't support dynamics.
What happens if you try to deserialize the result yourself? Granted, it's just a step away from parsing the xml manually, but it's something. If not, maybe you can find out what's going wrong.

Write a compiler for a language that looks ahead and multiple files?

In my language I can use a class variable in my method when the definition appears below the method. It can also call methods below my method and etc. There are no 'headers'. Take this C# example.
class A
{
public void callMethods() { print(); B b; b.notYetSeen();
public void print() { Console.Write("v = {0}", v); }
int v=9;
}
class B
{
public void notYetSeen() { Console.Write("notYetSeen()\n"); }
}
How should I compile that? what i was thinking is:
pass1: convert everything to an AST
pass2: go through all classes and build a list of define classes/variable/etc
pass3: go through code and check if there's any errors such as undefined variable, wrong use etc and create my output
But it seems like for this to work I have to do pass 1 and 2 for ALL files before doing pass3. Also it feels like a lot of work to do until I find a syntax error (other than the obvious that can be done at parse time such as forgetting to close a brace or writing 0xLETTERS instead of a hex value). My gut says there is some other way.
Note: I am using bison/flex to generate my compiler.
My understanding of languages that handle forward references is that they typically just use the first pass to build a list of valid names. Something along the lines of just putting an entry in a table (without filling out the definition) so you have something to point to later when you do your real pass to generate the definitions.
If you try to actually build full definitions as you go, you would end up having to rescan repatedly, each time saving any references to undefined things until the next pass. Even that would fail if there are circular references.
I would go through on pass one and collect all of your class/method/field names and types, ignoring the method bodies. Then in pass two check the method bodies only.
I don't know that there can be any other way than traversing all the files in the source.
I think that you can get it down to two passes - on the first pass, build the AST and whenever you find a variable name, add it to a list that contains that blocks' symbols (it would probably be useful to add that list to the corresponding scope in the tree). Step two is to linearly traverse the tree and make sure that each symbol used references a symbol in that scope or a scope above it.
My description is oversimplified but the basic answer is -- lookahead requires at least two passes.
The usual approach is to save B as "unknown". It's probably some kind of type (because of the place where you encountered it). So you can just reserve the memory (a pointer) for it even though you have no idea what it really is.
For the method call, you can't do much. In a dynamic language, you'd just save the name of the method somewhere and check whether it exists at runtime. In a static language, you can save it in under "unknown methods" somewhere in your compiler along with the unknown type B. Since method calls eventually translate to a memory address, you can again reserve the memory.
Then, when you encounter B and the method, you can clear up your unknowns. Since you know a bit about them, you can say whether they behave like they should or if the first usage is now a syntax error.
So you don't have to read all files twice but it surely makes things more simple.
Alternatively, you can generate these header files as you encounter the sources and save them somewhere where you can find them again. This way, you can speed up the compilation (since you won't have to consider unchanged files in the next compilation run).
Lastly, if you write a new language, you shouldn't use bison and flex anymore. There are much better tools by now. ANTLR, for example, can produce a parser that can recover after an error, so you can still parse the whole file. Or check this Wikipedia article for more options.