Recursive conditions - c#

Sorry to put up yet another recursion question, but I've looked over a fair few on here and haven't found the solution for my problem.
I use the below function:
unsafe
{
// Allocate global memory space for the size of AccessibleContextInfo and store the address in acPtr
IntPtr acPtr = Marshal.AllocHGlobal(Marshal.SizeOf(new AccessibleContextInfo()));
try
{
Marshal.StructureToPtr(new AccessibleContextInfo(), acPtr, true);
if (WABAPI.getAccessibleContextInfo(vmID, ac, acPtr))
{
acInfo = (AccessibleContextInfo)Marshal.PtrToStructure(acPtr, typeof(AccessibleContextInfo));
if (!ReferenceEquals(acInfo, null))
{
AccessibleTextItemsInfo atInfo = new AccessibleTextItemsInfo();
if (acInfo.accessibleText)
{
IntPtr ati = Marshal.AllocHGlobal(Marshal.SizeOf(new AccessibleTextItemsInfo()));
WABAPI.getAccessibleTextItems(vmID, ac, ati, 0); //THIS IS WHERE WE DO IT
atInfo = (AccessibleTextItemsInfo)Marshal.PtrToStructure(ati, typeof(AccessibleTextItemsInfo));
if (ati != IntPtr.Zero)
{
Marshal.FreeHGlobal(ati);
}
}
AccessibleTreeItem newItem = BuildAccessibleTree(acInfo, atInfo, parentItem, acPtr);
newItem.setAccessibleText(atInfo);
if (!ReferenceEquals(newItem, null))
{
for (int i = 0; i < acInfo.childrenCount; i++)
{
//Used roles = text, page tab, push button
if (acInfo.role_en_US != "unknown" && acInfo.states_en_US.Contains("visible")) // Note the optomization here, I found this get me to an acceptable speed
{
AccessibleContextInfo childAc = new AccessibleContextInfo();
IntPtr childContext = WABAPI.getAccessibleChildFromContext(vmID, ac, i);
GetAccessibleContextInfo(vmID, childContext, out childAc, newItem);
if (childContext != IntPtr.Zero)
{
Settings.Save.debugLog("Releasing object " + childContext.ToString() + " from JVM: " + vmID);
WABAPI.releaseJavaObject(vmID, childContext);
childContext = IntPtr.Zero;
}
}
}
}
return newItem;
}
}
else
{
acInfo = new AccessibleContextInfo();
}
}
finally
{
if (acPtr != IntPtr.Zero)
Marshal.FreeHGlobal(acPtr);
}
}
return null;
}
To build an AccessibleTreeItem representing the entire GUI of a Java application. However, this function takes 5-6 seconds to run. I'm only looking for one particular subsection of the tree (Lets call it Porkchops).
What I'd like to do is prior to building the tree, get the values and as soon as acRole.name == "Porkchop", use that as the parent object and create an AccessibleTreeItem that represents the subtree.
How on earth do I manage this? If this is a simple question, apologies, but it's driving me crazy.
Edit 1 - The performance hit is encountered on releaseJavaObject(), as when I remove that line the function completes in less than a second, but it creates a horrible memory leak.
Therefore, I'm not really looking for alternative solutions, as I know that the above does work correctly. I just need some way to check the value of acInfo.name prior to creating the tree, and then using the correct acInfo node as the parent.
Edit 2 - See the attached image for a better explanation than my rambling. Currently, the function will pull this entire tree from the JVM. I've highlighted the appropriate section that I work with, and would like to know if there's a way that will allow me to get that information, without building the entire tree. Or even if I could just return the tree once all children of that node have been populated.

Related

What parameter i have to assign inside my variable so i can start it from my Main?

