Menu
  • HOME
  • TAGS

Referencing Newtonsoft.Json from TypeProvider

Tag: f#,json.net,type-providers

I am trying to create Type Provider which uses Newtonsoft.Json. There is Provided Constructor accepting JObject:

let constr = ProvidedConstructor([ProvidedParameter("json",typeof<JObject>)])  
constr.InvokeCode <- fun args -> 
    <@@
        let jObject = %%args.[0]:JObject
        jObject
    @@>

Client code :

type ProvidedType = MyProvider<"source.file">
let json = JObject.Parse(str)
let objct = ProvidedType("""{ "name" = "foo bar" }""")

It fails in design time with the following error:

Type mismatch when splicing expression into quotation literal. The type of the
expression tree being inserted doesn't match the type expected by the splicing
operation. 
Expected 'Newtonsoft.Json.Linq.JObject', but received type 
'Newtonsoft.Json.Linq.JObject'. 
Consider type-annotating with the expected expression type, e.g., 
(%% x : string) or (%x : string).

When debugging the type provider, I can see that there are two versions of Newtonsoft.Json.dll: version 6.0.3.17227 from nuget download location in my project and version 4.5.11.15520 from C:\Program Files\Common Files\Microsoft Shared\Visual Studio\12.0\Newtonsoft.Json.dll.

The later, apparently, is loaded by Visual Studio 2013 Update 2 for Json editor.

Both client and type provider assembly specify version redirect:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.3.0" />
</dependentAssembly>

How do I solve this?

EDIT:

Turns out that just getting rid of VS version of Json.NET is not a good solution. VS throws exception on start which it hides until you try to login with different account. I don't even want to try and guess the logic behind it, the short answer is - don't mess with VS.

For the Type Provider, the workaround is to replace JObject with a string in all TP-provided methods and parse it into JObject inside the implementation.

Let's hope VS team will do something about it.

Best How To :

Check if the NewtonSoft.Json in the Visual Studio directory should actually be there. I had amazing pain trying to develop a type provider at one point, until I realised that for several days 3 months earlier NuGet had been unpacking all of the dependencies of anything I installed to C:\Program Files\Common Files\Microsoft Shared\Visual Studio\12.0\ - and those got loaded before the type provider could load anything. As a (very small) consolation prize, if you have the same issue as me the TP will run in FSI/compiled code - just not in Visual Studio.

Does let!/do! always run the async object in a new thread?

f#

Which part of that statement do you find surprising? That parts of a single async can execute on different threadpool threads, or that a threadpool thread is necessarily being released and obtained on each bind? If it's the latter, then I agree - it sounds wrong. Looking at the code,...

shift/reduce and reduce/reduce errors in F# using fsyacc and fslex

parsing,f#,dsl,lexer,fsyacc

First, your Expression non-terminal has two identical productions: Expression: | IDENTIFIER ASSIGN Expression { ScalarAssignmentExpression($1, $3) } | IDENTIFIER ASSIGN Expression { ArrayAssignmentExpression($1, $3) } So there is absolutely no way for the parser to distinguish between them, and thus know which action to take. I suppose you can tell...

F# Discriminated Union - “downcasting” to subtype

f#,discriminated-union

This is a common mistake when coming from an OO language: there are no subtypes involved in this code. The fact that you named your union cases the same as the type of the field they contain can make this confusing though, so let me give a slightly different example:...

Filtering a sequence of options and collecting the values of all the Somes. Is there a built-in function in F# for that?

.net,f#

The easiest way is to use Seq.choose s |> Seq.choose id Here we use id as the input is the same as the output...

Return to the same view when no image is selected

asp.net-mvc-4,razor,json.net,entity-framework-5,c#-5.0

Add a ModelState error and return the view (otherwise redirect), for example if (isSavedSuccessfully) { return Redirect(Url.Action("Edit", "Account") + "#tabs-2"); } else { ModelState.AddModelError("Image", "your message"); return View(user); } ...

Produce different serialized JSON for a given class in different scenarios

c#,json,serialization,asp.net-mvc-5,json.net

I finally went with a mix of Wrapper classes and the methodology suggested by Raphaël Althaus: use Wrappers where some amount of sophistication may be required and use Raphaël's suggestion when simplicity will do. Here's how I am using wrappers (intentionally left out null checks): public class Entity1View1 { protected...

Deserialize RestResponse to JSON data

c#,json.net

You just need to deserialise the JSON into your class. Assuming your class is called Foo, just use the JavaScriptSerializer object: Foo result = new JavaScriptSerializer().Deserialize<Foo>(json); You will need to add a reference to System.Web.Extensions in order to access the JavaScriptSerializer. EDIT Following additional clarification regarding the mapping of the...

How to recursively identify cells of specific type in grid?

recursion,f#,tail-recursion

This will return a set of all detonated cells including the one that started the chain reaction. module Location = type T = {Row: int; Column: int } let subtract l1 l2 = {Row=l1.Row - l2.Row;Column=l1.Column-l2.Colum let detonate (field:Field.T) (start:Cell.T) = let rec inner cells m acc = match cells...

How convert any record into a map/dictionary in F#?

dictionary,f#,converter,record

In practice, the best advice is probably to use some existing serialization library like FsPickler. However, if you really want to write your own serialization for records, then GetRecordFields (as mentioned in the comments) is the way to go. The following takes a record and creates a map from string...

Can't parse JSON object with Newtonsoft.JSON

c#,json,json.net

Working LinqPad example: void Main() { string obj = @"{ ""SERVER1/DeviceIpint.3/SourceEndpoint.video:0:0"" : { ""origin"" : ""SERVER1/DeviceIpint.3/SourceEndpoint.video:0:0"", ""state"" : ""connected"", ""friendlyNameLong"" : ""Camera 3"", ""friendlyNameShort"" : ""3"" }, ""SERVER2/DeviceIpint.5/SourceEndpoint.video:0:0"" : { ""origin"" : ""SERVER2/DeviceIpint.5/SourceEndpoint.video:0:0"", ""state"" : ""disconnected"", ""friendlyNameLong"" : ""Camera 5"", ""friendlyNameShort"" : ""5"" } }"; VideoSource s = new VideoSource();...

Return a modified version of same type in F#

f#

If you're looking for something both pure and idiomatic F#, then you shouldn't be using an inheritance hierarchy in the first place. That's an object-oriented concept. In F#, you could model Employee like this, using algebraic data types: type HourlyData = { Name : string; Rate : int } type...

Web API translating input into random int

c#,post,asp.net-web-api,json.net

This is a bug in JSON.NET as hinted at, but it's not as simple as it first seems. Versions prior to 5.0.4 work for both of these test cases. Anything after seems to fail but only for the first test case which is odd. I've gone through some of the...

Issues parsing a 1GB json file using JSON.NET

json,parsing,stream,json.net,large-object-heap

Thanks for all the help, I've managed to get it doing what I want which is de-serializing individual location objects. If the item is converted to a JObject it will read in the full object and de-serialize it, this can be looped to get the solution. This is the code...

Referencing event from .xaml file in .fs file

wpf,xaml,f#,fsxaml

As there's no code-behind you can't call the method from XAML but need to attach it from the outside: let AboutStack_MouseRightButtonDown args = // do whatever you want, return unit wnd.MouseRightButtonDown.Add(AboutStack_MouseRightButtonDown) or e.g. wnd.MouseRightButtonDown.Add(fun _ -> MessageBox.Show("Click!") |> ignore) Another approach would be to use a model (DataContext) and bindings...

How to handle Arithmetic operation OverflowException in F#?

python,f#

You should use bigint for large numbers, like this [1I..1234567I] |> List.filter (fun x -> x % 3I * x % 5I = 0I) |> List.sum or (less readable) [bigint 1..bigint 1234567] |> List.filter (fun x -> x % bigint 3 * x % bigint 5 = bigint 0) |>...

Is this definition of a tail recursive fibonacci function tail-recursive?

scala,f#,functional-programming,tail-recursion,continuation-passing

The second call to go on line 4 is not in tail position, it is wrapped inside an anonymous function. (It is in tail position for that function, but not for go itself.) For continuation passing style you need Proper Tail Calls, which Scala unfortunately doesn't have. (In order to...

How to accept multiple names for a single property on newtonsoft JSON de-serialization?

c#,json,json.net

You can make use of properties: class Person { protected string _Salary; public string Salary { get { return _Salary; } set { _Salary = value; } } public string Name { get; set; } } class BackwardCompatiblePerson : Person { public string Salari { get { return _Salary; }...

Newtonsoft inline formatting for subelement while serializing

c#,json.net,nsjsonserialization

Adding the converter as a JsonConverterAttribute on a class is trickier because the simplest implementation will lead to an infinite recursion as the converter calls itself. Thus it's necessary to disable the converter for recursive calls in a thread-safe manner, like so: public class NoFormattingConverter : JsonConverter { [ThreadStatic] static...

how to retrieve data from Json file and displaying it in HTML dropdown…?

javascript,json,angularjs,json.net

Firstly, your JSON is invalid due to the directory paths. Backslashes \ are escape characters. This causes the parse to fail. So simply change your JSON to { "Pipesmanuf":[ { "ManufacturerId":1, "ManufacturerName":"Avonplast", "Products":"PIPES", "ManufacturerLogo":"C:\\Users\\Suprith\\Desktop\\Manufacturerlogos\\Pipes\\avonplast.jpg" }, { "ManufacturerId":2, "ManufacturerName":"BEC", "Products":"PIPES", "ManufacturerLogo":"C:\\Users\\Suprith\\Desktop\\Manufacturerlogos\\Pipes\\BEC.png" } ] } This way you are escaping the escape...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

How to convert this JSON to a datatable?

c#,.net,json,asynchronous,json.net

The Json string you presented isn't a deserialised DataTable so you can't convert it into that object type directly. Not really sure if you absolutely need for this to be a DataTable, but if you do then here is a way. You can first get it into an array of...

How can I resolve the “Could not fix timestamps in …” “…Error: The requested feature is not implemented.”

linux,build,f#

This is usually a sign that you should update your mono. Older mono versions have issues with their unzip implementation

Why embed async in async?

f#

I can think of one reason why async code would call another async block, which is that it lets you dispose of resources earlier - when the nested block completes. To demonstrate this, here is a little helper that prints a message when Dispose is called: let printOnDispose text =...

Doc.Checkbox 'change' event does not occur in Websharper.UI.Next

web,f#,websharper

What happens is that Doc.AsPagelet adds a wrapper around the doc, so you are adding an event listener to that wrapper. And even if it did not, you would be adding an event listener to the Div0 you created instead of the CheckBox itself. That being said, there are two...

Value cannot be null when deserializing JSON

c#,winforms,json.net

Assuming your full JSON is as you show, your JSON doesn't give simple name/value pairs for name and email. Instead it has a dictionary of indexed property objects, where each object has a label property with value equal to the name of property you seek, and an adjacent value property...

Escaping quotes in Newtonsoft JSON

c#,asp.net-mvc,razor,json.net

You should not parse the string for a second time, since already serialized it as JSON, you can directly use it in Javascript (the JS in JSON). var myJson = @Html.Raw(JsonConvert.Serialize(Model.MyTest)); Will output: var myJson = {"Prop1":"\"Quoted text\""}; And, because you always need a JSFiddle to prove it works....

Querying JSON with JSONPath or SelectTokens? With JSON.NET in C#

json,json.net,querying

You can use LINQ to JSON and SelectTokens to do the required query: string json = GetJson(); var obj = JObject.Parse(json); var testEmail = "[email protected]"; var streamQuery = obj.SelectTokens("video.streams.*").Where(s => (string)s["email"] == testEmail); var firstEnabled = streamQuery.Select(s => (bool?)s["enable"]).FirstOrDefault(); The query returns a nullable bool that is true or false...

Duplicate Key in index of Deedle Series

f#,deedle

One of the design decisions we made in Deedle is that a series can be treated as a continuous series (rather than a sequence of events) and so Deedle does not allow duplicate keys (which make sense for events but not for time series). I wish there was a nicer...

What is the difference between member val and member this in F#?

.net,f#,immutability

If you try to compile the first version, and then use e.g. Reflector to decompile it to C#, you'll see that the stack member is defined like this: public class Interp { public Stack<int> stack { get { return new Stack<int>(); } } // Other members omitted for clarity... }...

F# Custom operators

f#,operator-overloading

Your operator takes an arg of type obj so you should define it as a standalone function, not a type member. let (&?) (value:obj) (defaultValue:'a) = match value with | null -> defaultValue | _ -> unbox value Now you can do this: let voltage = m.["VoltageCaps"] &? 0 I...

Why does the DeserializeXmlNode output XML enclose array elements in an extra tag?

json,xml,json.net,deserialization

It's because you have an extra [ and ] below "addresses": [ [{ "AddressLine1": "Address1", "AddressLine2": "Address2" }], [{ "AddressLine1": "Address3", "AddressLine2": "Address4" }] ] If you remove the extra [ and ] like below "addresses": [ { "AddressLine1": "Address1", "AddressLine2": "Address2" }, { "AddressLine1": "Address3", "AddressLine2": "Address4" } ]...

Duck typing with type provider instances [duplicate]

f#,type-providers,duck-typing

I'll maintain that this is a duplicate, but here's the exact code you need to get going: let inline getAllIds< ^a when ^a : not struct> (table : Table< ^a>) = table |> Seq.map (fun x -> (^a : (member Id : Guid with get) x)) Alternatively, the following syntax...

How get value from JSON string?

c#,json,json.net

You need to cast Instance to a Photo first like this: var photo = wall[0].Attachments[0].Instance as Photo if (photo != null) var uri = photo.Photo604 Of course there is no error checking here. You should check for nulls and array lengths before accessing or you may get a null reference...

Asynchronously manipulating data from streamReader in F#

asynchronous,f#,streamreader

Your Data value has a type seq<string>, which means that it is lazy. This means that when you perform some computation that accesses it, the lazy sequence will create a new instance of StreamReader and read the data independently of other computations. You can easily see this when you add...

F# - writing an (GA) evaluation function in F#

f#

you can pattern match on the list to count this up like this: let rec mismatchs xs = match xs with | [] | [_] -> 0 | (a::b::t) -> (if a > b then 1 else 0) + mismatchs (b::t) a slight problem with that is, that the function...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

Flattening nested JSON object in JSON.NET

c#,json.net

You could set up a class for variation and make VariationName a get-only property class Product { public int Id { get; set; } public string Name { get; set; } public Variation variation { get; set; } public string VariationName { get { return variation.VariationName; } } } class...

Android accessing JSONObject

java,android,arrays,json,json.net

You can handle like this: try { JSONObject _jObject = new JSONObject("YOUR_JSON_STRING"); JSONObject _jObjectSub = _jObject.getJSONObject("0"); int _id = _jObjectSub.getInt("id"); String _name = _jObjectSub.getString("name"); int _user_id = _jObjectSub.getInt("user_id"); String _created_at = _jObjectSub.getString("created_at"); String _updated_at = _jObjectSub.getString("updated_at"); JSONObject _users = _jObjectSub.getJSONObject("users"); int _idUsers = _users.getInt("id"); String _nameUsers = _users.getString("name"); String _lastNameUsers...

Populating non-serializable object with Json.NET

c#,.net,json,json.net

You can create a ContractResolver that interprets all classes as opt-out rather than opt-in: public class OptOutContractResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { return base.CreateProperties(type, MemberSerialization.OptOut); } } And then use it like: [JsonObject(MemberSerialization = MemberSerialization.OptIn)] //[DataContract] -- also works. public class TestClass { public...

Properly implement F# Unit in C#

c#,f#,functional-programming

I'm not sure what is the best way to define Unit for usage from C#. It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way). However, you can actually find the implementation of F# unit in the core library:...

interpreting a script through F#

scripting,f#,interpreted-language

I really like F# but I feel like it's not succinct and short enough. I want to go further. I do have an idea of how I'd like to improve it but I have no experience in making compilers so I thought I'd make it a scripting language. F#...

Deserialize malformed JSON with JSON.NET [duplicate]

c#,json.net

Try this: var json = "{\"123\":{\"name\":\"test\",\"info\":\"abc\"}}"; var rootObject = JsonConvert.DeserializeObject<Dictionary<string, User>>(json); var user = rootObject.Select(kvp => new User { ID = kvp.Key, Name = kvp.Value.Name, Info = kvp.Value.Info }).First(); This does have some unnecessary overhead, but considering the circumstances, it would do....

F# - Recursive function to copy a list

list,f#

Performing a lookup into the list (as well as getting the length of the list) is not very efficient, because the library needs to iterate over the entire list (or over the first N elements). For this reason, doing this is not really idiomatic in F#. You can still keep...

F# “The value of constructor … not defined”

visual-studio-2010,f#

When you use F# interactive, you first need to evaluate the code that defines the functions that you want to use. So, if you select just the last line of your script, you get an error. I suppose you are using Alt+Enter to send the code to F# interactive -...

FParsec parses only first half

parsing,f#,dsl,fparsec

You're right, the line: let ptypedef = ptypedef1 <|> ptypedef2 is the problem. ptypedef1 is consuming some of the input so attempt needs to be used to backtrack when it fails so that ptypedef2 parses the text you're expecting it to, the fixed line would look like: let ptypedef =...

Convert string[] of json object to List

c#,arrays,json,json.net

You can do that in a very simple way using Linq : var list = jsonobjects.Select(JsonConvert.DeserializeObject<T>).ToList(); ...

How to rewrite this C# code

f#

Aside from Patryk's point on comment: It's a really imperative problem so it will not get much prettier. The only thing I would try to change is the repeated read/writes - maybe like this: let copyInto (outstream : System.IO.Stream) (stream : System.IO.Stream) = let bufferLen : int = 4096 let...

F# computation expression transparent state passing with Bind

f#,computation-expression

@bytebuster is making good points of maintainability about custom computation expressions but I still thought I demonstrate how to combine the State and Maybe monad into one. In "traditional" languages we have good support for composing values such as integers but we run into problems when developing parsers (Producing values...

Serialize byte array in JSON.NET without $type

c#,json,serialization,json.net

One way to fix this would be to use a custom converter for byte[]: public class ByteArrayConverter : JsonConverter { public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer) { string base64String...

All the F# templates in VS 2015 RC disappear

templates,f#,visual-studio-2015

That's a bug in 2015 RC. It's already fixed, but we need to wait for another release. https://github.com/Microsoft/visualfsharp/issues/411