Confused by CaretOffset/LanguageItem methods - xamarin-studio

I am trying to find out over which source file element the cursor is located (code is inside a pad)
//Obtain document
Document sf = IdeApp.Workbench.ActiveDocument;
//out argument
DocumentRegion dr;
//Call using offset
Microsoft.CodeAnalysis.ISymbol o = sf.GetLanguageItem(sf.Editor.CaretOffset , out dr);
The ISymbol returned "o" is Object's Equals. The document sf is a simple class with a parameterless constructor. The cursor is inside the constructor. I was expecting my class constructor.
Where is the error?

Ok. I found a work around to get context data out of the current editor caret offset. It requires to obtain AnalysisDocument from the current document, then the SemanticModel of the document and after obtaining this model, calling GetEnclosingSymbol with the caret offset.

Related

Cannot serialize a string object with Microsoft.Bond

I am using Microsoft.Bond to serialize a class object which works perfectly fine. However, when I try to serialize a simple System.String object, the CompactBinaryWriter writes almost nothing to the output buffer. I am using this code:
string v = "test data";
var outputBuffer = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(outputBuffer);
Serialize.To(writer, v);
var output = outputBuffer.Data;
output in this case is a one element array : {0}, irrespective of the value of v. Can someone point out why this doesn't work?
Bond requires a top-level Bond struct to perform serialization/deserialization.
If only one value needs to be passed/returned, the type bond.Box<T> can be used to quickly wrap a value in a Bond struct. (There's nothing special about bond.Box<T>, except that it ships with Bond.)
Try this:
Serialize.To(writer, Bond.Box.Create(v));
You'll need to deserialize into a bond.Box<string>.
There's an open issue about having better behavior in cases like this.

gtk#: Tree View object always passed as call-by-reference

It seems as if my arguments in the method call of processing a Tree View is always done as call-by-reference.
I have a visible GTK "Tree View" control on a top level window. The data was written by the respective model.
Now I want to remove some of the columns (based on options set by the user) and pass the manipulated Tree View to an Export-Function.
In order to remove the columns only from the output, not from the GUI itself, I thought of copying the visible Tree View control into a temporary one, manipulating the temportary one and calling the export-functionality on the temporary one.
My problem is: even though I pass my origin, visible Tree View as referenc-by-value (as of my understanding), the origin will be manipulated and the removing of columns will be done on the visual Tree View.
It seem as if my arguments in the method call is always done as call-by-reference.
Code:
"treeview1" is the visual Gtk.Tree View...
I call my Export-function:
...
TreeView treeviewExport = SetExportViewAccordingToCheckboxes(treeview1);
ExportFile(treeviewExport);
...
In the method SetExportViewAccordingToCheckboxes() I just pass the global treeview1 as call-by-value, manipulate it internally and return the manipulated Tree View:
protected static TreeView SetExportViewAccordingToCheckboxes(TreeView tvSource)
{
TreeView tvRet = tvSource;
if (cbName == false)
tvRet.RemoveColumn( ... );
...
return tvRet;
}
But even though I have removed the columns from the internal Tree View "tvRet", my visual control "treeview1" lacks all the columns which were removed from "tvRet"; it looks like "treeview1" was passed as call-by-reference.
Question: why is that?
Note: I also tried with the keyword "in" which made no difference:
protected static TreeView SetExportViewAccordingToCheckboxes(in TreeView p_tvSource)
The problem comes here:
In the method SetExportViewAccordingToCheckboxes() I just pass the
global treeview1 as call-by-value, manipulate it internally and return
the manipulated Tree View:
protected static TreeView SetExportViewAccordingToCheckboxes(TreeView tvSource)
{
TreeView tvRet = tvSource;
if (cbName == false)
tvRet.RemoveColumn( ... );
...
return tvRet;
}
First some background. In C# terminology, value types are those that directly contain a value, while reference types are those that reference the data, instead of holding it directly.
So, int x = 5 means that you are creating the value object 5 of type integer, and storing it in x, while TreeView tree = new TreeView() means that you are creating a reference tree of type TreeView, which points to an object of the same type.
All of this means that you cannot pass an object by value, even if you want to. In the best case, you are passing the reference by value, which has no effect.
So, the next step is to copy the data, and modify the copied object instead of the original one. This is theoretically sound, but the line: TreeView tvRet = tvSource; unfortunately does not achieve that. You are creating a new reference, yes, but that reference points to the same object the original reference points to.
Now, say that we are managing objects of class Point instead of TreeView, with properties x and y.
class Point {
public int X { get; set; }
public int Y { get; set; }
}
You can create a point easily:
Point p1 = new Point { X = 5, Y = 7 };
But this does not copy it:
Point p2 = p1;
This would do:
Point p2 = new Point { X = p1.X, Y = p1.Y };
Now the original problem was that you wanted to pass a few columns to an Export() function. In that case, you only need to pass a vector of the filtered columns to the exporting function, instead of a copy of the TreeView.
void PrepareExporting()
{
var columns = new List<TreeViewColumn>();
foreach(TreeViewColumn col in this.treeView.Columns) {
if ( this.Filter( col ) ) {
columns.add( col );
}
}
this.Export( columns.ToArray() );
}
void Export(TreeViewColumn[] columns)
{
// ...
}
I think that would be easier, since it is not needed to try to achieve a pass-by-reference (impossible), nor copy the tree view.
Hope this helps.

MonoGame/XNA Mouse.GetState() always returns 0,0 position

I'm trying to get the position of the cursor by calling the mouse class and using the GetState method but the return value is always 0,0. I've searched everywhere and all the code looks the same on other examples. I've tried alternative ways of declare the class but I get the same results.
public void Update() {
var ms = Mouse.GetState();
cursorPos = new Vector2(ms.X, ms.y);
}
If you are using Mono, it's possible that Mouse.GetState method is extended. On some past versions there was problems Mouse.SetState method, could be that also problem was also in Mouse.GetState... so I suggest you take latest Mono framework.
Or you can try to access directly to that method.
var ms = Microsoft.Xna.Framework.Input.Mouse.GetState();
var mp = new Point(ms.X, ms.Y);

pdfbox - add visual signature. COSObject cast error

In org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions have setVisualSignature method. I can create a visual signature from some other pdf stream that has a visual signature appearance (to copy the appearance).
1) I created a signature appearance pdf, and using the setVisualSignature() method, I manage to copy the visual signature. Everything works;
2) I change the visual signature (change image) from PDFBox. To get COSObject:
Iterator<Entry<COSObjectKey, Long>> xrefEntriesIt = doc.getDocument()
.getXrefTable().entrySet().iterator();
while (xrefEntriesIt.hasNext()) {
COSObject object = doc.getDocument().getObjectFromPool(
xrefEntriesIt.next().getKey());
if (object.getDictionaryObject(COSName.SUBTYPE) == COSName.IMAGE) {
changeImage(object, doc);
}
}
and to change Image:
private static void changeImage(COSObject obj, PDDocument doc) {
PDXObjectImage imageInPdf =
(PDXObjectImage) PDXObject.createXObject((COSStream) obj.getObject());
File inputFile = new File("/new_SIGNATURE_IMG.jpg");
PDXObjectImage newImage = new PDJpeg(doc, new FileInputStream(inputFile));
imageInPdf.getCOSStream().replaceWithStream(newImage.getCOSStream());
doc.save("/new.pdf");
}
Everything works.
3) When I call setVisualSignature() method with the new pdf and with the new appearance image (that I change with my code), I have that error:
Exception in thread "main" java.lang.ClassCastException:
org.apache.pdfbox.cos.COSObject cannot be cast to
org.apache.pdfbox.cos.COSDictionary at
org.apache.pdfbox.pdmodel.PDDocument.addSignature(PDDocument.java:474)
Thats samples
What happens? Do I change images incorrectly?
The difference between template.pdf and CHANGED_TEMPLATE.pdf is that the signature field dictionary in the former one contains its appearance streams dictionary as a direct object:
9 0 obj
<< [...] /AP<</N 8 0 R>>>>
endobj
while in the latter one the appearance streams dictionary is an indirect object only referenced from the signature field dictionary:
5 0 obj
<<
[...]
/AP 10 0 R
>>
[...]
10 0 obj
<<
/N 15 0 R
>>
This is perfectly ok, the PDF specification does not require it to be direct in general:
AP dictionary (Optional; PDF 1.2) An appearance dictionary specifying how the annotation shall be presented visually on the page (see 12.5.5, “Appearance Streams”). Individual annotation handlers may ignore this entry and provide their own appearances.
(Table 164 in ISO 32000-1:2008)
Unfortunately the code where the exception occurs, i.e. the PDDocument method addSignature` in line 474, looks like this:
PDAppearanceDictionary ap =
new PDAppearanceDictionary((COSDictionary)cosBaseDict.getItem(COSName.AP));
Thus, PDFBox here expects the /AP value to be a direct dictionary object, not some reference to an indirect dictionary object.
I assume your first manipulation makes PDFBox rewrite the PDF in a way it assumes to be best (which seems to include making dictionaries indirect objects), and then PDFBox has other expectations...
If you made your first manipulation as an incremental update instead of a complete rewrite, PDFBox might leave the appearances dictionary untouched.

Creating WCF service by determining type at runtime

I am trying to create a WCF service without knowing its type/interface at runtime. To do this, I use ChannelFactory. ChannelFactory is a generic class so I need to use Type.MakeGenericType. The type I pass to MakeGenericType is from a list of interfaces I previously gathered with reflection by searching some assemblies.
Ultimately, I call MethodInfo.Invoke to create the object. The object is created just fine, but I cannot cast it to the proper interface. Upon casting, I receive the following error:
"Unable to cast transparent proxy to type 'Tssc.Services.MyType.IMyType'"
After some experimenting, I have found that the interface/type passed to MakeGenericType seems to be the problem. If I substitute the interface in my list with the actual interface, then everything works fine. I have combed through the two objects and cannot see a difference. When I modify the code to produce both types, comparing them with Equals returns false. It is unclear to me whether Equals is just checking that they are referring to the same object (not) or thety are checking all properties, etc.
Could this have something to do with how I gathered my interfaces (Reflection, saving in a list...)? A comparison of the objects seems to indicate they are equivalent. I printed all properties for both objects and they are the same. Do I need to dig deeper? If so, into where?
// createService() method
//*** tried both of these interfaces, only 2nd works - but they seem to be identical
//Type t = interfaces[i]; // get type from list created above - doesn't work
Type t = typeof(Tssc.Services.MyType.IMyType); // actual type - works OK
// create ChannelFactory type with my type parameter (t)
Type factoryType = typeof(ChannelFactory<>);
factoryType = factoryType.MakeGenericType(new Type[] { t });
// create ChannelFactory<> object with two-param ctor
BasicHttpBinding binding = new BasicHttpBinding();
string address = "blah blah blah";
var factory = Activator.CreateInstance(factoryType, new object[] { binding, address });
// get overload of ChannelFactory<>.CreateChannel with no parameters
MethodInfo method = factoryType.GetMethod("CreateChannel", new Type[] { });
return method.Invoke(factory, null);
//--------------- code that calls code above and uses its return
object ob = createService();
//*** this cast fails
Tssc.Services.MyType.IMyType service = (Tssc.Services.MyType.IMyType)ob;
Ok, I understand whats happening here - the problem is relating to loading the same assembly being effectively loaded twice - once via a reference, and once via the assembly load command. What you need to do is change the place where you load your assembly, and check to see if it already exists in the current AppDomain, like this maybe:
Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.Equals("ClassLibrary1Name"));
if (assembly == null)
{
assembly = System.Reflection.Assembly.LoadFile("path to your assembly");
}
//do your work here
This way if the assembly is already loaded into memory, it'll use that one.