Inline lambda - get rate with latest date - c#-4.0

The MVC ViewPage contains Users (intranet.Model.User). Each user may have one or more rates of pay represented in the model as intranet.model.User.UserRates.
I need to be able to display the latest rate of pay per user using an inline Lambda expression but I am having no success (an error message is displayed rather than the rate of pay).
My latest incarnation is:
<% var latestRate = item.UserRates
.GroupBy(hr=>hr.rate)
.Select(g=>g.Single(
d=>d.effective == g.Max(m=>m.effective))
); %>
<%= Html.Encode(latestRate) %>
</td>
Error message in column is:
System.Linq.Enumerable+WhereSelectEnumerableIterator2[System.Linq.IGrouping2[System.Decimal,intranet.Models.UserRate],intranet.Models.UserRate]

I can't figure out exactly what your data looks like, but couldn't you do something like this?
var latestRate = item.UserRates
.OrderByDescending(x => x.effective)
.First();

Final iteration (for now):
<% var userRate = item.UserRates
.OrderByDescending(hr=>hr.effective)
.FirstOrDefault() ?? new intranet.Models.UserRate(); %>
<td class="hrlyRate">
<%= Html.Encode(string.Format("{0:0.000}", userRate.rate))%>
</td>

Related

Ejs form, send array of data that can be converted into postgresql update queries

My app includes a scoresheet grid where each cell represents a student's score in one topic. The teacher can enter scores in each cell before clicking a submit button that sends them all at once.
Here is the ejs form that I have right now:
scoresheet.ejs
<tbody>
<% students.forEach((student, i) => { %>
<tr>
<td class="student-cell right">
<%= student.last_name %>, <%= student.first_name[0] %>
</td>
<% topics.forEach(topic=> { %>
<td class="score-cell center">
<input type="text" class="score-input" name="scores_<%= student.id %>_<%= topic.id %>">
</td>
<% }); %>
</tr>
<% }) %>
</tbody>
This form produces a req.body that looks something like this:
scores_1_2: '75',
scores_1_3: '92',
scores_1_4: '100',
scores_1_5: '100',
scores_1_6: '',
scores_2_1: '65',
scores_2_2: '60',
scores_2_3: '50',
scores_2_4: '35',
I'm trying to take this data and convert it into Postgresql query (or mutiple queries).
For example, the line scores_2_4: '35' would become
UPDATE scores SET points = 35 WHERE student_id = 2 AND topic_id = 4
The scores table is a many-to-many join table to connect students and topics.
I suspect that I still have a bit of work to do with my form. I'm probably not sending this data in an ideal way. This is my best solution so far to include a student_id and topic_id along with the teacher's score input.
If this approach is acceptable, then I also need a hint about how to convert all of this data into an update statement.
I'm using current versions of postgresql, nodejs, express, ejs and the node-postgres package.
Thank you in advance for any insight.
This is my best solution so far to include a student_id and topic_id along with the teacher's score input.
Yes, it's fine. You just have to parse the scores_${student_id}_${topic_id} format on the server back into the data structure you expect.
A more customary encoding is to use bracket notation instead of underscores though. Many parsers for application/x-www-form-urlencoded POST bodies can automatically transform this into a nested object, see e.g. Can not post the nested object json to node express body parser and How to get nested form data in express.js?.
<input type="text" class="score-input" name="scores[<%= student.id %>][<%= topic.id %>]">
I also need a hint about how to convert all of this data into an update statement.
Use multiple UPDATE statements for simplicity:
const { scores } = req.body;
for (const studentId in scores) {
const studentScores = scores[studentId];
for (const topicId in studentScores) {
const points = studentScores[topicId];
// TODO: check for permission (current user is a teacher who teaches the topic to the student)
await pgClient.query(
'UPDATE scores SET points = $3 WHERE student_id = $1 AND topic_id = $2',
[studentId, topicId, points]
);
}
}
You might want to throw in a parseInt or two with proper input validation for the studentId, topicId and points if you need them to be integers instead of strings; otherwise postgres will throw an exception.

How to edit the render information with if else in ejs file

Hi i am trying to add condition for the render value in ejs file. i want to do something if value is equal to blah blah. I tried as shown below.
<% if (user) { %>
<div class="user_info">
<div>
<p>User Name<%= user.username %></p>
<p>User bio<%= user.user_bio %></p>
//here i want to put if else statement
//like this
<% if (user.user_age = null){ %>
<p>Your age is not defined. </p>
<% } %>
<% else if (user.user_age = 10){ %>
<p>You are a <%= user.user_age %> old tween!! </p>
<% } %>
<% else { %>
<p>You are a <%= user.user_age %> old Adult!! </p>
<% } %>
</div>
</div>
<% } else { %>
<p>No User!</p>
<% } %>
Clearly this if else statement i tried is not working.
How can i do this?
I have worked on this type of project something like that of whatsapp web,
its going to be a little hard because there are not many good tutorials out there, but I can give you some tips or steps you need to follow, to give the code would be very lengthy and its propriety code that I've worked on so I cant share that.
First of all to connect to server using a mobile or qr scanner you have to have a private or seperate socket to connect to the server. For that you can have to use web sockets which is a big task but you can use a simple socket library socket.io its fairly easy.
You will have to create a unique socket and key which you need to pass through the r itself(you have to render the qr code image through node js with the key as value) for that you can use 'qrcode' npm package.
For now your task here is done.
The difficult part starts here. You have to make an android/ios app to use that data which will use it in its own way, for ex in whatsapp when you can qr code from app it logs you in to your account and load contacts, messages, etc on the screen.
Im not an android or app developer for now, that part has to solved by you.

How can I render specific piece of data from my mongodb into my html?

It's my first project. I'm creating a website where administrator have the privilege to change home page texts. So I'm keeping all texts in a collection called "Texts" , each document has a text:value . When home page is rendered I use Texts.find() to return an array containing objects each has a "text" value. I link it to my home page using index.
Like this..
<h2>Texts[0].text</h2>, so if i have 100 texts I go all the way to <h2>Texts[100].text</h2>. and they are different texts and I need to put them in a specific order so I can't just throw them into my html.
I know that's so stupid , so I'm looking for some idea instead of this.
--------------Modification------------------>>>>
I tried using find method for arrays but it also is so tiring , so something simpler would be great , here's a portion of the code
<div class="card bg-dark text-white">
<img src="<%=imgsArr.find(x => x.name === 'main2').src%>" class="card-img" alt="...">
<div class="card-img-overlay ">
<h2 class="card-title"><%=textArr.find(x => x.id === 14).text%></h2>
<div class="triangle-up"></div>
<hr class="ml-0 ">
<div class="triangle-down"></div>
<p class="card-text "><%=textArr.find(x => x.id === 15).text%></p>
<div class="card-topic">
<h2 class="card-title" style=";"><%=textArr.find(x => x.id === 16).text%></h2>
<p class="card-text"><%=textArr.find(x => x.id === 17).text%></p>
</div>
<div class="card-topic">
<h2 class="card-title" style=""><%=textArr.find(x => x.id === 18).text%></h2>
<p class="card-text"><%=textArr.find(x => x.id === 19).text%></p>
</div>
<div class="btnOut ">
<button class="btn btn-lg shadow-lg ">MENU</button>
</div>
</div>
</div>
Good news is that for loops are always a good option. If you are using ejs or a similar rendering engine something like this should work, although you will have to tweak it a bit. Take a look are the EJS rendering engine documentation for an exact format, but it would look something like below and no matter how long the list gets it will render as much as it receives(if it is a lot you might want to consider using pagination)
<% for text in Texts.text %>
<% if text==="some value"%>
<h2>text</h2>
<% else %>
<p> text </p>
If your front-end is perhaps react.js or vue.js or similar the same prnciple would work but the format will be different.
No offense friend but you need to get some tutorials. But let me help you as best i can. Everything in a web application is somewhat defined. Meaning it falls into one predetermined category or another. When you get json for example you get something base on how that particular data is defined in the database. Hence you can get json data from your backend that looks
{ 'title':'sneaker', 'price':'200', 'quantity':'50' }
Now assuming it is a list of json objects what you can do is loop through this and assign them to tags based on their object key(because it gets converted to a javscript object). so again you code would look something like
<% for text in Texts.text %>
<h2>text.title</h2>
<div>
<p>text.price</p>
<p>text.quantity</p>
</div>
This would be how you would render data from your database(the format might not exactly be spot on). Dealing with forms is a whole other ball game. So get a book or some tutorial videos that discuss it. You will better understand how to handle it.
For your code you are being very rigid, at first glance there is already a pattern, work with that pattern, you code just needs a simple for loop from what i gather.
for(let i=0; let i>100; i++){
if (i%2===0){
console.log(<h2> i </h2>)
}else{
console.log(<p> i </p>
}
}
The reason i have resulted to pure javascript is so you can see what the inner workings of your render should look like. You can get the total number of ids in your database(that is what the integer 100 represents in this case), loop through one by one and produce what you want. It is still javascript, do not let the html throw you off

Express with mongodb find one

Im new to nodejs , express and mongodb.
I got stuck at the findOne function using ObjectId of mongodb
With the code below, I got the error : "Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"
Im using lastest version of everything (because Im new to them)
My code in view:
<% for(var i = 0 ; i < posts.length; i++ ) { %>
<% post = posts[i] %>
<article class="post">
<div class="post-preview col-xs-10 no-gutter">
<h2>
<a href="/posts/<%=i%>">
<%= post.title %>
</a>
</h2>
<p><%= post.description %></p>
<p class="meta">
<%= post.author.name %> in
<%= post.category.name %> <i class="link-spacer"></i> <i class="fa fa-bookmark"></i> <%= post.created_at %>
</p>
</div>
<div class=" col-xs-2 no-gutter">
<img src="<%= post.author.image %>" class="user-icon" alt="user-image">
</div>
</article>
<% } %>
Please tell me what's wrong with my code .
p/s : the req.params.id is valid and logable.
Default mongo IDs don't increment from 1. They will look like "_id" : ObjectId("5908f94c06515dfa8522459c") in the database. Your problem is your href is navigating by index, not the id itself. You need to change:
<a href="/posts/<%=i%>">
<%= post.title %>
</a>
to:
<a href="/posts/<%=post._id%>">
<%= post.title %>
</a>
this will make your link /posts/5908f94c06515dfa8522459c instead of /posts/1
I'm guessing it's because the id is a string of not 12 bytes (nor 24 hex characters). When the URL comes in to your express web server, it's a string. When express matches a part of it and stores it, there's no rule that :id couldn't be myCoolId, which isn't a number.
So everything in req.params is a string. I would add some checking to make sure it's a number, cast it, and then give it to ObjectId.
EDIT: If you want to work with it as strings, then try some of the following:
const ObjectID = require('mongodb').ObjectID;
// When making a brand new record, just use a new object id.
let record = new ObjectID();
console.log(record);
// When giving the ID to the client as a string, make it a hex string.
let hexString = record.toHexString();
console.log(hexString);
// You can validate that it's a valid object id in your route when they post it back.
let valid = ObjectID.isValid(hexString);
console.log(valid);
// Then you can turn it back into an object id.
let fromHex = ObjectID.createFromHexString(hexString);
console.log(fromHex);

Searching Multiple Models with Ransack Rails 4

I'm trying to figure out how to search multiple models with Ransack. The goal is to have the search form in my shared header. I'm using a combination of their documentation, an old rails-cast, SO questions, and some code a friend shared with me. Right now I think it works, although I'm not sure because I can't get the results to show on my index page.
First, I created a search controller:
class SearchController < ApplicationController
def index
q = params[:q]
#items = Item.search(name_cont: q).result
#booths = Booth.search(name_cont: q).result
#users = User.search(name_cont: q).result
end
end
Next, I put this code in the header partial (views/layouts/_header.html.erb):
<%= form_tag search_path, method: :get do %>
<%= text_field_tag :q, nil %>
<% end %>
I added a route:
get "search" => "search#index"
My index.html.erb for the Search controller is empty and I suspect that is the problem, but I'm not sure what to place there. When I try something like:
<%= #items %>
<%= #users %>
<%= #booths %>
This is the output I get when I execute a search:
#<Item::ActiveRecord_Relation:0x007fee61a1ba10> #<User::ActiveRecord_Relation:0x007fee61a32d28> #<Booth::ActiveRecord_Relation:0x007fee61a20790>
Can someone please guide me on what the solution might be? I'm not sure if it's an index view problem, routing problem, or something else. On all of the tutorials the search field and results are only for one model so I'm a little confused on how to pull this off across multiple models.
Thanks!
The output you are getting is correct. Each of those variables contains an ActiveRecord_Relation object which can be treated like an array. Normally you'd do something like:
<% #items.each do |item| %>
<%= item.name %> # or whatever
<% end %>
<% #users.each do |user| %>
# and so on
Alternatively, you could combine your results #results = #items + #booths + #users and then:
<% #results.each do |result| %>
# display the result
<% end %>

Resources