DotNetRDF & AllegroGraph - c#

I'm working on an application for bulk parsing and uploading to an AllegroGraph triplestore, but have run into a snag. I am able to open and read the graph in question using the below code:
AllegroGraphConnector conn = new AllegroGraphConnector(myHost, myGraph, myUsername, myPassword);
Graph g = new Graph();
conn.LoadGraph(g, "");
g.BaseUri = new Uri(MOG);
foreach (RTSNode r in _nodes)
{
IUriNode sbj = g.CreateUriNode(new Uri(RTSuri + r.myName));
IUriNode pred = g.CreateUriNode(new Uri(MOG));
ILiteralNode obj = g.CreateLiteralNode(r.myName, "en");
g.Assert(new Triple(sbj, pred, obj));
}
conn.SaveGraph(g);
As mentioned the graph loads fine and triples are being added to the local version. But when I attempt to save it, I get an 400- Bad request error. Turning on full debugging shows the error to be due to:
UNSUPPORTED FILE FORMAT: 'application/n-triples' is not a supported content-type
Is there an option for changing the default format with which AllegroGraphConnector communicates?
Thank you for your time.

What version of dotNetRDF are you using?
This sounds like a bug which was fixed in our recent 1.0.8 release so I would first try upgrading to the latest version which should resolve the issue
Update
So it looks like this is a bug in AllegroGraph, according to their documentation they are expecting the MIME type for NTriples to be text/plain whereas most current systems (including dotNetRDF) use the now standard application/n-triples as the MIME type for NTriples.
Currently there is no workaround for this, filed as CORE-447 to be fixed for the next release

Related

Transforming XML with XSL to HTML Saxon library in .NET

