How to process JSON output from WCF in View( MVC3) - wcf

I have a scenario where the WCF returns the follwing data ( in the function given below) to a VIEW.
private List<KeyDatesCalendar> GetKeyDatesCalendarData()
{
//Dummy Data for BrandsCalendar CheckList
var keyDatesCalendar = new List<KeyDatesCalendar>()
{
new KeyDatesCalendar()
{
EventText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
EventDate = new DateTime(2011, 02, 09),
EventType = 3
},
new KeyDatesCalendar()
{
EventText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
EventDate = new DateTime(2011, 03, 05),
EventType = 3
},
new KeyDatesCalendar()
{
EventText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
EventDate = new DateTime(2011, 03, 06),
EventType = 4
},
};
The processing of the data in view is done by the following code:
initCalendars({
from : '02/01/2011',
to : '01/31/2013',
dates : [
#for(int i=0, l=#Model.KeyDatesCalendar.Count; i<l; i++)
{
#Html.Raw("['" + #Model.KeyDatesCalendar[i].EventDate.ToString("yyyy/MM/dd") + "'," + #Model.KeyDatesCalendar[i].EventType + ",'" + #Model.KeyDatesCalendar[i].EventText + "']" + (i < (l-1) ? "," : ""));
}
]
});
Instead of the hardcoded values in WCF method, how Do i recieve a JSON output and process the same in View.
I am a beginner here, appreciate your detail answers.
Thanks,
Adarsh

I would agree with many of the previous comments, if you're using ASP.NET MVC you might as well do the JSON conversion from there (have a look at JsonResult class). However, if you really want the WCF service to return the result in JSON format, this blog post I wrote a while back might help.
Iain

Related

Angular Material Table Dynamic Columns without model

I need to use angular material table without model, because I don't know what will come from service.
So I am initializing my MatTableDataSource and displayedColumns dynamically in component like that :
TableComponent :
ngOnInit() {
this.vzfPuanTablo = [] //TABLE DATASOURCE
//GET SOMETHING FROM SERVICE
this.listecidenKisi = this.listeciServis.listecidenKisi;
this.listecidenVazife = this.listeciServis.listecidenVazife;
//FILL TABLE DATASOURCE
var obj = {};
for (let i in this.listecidenKisi ){
for( let v of this.listecidenVazife[i].vazifeSonuclar){
obj[v.name] = v.value;
}
this.vzfPuanTablo.push(obj);
obj={};
}
//CREATE DISPLAYED COLUMNS DYNAMICALLY
this.displayedColumns = [];
for( let v in this.vzfPuanTablo[0]){
this.displayedColumns.push(v);
}
//INITIALIZE MatTableDataSource
this.dataSource = new MatTableDataSource(this.vzfPuanTablo);
}
The most important part of code is here :
for( let v in this.vzfPuanTablo[0]) {
this.displayedColumns.push(v);
}
I am creating displayedColumns here dynamically, it means; even I don't know what will come from service, I can show it in table.
For example displayedColumns can be like that:
["one", "two" , "three" , "four" , "five" ]
or
["stack","overflow","help","me]
But it is not problem because I can handle it.
But when I want to show it in HTML, I can't show properly because of
matCellDef thing:
TableHtml :
<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let disCol of displayedColumns; let colIndex = index" matColumnDef="{{disCol}}">
<mat-header-cell *matHeaderCellDef>{{disCol}}</mat-header-cell>
<mat-cell *matCellDef="let element "> {{element.disCol}}
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
My problem is here:
<mat-cell *matCellDef="let element "> {{element.disCol}} < / mat-cell>
In fact, I want to display element."disCol's value" in the cell, but I don't know how can I do that.
Otherwise, everything is ok except this element."disCol's value" thing.
When I use {{element.disCol}} to display value of element that has disCols's value , all cells are empty like that:
Other example that using {{element}} only:
Also as you can see:
Table datasource is changing dynamically. It means I can't use {{element.ColumnName}} easily, because I don't know even what is it.
First Example's displayedColumns = ['Vazife', 'AdSoyad', 'Kirmizi', 'Mavi', 'Yesil', 'Sari'];
Second Example's displayedColumns = ['Muhasebe', 'Ders', 'Egitim', 'Harici'];
matHeaderCellDef is correct , because it is using {{disCol}} directly.
But I need to read disCol's value, and display element.(disCol's value) in the cell.
How can I do that ?
I found solution :)
It is very very easy but i could't see at first :)
only like that :
<mat-cell *matCellDef="let element "> {{element[disCol]}}
</mat-cell>
I must use {{element[disCol]}} only in HTML.
Now , everything is ok:)
For a full working example based on #mevaka's
Where jobDetails$ is the array of items.
columns$ is equvilent to Object.keys(jobDetails$[0]) so is just a string[]
<table mat-table [dataSource]="jobDetails$ | async">
<ng-container *ngFor="let disCol of (columns$ | async); let colIndex = index" matColumnDef="{{disCol}}">
<th mat-header-cell *matHeaderCellDef>{{disCol}}</th>
<td mat-cell *matCellDef="let element">{{element[disCol]}}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="(columns$ | async)"></tr>
<tr mat-row *matRowDef="let row; columns: (columns$ | async)"></tr>
</table>
I've tried my best to boil a dynamic table down to the minimum. This example will display any columns given an array of flat objects with any keys. Note how the first object has an extra "foo" property that causes an entire column to be created. The DATA const could be some data you get from a service. Also, you could add a "column ID -> label" mapping into this if you know some common property names you'll be getting the JSON. See the stachblitz here.
import {Component, ViewChild, OnInit} from '#angular/core';
const DATA: any[] = [
{position: 1, name: 'sdd', weight: 1.0079, symbol: 'H', foo: 'bar'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
{position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}
];
#Component({
selector: 'dynamic-table-example',
styleUrls: ['dynamic-table-example.css'],
templateUrl: 'dynamic-table-example.html',
})
export class DynamicTableExample implements OnInit {
columns:Array<any>
displayedColumns:Array<any>
dataSource:any
ngOnInit() {
// Get list of columns by gathering unique keys of objects found in DATA.
const columns = DATA
.reduce((columns, row) => {
return [...columns, ...Object.keys(row)]
}, [])
.reduce((columns, column) => {
return columns.includes(column)
? columns
: [...columns, column]
}, [])
// Describe the columns for <mat-table>.
this.columns = columns.map(column => {
return {
columnDef: column,
header: column,
cell: (element: any) => `${element[column] ? element[column] : ``}`
}
})
this.displayedColumns = this.columns.map(c => c.columnDef);
// Set the dataSource for <mat-table>.
this.dataSource = DATA
}
}
<mat-table #table [dataSource]="dataSource">
<ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
<mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
<mat-cell *cdkCellDef="let row">{{ column.cell(row) }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

call render partial from view in elixir

I'm learning Elixir with Phoenix and just got stuck in a pretty dumb point. I want to call the render of a partial from inside my index template the following way:
#index.html.slim
- for element_here <- array_here do
= render MyApp.SharedView, "_game.html.slim", element: element_here
For this I created a View called shared_view.ex that looks like this:
defmodule MyApp.SharedView do
use MyApp.Web, :view
def render("game", _assigns), do: "/shared/_game.html.slim"
end
I expected it go through the loop rendering shared/_game.html.slim, which I copy here:
.col-md-4.portfolio-item
a href="#"
img.img-responsive alt="" src="http://placehold.it/700x400" /
h3
a href="#" Project Name
p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.
But nothing is being rendered. And I'm not getting an error neither. It just render the stuffs before and after that.
I'm not sure what I'm missing here. There's no route or controller action connected to "_game" partial because I didn't think it was neccesary (I'm used to rails and it works this way there).
Turned out to be a spelling issue. There were two problems:
Slim extension should not be explicit, as #radubogdan explained.
Loop should be added using = for instead of - for, as #Dogbert said.
In the end it looks like this:
index.html.slim
= for element_here <- array_here do
= render MyApp.SharedView, "_game.html", element: element_here
shared_view.ex
defmodule MyApp.SharedView do
use MyApp.Web, :view
def render("game", _assigns), do: "/shared/_game.html.slim"
end
_game.html.slim
.col-md-4.portfolio-item
a href="#"
img.img-responsive alt="" src="http://placehold.it/700x400" /
h3
a href="#" Project Name
p Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.

IntelliJ: wrap javadoc text but not markup

I'm trying to format the following Javadoc, but I can't figure out how.
Example input:
/**
* Headline.
* <p>
* Lorem ipsum dolor sit amet,
* consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
* <p>
* A list:
* <ul>
* <li>The description above should be wrapped at the right margin, and broken lines should be joined.</li>
* <li>A line starting or ending in a tag should not be joined.</li>
* </ul>
*
* #author Mark Jeronimus
*/
When I press 'format' I want to see this:
/**
* Headline.
* <p>
* Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
* ut labore et dolore magna aliqua.
* <p>
* A list:
* <ul>
* <li>The description above should be wrapped at the right margin, and broken lines should
* be joined.</li>
* <li>A line starting or ending in a tag should not be joined.</li>
* </ul>
*
* #author Mark Jeronimus
*/
Eclipse and NetBeans do this easily. IntelliJ, if I configure it to wrap text (which I require) it also joins tags except <p>. (Settings -> Editor -> Code Style -> Java -> JavaDoc -> Other -> Wrap at right margin). It looks like this:
/**
* Headline.
* <p>
* Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
* ut labore et dolore magna aliqua.
* <p>
* A list: <ul> <li>The description above should be wrapped at the right margin, and broken
* lines should be joined.</li> <li>A line starting or ending in a tag should not be joined.
* </li> </ul>
*
* #author Mark Jeronimus
*/
I tried changing the other settings in the hope some of them interfere with each other, to no avail.
What I don't want is to use the Eclipse Formatter plugin. I feel IntelliJ should be able to handle such basic behavior itself, or how is anyone supposed to format their Javadoc in a normal way?
Open Preferences
Select Editor > Code Style > Java
Open the JavaDoc tab
Set the following options
Blank lines
 ✓ After description This is a javadoc standard, other blank lines are optional
Other
 ✓ Wrap at right margin
 ✓ Enable leading asterisks
 ✓ Generate "<p>" on empty lines
 ✓ Keep empty lines
 ✗ Preserve line feeds
Click OK
Then just use Code > Reformat Code
Of course you can tweak the preferences according to your own...preference. This setup will realign the text to fit in the margins but you will have to put the <ul> tag on a new line before formatting.

Ember.js input fields

Is it possible to use standard HTML5 input fields in an Ember.js view, or are you forced to use the limited selection of built in fields like Ember.TextField, Ember.CheckBox, Ember.TextArea, and Ember.select? I can't seem to figure out how to bind the input values to the views without using the built in views like:
Input: {{view Ember.TextField valueBinding="objectValue" }}
Specifically, I'm in need of a numeric field. Any suggestions?
EDIT: This is now out of date you can achieve everything above with the following:
{{input value=objectValue type="number" min="2"}}
Outdated answer
You can just specify the type for a TextField
Input: {{view Ember.TextField valueBinding="objectValue" type="number"}}
If you want to access the extra attributes of a number field, you can just subclass Ember.TextField.
App.NumberField = Ember.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step']
})
Input: {{view App.NumberField valueBinding="objectValue" min="1"}}
#Bradley Priest's answer above is correct, adding type=number does work. I found out however that you need to add some attributes to the Ember.TextField object if you need decimal numbers input or want to specify min/max input values. I just extended Ember.TextField to add some attributes to the field:
//Add a number field
App.NumberField = Ember.TextField.extend({
attributeBindings: ['name', 'min', 'max', 'step']
});
In the template:
{{view App.NumberField type="number" valueBinding="view.myValue" min="0.0" max="1.0" step="0.01" }}
et voile!
Here is my well typed take on it :
App.NumberField = Ember.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step'],
numericValue: function (key, v) {
if (arguments.length === 1)
return parseFloat(this.get('value'));
else
this.set('value', v !== undefined ? v+'' : '');
}.property('value')
});
I use it that way:
{{view App.NumberField type="number" numericValueBinding="prop" min="0.0" max="1.0" step="0.01" }}
The other systems where propagating strings into number typed fields.
You may also wish to prevent people from typing any old letters in there:
App.NumberField = App.TextField.extend({
type: 'number',
attributeBindings: ['min', 'max', 'step'],
numbericValue : function (key,v) {
if (arguments.length === 1)
return parseFloat(this.get('value'));
else
this.set('value', v !== undefined ? v+'' : '');
}.property('value'),
didInsertElement: function() {
this.$().keypress(function(key) {
if((key.charCode!=46)&&(key.charCode!=45)&&(key.charCode < 48 || key.charCode > 57)) return false;
})
}
})
Credit where its due: I extended nraynaud's answer
This is how I would do this now (currently Ember 1.6-beta5) using components (using the ideas from #nraynaud & #nont):
App.NumberFieldComponent = Ember.TextField.extend
tagName: "input"
type: "number"
numericValue: ((key, value) ->
if arguments.length is 1
parseFloat #get "value"
else
#set "value", (if value isnt undefined then "#{value}" else "")
).property "value"
didInsertElement: ->
#$().keypress (key) ->
false if (key.charCode isnt 46) and (key.charCode isnt 45) and (key.charCode < 48 or key.charCode > 57)
Then, to include it in a template:
number-field numericValue=someProperty

Unable to Show Data insde dojox.grid.DataGrid with dojo.data.ItemFileReadStore

I am using DOJO ItemFileReadStore with dojox.grid.DataGrid to show Data Inside a Grid
Please see the Image here
http://imageshare.web.id/viewer.php?file=kdfvrkmn6k7xafmi4jdy.jpg
EMployee.Java
public class Employee {
String name;
String dept;
// Setters and Getters
}
This is My Servlet
response.setContentType("text/x-json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
List list = new ArrayList();
Employee emp1 = new Employee();
Employee emp2 = new Employee();
emp1.setDept("CSE");
emp1.setName("Vamsi");
emp2.setDept("EEE");
emp2.setName("Raju");
list.add(emp1);
list.add(emp2);
List jsonresponse = new ArrayList();
for (int i = 0; i < list.size(); i++) {
JSONObject nextObject = new JSONObject();
nextObject.put("name", list.get(i));
jsonresponse.add(nextObject);
}
JSONObject json = new JSONObject();
json.put("label", "name");
json.put("items", jsonresponse.toArray());
response.getWriter().write(json.toString());
}
This is MY JSP Page
<body class=" claro ">
<span dojoType="dojo.data.ItemFileReadStore" jsId="store1" url="http://localhost:8080/Man/MyServlet2"></span>
<table dojoType="dojox.grid.DataGrid" store="store1"
style="width: 100%; height: 500px;">
<thead>
<tr>
<th width="150px" field="name">Name</th>
<th width="150px" field="dept">Dept</th>
</tr>
</thead>
</table>
Please see the Image here
http://imageshare.web.id/viewer.php?file=kdfvrkmn6k7xafmi4jdy.jpg
Please help , Thank you .
+1 for posting the server output (firebug screenshot) in your question. This makes a lot easier for people to help you - for example I can easily see that the data format is still not quite right. You are getting better at both dojo and stackoverflow, it seems!
Remember that the ItemFileReadStore expects the data to be in a particular format. Your servlet is producing:
{label: "name", items: [
{name: {dept: "CSE", name: "Vansi"}},
{name: {dept: "ABC", name: "Abcd"}}
]}
You see you are telling the store that each item's "name" is an object with some properties ("dept" and "name"). This is why the grid shows object Object in the name column. It should be:
{label: "name", items: [
{dept: "CSE", name: "Vansi"},
{dept: "ABC", name: "Abcd"}
]}
I'm not very good with java, but I believe only a small change in your servlet is required:
// The for loop that adds employees to jsonresponse.
for (int i = 0; i < list.size(); i++)
{
// Instead of adding the
Emloyee e = (Employee)list.get(i);
JSONObject nextObject = new JSONObject();
nextObject.put("name", e.getName());
nextObject.put("dept", e.getDept());
jsonresponse.add(nextObject);
}
In fact, it's possible that you can just do json.put("items", list.toArray()); instead of adding each employee to jsonresponse.