Mvc Web Api Knouck and Json Tree Issue - json

I have 2 problems. Before I explain my problems I want to share my json result, a little part.
I wanna take all Category Properties(CategoryId,CategorySeoName...) and I write this.
public IEnumerable<Category> FindAllCategoryName()
{
return CategoryRepository.GetAll().Select(x => new Category
{
CategoryName = x.CategoryName
}).ToList();
}
But it gives an error like this "An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code" and additional information "Category class have a complex type, you don't create Linq to Entities query". I think this problem about ICollection Tales propeties
My second problem is, list of this tales in category. I use knockout.js.
talesCrud.js
function TalesViewModel() {
var self = this;
self.tales = ko.observableArray();
$.getJSON("/api/tales/kids/", self.tales);}
$(document).ready(function () {
ko.applyBindings(new TalesViewModel());})
Html
<ul data-bind="foreach: tales">
<li>
<div>
<div>Masal Adı</div>
<span data-bind="text: $data.TaleName"></span>
</div>
<div>
<div>İçerik</div>
<span data-bind="text: $data.Content"></span>
</div>
<div>
<div>Ses Dosyası</div>
<span data-bind="text: $data.VoicePath"></span>
</div>
</li>
</ul>
I didn't take this properties in json result. Because it's have different tree.

Firstly, you should post two questions, will get you answers more easily. The first issue seems fairly generic, and googling for the error message has lots of leads, but we'd really have to see more code, know more variables (whats your db/driver?) to tell more.
As for your second issue, it looks like you're using $.getJSON incorrectly. I assume you want to load the JSON into the tales array, if so, you should try this instead
$.getJSON("/api/tales/kids/", function(data) {
self.tales(data.Tales);
});
It looks correct otherwise.

Related

How to sort table in jhipster? Not sure how it works

I've been learning jhipster for the past week now and I'm trying to implement a sortable table. I wanna ask how does the jhiSort and jhiSortBy work? I don't quite understand what does the predicate, ascending and callback function in jhiSort do. Also, which files do the id, date and amount in jhiSortBy come from and how does jhiSortBy work?
<tr jhiSort [(predicate)]="predicate" [(ascending)]="reverse" [callback]="transition.bind(this)">
<th jhiSortBy="id"><span>ID</span> <span class="fa fa-sort"></span></th>
<th jhiSortBy="date"><span>Date</span> <span class="fa fa-sort"></span></th>
<th jhiSortBy="amount"><span>Amount</span> <span class="fa fa-sort"></span></th>
</tr>
jhiSort and jhiSortBy are two directives provided by JHipster that help you implement sorting in data tables. You can see exactly what they do in the links I've provided.
jhiSortBy
The call you see in the header of each column just tells the jhiSortBy directive the name of the attribute it will sort the table by. In your case this means id, date and amount are all attributes of the entities being listed in your table.
This directive handles the user interaction and calls jhiSort to do the actual sorting, plus some extra steps to manage icon changes.
jhiSort
This directive has three properties:
#Input() predicate: string;
#Input() ascending: boolean;
#Input() callback: Function;
When you do [(predicate)]="predicate" you are telling angular that the predicate property of the jhiSort directive (left hand side of the assignment) will bind to a property in your component of the same name (right hand side). So in your *.component.ts you must have a property named predicate that will store the sorting information.
The directive has also a boolean property named ascending, when you do [(ascending)]="reverse" you are telling angular to bind the ascending directive property to a component property named reverse, just like before but this time the names don't match. This property controls only the sorting direction (ascending or descending).
Finally, callback is just the method that will be called on user interaction (click on a table header) to put everything in motion. transition is the name of such method in your *.component.ts, and it looks something like this:
transition(): void {
this.router.navigate(['./'], {
relativeTo: this.activatedRoute.parent,
queryParams: {
page: this.page,
sort: this.predicate + ',' + (this.ascending ? 'asc' : 'desc'),
},
});
}
This will force a navigation change so that the new order and page information persist on the URL, allowing future navigation events to get back without resetting the table.
This navigation change eventually calls loadAll() sending a query to your server-side with the new ordering (and paging) parameters.
The result of this query (a properly ordered list of entities) will be later sent back to the client-side to be displayed.
Very roughly this is how they work.
I is not working correctly:
I found the solution,
it is related to the method
fillComponentAttributesFromResponseBody
change the content of that method to be like this::
protected fillComponentAttributesFromResponseBody(data: IReferences[] | null): IReferences[] {
const referencesNew = [];
if (data) {
for (const d of data) {
if (referencesNew.map(op => op.id).indexOf(d.id) === -1) {
referencesNew.push(d);
}
}
}
return referencesNew;
}
and it will work.
enjoy

