I need to add System.Web.Script.Serialization and System.Web.Extensions to my function app so that I can deserialize json string using the following code :
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
This does not work :
#r "System.Web.Script.Serialization"
#r "System.Web.Extensions"
How do I add resolve this issue?
I can't get that work, so I ended up using Newtonsoft Json serializer/deserializer. What you need to do is, follow this instruction to upload project.json file to your function app with this content -
{
"frameworks": {
"net46":{
"dependencies": {
"Newtonsoft.Json": "9.0.1"
}
}
}
}
This basically creates dependency. Then add this name space to your code : "using Newtonsoft.Json.Linq". Voila, you can convert your json string to object like this :
dynamic item = JObject.Parse("{number:1000}");
log.Info($"My number is: {item.number}");
The initial reference likely failed because you were trying to add an assembly reference to System.Web.Script.Serialization, which is a namespace. Adding a reference to System.Web.Extensions should work, but using Json.NET is recommended anyway.
Related
I'm trying to create a custom html helper class.
I have the below as a very simple start, complies fine:
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Mobile.HtmlHelpers
{
public static class RequestBox
{
public static HtmlString CascadeBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
HtmlString html = (HtmlString)HtmlHelperInputExtensions.TextBoxFor(helper, expression);
return html;
}
// IHtmlContent html = HtmlHelperInputExtensions.TextBoxFor(htmlHelper, expression);
}
}
I am trying to call it and the system doesn't like it..
I can see it if I use:
#foreach (var item in Model.RequestModel.Requests)
{
#RequestBox.CascadeBoxFor(x=>item.EmployeeDescription)
}
But I get:
Severity Code Description Project File Line Suppression State
Error CS7036 There is no argument given that corresponds to the required formal parameter 'expression' of 'RequestBox.CascadeBoxFor<TModel, TValue>(HtmlHelper, Expression<Func<TModel, TValue>>, object)' Mobile..NET Framework 4.6.1
If I try suggestions of it being an extension and I should be able to use #Html.CascadeBoxFor(x => item.EmployeeDescription), I get:
Severity Code Description Project File Line Suppression State
Error CS1061 'IHtmlHelper<RequestPageModel>' does not contain a definition for 'CascadeBoxFor' and no extension method 'CascadeBoxFor' accepting a first argument of type 'IHtmlHelper<RequestPageModel>' could be found (are you missing a using directive or an assembly reference?) Mobile..NET Framework 4.6.1
Can anyone tell me what is missing here?
I'm trying to output information from my database to an Excel File using ASP.Net 5. In my controller I have two methods for this.
public void ExportData()
{
var data = new[]{
new{ Name="Ram", Email="ram#techbrij.com", Phone="111-222-3333" },
new{ Name="Shyam", Email="shyam#techbrij.com", Phone="159-222-1596" },
new{ Name="Mohan", Email="mohan#techbrij.com", Phone="456-222-4569" },
new{ Name="Sohan", Email="sohan#techbrij.com", Phone="789-456-3333" },
new{ Name="Karan", Email="karan#techbrij.com", Phone="111-222-1234" },
new{ Name="Brij", Email="brij#techbrij.com", Phone="111-222-3333" }
};
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Contact.xls");
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/vnd.ms-excel");
WriteTsv(data, System.Web.HttpContext.Current.Response.Output);
System.Web.HttpContext.Current.Response.End();
}
public void WriteTsv<T>(IEnumerable<T> data, TextWriter output)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.DisplayName); // header
output.Write("\t");
}
output.WriteLine();
foreach (T item in data)
{
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.Converter.ConvertToString(
prop.GetValue(item)));
output.Write("\t");
}
output.WriteLine();
}
}
I am forced to use System.Web because I have no idea how to export an excel file using ASP.Net 5, thus I'm currently using dnx451. I deleted dnxcore50 from my project.json in order to use System.Web.
However when calling the top method, I get the following error:
NullReferenceException: Object reference not set to an instance of an object.
on
System.Web.HttpContext.Current.Response.ClearContent();
The original example of this code used:
Response
Instead of:
System.Web.HttpContext.Current.Response
I cannot use just use Response because it uses Microsoft.AspNet.Http.HttpResponse instead of System.Web
Using System.Web.HttpResponse also doesn't work because it gives the following error:
An object reference is required for the non-static field, method, or property
This is my first web application and this problem has caused me to grind into a halt. Can anyone help me?
You can't use System.Web. One of the goals of ASP.Net Core was to remove the dependency on System.Web. Since ASP.Net Core is does not depend on System.Web the HttpContext et al. won't be initialized and hence NRE. You can use IHttpContextAccessor to get HttpContext in ASP.Net Core and access the Response from there.
I have read the documentation but I can't quite seem to get the skipPrefix to work with xml2js. What I would like do to do is given the following xml remove the namespace prefix.
<root>
<part:tire>A</part:tire>
</root>
I would like the json object to exclude "part:".
Thanks
From the source code
prefixMatch = new RegExp(/(?!xmlns)^.*:/);
...
exports.stripPrefix = function(str) {
return str.replace(prefixMatch, '');
};
i think your xml string need to have proper namespace in order for that feature to work.
I'm working with the revit api, and one of its problems is that it locks the .dll once the command's run. You have to exit revit before the command can be rebuilt, very time consuming.
After some research, I came across this post on GitHub, that streams the command .dll into memory, thus hiding it from Revit. Letting you rebuild the VS project as much as you like.
The AutoReload Class impliments the revit IExteneralCommand Class which is the link into the Revit Program.
But the AutoReload class hides the actual source DLL from revit. So revit can't lock the DLL and lets one rebuilt the source file.
Only problem is I cant figure out how to implement it, and have revit execute the command. I guess my C# general knowledge is still too limited.
I created an entry in the RevitAddin.addin manifest that points to the AutoReload Method command, but nothing happens.
I've tried to follow all the comments in the posted code, but nothing seems to work; and no luck finding a contact for the developer.
Found at: https://gist.github.com/6084730.git
using System;
namespace Mine
{
// helper class
public class PluginData
{
public DateTime _creation_time;
public Autodesk.Revit.UI.IExternalCommand _instance;
public PluginData(Autodesk.Revit.UI.IExternalCommand instance)
{
_instance = instance;
}
}
//
// Base class for auto-reloading external commands that reside in other dll's
// (that Revit never knows about, and therefore cannot lock)
//
public class AutoReload : Autodesk.Revit.UI.IExternalCommand
{
// keep a static dictionary of loaded modules (so the data persists between calls to Execute)
static System.Collections.Generic.Dictionary<string, PluginData> _dictionary;
String _path; // to the dll
String _class_full_name;
public AutoReload(String path, String class_full_name)
{
if (_dictionary == null)
{
_dictionary = new System.Collections.Generic.Dictionary<string, PluginData>();
}
if (!_dictionary.ContainsKey(class_full_name))
{
PluginData data = new PluginData(null);
_dictionary.Add(class_full_name, data);
}
_path = path;
_class_full_name = class_full_name;
}
public Autodesk.Revit.UI.Result Execute(
Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message,
Autodesk.Revit.DB.ElementSet elements)
{
PluginData data = _dictionary[_class_full_name];
DateTime creation_time = new System.IO.FileInfo(_path).LastWriteTime;
if (creation_time.CompareTo(data._creation_time) > 0)
{
// dll file has been modified, or this is the first time we execute this command.
data._creation_time = creation_time;
byte[] assembly_bytes = System.IO.File.ReadAllBytes(_path);
System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(assembly_bytes);
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass && type.FullName == _class_full_name)
{
data._instance = Activator.CreateInstance(type) as Autodesk.Revit.UI.IExternalCommand;
break;
}
}
}
// now actually call the command
return data._instance.Execute(commandData, ref message, elements);
}
}
//
// Derive a class from AutoReload for every auto-reloadable command. Hardcode the path
// to the dll and the full name of the IExternalCommand class in the constructor of the base class.
//
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
public class AutoReloadExample : AutoReload
{
public AutoReloadExample()
: base("C:\\revit2014plugins\\ExampleCommand.dll", "Mine.ExampleCommand")
{
}
}
}
There is an easier approach: Add-in Manager
Go to Revit Developer Center and download the Revit SDK, unzip/install it, the check at \Revit 2016 SDK\Add-In Manager folder. With this tool you can load/reload DLLs without having to modify your code.
There is also some additional information at this blog post.
this is how you can use the above code:
Create a new VS class project; name it anything (eg. AutoLoad)
Copy&Paste the above code in-between the namespace region
reference revitapi.dll & revitapiui.dll
Scroll down to AutoReloadExample class and replace the path to point
your dll
Replace "Mine.ExampleCommand" with your plugins namespace.mainclass
Build the solution
Create an .addin manifest to point this new loader (eg.
AutoLoad.dll)
your .addin should include "FullClassName" AutoLoad.AutoReloadExample
This method uses reflection to create an instance of your plugin and prevent Revit to lock your dll file! You can add more of your commands just by adding new classes like AutoReloadExample and point them with seperate .addin files.
Cheers
Another question on migrating code from v3 to v4:
For v3, I had a customized error reporting, using code like this (in the grammar file):
#members {
public void displayRecognitionError(String[] tokenNames,
RecognitionException e) {
String hdr = getErrorHeader(e);
String msg = getErrorMessage(e, tokenNames);
System.out.println("ERR:"+hdr+":"+msg);
errCount += 1;
}
}
In v4, when compiling the generated java files, I am getting the error:
MyParser.java:163: cannot find symbol
symbol : method getErrorMessage(org.antlr.v4.runtime.RecognitionException,java.lang.String[])
location: class MyParser
String msg = getErrorMessage(e, tokenNames);
^
Is this function replaced by some other function in v4? (I saw some questions and answers on ANTLRErrorListener, but I could not get how to use it for my situation.)
The displayRecognitionError method was removed in ANTLR 4, so even if you correct the body of that method it will not do anything. You need to remove the method from your grammar entirely, and implement ANTLRErrorListener instead. The documentation includes a list of classes that implement the interface, so you can reference those and/or extend one of them to produce the desired functionality.
Once you have an instance of an ANTLRErrorListener, you can use the following code to attach it to a Parser instance.
// remove the default error listener
parser.removeErrorListeners();
// add your custom error listener
parser.addErrorListener(listener);