Search with SharePoint CSOM (portable) throws an exception - c#

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

Related

Stackoverflow exception in JSON.net

I am using MongoDB + C# + Knockout. Recently I have added new column "SubmitCount" of data type "int" in my existing database (MongoDB).
When I query mongodb using C#, it is giving me Stackoverflow exception with no stack trace. I figured out it is giving me exception at:
var query = Query.EQ("Shelf", "Create");
var result = CollectionName.FindAs<BsonDocument>(query);
//Throwing exception at below line
var trialList = (from clnTrial in result
select new { TrialID = clnTrial["TrialID"].ToString(), CreatedBy = clnTrial["CreatedBy"].ToString() }).Distinct().ToList();
It was working properly before adding new column.
I searched a lot but found nothing. Any help would be appreciated.
EDIT: I just rerun the code removing "ToList()" now it is not giving exception. :-/. But I need ToList().
This is bit weird. But After trying all possible solutions, I noticed that NewtonSoft.JSON dll I was using was not of latest version.
I updated DLL through Nuget and Bingo! it starts working again.
Some suggestion for updating NewtonSoft.JSON dll
First uninstall old one and then update to latest one.
If you get FileLoadException for referring two NewtonSoft.JSON dll of different version then try this solution FileLoadException was unhandled by user code

Getting MissingMethodException when using Manatee.trello to get list of users

I have the following code which is intended to fetch a list of all the user of an organisation.
public static IEnumerable<Member> ListTrelloUsers()
{
var serializer = new ManateeSerializer();
TrelloConfiguration.Serializer = serializer;
TrelloConfiguration.Deserializer = serializer;
TrelloConfiguration.JsonFactory = new ManateeFactory();
TrelloConfiguration.RestClientProvider = new RestSharpClientProvider();
TrelloAuthorization.Default.AppKey = ApplicationKey;
TrelloAuthorization.Default.UserToken = GrandToken;
var myOrganization = Member.Me.Organizations.FirstOrDefault().Id; //Exception thrown here.
var orgToAddTo = new Organization(myOrganization);
return orgToAddTo.Members.AsEnumerable();
}
But I'm getting a
System.MissingMethodException
thrown on
RestSharp.IRestRequest RestSharp.RestRequest.AddFile(System.String, Byte[], System.String)
So why is this exception thrown and what should the correctly working code look like?
Clarifications
I will also accept working C#/ASP.Net MVC code that isn't based on Manatee.Trello as an answer. (Including pure API-calls.)
I have tried using the Organisation ID directly as
var orgToAddTo = new Organization(OrganisationId);
but that just caused the same exception to be thrown later when I make a call to the method's returned object (e.g. using Count()).
UPDATE: I tried setting the build to Release instead of Debug and now the (same) exception is instead thrown at
TrelloConfiguration.RestClientProvider = new RestSharpClientProvider();
This is an issue with RestSharp that I reported quite some time ago, though they deny that it's a problem. If you're using .Net 4.5+, you can try the Manatee.Trello.WebApi package instead of Manatee.Trello.RestSharp.
TrelloConfiguration.RestProvider = new WebApiClientProvider();
Here's my Trello card for tracking the issue. This and this are the RestSharp issues I created.
I have been able to recreate this as well, but have received no help from them to resolve it.
Apperently, the class with missing method is located in an assembly, which differ from the one, which you used while compiling the project. Double check and make sure both at compiling and at execution you use the same assembly with the aforementioned class.
That is my best clue based on the info you've provided.
basically, check project references and make sure, you use correct ones for the class-holding assembly.

DotNetRDF & AllegroGraph

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

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(...).

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