How to parse Json in C# Web as open Source - c#

net and i just want to read a Json and want to update or add the nodes in JSON. I have used Angular and PHP for this and i was able to read and write the file easily. But My server is now IIS, So i want to parse JSON file on C# and want to change the values in it.
I googled a lot and found a lot of solution for JSON.NET or Newtonsoft.Json. I have only one index.aspx page, where i am successfully able to read the json file as below
string json = System.IO.File.ReadAllText(Server.MapPath("json/myJsonFile.json"));
Response.Write(json);
And this is printing JSON text in web easily. But i am not able to parse it properly. I am writing code in Notepad++, as i don't have Visual Studio and don't want to install. I heard that .net code is open source now, So i tried this from Notepad++. Now please let me know, how to Parse JSON without using Visual Studio?
My code in more detail is as below
index.aspx
<%# Page Language="C#" %>
<!Doctype html>
<html>
<body>
<form action="index.aspx" method="post" enctype="multipart/form-data" runat="server">
<input type="text" id="empname" name="empname" placeholder="Enter Full Name"/>
<p><button id="addBtn" class="btn btn-success" onclick='return addEmployee()' type="submit">Add</button> <button id="removeBtn" class="btn btn-success" onclick='removeEmployee()'>Remove</button></p>
</form>
<%
string ename = Request.Form["empname"];
string json = System.IO.File.ReadAllText(Server.MapPath("json/myJsonFile.json"));
Response.Write(json);
//Here i want to parse JSON file
%>
</body>
</html>
Javascript
function addEmployee()
{
if($("#empname").val() == "")
{
alert("Please type Name.");
$("#empname").focus();
return false;
}
return true;
}
JSON
[
{
"ID": "ID01",
"Name": "First One"
},
{
"ID": "ID02",
"Name": "Second One"
}
]
Remember i am writing code in Notepad++, So please let me know accordingly. Thanks in advance.

JavaScriptSerializer has been deprecated and Microsoft recommends using Json.NET.
Download Json.NET here.
In your aspx page link to Json.NET:
<%# Assembly Name="Newtonsoft.Json" %>
<%# Import namespace="Newtonsoft.Json" %>
Make a class for Employee:
public class Employee
{
public string ID { get; set; }
public string Name { get; set; }
}
Add a reference to Json.NET:
using Newtonsoft.Json;
Deserialize your Json from disk:
List<Employee> list = JsonConvert.DeserializeObject<List<Employee>>(json);
// ...
list.Add(employee);
// deserialize + save
string json = JsonConvert.SerializeObject(list);

Related

How to read an HTML file into an angular component so as to allow for the updating of the HTML file without redeploying code

I am trying to have a HTML file in my assets folder that is nothing but some header tags, dates and feature lists to serve as release notes for our website. I have an angular modal component that I want to read this file each time its route is called, rather than the alternative of having the HTML in the component itself which would require us to redeploy anytime we updated the release notes.
As mentioned I originally had this as part of my components HTML file but this was then being compiled into javascript each time and unable to be updated without a redeploy. Everything I have tried to search for doing something similar seems to be pointing me to just doing it that way.
ReleaseNotes.html
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<body>
<h1>Example header one</h1>
<h3>03/01/2019</h3>
<h4>Patch 1.03 Title</h4>
<ul>
<li>Feature that was added</li>
<li>Feature that was added</li>
<li>Feature that was added</li>
</ul>
<hr>
release-notes-modal.component.ts
export class ReleaseNotesModalComponent implements OnInit {
faTimesCircle = faTimesCircle;
contents: string;
constructor(public dialogRef: MatDialogRef<ReleaseNotesModalComponent>) {
//this.contents = System.IO.File.ReadAllText("ReleaseNotes.html");
}
ngOnInit() {
}
close() {
this.dialogRef.close();
}
}
There are a few ways you can accomplish this. This is how I've done this in the past.
In a Controller in the c# application, you would read the html file and return it:
[HttpGet]
[Route("releasenotes")]
public async Task<IActionResult> ReadReleaseNotes()
{
var viewPath = Path.GetFullPath(Path.Combine(HostingEnvironment.WebRootPath, $#"..\Views\Home\releasenotes.html"));
var viewContents = await System.IO.File.ReadAllTextAsync(viewPath).ConfigureAwait(false);
return Content(viewContents, "text/html");
}
Then in the angular application in a service you would call this method and retrieve this file as follows:
getReleaseNotes(): Observable<string> {
return this.http
.get([INSERT_BASE_URL_HERE] + '/releasenotes', { responseType: 'text' });
}
You can then utilize that in the ReleaseNotesModalComponent through something like this:
#Component({
template: '<span [innerHTML]="contents"></span>'
})
export class ReleaseNotesModalComponent implements OnInit {
faTimesCircle = faTimesCircle;
contents: string;
constructor(public dialogRef: MatDialogRef<ReleaseNotesModalComponent>, private service: ReleaseNotesService) {
service.getReleaseNotes(html => this.contents = html);
}
ngOnInit() {
}
close() {
this.dialogRef.close();
}
}
For the Angular side of things, I created a StackBlitz example.