im new to C# and Tia Openness and have an problem. I dont know what parameter goes inside my ImportSingleTextList();.Its an example from Siemens but there is never mentioned how to call it inisde the main. That is my code.
private static void ImportSingleTextList(HmiTarget hmitarget)
{
TextListComposition textListsComposition = hmitarget.TextLists;
IList<TextList> importedTextLists = textListsComposition.Import(new FileInfo(#"D:\SamplesImport\myTextList.xml"), ImportOptions.Override);
}
I guess you have to look into your HmiTarget exactly. Is it a class, then you should instantiate a first instance of it; what constructor does this class have - with or without parameters? Click on HmiTarget and see what input it expects.
I guess you class has some kind of enumerable hmitarget.TextLists that you have to fill or get too.
Presumably you have a Project instance. You have to drill down from Project->Device->DeviceItem(->DeviceItem) until you find a DeviceItem that can provide a SoftwareContainer service. It may be that all such DeviceItems reside at the first level below Device; I haven't checked. Anyway, here's a method I wrote that searches the first and second DeviceItem levels:
public static HmiTarget GetHmiTarget(Device hmiDevice)
{
//search first level of DeviceItems
foreach (DeviceItem di in hmiDevice.DeviceItems)
{
SoftwareContainer container =
di.GetService<SoftwareContainer>();
if (container != null)
{
HmiTarget hmi = container.Software as HmiTarget;
if (hmi != null)
return hmi;
}
//search second level of DeviceItems
foreach (DeviceItem devItem in di.DeviceItems)
{
SoftwareContainer subContainer = devItem.GetService<SoftwareContainer>();
if(subContainer != null)
{
HmiTarget hmi = subContainer.Software as HmiTarget;
if (hmi != null)
return hmi;
}
}
}
return null; //nothing was found at the first or second levels
}
to get the Device, you can use PROJECT.Devices.Find(NAME) where PROJECT is your TIA portal project instance, and NAME is the string name of your HMI device.

Running out of memory looping through mail items

Hi I have a Outlook com addin that is doing some simple searching tricks for me. I am part way through putting it together but I am having issues with it running out of memory. The process is very simple and basically loops through an outlook folder checking each mailItem for a match. given the loop reinitialize the variables each time I would have expected the garbage collector to keep up but when I watch the memory it loses ~10m/sec until the system is out of memory and I get unhandled exceptions.
This is part of the code
private void FindInFolder(Outlook.MAPIFolder FolderToSearch)
{
Outlook.MailItem mailItem;
Outlook.MAPIFolder ParentFolder;
int counter = 0;
StatusBar.Text = "Searching in Folder " + FolderToSearch.FolderPath + "/" + FolderToSearch.Name;
StatusBar.Update();
this.Update();
foreach (COMObject item in FolderToSearch.Items)
{
counter++;
if (counter % 100 == 0)
{
StatusBar.Text = FolderToSearch.FolderPath + "/" + FolderToSearch.Name + " item " + counter + " of " + FolderToSearch.Items.Count;
StatusBar.Update();
if (counter % 1000 == 0)
{
GC.Collect();
}
}
if (item is Outlook.MailItem)
{
mailItem = item as Outlook.MailItem;
if (IsMatch(mailItem))
{
if (mailItem.Parent is Outlook.MAPIFolder)
{
ParentFolder = mailItem.Parent as Outlook.MAPIFolder;
ResultGrd.Rows.Add(mailItem.EntryID, ParentFolder.FolderPath, mailItem.SenderName, mailItem.Subject, mailItem.SentOn);
}
}
}
mailItem = null;
}
}
Which calls
private Boolean IsMatch(Outlook.MailItem inItem)
{
Boolean subBool = false;
Boolean NameBool = false;
try
{
if (null != inItem)
{
if (SubjectTxt.Text != "")
{
if (inItem.Subject.Contains(SubjectTxt.Text))
{
subBool = true;
}
}
else
{
subBool = true;
}
if (NameTxt.Text != "")
{
if (inItem.Sender != null)
{
if (inItem.Sender.Name.Contains(NameTxt.Text))
{
NameBool = true;
}
}
}
else
{
NameBool = true;
}
return subBool && NameBool;
}
}
catch (System.Runtime.InteropServices.COMException ce)
{
if (ce.ErrorCode == -2147467259)
{
//DO nothing just move to the next one
}
else
{
MessageBox.Show("Crash in IsMatch error code = " + ce.ErrorCode + " " + ce.InnerException);
}
}
return false;
}
Please excuse all the error catching part at the bottom and the GC.collect they are some of my attempts to work out what is wrong and free up memory.
Note also FindInFolder is called by a new thread so I can interact with results while it continues to search.
What I have tried so far:
Making variables local to function not class so the are retrievable by G, however the most used variable in 'item' as it is part of foreach it must be declared that way.
every 1000 mailItems do a manual GC, this made no difference at all.
For some reason it needs alot of memory just looping through the items and GC never frees them up.
Please also note I am using netoffice not VSTO for Com addin.
First of it all: This is NetOffice code and you dont need Marshal.ReleaseComObject in NetOffice. (Moreover, its useless to call ReleaseComObject here) Use Dispose() for the instance instead.
Keep in your mind: NetOffice handle COM proxies for you (Thats why its allowed to use two 2 dots in NetOffice).
In your case its internaly stored as:
// FolderToSearch
-- Items
--Enumerator
-- Item
-- Item
-- ....
Use item.Dispose() at the end of each loop to remove/free the item instance or use the following after foreach
FolderToSearch.Dipose()
// dispose folder instance and all proxies there comes from
FolderToSearch.DisposeChildInstances()
// dispose all proxies there comes from but keep the folder instance alive
Next:
The Items enumerator here is a custom enumerator(given by NetOffice)
However it works fine with small amount of items but dont do this in a more
heavier scenario(may exchange server and thousands of items). The local workstation/program can't handle this in memory. For this reason Microsoft provides only the well kown GetFirst/GetNext pattern. In NetOffice it looks like:
Outlook._Items items = FolderToSearch.Items;
COMObject item = null;
do
{
if (null == item)
item = items.GetFirst() as COMObject;
if (null == item)
break;
// do what you want here
item.Dispose();
item = items.GetNext() as COMObject;
} while (null != item);
This should works as well.
When working with COM objects from C#, there were 2 tricks that I used to prevent memory and COM object reference counts from building:
Use System.Runtime.InteropServices.Marshal.ReleaseComObject() to release COM objects as you are done with them. This forces a COM "release" on the object.
Do not foreach to iterate through a COM collection. foreach holds on to an enumerator object, which prevents other objects from being released.
So, instead of this:
foreach (COMObject item in FolderToSearch.Items)
{
// ....
}
do this:
Items items = FolderToSearch.Items;
try
{
for (int i = 0; i < items.Count; ++i)
{
COMObject item = items[i];
try
{
// work
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(item);
}
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(items);
}
These tips helped me reduce memory and object consumption.
Disclaimer: I cannot attest to whether this is good practice or not though.
First, I'd recommend using the Find/FindNext or Restrict methods of the Items class instead of iterating through all items in the folder. For example:
Sub DemoFindNext()
Dim myNameSpace As Outlook.NameSpace
Dim tdystart As Date
Dim tdyend As Date
Dim myAppointments As Outlook.Items
Dim currentAppointment As Outlook.AppointmentItem
Set myNameSpace = Application.GetNamespace("MAPI")
tdystart = VBA.Format(Now, "Short Date")
tdyend = VBA.Format(Now + 1, "Short Date")
Set myAppointments = myNameSpace.GetDefaultFolder(olFolderCalendar).Items
Set currentAppointment = myAppointments.Find("[Start] >= """ & tdystart & """ and [Start] <= """ & tdyend & """")
While TypeName(currentAppointment) <> "Nothing"
MsgBox currentAppointment.Subject
Set currentAppointment = myAppointments.FindNext
Wend
End Sub
See the following articles for more information and sample code:
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
How To: Use Restrict method to retrieve Outlook mail items from a folder
Also you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch method are listed below:
The search is performed in another thread. You don’t need to run another thread manually since the AdvancedSearch method runs it automatically in the background.
Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).
Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).
You can stop the search process at any moment using the Stop method of the Search class.
Second, I always suggest releasing underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects article.
If you want to use GC, you need to call the Collect and WaitForPendingFinalizers methods twice.
Matt, you still don't release all objects in the code. For example:
for (int i = 0; i < FolderToSearch.Items.Count; ++i)
{
COMObject item = FolderToSearch.Items[i];
The Items property of the Folder class returns an instance of the corresponding class which should be released after. I see at lease two lines of code where the reference counter is increased.

Making elements changeable from references

So! I've got a C# array.
And I've got a function that returns an element from the array, so the data from that reference can be accessed. Yay!
It would be really super awesome convenient if changing that reference then affected that original element in the array. Is this what static variables do? Is there a way to do it? How to do? For example:
Function A finds an item:
public TutorialPopupBehavior GetBehavior(string behaviorName) {
foreach(TutorialPopupBehavior beh in _tutorialItems) {
if(beh._popupName == behaviorName) {
return beh;
}
}
print ("Could not find behavior of name " + behaviorName);
return null;
}
And then returns it to function B, which then, ideally, would be able to change a property of the returned item:
public void SetTutorialItem(bool state, string itemName) {
TutorialPopupBehavior beh = GetBehavior(itemName);
if(beh == null) {
print ("No tutorial item found, so can't set it to " + state);
return;
}
//idealistic code: beh._isShown = true;
}
The _isShown property of that element would then be changed permanently in the original _tutorialItems array...how do you all accomplish this, or design differently, so as to avoid the problem? The reason I ask is because I have a number of arrays to search, and I don't want to complicate my code by asking the same class to search through the same set of arrays more than once.
public void GetBehavior(string behaviorName, ref TutorialPopupBehavior b) {
foreach(TutorialPopupBehavior beh in _tutorialItems) {
if(beh._popupName == behaviorName) {
b = beh;
Return;
}
}
print ("Could not find behavior of name " + behaviorName);
b = null;
}
Read this msdn article

Depth first search did find solution state in Missionaries and Cannibals problems

I am doing my project on Missionaries and Cannibals using C#. I have used two search algorithms namely breadth first search and depth first search. Using Breadth first search, the program finds the result at level 12 from the root. But using Depth first search, it can not find solution and this hangs my computer. I think it enters a cycle in the graph. So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Code for Breadth first search is
public State getSolutionStatesBFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, true);
while (searchAgenda.Count > 0) {
CurState = (State)searchAgenda.Dequeue();
if (CurState.Equals(EndState)) {
break;
} else {
if (!isVisited(CurState, visited))
{
generateSucessors(CurState, true);
visited.Add(CurState);
}
}
}
return CurState;
}
and the code for depth first search is
public State getSolutionStatesDFS(State StartState, State EndState)
{
State CurState = new State();
ArrayList visited = new ArrayList();
addStateToAgenda(StartState, false);
while (searchAgendaS.Count > 0)
{
CurState = (State)searchAgendaS.Pop();
if (CurState.Equals(EndState))
{
break;
}
else
{
if(!isVisited(CurState,visited))
{
generateSucessors(CurState, false);
}
}
}
return CurState;
}
It is hard to tell answer seeing your code. However, based upon my experience: a DFS search does not provide complete solution. There is a good possibility that your code might have got stuck into some infinite loop (which is common with dfs) or (since, you are checking isVisited), there is a possibility that you are not reaching the end goal.
So my question is, can't i use Depth first search to solve Missionaries and cannibals problem?
Yes, it is deffinatly possible, take a look at this site:
http://www.aiai.ed.ac.uk/~gwickler/missionaries.html
With the code given its hard to tell where your issue is.

strange behavior of XamlReader.Load()?

I've got a very strange issue while parsing an external XAML file. The pre-history is that I want to load an external XAML file with content to process. But I want to load as many different files as I want. That happens by unloading the old and loading the new one.
My issue is:
When I load a xaml the first time, everything is good, all as it should be.
But when I load the same xaml the second time, every entry of the object im Loading is there twice. If I run this again, every object is there three times and so on...
To debug the project yourself, download it here. The function starts at line 137 in the file "Control Panel.xaml.cs". I realy don't know what this is. Is it my fault or simply a bug? If yes, is there a workaround?
/// <summary>
/// Load a xaml file and parse it
/// </summary>
public void LoadPresentation()
{
this.Title = "Control Panel - " + System.IO.Path.GetFileName(global.file);
System.IO.FileStream XAML_file = new System.IO.FileStream(global.file, System.IO.FileMode.Open);
try
{
System.IO.StreamReader reader = new System.IO.StreamReader(XAML_file);
string dump = reader.ReadToEnd(); //This is only for debugging purposes because of the strange issue...
XAML_file.Seek(0, System.IO.SeekOrigin.Begin);
presentation = (ResourceDictionary)XamlReader.Load(XAML_file);
//Keys the resourceDictionary must have to be valid
if (presentation["INDEX"] == null || presentation["MAIN_GRID"] == null || presentation["CONTAINER"] == null || presentation["LAYOUTLIST"] == null)
{
throw new Exception();
}
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
for (int i = 0; i < topics.Count; )
{
topics.RemoveAt(i);
}
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
}
catch
{
System.Windows.Forms.MessageBox.Show("Failed to load XAML file \"" + global.file + "\"", "Parsing Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
presentation = null;
}
finally
{
XAML_file.Close();
}
}
Edit:
I have tried to serialize the object that was read from the XamlReader and in the output was nowhere any childelement... But if I pull the object out of the dictionary, the children are all there (duplicated and triplicated, but there).
I have already tried to clear the list over
topics.Clear();
and
topics=new ObservableCollection<TopicListItem>();
lv_topics.ItemsSource=topics;
Try Index.Topics.Clear() after loading the Topics into your topics object. That appears to get rid of the duplication.
//When this list is loaded, every item in it is there twice or three times or four... Why????
TopicList Index = null;
Index = (TopicList)presentation["INDEX"];
topics.Clear();
foreach (TopicListItem item in Index.Topics)
{
topics.Insert(item.TopicIndex, (Topic)presentation[item.ResourceKey]);
}
Index.Topics.Clear(); //Adding this will prevent the duplication
lv_topics.SelectedIndex = 0;
selectedIndex = 0;
In the code post topics is not declared in LoadPresentation() so naturally it will have any prior values.
I know you said you tried topics=new ObservableCollection(); but please try again. And put that IN LoadPresentation()
public void LoadPresentation()
{
ObservableCollection<TopicListItem> topics = new ObservableCollection<TopicListItem>()
I would pass filename
public void LoadPresentation(string fileName)
I get you may need to use topics outside LoadPresentation but this is debugging. If you need topics outside the return it.
public ObservableCollection<TopicListItem> LoadPresentation(string fileName)
If that does not fix it I would put a try catch block on the XAML_file.Close(); to see if something weird is not going on.

Categories

Resources