Locals variables in the debug windows - c#

I'm unable to see local variable result within Locals windows of MS Visual Studio, all the other variables and their types display just fine.
Control is already at line 33 but I don't see effect of line 29 (refer to the image)
Code for line 28 and 29
let dataContractJsonSerializer = new DataContractJsonSerializer(typeof<List[]>)
let result = (dataContractJsonSerializer).ReadObject(memoryStream) :?> List[]
Edit - as per request for more code
[<DataContract>]
type List= {
[<field: DataMemberAttribute(Name="href") >]
Href: string
}
service call
let response = request.GetResponse() :?> HttpWebResponse
use reader = new StreamReader(response.GetResponseStream())
use memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd()))
let result = (new DataContractJsonSerializer(typeof<List[]>)).ReadObject(memoryStream) :?> List[]

Update: It looks like it's not appearing because of optimization.
Quote from https://msdn.microsoft.com/en-us/library/aa309368(v=vs.71).aspx : "The effect of the optimization is to remove the code related to variable z, which is never used. Note also that the Locals window does not contain a node for the variable z."
private void InitializeComponent() {
...
int j = 10, k = 20, z = 0;
for (int i = 0; i < 10; i++) {
z = j+k;
btnNumbers[i].Size = new Size(30, 30);
btnNumbers[i].Click += new System.EventHandler(btnNumbersClicked);
}
...
If you could, please paste the complete code rather than just two lines.
That being said, this works for me. It's possible you left out DataContracts and DataMember from your class.

Related

How to test akka.net persistent actors

I'am using [Akka.Net 1.3.1] a mix of ReceiveActors and ReceivePersistentActors and now I want to write tests for my actorsystem.
MyPersistentActor inherits from ReceivePersistentActor and MyActor inherits from ReceiveActor.
I also installed Akka.TestKit using version 1.3.1 .
But it seems that only ReceiveActors can be tested by Akka.TestKit.
IActorRef myActorRef = this.Sys.ActorOf<MyActor>(); // is fine
IActorRef myPersistentActorRef = this.Sys.ActorOf<MyPersistentActor>(); // is a problem
I also found the nuget package Akka.Persistence.TestKit version 1.2.3.43-beta . The beta wasn't changed since three month and only support akka 1.2.2 . Is it still in development or is it dead. I can not find any kind of information regarding that.
How do you test your persistent actors?
Thanks for your help!
Richi
Akka.Persistence.TestKit has been renamed to Akka.Persistence.TCK and it is used only for testing custom event journal and snapshot store implementations for compatibility with Akka.Persistence protocol. It doesn't bring any utilities for testing user actors.
There are no built-in methods to cooperate with journals/snapshot stores for testing purposes beside having implementations of them working in-memory. With that being said, you can actually work with journal/snapshot store just like with any other actor. If you look into implementations of persistence TCK specs like JournalSpec, you may get some insights into how that protocol works.
For example, if you want to initialize your journal with some events before firing the test case, you can do it like following:
void InitWithEvents(string persistenceId, params object[] events)
{
var probe = CreateTestProbe();
var writerGuid = Guid.NewGuid().ToString();
var writes = new AtomicWrite[events.Length];
for (int i = 0; i < events.Length; i++)
{
var e = events[i];
writes[i] = new AtomicWrite(new Persistent(e, i+1, persistenceId, "", false, ActorRefs.NoSender, writerGuid));
}
var journal = Persistence.Instance.Apply(Sys).JournalFor(null);
journal.Tell(new WriteMessages(writes, probe.Ref, 1));
probe.ExpectMsg<WriteMessagesSuccessful>();
for (int i = 0; i < events.Length; i++)
probe.ExpectMsg<WriteMessageSuccess>();
}
PS: There is clearly a missing part in the persistence TestKit API, any contributions on that field are more than welcome.
I know this is an ols answer, but I couldn't find any better resource. In my tests I am actually only interested if the correct event(s) is (are) persisted after I give my command. Multiple events could be raised by starting a saga. Most of the time I am only interested in the last persisted event.
If somebody is hitting the same issue as me, this is how I fixed getting the last message, based on Bartosz initWithEvents.
private void InitWithEvents(string persistenceId, IList<object> events)
{
var probe = CreateTestProbe();
var writerGuid = Guid.NewGuid().ToString();
var writes = new AtomicWrite[events.Count];
for (int i = 0; i < events.Count; i++)
{
var e = events[i];
writes[i] = new AtomicWrite(new Persistent(e, i+1, persistenceId, "", false, ActorRefs.NoSender, writerGuid));
}
journal = Persistence.Instance.Apply(Sys).JournalFor(null);
journal.Tell(new WriteMessages(writes, probe.Ref, 1));
probe.ExpectMsg<WriteMessagesSuccessful>();
for (int i = 0; i < events.Count; i++)
probe.ExpectMsg<WriteMessageSuccess>();
}
private object GetLastPersistedMessageFromJournal(string persistenceId)
{
var repointable = journal as RepointableActorRef;
var underlying = repointable.Underlying as ActorCell;
PropertyInfo prop = typeof(ActorCell).GetProperty("Actor", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo getter = prop.GetGetMethod(nonPublic: true);
MemoryJournal jrnl = getter.Invoke(underlying, null) as MemoryJournal;
var read = jrnl?.Read(persistenceId, 0, Int64.MaxValue, Int64.MaxValue);
return read?.Last().Payload;
}

How to prevent MS-Word memory error

Is there a way of releasing memory and preventing the following code from crashing in MS-Word?
I get the following error message:
This method or property is not available because there is a memory or disk problem.
Sub vbaTest()
Dim doc As Document
Dim sty As Style
Dim s As Style
Dim readingOrder As WdReadingOrder
Dim i As Integer
Set doc = ActiveDocument
Set sty = doc.Styles(wdStyleNormal)
For i = 0 To 100
readingOrder = sty.ParagraphFormat.readingOrder
For Each s In doc.Styles
s.Font.SizeBi = s.Font.Size + 3
Next
Set s = Nothing
Next
Set sty = Nothing
End Sub
-- or --
public void CsharpRibbon_Click(O.IRibbonControl c)
{
var doc = app.ActiveDocument;
var style = doc.Styles[Wd.WdBuiltinStyle.wdStyleNormal];
for (int i = 0; i < 100; i++)
{
var readingOrder = style.ParagraphFormat.ReadingOrder;
foreach (Wd.Style s in doc.Styles)
s.Font.SizeBi = s.Font.Size + 3;
}
}
The code above doesn't really do anything helpful. I have a ribbon button that I noticed causes a crash on repeated button presses (around 5 or 6 times in a Word session). I stripped back the code and added the for loop to simulate multiple presses of the button.
I'm not sure if this is your error, because 100 iterations doesn't seem like enough to cause memory errors, but VSTO uses COM objects, which must be released after use. The simple way to do this is:
Paragraph para = Paragraphs[1];
// etc.
Marshal.ReleaseComObject(yourObject);
There's also VSTO Contrib which makes this a little easier. Instead of making a call to ReleaseComObject, you would do something like this:
using (var doc = Document.WithComCleanup())
using (var paragraphs = doc.Resource.Paragraphs.WithComCleanup())
{
int count = paragraphs.Resource.Count;
// etc.
}
Or, for collections:
foreach (Paragraph para in Paragraphs.ComLinq<Paragraph>())
{
int pageBreakBefore = para.PageBreakBefore;
// etc.
}

Could not load type 'SAS.LanguageServiceCarriageControl' from assembly

In addition to using the integration components of SAS Enterprise Edition, I am using parts of the following project I found on Github to connect with a SAS server. The goal here is to command the server to run programs on a schedule. However, the programs need to be modified each time, which is why I am attempting to trigger them to run in this manner. However, it keeps throwing an error at lang.FlushLogLines.
https://github.com/cjdinger/SasHarness
SAS.Workspace ws = server.Workspace;
List<string> results = new List<string>();
Array CCs;
Array lineTypes;
Array logLines;
int maxLines = 100;
SAS.LanguageService lang = (SAS.LanguageService)ws.LanguageService;
Array linesVar = (Array)new string[] { PROGRAM_TEXT };
lang.SubmitLines(ref linesVar);
//THROWS AN ERROR HERE
lang.FlushLogLines(maxLines, out CCs, out lineTypes, out logLines);
for (int i = 0; i < logLines.Length; i++)
{
results.Add((string)logLines.GetValue(i));
}
After a bit of research I found the following thread where it is recommended to make sure that all the required dlls are referenced in my project. The mystery here is that I do have them referenced, but the error still occurs.
http://blogs.sas.com/content/sasdummy/2013/06/09/sas-client-with-microsoft-dot-net/
Moreover, starting after the very first line, the code is no longer using SASHarness, but is using native SAS integration libraries only. The code above is also based on examples listed in the following documentation from SAS.
https://support.sas.com/documentation/cdl/en/itechwcdg/61500/PDF/default/itechwcdg.pdf (page 27-28)
Has anybody encountered an error similar to this, and if so, how did you correct it?
Strangely, fixing this error required declaring an instance for each of the assemblies that could not be loaded. I have no idea why this fixes the problem, but it works now.
SAS.Workspace ws = server.Workspace;
string wsId = ws.UniqueIdentifier;
List<string> results = new List<string>();
Array CCs;
Array lineTypes;
Array logLines;
int maxLines = 100;
SAS.LanguageService lang = (SAS.LanguageService) server.Workspace.LanguageService;
Array linesVar = (Array) new string[] { PROGRAM_TEXT };
lang.SubmitLines(ref linesVar);
//For some reason, these two declarations need to be here
SAS.LanguageServiceCarriageControl CarriageControl = new SAS.LanguageServiceCarriageControl();
SAS.LanguageServiceLineType LineType = new SAS.LanguageServiceLineType();
lang.FlushLogLines(maxLines, out CCs, out lineTypes, out logLines);
for (int i = 0; i < logLines.Length; i++)
{
results.Add((string) logLines.GetValue(i));
}

Wrong values passed as parameter to C library using SWIG

Following my three previous posts, I can now pass a managed array of struct to my wrapped method. Here is an extract from the files:
// packer.i
typedef struct {
int width; // input
int height; // input
frame_t view; // output
frame_t dest; // output
} image_t;
CSHARP_ARRAYS(image_t, image_t)
%apply image_t INOUT[] { image_t *images }
int pack(image_t *images, int nb_images, parameters_t params);
Which generates a function with this signature:
// packer_cs.cs
public static int pack(image_t[] images, int nb_images, parameters_t arg2)
Which I call like this:
// Program.cs
var files = Directory.GetFiles("./images");
var images = new image_t[files.Length];
for (var f = 0; f < files.Length; f++)
{
using (var imgInfo = Image.FromFile(files[f]))
{
var imgStruct = new image_t()
{
width = imgInfo.Width,
height = imgInfo.Height,
dest = new frame_t(),
view = new frame_t()
};
images[f] = imgStruct;
}
}
var result = packer_cs.pack(images, images.Length, new parameters_t());
All is well and done, but when I run the pack() method, I have a protected memory access problem (System.AccessViolationException). Thankfully I have access to the source code of the C library, and Visual Studio automagically opens it for debugging and stepping through as soon as I enable unmanaged code debugging.
So, if I add a breakpoint at the start of the pack() function, and I use a watch to check images[x], I can see that the width and height values have nothing to do with what is provided (sometimes it's even 0 or negative). What's going on ? If I inspect my managed array on the C# side, the values are correctly stored and retrieved. Why doesn't C get the right values ? The other parameters (nb_images and params) don't have any problem.
Thank you !
Do the following:
Check that images[f].width and height have the values you expect
If yes, then check the SWIG-generated code to verify that those fields are properly copied.
If you can't spot any problem by looking at the code, you should break on packer_cs.pack and use the debugger to look at the wrapper code that copies the C# array to the C++ array, see what is wrong.
It is probably something in the typemaps that is incorrect. Once you know what that is, you can copy the typemaps code from SWIG source (the csharp_array.i file) to a new typemap in your .i and fix as required.

Removing features from the Google Earth Plugin in c#

Using the Visual Studio C# Winforms Google Earth plugin, 4 placemarks have been added to the globe as can be seen in the picture below:
My goal is to be able to remove the linestring placemark. The steps would seem to be to get all the placemarks, find the linestring and remove it.
Here is the code being used to create the linestring placemarks (more or less from the API website)
var lineStringPlacemark = ge2.createPlacemark("Line_" + name);
// create the line string geometry
var lineString = ge2.createLineString("");
lineStringPlacemark.setGeometry(lineString);
// add the the points to the line string geometry
double dlat1 = Convert.ToDouble(lat1) / 100000;
double dlon1 = Convert.ToDouble(lon1) / 100000;
double dlat2 = Convert.ToDouble(lat2) / 100000;
double dlon2 = Convert.ToDouble(lon2) / 100000;
lineString.getCoordinates().pushLatLngAlt(dlat1, dlon1, 0);
lineString.getCoordinates().pushLatLngAlt(dlat2, dlon2, 0);
// Create a style and set width and color of line
lineStringPlacemark.setStyleSelector(ge2.createStyle(""));
var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
lineStyle.setWidth(5);
lineStyle.getColor().set("9900ffff"); // aabbggrr format
// Add the feature to Earth
ge2.getFeatures().appendChild(lineStringPlacemark);
And here is the code I ended up using to remove the line. Note that the GEHelpers.RemoveFeatureById(ge2, s); is commented out since it isn't working for me for some reason.
for (int i = 0; i < ge2.getFeatures().getChildNodes().getLength(); i++)
{
var kmlobject = ge2.getFeatures().getChildNodes().item[i];
string s = kmlobject.getId();
if (s.Contains("Line_"))
{
ge2.getFeatures().removeChild(kmlobject);
kmlobject.release();
//GEHelpers.RemoveFeatureById(ge2, s);
}
}
The line you have should work and remove all the currently loaded content.
GEHelpers.RemoveAllFeatures(ge); // removes all loaded features from 'ge'
If you wish to remove a specific placemark, or any other feature, simply specify its ID as the parameter to the RemoveFeatureById method.
GEHelpers.RemoveFeatureById(ge, 'foo'); // remove the feature with the id 'foo'
An ID can be set either when you create the feature via the api or when you define the feature in kml. e.g.
// api
ge.createPlacemark('foo');
//kml id
<Document id="foo">
</Document>
Edit:
You should not have to do anything other than...
for (int i = 0; i < ge2.getFeatures().getChildNodes().getLength(); i++)
{
var kmlobject = ge2.getFeatures().getChildNodes().item[i];
if (kmlobject.getId().Contains("Line_"))
{
ge2.getFeatures().removeChild(kmlobject);
}
}
I think that there is possibly something else going on with your set up, maybe to do with having multiple instances of the plugin running at the same time.

Categories