Can I use JSON.Stringify in code-behind of an ASP.Net project?

In the code-behind of an ASP.NET project (MVP-pattern) I get in one of the presenters a string which contains something which looks like the content of a JSON file.
Then I set one of the properties of the view - which is assigned to the presenter - with that string.
In the view the string is displayed in a TextBox, but it doesn't look good, because it is not structured with newlines and line feeds.
I know there is a JSON-function called Stringify which can make such strings pretty.
Can I call that JSON-function in code-behind?
Per example when I set the property of the view in the presenter?
So I set it in the presenter:
this.view.ContentAsJson = GetContentAsJson(uuid);
This is what I would like to do, if it's possible:
this.view.ContentAsJson = JSON.Stringify(GetContentAsJson(uuid));
GetContentAsJson is a function which creates and returns the JSON-string.
This is my view:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ContentJsonView.ascx.cs" Inherits="WebCenter.PP.PI.WebGui.View.FolderView.ContentJsonView" %>
<%# Import Namespace="WebCenter.PP.Common.Domain" %>
<div id="DivContentJson" class="clearfix">
<p>
<asp:TextBox runat="server" ID="TbContentJson" TextMode="MultiLine" Height="100%" Width="100%" />
</p>
</div>
This is the property in the view which gets the string:
public string ContentAsJson
{
set
{
if (!string.IsNullOrEmpty(value))
{
TbContentJson.Text = value;
}
else
{
TbContentJson.Text = "";
}
}
}
You can use something like
JsonConvert.SerializeObject(ob)
From library: Newtonsoft.Json
JSON.stringify() Actually converts a JavaScript object into a string, you can do it in server side like this:
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
Edit: JSON.stringify() is a client side(browser) functionality. So you can't do that on the server side.
using System.Web.Helpers;
Json.Encode(obj)

A potentially dangerous Request.Form value was detected from the client (editor="<div id="header" sty...")