How to display long string data from JSON as a list wise using react typescript

How to display long string data from JSON as a list wise if Description string is too long. How do i split or format description Using react and typescript .
I have below JSON data:
"options": [
{
"perkType": "GIFT_CARD",
"tierRewardId": "ff592a61-3e64-474e-a3e5-cb7c14cc73e1",
"perkDescription": "**Important details about the Perk:**\n* Perks are random additional items. These are not earned, but extra items given to customers outside of the spend levels.\n* See Terms and Conditions for exclusions and additional information.\n* [Terms & Conditions](www.xyz.net/TermsandConditions)",
},
{
"tierRewardId": "0aa6b029-3179-41dd-8726-78ca7e4bfe18",
"perkType": "TOOL_RENTAL",
"perkDescription": "**Important details about the Mik Perk:**\n* Mik Perks are random additional items. These are not earned, but extra items given to customers outside of the spend levels.\n* See Terms and Conditions for exclusions and additional information.\n* [Terms & Conditions](www.xyz.net/TermsandConditions)"
}
],
already i filter the data :
const optionGift = this.state.currentData.item.tierPerks[0].options.filter(
(list) => list.perkType === 'GIFT_CARD');
const optionGiftCard= optionGift.map((value)=> value );
const OptionRental = this.state.currentData.item.tierPerks[0].options.filter(
(list) => list.perkType === 'TOOL_RENTAL',);
const OptionRentalTool= OptionRental.map((value)=> value );
component tsx code :
<div> <ul className="YourPerkOption__modelParagraph">
<li>{props.optionGiftCard[0].perkDescription}</li></ul></div>
I am trying to display a list wise data into below format
if anybody can help please .
Custom Code
If I am understanding this correctly, the first line of the perkDescription is the title (**Important details about the Mik Perk:**) and the subsequent lines are bullet points. We need to break up the string into multiple string segments and then render them to the DOM through JSX. Let's make that into it's own reusable component.
The only prop that we need is the string text.
interface PerkDescriptionProps {
text: string;
}
Our component breaks that text into an array of lines with the string.Prototype.split() method. We store the first element of the array to a variable title and the rest of the lines to another variable bullets using spread syntax. We then loop through the bullets array and put each one inside of a li element.
export const PerkDescription = ({ text }: PerkDescriptionProps) => {
const lines = text.split("\n");
const [title, ...bullets] = lines;
return (
<div className="perkDescription">
<div className="perkDescriptionTitle">{title}</div>
<ul className="perkDescriptionList">
{bullets.map((line, i) => (
<li key={i}>{line}</li>
))}
</ul>
</div>
);
};
You would call it like this:
<PerkDescription text={optionGiftCard[0].perkDescription} />
But I think you should create a Perk component that uses this PerkDescription!
I am not dealing with the asterisks here so you'll still see them in the HTML output. Are you using some some of package to parse markdown syntax?
Markdown Parsing
Your JSON is using a standardized markdown syntax to denote the list. There are already packages out there which can handle the bulleted list as well as turning the link into an a element and adding the bold styling to the title.
Using react-markdown, all you need to do is put your text inside of a ReactMarkdown component.
import ReactMarkdown from 'react-markdown'
<ReactMarkdown>{optionGiftCard[0].perkDescription}</ReactMarkdown>
You could use a RegEx to split perkDescription into an array and then map that array.