I am programming in C#. I was previously using the following command line to convert an xml with a xsl and output it as a html.
java -jar "C:\Data\saxon-he-9.4.0.7.jar" View.xml Stylesheet.xsl -o:output.html
However, I am now trying to use the Saxon .Net API to do the same process using the following code:
var xslt = new FileInfo(#"C:\\Data\\Stylesheet.xsl");
var input = new FileInfo(#"C:\\Data\\View.xml");
var output = new FileInfo(#"C:\\Data\\test.html");
// Compile stylesheet
var processor = new Processor();
var compiler = processor.NewXsltCompiler();
var executable = compiler.Compile(new Uri(xslt.FullName));
// Do transformation to a destination
var destination = new DomDestination();
using (var inputStream = input.OpenRead())
{
var transformer = executable.Load();
transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));
transformer.Run(destination);
}
// Save result to a file (or whatever else you wanna do)
destination.XmlDocument.Save(output.FullName);
However I recieve the error:
"An unhandled exception of type 'Saxon.Api.DynamicError' occurred in saxon9he-api.dll"
When running the line "transformer.Run(destination);"
The following screenshots are from the Visual Studio's Locals Debugging:
$exception {"XSLT 1.0 compatibility mode is not available in this configuration"} Saxon.Api.DynamicError
transformer {Saxon.Api.XsltTransformer} Saxon.Api.XsltTransformer
The first thing you need to do is to get more specific information about the nature of the error. Catching the exception and printing the exception message would be a good start. But Saxon will have written diagnostics to the standard error output, which probably ends up in some log file somewhere, depending on how your application is configured and run. If you can't track it down, try redirecting it as described here: How to capture a Processes STDOUT and STDERR line by line as they occur, during process operation. (C#)
Once you've established the actual error, edit the question and we can start investigating what's wrong if it's not obvious.
A common cause of problems when writing to a DomDestination is that your result tree isn't well-formed, e.g, it has text nodes or multiple elements at the top level. It's not clear why you are writing to a DomDestination - if you just want to produce serialized XML, then write to a Serializer.
LATER
Now you've found the error message ("XSLT 1.0 compatibility mode is not available in this configuration") it should be fairly clear. When a stylesheet specifies version="1.0" and is run with an XSLT 2.0 or 3.0 processor, it runs in a compatibility mode where certain things behave differently (for example xsl:value-of ignores all but the first selected item). This compatibility mode, from Saxon 9.8 onwards, is not available in Saxon-HE. You need to do one of three things: upgrade to Saxon-PE or -EE; revert to an earlier Saxon-HE version; or convert your stylesheet to XSLT 2.0 (which basically means (i) change the value of the version attribute (ii) test that it still works.)

Search with SharePoint CSOM (portable) throws an exception

I am trying to use SharePoint client framework to execute a search, using the portable dll's from a Windows app.
Using Fiddler I can see that my search is executed, and returns a JSON collection of metadata and search results. This is identical to the result from the non-portable CSOM.
When CSOM tries to map the result to it's data objects I get the following exception:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'Microsoft.SharePoint.Client.Search.Query.ResultTableCollection'.
This exception occurs inside CSOM (portable). Non-portable CSOM runs without exception, and returns the expected result.
The code I am running to get this exception is:
var query = new KeywordQuery(ctx);
query.QueryText = "something";
var executor = new SearchExecutor(ctx);
var results = executor.ExecuteQuery(query);
await ctx.ExecuteQueryAsync();
In the above, ctx is a ClientContext that has already been authenticated. Other requests, such as getting a specific list, works as expected.
I am referencing the following dll's from c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI:
Microsoft.SharePoint.Client.Portable.dll
Microsoft.SharePoint.Client.Runtime.Portable.dll
Microsoft.SharePoint.Client.Runtime.WindowsStore.dll
Microsoft.SharePoint.Client.Search.Portable.dll
My question is.
How do I solve this, so that I can use CSOM to run search queries from a Windows Store app?
UPDATE:
I added the following after authenticating the ClientContext:
ctx.ExecutingWebRequest += (s, e) =>
e.WebRequest.Headers["Accept-Encoding"] = "gzip, deflate";
This solved the immediate problem, but introduced a new one. I am now getting a System.FormatException:
Not well formatted JSON stream.
Since the JSON from portable and non-portable CSOM is the same, there should not be a parsing error in one CSOM and not the other.
What I can identify from your exception is that casting of execute query result creates problem here.
Use below code to cast execute query result
ResultTable rtSharePointSearchResult = new ResultTable();
KeywordQuery query = new KeywordQuery(clientContext);
query.QueryText = "Keywords";
query.TrimDuplicates = false;
SearchExecutor searchExecutor = new SearchExecutor(clientContext);
ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(query);
clientContext.ExecuteQuery();
rtSharePointSearchResult = results.Value[0];
Notice that the first post uses ctx.ExecuteQueryAsync but the "answer" uses ctx.ExecuteQuery.
The bug is in the portable class library (that the first post uses) but this works in the non-portable version (the second post).
Cheers,
Paul

Unsupported Media Type error when using json-patch in Ramone

Update: I downloaded Ramone project, added it to my project and then ran the application again with debugger. The error is shown below:
public MediaTypeWriterRegistration GetWriter(Type t, MediaType mediaType)
{
...
CodecEntry entry = SelectWriters(t, mediaType).FirstOrDefault(); => this line throws error
...
}
Error occurs in CodecManager.cs. I am trying to figure out why it does not recognize json-patch media type. Could it be because writer is not being registered correctly? I am looking into it. If you figure out the problem, please let me know. Since you are the author of the library, it will be easier for you to figure out the issue. I will have to go through all the code files and methods to find the issue. Thanks!
I was excited to know that Ramone library supports json-patch operations but when I tried it, I got following error:
415- Unsupported Media Type
This is the same error that I get when I use RestSharp. I thought may be RestSharp does not support json-patch and errors out so I decided to try Ramone lib but I still get same error. Endpoint has no issues because when I try same command using Postman, it works but when I try it programmatically in C#, it throws unsupported media type error. Here is my code:
var authenticator = new TokenProvider("gfdsfdsfdsafdsafsadfsdrj5o97jgvegh", "sadfdsafdsafdsfgfdhgfhehrerhgJ");
JsonPatchDocument patch = new JsonPatchDocument<MetaData>();
patch.Add("/Resident2", "Boyle");
//patch.Replace("/Resident", "Boyle");
RSession = RamoneConfiguration.NewSession(new Uri("https://api.box.com"));
RSession.DefaultRequestMediaType = MediaType.ApplicationJson;
RSession.DefaultResponseMediaType = MediaType.ApplicationJson;
Ramone.Request ramonerequest = RSession.Bind("/2.0/files/323433290812/metadata");
ramonerequest.Header("Authorization", "Bearer " + authenticator.GetAccessToken(code).AccessToken);
//var ramoneresponse = ramonerequest.Patch(patch); //results in error: 405 - Method Not Allowed
var ramoneresponse = ramonerequest.Put(patch); //results in error: 415 - Unsupported Media Type
var responsebody = ramoneresponse.Body
Endpoint information is available here: http://developers.box.com/metadata-api
I used json-patch section in the following article as a reference:
http://elfisk.dk/Ramone/Documentation/Ramone.pdf
By the way I tried Patch() method (as shown in above ref. article) but that resulted in "Method not allowed" so I used Put() method which seems to work but then errors out because of json-patch operation.
Any help, guidance, tips in resolving this problem will be highly appreciated. Thanks much in advance.
-Sham
The Box documentation says you should use PUT (which is quite a bit funny). The server even tells you that it doesn't support the HTTP PATCH method (405 Method Not Allowed) - so PUT it must be.
Now, you tell Ramone to use JSON all the time (RSession.DefaultRequestMediaType = MediaType.ApplicationJson), so you end up PUT'ing a JSON document to Box - where you should be PUT'ing a JSON-Patch document.
Drop the "RSession.DefaultRequestMediaType = MediaType.ApplicationJson" statement and send the patch document as JSON-Patch with the use of: ramonerequest.ContentType("application/json-patch+json").Put(...).

C# code completion with NRefactory 5

I just found out about NRefactory 5 and I would guess, that it is the most suitable solution for my current problem. At the moment I'm developing a little C# scripting application for which I would like to provide code completion. Until recently I've done this using the "Roslyn" project from Microsoft. But as the latest update of this project requires .Net Framework 4.5 I can't use this any more as I would like the app to run under Win XP as well. So I have to switch to another technology here.
My problem is not the compilation stuff. This can be done, with some more effort, by .Net CodeDomProvider as well. The problem ist the code completion stuff. As far as I know, NRefactory 5 provides everything that is required to provide code completion (parser, type system etc.) but I just can't figure out how to use it. I took a look at SharpDevelop source code but they don't use NRefactory 5 for code completion there, they only use it as decompiler. As I couldn't find an example on how to use it for code completion in the net as well I thought that I might find some help here.
The situation is as follows. I have one single file containing the script code. Actually it is not even a file but a string which I get from the editor control (by the way: I'm using AvalonEdit for this. Great editor!) and some assemblies that needs to get referenced. So, no solution files, no project files etc. just one string of source code and the assemblies.
I've taken a look at the Demo that comes with NRefactory 5 and the article on code project and got up with something like this:
var unresolvedTypeSystem = syntaxTree.ToTypeSystem();
IProjectContent pc = new CSharpProjectContent();
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(unresolvedTypeSystem);
// Add referenced assemblies:
pc = pc.AddAssemblyReferences(new CecilLoader().LoadAssemblyFile(
System.Reflection.Assembly.GetAssembly(typeof(Object)).Location));
My problem is that I have no clue on how to go on. I'm not even sure if it is the right approach to accomplish my goal. How to use the CSharpCompletionEngine? What else is required? etc. You see there are many things that are very unclear at the moment and I hope you can bring some light into this.
Thank you all very much in advance!
I've just compiled and example project that does C# code completion with AvalonEdit and NRefactory.
It can be found on Github here.
Take a look at method ICSharpCode.NRefactory.CSharp.CodeCompletion.CreateEngine. You need to create an instance of CSharpCompletionEngine and pass in the correct document and the resolvers. I managed to get it working for CTRL+Space compltition scenario. However I am having troubles with references to types that are in other namespaces. It looks like CSharpTypeResolveContext does not take into account the using namespace statements - If I resolve the references with CSharpAstResolver, they are resolved OK, but I am unable to correctly use this resolver in code completition scenario...
UPDATE #1:
I've just managed to get the working by obtaining resolver from unresolved fail.
Here is the snippet:
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var resolver3 = unresolvedFile.GetResolver(cmp, loc); // get the resolver from unresolvedFile
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
Update #2:
Here is the complete method. It references classes from unit test projects, sou you would need to reference/copy them into your project:
public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
{
var doc = new ReadOnlyDocument(editorText);
var location = doc.GetLocation(offset);
string parsedText = editorText; // TODO: Why there are different values in test cases?
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze();
var unresolvedFile = syntaxTree.ToTypeSystem();
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
IProjectContent pctx = new CSharpProjectContent();
var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value};
pctx = pctx.AddAssemblyReferences(refs);
pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation();
var resolver3 = unresolvedFile.GetResolver(cmp, location);
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
var data = engine.GetCompletionData(offset, controlSpace: false);
return data;
}
}
Hope it helps,
Matra
NRefactory 5 is being used in SharpDevelop 5. The source code for SharpDevelop 5 is currently available in the newNR branch on github. I would take a look at the CSharpCompletionBinding class which has code to display a completion list window using information from NRefactory's CSharpCompletionEngine.

DotNetCharting exception thrown

I am using DotNetCharting version 4.2. I am trying to create a chart, save it to disk and return the path as a string. Here is a simplified version of my code thus far.
Chart aChart = new Chart();
aChart aChart.Title = "Some Title";
aChart aChart.ChartArea.Background = new Background(Color.White);
aChart.TempDirectory = "C:\\temp\\"
aChart.Width = chartWidth;
aChart.Height = chartHeight;
imageName = aChart.FileManager.SaveImage();
I got this from this dotnetCharting support page. It is very straightforward code.
Here is the problem: The code above actually DOES create an image in the appropriate directory. This is NOT a directory permissions issue. When I add my actual data to the aChart, it actually DOES add it and an image is created. However, the SaveImage() method always throws an exception of "Failed to map the path '/'." The SaveImage() method is supposed to return a String, however, it always returns "" and the exception is thrown.
More Info: I am doing this in a WCF Service. Is it possible that since it's in a service the dotNetCharting DLL is having trouble with some internal MapPath?
I just upgraded the DotNetCharting to the latest version (7.0) and now it works fine. I believe that it was an issue with the old version of the DLL. I'll leave this here in case anyone else has this issue.

Categories

Resources