First of all I should say I have followed almost all the Questions and forum Post below
Stackoverflow Question 1
Stackoverflow Question 2
Stackoverflow Question 3
Stackoverflow Question 4
aspsnippets.com
Server Error in Application ... A potentially dangerous Request.Form value was detected
Avoiding the ‘A potentially dangerous Request.Form value was detected’
c-sharpcorner.com
A potentially dangerous Request.Form value was detected from the client in asp.net
all the thread mentioned to add <httpRuntime requestValidationMode = "2.0" /> or <pages validateRequest ="false" /> inside the web.config file , but this isn't working for me .
Once I did that and start debugging , getting this kind of error
Actually I'm trying to is Loading a HTML file into Rich Text Editor content then Once I click Save as PDF button saving that Rich Text Editor content to PDF file
these are the relevant controller class methods
[ValidateInput(false)]
public ActionResult output_xhtml()
{
PrepairEditor(delegate(Editor editor)
{
editor.LoadHtml("~/example.html");
});
return View();
}
[HttpPost]
[ValidateInput(false)]
public ActionResult output_xhtml(string m)
{
Editor theeditor = PrepairEditor(delegate(Editor editor)
{
});
theeditor.SavePDF("~/aaa.pdf");
return View();
}
PrepairEditor() method
protected Editor PrepairEditor(Action<Editor> oninit)
{
Editor editor = new Editor(System.Web.HttpContext.Current, "editor");
editor.ClientFolder = "/richtexteditor/";
editor.ContentCss = "/Content/example.css";
//editor.ClientFolder = "/Content/richtexteditor/";
//editor.ClientFolder = "/Scripts/richtexteditor/";
editor.Text = "Type here";
editor.AjaxPostbackUrl = Url.Action("EditorAjaxHandler");
if (oninit != null) oninit(editor);
//try to handle the upload/ajax requests
bool isajax = editor.MvcInit();
if (isajax)
return editor;
//load the form data if any
if (this.Request.HttpMethod == "POST")
{
string formdata = this.Request.Form[editor.Name];
if (formdata != null)
editor.LoadFormData(formdata);
}
//render the editor to ViewBag.Editor
ViewBag.Editor = editor.MvcGetString();
return editor;
}
//this action is specified by editor.AjaxPostbackUrl = Url.Action("EditorAjaxHandler");
//it will handle the editor dialogs Upload/Ajax requests
[ValidateInput(false)]
public ActionResult EditorAjaxHandler()
{
PrepairEditor(delegate(Editor editor)
{
});
return new EmptyResult();
}
this is screenshot of error occurring place in PrepairEditor() method
output_xhtml.cshtml view file
<!DOCTYPE html>
<html>
<head>
<title>RichTextEditor - Output XHTML</title>
</head>
<body>
<script type="text/javascript">
var editor;
function RichTextEditor_OnLoad(editor) {
editor = editor;
var content = true;
if (!content) {
setTimeout(function () {
editor.SetText("<table>.....</table>");
}, 1000);
return;
}
}
</script>
<script type='text/javascript'>
function RichTextEditor_OnLoad(editor) {
editor.SetWidth(1150); //Sets the width.
editor.SetHeight(612); //Sets the height.
}
</script>
#using (Html.BeginForm())
{
<div>
#Html.Raw(ViewBag.Editor)
<br />
<button id="btn_sumbit" type="submit" class="btn btn-danger submit">Save as PDF</button>
</div>
<br />
<div>
<h3>
Result html:
</h3>
<div>
#ViewBag._content
</div>
</div>
}
</body>
</html>
Once I did that and start debugging , getting this kind of error
Look at the error you are getting. You already have a <httpRuntime /> section in your web.config. You can't have two of them. Instead of adding a new one, change the existing one.
It is because you are passing HTML
add: [AllowHtml] above your method
[AllowHtml] goes on the property in your model not the controller method. Its namespace is System.Web.MVC

CKEditor html content lifecycle: asp net mvc case

My content will be edited number of times.So i need to store result html to database and load it again when it is neccessary.Here is my current start implementation:
#using (#Html.BeginForm("EditArticle", "Admin", new { id = ViewData["id"] }))
{
<div id="editor"> </div>
<input type="submit" value="save changes" onclick = "setValue()" />
<input type ="hidden" id="value" name="html" />
}
<script>
var editor, html = 'Model.Text';
function createEditor() {
if (editor)
return;
var config = { width:"900px"};
editor = CKEDITOR.appendTo('editor', config,html);
}
function setValue() {
$("#value").val(editor.getData());
}
createEditor();
</script>
But I get eror with initialization html variable.So, could anyone show how correct encode / decode html?
EDIT
Here is data controller receives:
html = <p>ARTICLE 3</p>\r\n
Values like this I store in database and try insert again.
First things first, to fix your code syntactically, it should probably read something like:
var editor, html = '#Html.Raw(Model.Text)';
However, why not instead of dealing with the markup in JavaScript and having to escape and unescape it, dump it directly where it should go i.e.
<textarea name="editor1">#Html.Raw(Model.Text)</textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
And then transform that textarea into your ckEditor? As per their basic example here: http://docs.ckeditor.com/#!/guide/dev_framed
Secondly, aside from that I am not sure what errors you are receiving with your controller, so you will have to post further details for me to help you beyond the above.
I hope this helps.

Add CSS references to page's <head> from a partial view

Is there a way to add CSS references to a page from a partial view, and have them render in the page's <head> (as required by the HTML 4.01 spec)?
If you're using MVC3 & Razor, the best way to add per-page items to your section is to:
1) Call RenderSection() from within your layout page
2) Declare a corresponding section within your child pages:
/Views/Shared/_Layout.cshtml:
<head>
<!-- ... Rest of your head section here ... ->
#RenderSection("HeadArea")
</head>
/Views/Entries/Index.cshtml:
#section HeadArea {
<link rel="Stylesheet" type="text/css" href="/Entries/Entries.css" />
}
The resultant HTML page then includes a section that looks like this:
<head>
<!-- ... Rest of your head section here ... ->
<link rel="Stylesheet" type="text/css" href="/Entries/Entries.css" />
<head>
You could also use the Telerik open source controls for MVC and do something like :
<%= Html.Telerik().StyleSheetRegistrar()
.DefaultGroup(group => group
.Add("stylesheet.css"));
in the head section
and
<%= Html.Telerik().ScriptRegistrar()
.DefaultGroup(group => group
.Add("script.js"));
in the script section at the botttom of your page.
And you can keep adding scripts on any view , or partial view and they should work.
If you don't want to use the component you can always inspire yourself from there and do something more custom.
Oh, with Telerik you also have options of combining and compressing the scripts.
You could have the partial view load in a javascript block that drops in the style to the head, but that would be silly considering that you probably want the javascript block in the head section for the same reason.
I recently discovered something pretty cool though. You can serialize a partial view into a string and send it back to the client as part of a JSON object. This enables you to pass other parameters as well, along with the view.
Returning a view as part of a JSON object
You could grab a JSON object with JQuery and ajax and have it loaded with the partial view, and then another JSON property could be your style block. JQuery could check if you returned a style block, if so then drop it into the head section.
Something like:
$.ajax(
{
url: "your/action/method",
data: { some: data },
success: function(response)
{
$('#partialViewContainer).html(response.partialView);
if (response.styleBlock != null)
$('head').append(response.styleBlock);
}
});
You can use a HttpModule to manipulate the response HTML and move any CSS/script references to the appropriate places. This isn't ideal, and I'm not sure of the performance implications, but it seems like the only way to resolve the issue without either (a) a javascript-based solution, or (b) working against MVC principles.
Another approach, which defeats the principles of MVC is to use a ViewModel and respond to the Init-event of your page to set the desired css/javascript (ie myViewModel.Css.Add(".css") and in your head render the content of the css-collection on your viewmodel.
To do this you create a base viewmodel class that all your other models inherits from, ala
public class BaseViewModel
{
public string Css { get; set; }
}
In your master-page you set it to use this viewmodel
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<BaseViewModel>" %>
and your head-section you can write out the value of the Css property
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<%= Model.Css %>
</head>
Now, in your partial view you need to have this code, which is kinda ugly in MVC
<script runat="server">
protected override void OnInit(EventArgs e)
{
Model.Css = "hej";
base.OnInit(e);
}
</script>
The following would work only if javascript were enabled. it's a little helper that i use for exactly the scenario you mention:
// standard method - renders as defined in as(cp)x file
public static MvcHtmlString Css(this HtmlHelper html, string path)
{
return html.Css(path, false);
}
// override - to allow javascript to put css in head
public static MvcHtmlString Css(this HtmlHelper html,
string path,
bool renderAsAjax)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return null;
// otherwise, add it to the context and put on page
// this of course only works for items going in via the current
// request and by this method
context.Items.Add(filePath, filePath);
// js and css function strings
const string jsHead = "<script type='text/javascript'>";
const string jsFoot = "</script>";
const string jsFunctionStt = "$(function(){";
const string jsFunctionEnd = "});";
string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
string jsBody = string.Format("$('head').prepend('{0}');", linkText);
var sb = new StringBuilder();
if (renderAsAjax)
{
// join it all up now
sb.Append(jsHead);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionStt);
sb.AppendFormat("\r\n\t\t");
sb.Append(jsBody);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionEnd);
sb.AppendFormat("\r\n");
sb.Append(jsFoot);
}
else
{
sb.Append(linkText);
}
return MvcHtmlString.Create( sb.ToString());
}
usage:
<%=Html.Css("~/content/site.css", true) %>
works for me, tho as stated, only if javascript is enabled, thus limiting its usefulness a little.

Categories