How can I load a page with checkboxes checked according to database info - sql

I know there is a few post about it. I've tryed to work with the answer but I must be missing something somewhere (I'm pretty noob).
As I said in the title, I would like to have a page that show a big list of item checked or not according to database information. The page load with an Id.
Type: CSHTML, Razor
Database: defect
Table name: defectqc
The table is looking a bit like that so far:
<table>
<tr><td><p><input type="checkbox" name="ltcheck1" checked="#ltcheck1"></td></tr>
<tr><td><p><input type="checkbox" name="ltcheck2" checked="#ltcheck2"></td></tr>
<tr><td><p><input type="checkbox" name="ltcheck3" checked="#ltcheck3"></td> </tr>
</table>
So the code script I've tryed at the begining is this one...
var Id = "";
var ltcheck1 = "";
var ltcheck2 = "";
var ltcheck3 = "";
if(!IsPost){
if(!Request.QueryString["Id"].IsEmpty() && Request.QueryString["Id"].IsInt()) {
Id = Request.QueryString["Id"];
var db = Database.Open("defect");
var dbCommand = "SELECT * FROM defectqc WHERE Id = #0";
var row = db.QuerySingle(dbCommand, Id);
if(row != null) {
ltcheck1 = row.ltcheck1;
ltcheck2 = row.ltcheck2;
ltcheck2 = row.ltcheck3;
}
The database got column written "True" or "False" into it. I want the checkboxes to be checked if the column is "true"
Please MTV! Pimp my ride! ;D
Sorry for my english, I'm trying hard

<input type="checkbox"/>
Will only be checked if you use the attribute
checked
or
checked="checked"
So try to generate this:
<input type="checkbox" checked/>

Following your logic Schaemelhout Would it be possible if I use this kind of statement
var Id = "";
var ltcheck1 = "";
var ltcheck2 = "";
var ltcheck3 = "";
if(!IsPost){
if(!Request.QueryString["Id"].IsEmpty() && Request.QueryString["Id"].IsInt()) {
Id = Request.QueryString["Id"];
var db = Database.Open("defect");
var dbCommand = "SELECT * FROM defectqc WHERE Id = #0";
var row = db.QuerySingle(dbCommand, Id);
if(row.ltcheck1 = "true") {
ltcheck1.checked
}
if(row.ltcheck2 = "true") {
ltcheck1.checked
}
(I know the syntax isn't correct)
I found this which is in PHP
<input type="checkbox" name="ltcheck1" value="True" <?php echo $checked; ?> />
if ($row['letcheck1'] == 'True') $checked = 'checked="checked"';
Assuming that the data have already been pulled out. It would do exactly what I need... Is there a way to translate it?

Why don't you use the html helpers?
#Html.CheckBox("ltcheck1")
#Html.CheckBox("ltcheck2")
#Html.CheckBox("ltcheck3")

Related

How to divide WebRTC by muaz-khan chat out-put into two columns?

I'm newbie in using WebRTC and I am using this git project by Muaz-khan. I have problem when divided chat output into two columns (User name 1 and User name 2), this is default of chat output
id of this div is #chat-output
Can you show code for example? I think you just create two html containers (left and rigth for example) and push messages first to the left, and messages from the second to the right.
I am using this demo of him , [ https://github.com/muaz-khan/RTCMultiConnection/blob/master/demos/TextChat%2BFileSharing.html].
Here is function that Text Message Out Put will put here in . I want to change it in two columns, such as for User name 1 : <div id="usename1"></div>, for user name 2 : <div id="username2"></div>
document.getElementById('input-text-chat').onkeyup = function(e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
this.value = this.value.replace(/^\s+|\s+$/g, '');
if (!this.value.length) return;
connection.send(this.value);
appendDIV(this.value);
this.value = '';
};
var chatContainer = document.querySelector('.chat-output');
function appendDIV(event) {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.insertBefore(div, chatContainer.firstChild);
div.tabIndex = 0;
div.focus();
document.getElementById('input-text-chat').focus();
}
Modify function appendDIV().
function appendDIV(event) {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.insertBefore(div, chatContainer.firstChild);
div.tabIndex = 0;
div.style.width = '100%';
if (event.data)
div.style.textAlign = 'left';
else
div.style.textAlign = 'right';
div.focus();
document.getElementById('input-text-chat').focus();
}
P.S. I apologize for the late reply :)

SQL like query features in Google App Script to pull data from Google Sheets

I am trying to build a Google Apps Script web app that will pull data from a Google sheet and display it in rows and columns in an HTML page in the browser.
By following the samples etc I wrote this code that WORKS!
function doGet(){
return HtmlService
.createTemplateFromFile('Report3')
.evaluate();
}
function getData(){
var spreadsheetId = '1Z6G2PTJviFKbXg9lWfesFUrvc3NSIAC7jGvhKiDGdcY';
var rangeName = 'Payments!A:D';
var values = Sheets
.Spreadsheets
.Values
.get(spreadsheetId,rangeName)
.values;
return values;
}
the data lying in columns A,B,C,D is getting pulled and being displayed correctly through the following HTML template
<? var data = getData(); ?>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
Instead of getting all the rows and all the columns from A,B,C,D I would like to run an SQL Query to retrieve some of the columns with a WHERE clause like SQL. I understand that the =QUERY() function that works in the spreadsheet does not work inside the GAS. So my next attempt was to retrieve SOME of the rows by using a getBatch method .. and this is where I get ERRORs
in this case, i want to exclude column C and get only A,B and D,E
the code that throws an error is as follows :
function getData2(){
var spreadsheetId = '1Z6G2PTJviFKbXg9lWfesFUrvc3NSIAC7jGvhKiDGdcY';
/* var rangeName1 = 'Payments!D'; */
/* var rangeName2 = 'Payments!A'; */
var values = Sheets
.Spreadsheets
.Values
.batchGet(spreadsheetId,{ranges: ['Payments!D:E', 'Payments!A:B']})
.values;
return values;
}
In the corresponding HTML template, all that changes is getData is replaced with getData2
<? var data = getData2(); ?>
with this code, I get the following error :
TypeError: Cannot read property "length" from undefined. (line 6, file
"Code", project "Report003")
Now I have two questions :
What is wrong in my code and how can i fix it?
Is it possible to use SQLite to simplify the process of extracting the desired rows and columns
I have seen this question but I am not able to understand the answer adequately
I finally understood what this solution was and modified it as given below. Now we can use any SQL that is supported by the QUERY() function.
function mostSQL(){
var spreadsheetId = '1Z6G2PTJviFKbXg9lWfesFUrvc3NSIAC7jGvhKiDGdcY';
var targetRange = 'Payments!A:G';
var SQL = 'select A, G where G >= 700 and G <= 800'
var Query = '=QUERY('+targetRange+',\"'+SQL+'\")'
var currentDoc = SpreadsheetApp.openById(spreadsheetId)
var tempSheet = currentDoc.insertSheet();
var pushQuery = tempSheet.getRange(1, 1).setFormula(Query);
var pullResult = tempSheet.getDataRange().getValues();
currentDoc.deleteSheet(tempSheet);
return pullResult;
}
You can use Google Visualization API Query Language to perform data manipulations with the query to the data source. The syntax of the query language is similar to SQL
code.gs
function doGet() {
// SpreadsheetApp.openById("SSID"); // To define the oAUTH Scope - https://www.googleapis.com/auth/spreadsheets
var output = HtmlService.createTemplateFromFile('index');
output.token = ScriptApp.getOAuthToken();
return output
.evaluate()
.setTitle('SQL Query');
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="dataTable"><h4>Loading...</h4></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.load('visualization', '1.0', {packages: ['corechart','table']});
google.setOnLoadCallback(loadEditor);
function loadEditor() {
var queryString = encodeURIComponent("SELECT A,B,D,E where A!= 'JACK'");
var SSID = "ADD YOUR SPREADSHEET"
var SHEET_NAME = "SHEET NAME"
var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key='+SSID+'&sheet='+SHEET_NAME+'&oauth_token=<?=ScriptApp.getOAuthToken()?>&headers=1&tq=' + queryString);
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
console.log(response)
var data = response.getDataTable();
console.log(data);
var chartTbl = new google.visualization.Table(document.getElementById('dataTable'));
chartTbl.draw(data);
}
</script>
</body>
</html>

How create simple generic grid component in Asp.Net Core MVC?

I've created the web application using Asp.Net Core MVC and I want to create the component with the grid.
I've repeatedly used for the grid in the view following code:
View:
<div class="row table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>UserId</th>
<th>UserName</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model.Users)
{
<tr>
<th scope="row"><a class="btn btn-info" asp-action="User" asp-route-id="#user.Id">Edit</a></th>
<td>#user.Id</td>
<td>#user.UserName</td>
<td>#user.Email</td>
</tr>
}
</tbody>
</table>
</div>
How create the grid component with the input like a Generic List with the dynamic data structure?
Actually i had the same question. I am working on it, and i am about to do it. There too many steps to be done, it will be better doing a blog post, rather than an answer over here.
I will recommend to check out this, and then make your own customizations depending on your needs:
http://www.c-sharpcorner.com/article/using-jquery-datatables-grid-with-asp-net-core-mvc/
I will recommend to generalize it working with APIs and JS, not with pure C# and server side (which i also did, but since we are in 2017/2018 and in a Mobile world, better not to do so).
Just some help following this tutorial. I had some problems with the order by on server side, which i solved like this:
// POST: api/Curso/LoadData
[HttpPost]
[Route("LoadData")]
public IActionResult LoadData()
{
try
{
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
// Skip number of Rows count
var start = Request.Form["start"].FirstOrDefault();
// Paging Length 10,20
var length = Request.Form["length"].FirstOrDefault();
// Sort Column Name
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
// Sort Column Direction (asc, desc)
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
// Search Value from (Search box)
var searchValue = Request.Form["search[value]"].FirstOrDefault();
//Paging Size (10, 20, 50,100)
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
/**start of improved code
// getting all Curso data
var cursoData = (IEnumerable<Curso>) _context.Curso.Include(c => c.CoordinadorAsignado).Include(e => e.Empresa).ToList();
//Sorting
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
{
PropertyInfo propertyInfo = typeof(Curso).GetProperty(sortColumn);
if (sortColumnDirection.Equals("asc"))
{
cursoData = cursoData.OrderBy(x => propertyInfo.GetValue(x, null));
}
else
{
cursoData = cursoData.OrderByDescending(x => propertyInfo.GetValue(x, null));
}
}
//Search
if (!string.IsNullOrEmpty(searchValue))
{
cursoData = cursoData.Where(m => m.Nombre.ToLower().Contains(searchValue.ToLower()));
}
End of improved code**/
//total number of rows counts
recordsTotal = cursoData.Count();
//Paging
var data = cursoData.Skip(skip).Take(pageSize).ToList();
//Returning Json Data
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
}
catch (Exception)
{
throw;
}
}
I also improved the search, but it still works just for one column.
Rember to include:
using Microsoft.EntityFrameworkCore;
using System.Reflection;
I hope this helps some othe guys working on it in the future.
WARNING
Sort does not work with FK columns (For example, Curso.Name).

YUI Datatable - Get ID of DOM Element after page has loaded and use it in other YUI events

Okay so I have a YUI Datatable. Most of it is exactly as the how to guide says to construct it.
I have an event that governs changing the rows per page. It's linked to the rows per page drop down element and it saves the value of that drop down as a cookie when the drop down is changed.
var onRPPChange1 = YAHOO.util.Event.addListener("yui-pg0-1-rpp24", "change", getRPP_1);
The problem is that "yui-pg0-1-rpp24" (the ID of the drop down) changes whenever I make updates to my data table. I would like to extend this so that when the page loads it will dynamically insert the ID of that drop down into this event listener so that I don't have to keep editing it after future updates.
I've managed to construct that following that will capture the ID and I can alert it after the table loads, but so far, including the result of this function in the above addListener code isn't working.
var setRPPVars = function() {
YAHOO.util.Event.onAvailable("rppSpan", this.handleOnAvailable, this);
}
var rppSpanIds = new Array();
var rppArray = new Array();
setRPPVars.prototype.handleOnAvailable = function() {
var spans = document.getElementsByTagName("span");
var n = 0;
for(var i=0; i<spans.length; i++){
if(spans[i].id == "rppSpan"){
rppSpanIds[n] = spans[i];
if(n == 0){
rppTopID = rppSpanIds[n].firstChild.id;
rppArray[0] = rppTopID;
}
else if(n==1){
rppBottomID = rppSpanIds[n].firstChild.id;
rppArray[1] = rppBottomID;
}
n++;
}
}
alert(rppTopID);
alert(rppBottomID);
alert(rppArray);
}
var rppEvent = new setRPPVars();
//this is the part that doesn't work:
var onRPPChange0 = YAHOO.util.Event.addListener(rppArray[0], "onchange", getRPP_0);
function getRPP_0(){setRPPVars();oRPP = rppTopID;alert("rppTopID: "+rppTopID); alert("oRPP: "+oRPP);};
Any suggestions you've got would be awesome!
EDIT: For clarity's sake, this element is the rows per page drop down:
<span id="rppSpan">
<select id="yui-pg0-1-rpp24" class="yui-pg-rpp-options" title="Rows per page">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</span>
Subscribe to YAHOO.widget.Paginator's rowsPerPageChange instead:
http://developer.yahoo.com/yui/docs/YAHOO.widget.Paginator.html#event_rowsPerPageChange
Then you don't have to find the actual element.

HQL to SQL converter

Does anyone know how to convert NHibernate HQL to SQL Scripts?
Since HQL translation depends on your mappings and also runtime behaviour, I think it is unlikely there is a way to do so statically.
You could run the HQL against a real database and capture the generated SQL either via a profiler for your specific rdbms or NHProf.
My old trainings. That was beta-version. Here it is! (hql2sql.jsp)
<SCRIPT type="text/javascript">
<%
org.hibernate.Session ThisSession = SessionFactory.getSession();
org.hibernate.engine.SessionImplementor ThisSessionImplementor = (org.hibernate.engine.SessionImplementor) ThisSession;
org.hibernate.engine.SessionFactoryImplementor ThisSessionFactory = (org.hibernate.engine.SessionFactoryImplementor) ThisSession.getSessionFactory();
String HQL_Query = "SELECT ... ";
String SQL_Query;
try{
org.hibernate.engine.query.HQLQueryPlan HQL_Query_Plan = new org.hibernate.engine.query.HQLQueryPlan(HQL_Query, true, ThisSessionImplementor.getEnabledFilters(), ThisSessionFactory);
SQL_Query = org.apache.commons.lang.StringUtils.join(HQL_Query_Plan.getSqlStrings(), ";");
}catch(Exception e){SQL_Query = "ERROR!! :: " + e.getMessage();}
%>
$(document).ready(function(){
$('span[role="HQL"]').text(" <%=HQL_Query%>");
$('span[role="SQL"]').text(" <%=SQL_Query%>");
});
</SCRIPT>
<div style="border:2px solid brown">
Ваш запрос на HQL:
<br/><br/><span role="HQL"> </span>
</div>
<br>
<div style="border:2px solid green">
Ваш запрос на SQL:
<br/><br/><span role="SQL"> </span>
</div>
I'm not familiar with all the parameters, but this seems to work:
ISessionFactory sessionFactory = ...
var sf = (SessionFactoryImpl) sessionFactory;
var hql = "from Person";
var qt = sf.Settings.QueryTranslatorFactory.CreateQueryTranslator("", hql, new Dictionary<string, IFilter>(), (ISessionFactoryImplementor) sessionFactory);
qt.Compile(new Dictionary<string, string>(), true);
var sql = qt.SQLString;
Console.WriteLine(sql);
I'm not sure what the value of auto-converting HQL to SQL is dynamically...
What exactly are you trying to accomplish by this?
The easiest way would be to run your code while running SQL Server Profiler to see the generated SQL. But a better approach would be to download nhProf (www.nhprof.com) and use that with your code. You will be able to see exactly what your code is outputting in SQL and it will format and color code it and also give you tips on ways to improve your usage of nhibernate.
With NHibernate 3.2, this seems to be the easiest way to get the SQL from an HQL query:
private string GetSQL(string hql)
{
using (var iSession = ...)
{
var session = (NHibernate.Engine.ISessionImplementor)iSession;
var sf = (NHibernate.Engine.ISessionFactoryImplementor)iSession.SessionFactory;
var sql = new NHibernate.Engine.Query.HQLStringQueryPlan(hql, true, session.EnabledFilters, sf);
return string.Join(";", sql.SqlStrings);
}
}
Here is how to do it with NH 5.2 (see https://stackoverflow.com/a/55542462/2047306)
public static string HqlToSql(string hql, ISession session)
{
var sessionImp = (ISessionImplementor)session;
var translatorFactory = new ASTQueryTranslatorFactory();
var translators = translatorFactory.CreateQueryTranslators(new NHibernate.Hql.StringQueryExpression(hql),
null, false, sessionImp.EnabledFilters, sessionImp.Factory);
var hqlSqlGenerator = new HqlSqlGenerator(((QueryTranslatorImpl)translators[0]).SqlAST, sessionImp.Factory);
hqlSqlGenerator.Generate();
return hqlSqlGenerator.Sql.ToString();
}