Access filter result Angular 6

How can I access filteredArray in my .ts component? Because right now it is accessible only inside ng-container.
<ng-container *ngIf="(userList | filter: 'name' : value) as filteredArray">
<tr *ngFor="let user of filteredArray">
<td>{{user.name}}</td>
<td>{{user.group}}</td>
</tr>
<div>Count: {{ filteredArray.length }}</div>
</ng-container>
How can I modify the code in order to obtain what I want? Thank you for your time!
To answer your question directly: it's not possible the way you describe it. But read on.
Pipes (sometimes still called "filters") should be used only to format data, i.e. prepare it in a human-readable form. For example, the build-in date pipe can be used to transform an ISO string to a string such as "March 21st, 1995", which is how a human from the USA might expect to read the date.
The way you're using pipes is not recommended, precisely because of the question you have. You've essentially put application logic inside a template, which is an anti-pattern and beats the purpose of having easy-to-read declarative templates, which Angular uses in order to figure out how to update DOM.
You should move the filtering logic back to the class. For example, instead of setting this.userList = xxx, you could have a function which you call every time, such as this.changeUserList(xxx).
changeUserList (list) {
this.userList = list
this.filteredArray = list.filter(...)
}
You can put this logic in a setter as well, which allows you to run custom code when you write the usual this.userList = list, but you'll need a separate (usually prefixed private) property on the class where you'd actually store the value. It's not really a limitation since you can also have a trivial getter, so you can still us this.userList normally as a getter without having to remember to use this._userList, essentially tucking this away as the get/set pair's implementation detail.
private _userList
public set userList (list) {
this._userList = list
this.filteredArray = list.filter(...)
}
public get userList (list) { return this._userList }
Observables could really come in handy here as well, since you could just rx.map the userList$ to filteredArray$ with an Array#filter.
public userList$
public filteredArray$ = this.userList$.pipe(map(arr => arr.filter(...))
Then in the template, you can use the async pipe.
*ngIf="filteredArray$ | async as filteredArray"
Avoid doing the following.... but it works for demo purposes 😃
Create a component (e.g. demo-element.component.ts) that takes a single #Input() value:any
Add this new component as the first child of the <ng-container>, and give it a template reference #containerRef e.g.:
<ng-container *ngIf="(userList | filter: 'name' : value) as filteredArray">
<demo-element #containerRef [value]="filteredArray"></demo-element>
In your main component, add
#ViewChild('containerRef') ref;
ngAfterViewInit() {
this.filteredArray = this.ref.value; // Terrible pattern, but answers the question:-)
}
I hope this below code will help you.
<div class="rsrvtn_blk" *ngIf="(items | fSearch:firstname) as filteredItems">
<div class="col-md-3 pl-0" *ngFor="let item of filteredItems">
// you can display the filtered content here
</div>
</div>

Grails losing image if not select new one on edit page

I'm making a website using spring security and grails 3.1.10. In this site I'm listing all image from database and show them at index. The problem is when I tried to edit one of those image. For example I want to just edit name but if I do not select an image this field become null.But I want to protect the image. How can i through this.
edit gsp
<div class="col-xs-2 col-sm-2 col-md-2">
<input type="file" class="form-control" name="productImage" id="productImage">
</div>
I tried to write a controller to protect old one but this one not work.
def id=params.id
Product old=Product.findById(params.id)
def f = request.getFile('productImage')
if(f.empty){
print("file is empty")
if(old.productImage){
println("there is a file in database")
product.productImage=old.productImage
}}
I think I kind of understand there are a few issues here:
//These two are the same
Long id=params.id ? params.id as Long : null
Long id=params.id ? params.long('id') : null
It says
Long id= (is there a params.id )
{ yes ? } -> params.id as Long {otherwise :} -> null
findById should be used in rare cases:
//You should never use findById unless an example would be findByIdAndSomethingElse(id,somethingElse)
// Product old=Product.findById(params.id)
Instead you should use (look int get read and load) get is the best since it ensures the record actually exists and where as read could return a cached copy (that may since be removed) (read load are less resource intensive) worth reading up about - so sticking with get : and you may not have id so it should be wrapped around a further
if (id) {
// Product old=Product.get(id)
// Product old=Product.read(id)
// Product old=Product.load(id)
// You could have just done this which should convert params.id as long itself as the method
Product old=Product.get params.id
def f = request.getFile('productImage')
if(f.empty){
print("file is empty")
if(old.productImage){
println("there is a file in database")
//I think this may be the issue:
product.productImage=old.productImage
//should this not be ?
product=old
}}
you have now outlined what old or product do after your statement which is the reason for my comment.
Does product or old then get sent as variables to the gsp page how are they represented ?
Also if this is your edit form;
<div class="col-xs-2 col-sm-2 col-md-2">
<input type="file" class="form-control" name="productImage" id="productImage">
</div>
This is missing value
<input type="file" class="form-control" name="productImage"
value="${someParams?.value}" id="productImage">
You state it returns null so it must be some other form field that you have not provided since this field actually has no value defined and therefore can never be a null.
Also notice
value="${someParams?.value}"
vs
value="${someParams.value}"
The ? is protecting the field from returning a null value. So upon start of a form where there may not be a value that would then save it showing null on the user's screen.
With all that said there appears to a be a conflict in what you say something going null vs what you are trying to set etc.. maybe a clash in what you want or maybe an easier way of putting it all
def f = request.getFile('productImage')
if (f.empty) {
if (params.id) {
Product old=Product.get(params.id as Long)
print("file is empty")
if (old.productImage) {
println("there is a file in database")
product.productImage=old.productImage
} else {
//what should produce.productImage be now if no file and nothing on db ?
}
} else {
//what should happen if there is no product.id ?
}
} else {
//what happens when there is a file provided - should that Product check be outside of this loop entirely should that file being returned be merged with the existing record ?
}
There is lots there that will hopefully help you understand what is going wrong. With that all said this sort of stuff should really be done with the aid of a validation class this saves on you having to code out lots of logic in your controllers that in the end looks all too long winded and messy and hard to follow.
I will update an example project: https://github.com/vahidhedayati/grails-bean-validation-examples a bit later today with an image example. Hopefully with a video to explain what I have added. Will leave a comment on here when done.

Filtering and rearranging model/content in Ember Controllers

Let's say I have a JSON array of data, something like:
[ {"name":"parijat","age":28},
{"name":"paul","age":28},
{"name":"steven","age"27},
...
]
that is part of my model, and this model is setup like this:
App.UserRoute = Ember.Route.extend({
model:function(){
return App.User.FIXTURES ; // defined above
}
});
I want to get the unique ages from this JSON array and display them in my template, so I reference the computed properties article and read up a little on how to enumerate Ember Enumerables, to eventually get this:
App.UserController = Ember.ArrayController.extend({
ages:function(){
var data = this.get('content');
var ages = data.filter(function(item){
return item.age;
});
}.property('content');
});
Now the above piece of code for controller is not correct but the problem is that it doesn't even go into data.filter() method if I add a console.log statements inside. IMO, it should typically be console logging as many times as there exist a App.Users.FIXTURE. I tried using property('content.#each') which did not work either. Nor did changing this.get('content') to this.get('content.#each') or this.get('content.#each').toArray() {spat an error}.
Not sure what to do here or what I am completely missing.
Filter is used for reducing the number of items, not for mapping.
You can use data.mapBy('age') to get an array of your ages:
ages:function(){
return this.get('content').mapBy('age');
}.property('content.#each')
or in your handlebars function you can just use the each helper:
{{#each item in controller}}
{{item.age}}
{{/each}}