Problem
How to modify function GetSelectStatement to generate inner join select statement by using csharp ?
I have json string data as following
{
"Details":{
"table":[
"MasterTable",
"FooterTable"
],
"fields":{
"ItemCode":"string",
"Quantity":"int",
"Price":"decimal"
},
"keys":{
"BranchCode":1,
"Year":2019,
"Serial":2
}
}
}
How to modify csharp function GetSelectStatement to generate inner join select statement as :
public string GetSelectStatement(string JsonDataForSelect)
{
var root = (JObject)JsonConvert.DeserializeObject(JsonDataForSelect);
var query = "";
var items = root.SelectToken("Details").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
foreach (var item in items)
{
if (item.Key == "table")
{
var tableName = item.Value;
query = string.Format("select from table {0} inner join table{1} where", tableName);
}
else if (item.Key == "keys")
{
var key = item.Value.SelectToken("").OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
var count = 0;
foreach (var id in key)
{
count++;
if (count == key.Count())
{
query += string.Format("{0} = {1}", id.Key, id.Value);
}
else
{
query += string.Format("{0} = {1} and ", id.Key, id.Value);
}
}
}
}
return query;
}
select Statement desired result is :
select FooterTable.ItemCode,FooterTable.Quantity,FooterTable.UniPrice from
MasterTable inner join FooterTable on MasterTable.Serial=FooterTable.Serial,MasterTable.BranchCode=FooterTable.BranchCode,MasterTable.Year=FooterTable.Year
where MasterTable.Serial=10 AND MasterTable.Year=2019 AND MasterTable.BranchCode=1
Here is a simple workaround like below:
public string GetSelectStatement(string JsonDataForSelect)
{
var root = (JObject)JsonConvert.DeserializeObject(JsonDataForSelect);
var query = "";
var query1 = "";
var query2 = "";
string[] tableName = new string[] { };
var items = root.SelectToken("Details").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
foreach (var item in items)
{
if (item.Key == "table")
{
tableName = JsonConvert.DeserializeObject<string[]>(item.Value.ToString());
}
else if (item.Key == "fields")
{
var key = item.Value.SelectToken("").OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
var count = 0;
foreach (var id in key)
{
count++;
if (count == key.Count())
{
query1 += string.Format("{0}.{1}", tableName[1], id.Key);
}
else
{
query1 += string.Format("{0}.{1},", tableName[1], id.Key);
}
query = string.Format("select {0} from {1} inner join {2} on {3} where ", query1, tableName[0], tableName[1], query2);
}
}
else if (item.Key == "keys")
{
var key = item.Value.SelectToken("").OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
var count = 0;
if (query2 == "")
{
foreach (var id in key)
{
count++;
if (count == key.Count())
{
query2 += string.Format("{0}.{1}={2}.{3}", tableName[0], id.Key, tableName[1], id.Key);
}
else
{
query2 += string.Format("{0}.{1}={2}.{3},", tableName[0], id.Key, tableName[1], id.Key);
}
query = string.Format("select {0} from {1} inner join {2} on {3} where ", query1, tableName[0], tableName[1], query2);
}
}
count = 0;
foreach (var id in key)
{
count++;
if (count == key.Count())
{
query += string.Format("{0}.{1}={2} ", tableName[0], id.Key, id.Value);
}
else
{
query += string.Format("{0}.{1}={2} and ", tableName[0], id.Key, id.Value);
}
}
}
}
return query;
}
Result:
Please Guys, I have a forum and I want users to be able to reply comments so that the reply would appear with the comment.
This is what I have:
public ActionResult Quote(int? id)
{
var user = User.Identity.Name;
var userId = WebSecurity.CurrentUserId;
//var userId = db.UserProfiles.FirstOrDefault(x => x.UserName == user).UserId;
if (User.Identity.Name == null)
{
return RedirectToAction("Login", "Account");
}
if (id == null)
{
return RedirectToAction("topics", "forum");
}
//var p = db.Posts.FirstOrDefault(x => x.PostId == id.Value);
var post = db.Posts.Find(id.Value);
var comment = db.UserComments.FirstOrDefault();
var usercomment = db.UserComments.Find(comment.UserCommentId);
if (usercomment == null)
{
return RedirectToAction("topics");
}
return View(new Quote { UserId = WebSecurity.CurrentUserId, PostId = id.Value, UserCommentId = usercomment.UserCommentId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Quote(Quote quote, int id = 0)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
System.Random randomInteger = new System.Random();
int genNumber = randomInteger.Next(1000000);
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0 && file.ContentType.ToUpper().Contains("JPEG") || file.ContentType.ToUpper().Contains("PNG") || file.ContentType.ToUpper().Contains("JPG"))
{
WebImage img = new WebImage(file.InputStream);
if (img.Width > 500)
{
img.Resize(width: 500, height: 400, preserveAspectRatio: true, preventEnlarge: true);
}
if (img.Height > 700)
{
img.Resize(width: 500, height: 400, preserveAspectRatio: true, preventEnlarge: true);
}
string fileName = Path.Combine(Server.MapPath("~/Uploads/"), Path.GetFileName(genNumber + file.FileName));
img.Save(fileName);
if (fileName == null)
{
ViewBag.image = "True";
}
quote.QuoteFile = fileName;
}
}
var user = WebSecurity.CurrentUserId;
//var userId = db.UserProfiles.FirstOrDefault(a => a.UserId == user);
db.Quotes.Add(quote);
quote.QuotedBy = User.Identity.Name;
var post = db.Quotes.Include(f => f.Posts).Where(x=>x.UserCommentId == quote.UserCommentId).OrderByDescending(s => s.QuoteId);
quote.DateQuoted = DateTime.Now;
db.SaveChanges();
return RedirectToAction("topics", "forum", new { id = quote.PostId});
}
return View(quote);
}
public ActionResult _Quote(int id = 0)
{
//var comment = db.UserComments.FirstOrDefault(x => x.PostId == id);
var user = WebSecurity.CurrentUserId;
var comments = db.Quotes.Where(x => x.PostId == id).ToList();
//var quotes = db.UserComments.Where(x => x.PostId == id).ToList();
var p = new UserComment();
p.DateUserCommented = DateTime.Now;
DateTime dt = Convert.ToDateTime(p.DateUserCommented);
string strDate = dt.ToString("dd MMMM yyyy - hh:mm tt");
ViewBag.p = strDate;
ViewBag.data = comments;
return PartialView(comments);
}
[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.
The Class Employee.cs is like that
public class Employee
{
public int EmployeeID;
public string Name;
}
The Class Order.cs is like that
public class Order
{
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public string OrderDescription { get; set; }
public int EmployeeID { get; set; }
public bool checker { get; set; }
public bool Maker { get; set; }
public bool Supervisor { get; set; }
}
The Home Controller is like that
public class HomeController : Controller
{
public static List<Order> orderList = new List<Order> {
new Order {OrderID = 1, OrderDate = new DateTime(2012,8,1), EmployeeID = 1, OrderDescription = "Order Food",checker=true,Maker=true,Supervisor=true },
new Order {OrderID = 2, OrderDate = new DateTime(2012,8,1), EmployeeID = 2, OrderDescription = "Order Office Materials",checker=false,Maker=true,Supervisor=true },
new Order {OrderID = 3, OrderDate = new DateTime(2012,8,2), EmployeeID = 1, OrderDescription = "Order Production Materials",checker=true,Maker=true,Supervisor=true },
new Order {OrderID = 4, OrderDate = new DateTime(2012,8,3), EmployeeID = 4, OrderDescription = "Order Food",checker=true,Maker=true,Supervisor=true },
new Order {OrderID = 5, OrderDate = new DateTime(2012,8,4), EmployeeID = 3, OrderDescription = "Order Production Materials" ,checker=false,Maker=true,Supervisor=true},
new Order {OrderID = 6, OrderDate = new DateTime(2012,8,5), EmployeeID = 3, OrderDescription = "Order Production Materials" ,checker=true,Maker=true,Supervisor=true},
new Order {OrderID = 7, OrderDate = new DateTime(2012,8,5), EmployeeID = 4, OrderDescription = "Order Food", checker=true,Maker=true,Supervisor=true},
new Order {OrderID = 8, OrderDate = new DateTime(2012,8,6), EmployeeID = 1, OrderDescription = "Order Food", checker=true,Maker=true,Supervisor=true},
new Order {OrderID = 9, OrderDate = new DateTime(2012,8,6), EmployeeID = 1, OrderDescription = "Order Office Materials" ,checker=false,Maker=true,Supervisor=true},
new Order {OrderID = 10, OrderDate = new DateTime(2012,8,7), EmployeeID = 2, OrderDescription = "Order Production Materials",checker=true,Maker=true,Supervisor=true },
};
public static List<Employee> employeeList = new List<Employee> {
new Employee {EmployeeID = 1, Name = "Anrew"},
new Employee {EmployeeID = 2, Name = "John"},
new Employee {EmployeeID = 3, Name = "Peter"},
new Employee {EmployeeID = 4, Name = "Ivan"},
new Employee {EmployeeID = 5, Name = "Nancy"},
};
public ActionResult Index()
{
ViewData["employees"] = employeeList.Select(e => new {
EmployeeID = e.EmployeeID,
Name = e.Name
});
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var allOrders = from orders in orderList
select new Order{
OrderID = orders.OrderID,
OrderDate = orders.OrderDate,
EmployeeID = orders.EmployeeID,
OrderDescription = orders.OrderDescription,
checker=orders.checker,
Maker=orders.Maker
};
return Json(allOrders.ToDataSourceResult(request));
}
public ActionResult Delete([DataSourceRequest] DataSourceRequest request, Order order)
{
if (order != null && ModelState.IsValid)
{
var target = orderList.Where(o => o.OrderID == order.OrderID).FirstOrDefault();
if (target != null)
{
orderList.Remove(target);
}
}
return Json(ModelState.ToDataSourceResult());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update([DataSourceRequest] DataSourceRequest request, Order order)
{
if (order != null && ModelState.IsValid)
{
var target = orderList.Where(o => o.OrderID == order.OrderID).FirstOrDefault();
if (target != null)
{
int targetIndex = orderList.IndexOf(target);
orderList[targetIndex].OrderDate = order.OrderDate;
orderList[targetIndex].EmployeeID = order.EmployeeID;
orderList[targetIndex].OrderDescription = order.OrderDescription;
orderList[targetIndex].checker = order.checker;
orderList[targetIndex].Maker = order.Maker;
orderList[targetIndex].Supervisor = order.Supervisor;
}
}
return Json(ModelState.ToDataSourceResult());
}
public ActionResult Create([DataSourceRequest] DataSourceRequest request, Order order)
{
order.OrderID = orderList[orderList.Count - 1].OrderID + 1;
orderList.Add(order);
return Json(new[] { order }.ToDataSourceResult(request, ModelState));
}
public ActionResult UpdateCreateDelete(
[Bind(Prefix = "updated")]List<Order> updatedOrders,
[Bind(Prefix = "new")]List<Order> newOrders,
[Bind(Prefix = "deleted")]List<Order> deletedOrders)
{
if (updatedOrders != null && updatedOrders.Count > 0)
{
for (int i = 0; i < updatedOrders.Count; i++)
{
var target = orderList.Where(o => o.OrderID == updatedOrders[i].OrderID).FirstOrDefault();
if (target != null)
{
int targetIndex = orderList.IndexOf(target);
orderList[targetIndex].OrderDate = updatedOrders[i].OrderDate;
orderList[targetIndex].EmployeeID = updatedOrders[i].EmployeeID;
orderList[targetIndex].OrderDescription = updatedOrders[i].OrderDescription;
orderList[targetIndex].checker = updatedOrders[i].checker;
orderList[targetIndex].Supervisor = updatedOrders[i].Supervisor;
orderList[targetIndex].Maker = updatedOrders[i].Maker;
}
}
}
if (newOrders != null && newOrders.Count > 0)
{
for (int i = 0; i < newOrders.Count; i++)
{
newOrders[i].OrderID = orderList[orderList.Count - 1].OrderID + 1;
orderList.Add(newOrders[i]);
}
}
if (deletedOrders != null && deletedOrders.Count > 0)
{
for (int i = 0; i < deletedOrders.Count; i++)
{
var target = orderList.Where(o => o.OrderID == deletedOrders[i].OrderID).FirstOrDefault();
if (target != null)
{
orderList.Remove(target);
}
}
}
return Json("Success!");
}
The html page Index.cshtml is like that
#(Html.Kendo().Grid<GridSyncChangesWithOneRequest.Models.Order>()
.Name("Grid")
.Columns(columns => {
columns.Bound(p => p.OrderID);
columns.ForeignKey(p => p.EmployeeID,(System.Collections.IEnumerable)ViewData["employees"], "EmployeeID", "Name");
columns.Bound(p => p.OrderDescription);
columns.Bound(p => p.Maker);
columns.Bound(p => p.checker);
//columns.Bound(p => p.checker).HeaderTemplate("Checker").ClientTemplate("<input type='checkbox' id='#= ID#,#= Name#' class='grid_checkbox'/>");
columns.Bound(p => p.Supervisor);
columns.Bound(p => p.OrderDate).Format("{0:d}");
columns.Command(c => {
c.Destroy();
});
})
.ToolBar(toolBar => toolBar.Create())
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Model(model => {
model.Id(p => p.OrderID);
model.Field(p => p.OrderDescription).Editable(false);
model.Field(p => p.EmployeeID).Editable(false);
model.Field(p => p.OrderID).Editable(false);
model.Field(p => p.Maker).Editable(false).DefaultValue(true);
model.Field(p => p.OrderDate).Editable(false);
})
.Create(create => create.Action("Create", "Home"))
.Destroy(destroy => destroy.Action("Delete", "Home"))
.Read(read => read.Action("Read", "Home"))
.Update(update => update.Action("Update", "Home"))
) )
Pressing the saveChanges will send all current changes to the
server:
<button onclick="sendData()">Save Changes</button>
<script>
function sendData() {
var grid = $("#Grid").data("kendoGrid"),
parameterMap = grid.dataSource.transport.parameterMap;
//get the new and the updated records
var currentData = grid.dataSource.data();
var updatedRecords = [];
var newRecords = [];
for (var i = 0; i < currentData.length; i++) {
if (currentData[i].isNew()) {
//this record is new
newRecords.push(currentData[i].toJSON());
} else if(currentData[i].dirty) {
updatedRecords.push(currentData[i].toJSON());
}
}
//this records are deleted
var deletedRecords = [];
for (var i = 0; i < grid.dataSource._destroyed.length; i++) {
deletedRecords.push(grid.dataSource._destroyed[i].toJSON());
}
var data = {};
$.extend(data, parameterMap({ updated: updatedRecords }), parameterMap({ deleted: deletedRecords }), parameterMap({ new: newRecords }));
$.ajax({
url: "/Home/UpdateCreateDelete",
data: data,
type: "POST",
error: function () {
//Handle the server errors using the approach from the previous example
},
success: function () {
alert("update on server is completed");
grid.dataSource._destroyed = [];
//refresh the grid - optional
grid.dataSource.read();
}
})
} </script>
Instead of True of False i need to show only checkBox while
Editing.Is there any possible solutions? !enter image description
here
Check the checker field for true and false in client template
columns.Bound(p=> p.checker).ClientTemplate("# if(checker==true){#" + "<input type='checkbox' checked='checked' />" + "#}else{#" + "<input type='checkbox' />" + "#}#");
You could either use this Telerik answer
or this from the documentation :
columns.Bound(p => p.Enabled).ClientTemplate(
"<input type='checkbox' value='#= ProductID #' " +
"# if (Enabled) { #" +
"checked='checked'" +
"# } #" +
"/>"
);
I am using a Data Entity from the db, and a Domain Service.
I am using .net's generated code for the simple queries, like this
public IQueryable<employee> GetEmployeesByLocale(int localeID)
{
return ObjectContext.employees.Where(e => e.Locale_ID == localeID);
}
Now, I need to change the .Where section accordingly, so:
if (localeID > 0)
{
['Where' should be like .Where(e => e.Locale_ID == localeID)];
}
if (projectID > 0)
{
[IF localeID == 0, 'Where' should be like .Where(e => e.Project_ID == projectID)
Else if localeID > 0, Where should use both, sort of .Where(e => e.Locale_ID == localeID && e.Project_ID == projectID)];
}
and so on with other variables.
There are many possible combinations , which is why I was trying to use the overload for .Where(string, parameter[])
string q = string.Empty;
if (localeID > 0)
{
q = "Locale_ID = " + localeID.ToString();
}
if (projectID > 0)
{
q = q == string.Empty ? "Project_ID = " + projectID.ToString() : q + " and " + "Project_ID = " + projectID.ToString();
}
... (for other variables and fields)
...
System.Data.Objects.ObjectParameter[] param = new System.Data.Objects.ObjectParameter[1];
param[0] = new System.Data.Objects.ObjectParameter("param", 1);
return ObjectContext.employees.Where(q, param);
However, this only gives an error, because then all the fieldnames are supposedly out-of-scope/non-existing. Even if use employees.[field_name] in the string, they "don't exist"
Does anyone know of a way to use conditionals inside the .Where part of the query? Or how to create some var or object containing my query so I can just parse it?
You can use
IQueryable<Employee> emp = ObjectContext.employees;
if (localeID > 0)
emp=emp.Where(e => e.Locale_ID == localeID).AsQueryable();
if (projectID > 0)
emp=emp.Where(e => e.Project_ID == projectID).AsQueryable();
This will concatenate the where clauses