Issue using RazorEngine with a dynamic model composed using JSON.net - asp.net-mvc

I am using Json.net to convert a json string into a dynamic. When I use this dynamic as a model for a Razor template, I am getting an error...
Unable to compile template. 'Newtonsoft.Json.Linq.JObject' does not
contain a definition for 'Name' and no extension method 'Name'
accepting a first argument of type 'Newtonsoft.Json.Linq.JObject'
could be found (are you missing a using directive or an assembly
reference?)
If I just use a simple anonymous object as the model, it works fine.
Here is the problem displayed in a simple console app where I used NuGet to pull in two libraries...Newtonsoft JSON and RazorEngine.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// template used for generation
var template = "<div>Hello #Model.Name</div>";
// create model
dynamic model = new System.Dynamic.ExpandoObject();
model.Name = "Foo";
// this works just fine
RazorEngine.Razor.Parse(template, model);
// convert model to string
var json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
// regenerate model
model = Newtonsoft.Json.Linq.JObject.Parse(json);
// this prints 'Foo' to the console just fine so the model is valid!
string name = model.Name;
System.Diagnostics.Debug.WriteLine(name);
// this throws the error above!
RazorEngine.Razor.Parse(template, model);
}
}
}
Can someone help me with the problem here?

You can't directly pass the JObjects into the RazorEngine because whenever you assign a value to the JObject they are stored as type JValue. When you try to retrieve the assigned value also you will get a JValue not the assigned one.
Ex.
dynamic person = new JObject();
person.Name = "Vijay";
Console.WriteLine(person.Name.GetType());
==> NewtonSoft.Json.Linq.JValue

Related

No parameterless constructor defined for this object error when using HttpPost in F# mvc 5

Using the F# MVC 5 Visual Studio extension and it works perfect for GET requests. However, I'm getting a No parameterless constructor defined for this object error when trying to perform a POST.
Here's the method in the HomeController:
[<HttpPost>]
member this.Edit product =
Products.updateProduct product
this.RedirectToAction("Index")
Here's the Product type it's using where I guess the problem is originating:
type Product = {
ProductId: int
ProductName: string
ProductCount: int
ProductPrice: string
}
Is it possible to fix this within the type or is there something else I'm missing?

TFS Build 2013 - Variable scope and custom activities

I was trying to do something similar to the stackoverflow article referenced below and am finding I can't set values in the code activity. I seem to be able to read values OK. I suspect this has something to do with the scope of these. In the stackoverflow article the code implied that the variable was set for the loop,
I am after guidance on how to set these correctly or a way for my codeactivity to flag to exit the external DoWhile loop ?
Refs
StackOverflow Article
Code Activity article
OK here is the missing story and is not in the MS doco that I have found..
e.g. https://msdn.microsoft.com/en-us/library/dd647551(v=vs.120).aspx
Although MS document In, InOut, Out args their scope is not shared... i.e.
WRONG View of the world
XAML argument like MyBoolInOut Inout is the same argument that the C# code is using , e.g.
public InOutArgument MyBoolInOut { get; set; }
thus you only need to change values in C# code to change the values in the TFS XAML
Correct view of this handling
The custom code activity variables are visible in the XAML BUT are different from the XAML arguments. i.e.
as below, your C# codeactivity args have to be manually linked to the XAML args
So even though XAML has arguments and C# have arguments, these are separate.
This is an area MS could greatly improve their doco in.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
namespace SampleActivityLibrary
{
[BuildActivity(HostEnvironmentOption.All)]
// Sample Acitivty that will Flip a bool from True to False or from False to True
public sealed class SampleFlipInOutBoolean : CodeActivity<Boolean>
{
public InOutArgument<Boolean> MyBoolInOut { get; set; }
protected override Boolean Execute(CodeActivityContext context)
{
Boolean MyBool = context.GetValue(MyBoolInOut);
context.TrackBuildWarning("SampleFlipInOutBoolean: In Value of Bool: " + MyBool.ToString(), BuildMessageImportance.High);
MyBoolInOut.Set(context, !MyBool);
MyBool = context.GetValue(MyBoolInOut);
context.TrackBuildWarning("SampleFlipInOutBoolean: Out Value of Bool: " + MyBool.ToString(), BuildMessageImportance.High);
return MyBool;
}
}
}

Struts2 annotation with parameter when using json plugin

Simply I want to evaluate a property of my action and use it's value within an annotation.
The following is exactly where I want to use it.
I want to define a excludeProperties parameter at run time.
Consider the following annotation which currently works on the action:
#Result(name = "success", type = "json", params = {"root", "model", "excludeProperties", "myCollection"})
There the actions model has a myCollection collection which I do not want serialized.
However I would like to create an exclusion String (a string will do for now).
If I create a getter setter for exclusion, I would expect the following annotation to work (which does not):
#Result(name = "success", type = "json", params = {"root", "model", "excludeProperties", "${exclusion}"})
Any ideas?
I have created actions similar to this answer which shows resolving a parameter within an annotation. I am using the named variable pattern matcher to extract values from the namespace... but I just can't seem to set this parameter no matter what I do.
Part of the issue was that I was working with entity objects and serializing collections was an issue. With your own custom JSON result type you can do what ever you want. Since created getter setter for jsonModel, I just constructed what I needed there. I don't need to worry about lazy initialization errors because you need to explicitly include collections with flexjson so if you just want the primitives (which I did) then flexjson is perfect.
This very simple result type using flexjson which worked for my needs:
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;
import flexjson.JSONSerializer;
import java.io.PrintWriter;
import org.apache.struts2.ServletActionContext;
public class Kjson implements Result {
#Override
public void execute(ActionInvocation invocation) throws Exception {
ServletActionContext.getResponse().setContentType("text/plain");
PrintWriter responseStream = ServletActionContext.getResponse().getWriter();
ValueStack valueStack = invocation.getStack();
Object jsonModel = valueStack.findValue("jsonModel");
//create json and put it into response stream
responseStream.println(new JSONSerializer().exclude("class").serialize(jsonModel));
}
}

weird behavior using f# class with redis service stack lib

I'm testing a bit redis using .Net, I've read this tutorial
http://www.d80.co.uk/post/2011/05/12/Redis-Tutorial-with-ServiceStackRedis.aspx
and follow using c# and worked perfect, now when I'm trying translate this to f# I've a weird behavior, first I create a simple f# class (using type didn't work neither but it was expected)...basicaly the class is something like this:
//I ve used [<Class>] to
type Video (id : int, title : string , image : string , url : string) =
member this.Id = id
member this.Title = title
member this.Image = image
member this.Url = url
when I run the code, my db save an empty data, if I use a c# class inside my f# code this work, so I'm sure than the problem is the f# class...How can resolve this without depend c# code inside my f# code
Thanks !!!
Based on your tutorial, it looks like you want your F# Video class to be full of getter and setter properties instead of having a constructor with getters only as it is now (and it is a class, which you can verify by running it through FSI).
You can achieve this using a record type full of mutable fields (which is compiled down to a class type full of public getters and setters):
type Video = {
mutable Id : int
mutable Title : string
mutable Image : byte[]
mutable Url : string
}

I get the following error, when trying to use C# Lambda extension method All

private void EnsureCurrentlyValid()
{
//I'm valid if IDataErrorInfo.this[] returns null for every property
var propsToValidate = new[] { "Name", "Email", "Phone", "WillAttend" };
bool isValid = propsToValidate.All(x => this[x] == null);
if (!isValid)
throw new InvalidOperationException("Can't submit invalid GuestResponse");
}
'System.Array' does not contain a definition for 'All' and no extension method 'All' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) C:\dev\aspnet\PartyInvites\Models\GuestResponse.cs
What am I missing?
Add this to the top of your file:
using System.Linq;
All is an extension method defined on Enumerable. The extension methods (including All) are defined in the System.Linq namespace, so you need to include a using directive for System.Linq to your class in order to reference the extension methods. You'll also need to be using C# 3.0 and .NET 3.5.

Resources