I have a table displaying vacation requests from employees. Right now I'm displaying requests from all years in that table with the "onAttach" event. I want to implement a dropdown with a binding to the "year" column in my external sql data. so whenever I select a year out of that dropdown, I want the table to update only showing requests from that specific year in the table. How do I implement it?
the onAttach function loadHolidayTable() of the table leads to this client function
function loadHolidayTable() {
app.datasources.HolidayModel.load({
failure: function (error) {
displayTimedSnackbar('Unable to load holidays table: ' + error);
}
});
}
My Server Script in the datasource "HolidayModel"
return calculateHolidayModel(query);
leads to this server function:
function calculateHolidayModel(query) {
var queryStr = '';
var currentYear = null; --> to be replaced by dropdown value
if (currentYear === null || currentYear == 'undefined') {
queryStr = 'SELECT * FROM Holidays WHERE employeeID = ' + "'" + empID + "'";
}
else {
queryStr = 'SELECT * FROM Holidays WHERE employeeID = ' + "'" + empID + "'" + ' AND year = ' + "'" + currentYear + "'";
}
console.log(queryStr);
//var dayRecords = [];
var holidayRecords = [];
var connection = getJDBCConnection_();
var statement = connection.prepareStatement(queryStr);
try {
var results = statement.executeQuery();
while(results.next()) {
var holidayRecord = app.models.HolidayModel.newRecord();
holidayRecord.ID = results.getInt(2);
holidayRecord.From = new Date(results.getString(3));
holidayRecord.To = new Date(results.getString(4));
holidayRecord.Status = results.getString(5);
holidayRecords.push(holidayRecord);
console.log(results.getInt(2));
}
results.close();
statement.close();
} catch (err) {
console.log(err);
}
return holidayRecords;
}
currentYear should be replaced by the value from the dropdown.
any suggestions are welcome!
Related
I'm currently working on UWP project and I use sqlite database.In this project I want to update field in sqlite table(classroomteam).When I entered value with apostrophe(') It gives error saying "SQLite.SQLiteException: 'near "s": syntax error'"
This is the code that I used to save updated data to the table
public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
{
IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
ClassroomTeam classroomTeam = new ClassroomTeam()
{
TeamName = classroomTeamItem.TeamName,
Id = classroomTeamItem.Id,
};
String teamName = classroomTeamItem.TeamName;
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
//Task<int> a = conn.UpdateAsync(configInfo);
await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '" + classroomTeamItem.TeamName + "' WHERE Id = '" + classroomTeam.Id + "'");
await conn.CloseAsync();
IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
}
I tried this to solve my issue and what I did is applying new String[] {classroomTeamItem.TeamName } in the query.Then I didn't get any error but the value is stored as System.String[] not the value I entered in sqlite table.The code I tried as follows.
public static async Task UpdateTeamName(ClassroomTeamItem classroomTeamItem)
{
IWAppUtils.PrintDebug("====Start ", CLASS_NAME, "UpdateTeamName()");
ClassroomTeam classroomTeam = new ClassroomTeam()
{
TeamName = classroomTeamItem.TeamName,
Id = classroomTeamItem.Id,
};
String teamName = classroomTeamItem.TeamName;
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(IWSQLite.DATABASE_NAME);
//Task<int> a = conn.UpdateAsync(configInfo);
await conn.ExecuteAsync("UPDATE classroomteam SET TeamName = '" + new String[] { classroomTeam.TeamName } + "' WHERE Id = '" + classroomTeam.Id + "'");
await conn.CloseAsync();
IWAppUtils.PrintDebug("====End ", CLASS_NAME, "UpdateTeamName()");
}
I would appreciate if anyone can help me to resolve this issue.
The sql string about how to update field is:
string SQL_UPDATE = "UPDATE " + TABLE_NAME + " SET Value = ? WHERE Key = ?";
So you could try to change your update string to
await db.ExecuteAsync("UPDATE classroomteam SET TeamName = " + classroomTeamItem.TeamName + " WHERE Id = " + classroomTeam.Id);
Or you can query for the specific data is most straightforwardly done using the Table method and then update your field. For example:
private async void update(ClassroomTeamItem classroomTeamItem)
{
var query = db.Table<ClassroomTeam>().Where(s => s.Id==classroomTeam.Id);
var result = await query.ToListAsync();
foreach (var s in result)
{
s.TeamName = classroomTeamItem.TeamName;
await db.UpdateAsync(s);
}
}
select rows between two dates in sqlite using java.
When i try to retrieve rows between to two dates from sqlite database in javafx program i always get one row from the whole rows even if there is multiple rows it select the first row and discard the remaining or not included in the result set at all, how can solve this problem and again the database has some records but the query always return the first one
#FXML
private void report(ActionEvent event)
{
if(searchfromDate.getValue() != null && searchToDate.getValue() != null)
{
try
{
DBconnector.connect();
LocalDate startDate = searchfromDate.getValue();
LocalDate endDate = searchToDate.getValue();
String query = "select * from selled where date between '" + startDate
+ "' and '" + endDate + "'";
ResultSet rs = DBconnector.query(query);
Alert alert = new Alert(AlertType.INFORMATION);
JSONObject file = new JSONObject();
if(rs.next())
{
int id = rs.getInt("id");
String customer = rs.getString("costomer");
String name = rs.getString("name");
String barcode = rs.getString("barcode");
int amount = rs.getInt("amount");
LocalDate date = LocalDate.parse(rs.getString("date"));
double price = rs.getDouble("price");
String garentee = rs.getString("garentee");
file.put("id", id);
file.put("customer", customer);
file.put("name", name);
file.put("barcode", barcode);
file.put("amount", amount);
file.put("date", date);
file.put("price", price);
file.put("garentee", garentee);
}
FileWriter writer = new FileWriter("تقرير المبيعات.json");
writer.write(file.toString());
writer.flush();
writer.close();
alert.setTitle("رسالة تاكيد");
alert.setHeaderText(null);
alert.setContentText("تم استخراج الملف بنجاح");
alert.showAndWait();
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI("https://arabsefr.com/save-report?fbclid=IwAR2ON1Tl8ETQ--3QEAVFJLMjTuWUhpLCZrD3PXhg8TZpdlUH4umKBfl78OM"));
}
catch (Exception ex)
{
System.out.println(ex);
}
}
else
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("رسالة تاكيد");
alert.setHeaderText(null);
alert.setContentText("لم يتم تحديد التاريخ");
alert.showAndWait();
}
}
When you are using SQLite, use of strftime() method is always recommended while manipulating with dates this makes sure that future troubles are avoided.
WHERE strftime('%s', date) between strftime('%s', startDate) and strftime('%s', endDate)
[HttpPost]
public ActionResult Create(Showroom showroom)
{
objShowroom.InsertShowroomDetails(showroom);
return RedirectToAction("Index");
}
I had separate data access layer
how to update the upload image in database
insert query no problem with that
if I edit any textbox image will disappear in postback or roundtrip
5. I will use not entity framework so I want to connect with model using ado.net
model folder:
public int UpdateShowroomDetails(Showroom objShowroom)
{
sqlCommandText = "Update Showroom Set CARIMAGE='" + objShowroom.CARIMAGE + "', CARNAME='" + objShowroom.CARNAME + "', CARBRAND='" + objShowroom.CARBRAND + "', PRICE=" + objShowroom.PRICE + " Where ID="+objShowroom.ID ;
return objDAL.ExecuteNonQuery(sqlCommandText);
}
Here is how i save d my image to db using ado.net . Hope this will help you
string fileName = string.Empty;
string servr_path = string.Empty;
string serviceId = string.Empty;
string planId = string.Empty;
if (IdProofFile.HasFile && IdProofFile.PostedFile.FileName != "")
{
string fileType = IdProofFile.PostedFile.ContentType;
if (fileType == "image/jpg" || fileType == "image/jpeg" || fileType == "image/png" || fileType == "image/gif")
{
int fileSize = IdProofFile.PostedFile.ContentLength;
if (fileSize <= 2097152)
{
//fileName = System.IO.Path.GetFileName(IdProofFile.PostedFile.FileName);
fileName = "ID-" + txt_FirstName.Text + "_" + txt_LstName.Text + DateTime.Now.ToString("ddmmyy_hhMMss") + Path.GetExtension(IdProofFile.PostedFile.FileName);
string serverFolder = Server.MapPath("idProof//");
if (!System.IO.Directory.Exists(serverFolder))
{
System.IO.Directory.CreateDirectory(serverFolder);
}
servr_path = serverFolder + fileName;
foreach (int i in ddlservices.GetSelectedIndices())
{
serviceId += "," + ddlservices.Items[i].Value;
}
IdProofFile.SaveAs(servr_path);
}
}
else
{
}
}
else
{
}
}
else
{
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
mpepopup.Show();
lblMsg.Text = "Min File Size Must Be Greater Than 5 KB and Less Than 2 MB";
}
}
else
{
mpepopup.Show();
// ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
lblMsg.Visible = true;
lblMsg.Text = "Please upload an image of *.jpg/*.jpeg/*.png/*.gif/*.bmp file type only!!!";
}
}
else
{
mpepopup.Show();
lblMsg.Text = "ID Proof File Not Selected.";
}
I have a jQuery bootgrid implemented into my ASP.Net application which is filled using a Generic Handler.
I fill the bootgrid using the Generic Handler as follows:
$(function () {
var grid = $("#grid").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
},
url: "/MyHandler.ashx",
rowCount: [10, 50, 75, 100, 200, -1]
});
}
Here's MyHandler.ashx code:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
context.Response.Write(GetData());
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData()
{
var result = string.Empty;
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
var sNumRows = dt.Rows.Count.ToString();
var sDT = JsonConvert.SerializeObject(dt);
result = "{ \"current\": 1, \"rowCount\": 10, \"rows\": " + sDT + ", \"total\": " + sNumRows + " }";
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
THF.Models.SQLConnectionManager.CloseConn(con);
}
return result;
}
}
Basically all the important functionality of my bootgrid that worked before I implemented it the ajax way doesn't work anymore. Specifically the ordering, searching and pagination functionality aren't working at all without any errors.
As far as I know from a bit of research. This is because every time a search phrase is made, or a header is clicked (for ordering) etc. The bootgrid performs an ajax call.
Any idea on how to fix the functionality here?
After much work I ended up getting it working and this is the final code result:
public class RolesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
var current = context.Request.Params["current"];
var rowCount = context.Request.Params["rowCount"];
var orderById = context.Request.Params["sort[Id]"];
var orderByName = context.Request.Params["sort[Name]"];
var searchPhrase = context.Request.Params["searchPhrase"];
var orderBy = "Id";
var orderFrom = "ASC";
if (orderById != null)
{
orderBy = "Id";
orderFrom = orderById;
}
else if (orderByName != null)
{
orderBy = "Name";
orderFrom = orderByName;
}
context.Response.Write(GetData(current, rowCount, orderBy, orderFrom, searchPhrase));
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetData(string current, string rowCount, string orderBy, string orderFrom, string searchPhrase)
{
var result = string.Empty;
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if (!"Id".Equals(orderBy, StringComparison.OrdinalIgnoreCase)
&& !"Name".Equals(orderBy, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderBy is not a valid value");
if (!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if (!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT Id, Name
FROM dbo.AspNetRoles
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase
ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
command.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase + "%"));
command.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
connection.Close();
}
}
var total = string.Empty;
string sSQLTotal = #"SELECT COUNT(*)
FROM dbo.Log
WHERE Id LIKE #searchPhrase
OR Name LIKE #searchPhrase;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQLTotal, connection))
{
command.Parameters.Add(new SqlParameter("searchPhrase", "%" + searchPhrase + "%"));
connection.Open();
command.CommandTimeout = 0;
total = command.ExecuteScalar().ToString();
connection.Close();
}
}
var rows = JsonConvert.SerializeObject(dt);
return result = "{ \"current\": " + current + ", \"rowCount\": " + rowCount + ", \"rows\": " + rows + ", \"total\": " + total + " }";
}
}
I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV