I have a Class that return a List of Users
public IList<RegisterUsers> GetUsers()
{
var query = (from up in _context.UserProfile
join um in _context.Membership on up.UserID equals um.UserID
select new RegisterUsers { ID = ua.UserID, FirstName = ua.FirstName, LastName = ua.LastName, LastLogIn = up.LastLogIn, Status = up.Status });
return query.ToList();
}
I call this class by doing the following on my Action
var UserRepository = new UserRepository();
var AllUsers = UserRepository.GetUsers();
var result = from c in AllUsers
select new List<string> { c.ID.ToString(), c.FirstName, c.LastName, c.LastLogIn,c.Status };
return Json(new { sEcho = param.sEcho,
iTotalRecords = result.Count(),
iTotalDisplayRecords = result.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
The above code works fine and it return JSON data. But I'm trying o figure out why I get an error if I just attach the AllUsers directly to the aaData variable. Please see below.
var UserRepository = new UserRepository();
var AllUsers = UserRepository.GetUsers();
return Json(new { sEcho = param.sEcho,
iTotalRecords = AllUsers.Count(),
iTotalDisplayRecords = AllUsers.Count(),
aaData = AllUsers
},
JsonRequestBehavior.AllowGet);
I was able to Return a List by doing the following
var AllUsers = UserRepository.GetUsers().Select(p => new List<string> { p.UserID.ToString(), p.FirstName, p.LastName }).ToList();
Basically the above code just eliminates the following line of code
var result = from c in AllUsers
select new List<string> { c.ID.ToString(), c.FirstName, c.LastName, c.LastLogIn,c.Status };
Hopefully I was able to answer your question.
Related
Here's my old code.
public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
DatawarehouseEntities db = new DatawarehouseEntities();
// Get JSON from WebHook
JObject data = context.GetDataOrDefault<JObject>();
var tableName = data["Table_Name"].ToString();
var columnNames = db.Database.SqlQuery<string>(String.Format("SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('{0}'); ", tableName)).ToList();
var table = db.GetType().GetProperty(tableName).GetValue(db, null);
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.SingleOrDefault(a => a.GetName().Name == "DSI.Data");
var type = assembly.GetTypes().FirstOrDefault(t => t.Name == tableName);
var dbset = Activator.CreateInstance(type);
//var dbset = db.Set(type);
var jsonParams = data.Properties().Select(x => x.Name).ToList();
var selectedColumnNames = columnNames.Intersect(jsonParams);
foreach (var columnName in selectedColumnNames)
{
var property = dbset.GetType().GetProperties().FirstOrDefault(x => x.Name == columnName);
property.SetValue(dbset, data[columnName].ToString(), null);
}
db.Set(type).Add(dbset);
db.SaveChanges();
return Task.FromResult(true);
}
Here's what I try to post http://localhost:port/api/webhooks/incoming/genericjson?code=secret&Table_Name=Table_Name. The type always comes back null. How can I select a table using the string that I pass in?
To make this easier, faster and less error-prone enumerate your entity types and add them to a lookup. EG
public static Dictionary<string, Type> EntityTypesByName { get; } = new Dictionary<string, Type>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var et in modelBuilder.Model.GetEntityTypes())
{
EntityTypesByName.Add(et.Name, et.ClrType);
}
}
This is what finally worked for me.
public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
DatawarehouseEntities db = new DatawarehouseEntities();
// Get JSON from WebHook
JObject data = context.GetDataOrDefault<JObject>();
var tableName = data["Table_Name"].ToString();
var columnNames = db.Database.SqlQuery<string>(String.Format("SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('{0}'); ", tableName)).ToList();
var table = db.GetType().GetProperty(tableName).GetValue(db, null);
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.SingleOrDefault(a => a.GetName().Name == "DSI.Data");
var type = assembly.GetTypes().FirstOrDefault(t => t.Name == tableName);
var dbset = Activator.CreateInstance(type);
var jsonParams = data.Properties().Select(x => x.Name).ToList();
var selectedColumnNames = columnNames.Intersect(jsonParams);
foreach (var columnName in selectedColumnNames)
{
var property = dbset.GetType().GetProperties().FirstOrDefault(x => x.Name == columnName);
property.SetValue(dbset, data[columnName].ToString(), null);
}
db.Set(type).Add(dbset);
db.SaveChanges();
return Task.FromResult(true);
}
When I add new Role to my own account I have to log out and log back in so this role will start working. Is there a way to re-load roles on the fly (after adding/deleting) ?
I'm using Individual Accounts stored in Ms SQL Server 2012 in MVC 5.1.2 and Identity v. 2.0.0
Below is controller code:
// GET: /Users/Edit/1
public async Task<ActionResult> Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
var userRoles = await UserManager.GetRolesAsync(user.Id);
return View(new EditUserViewModel()
{
Id = user.Id,
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
CustomerID = user.CustomerID,
siteID = user.SiteID,
RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
}),
SitesList = db.sites.ToList().Select(y=> new SelectListItem()
{
Selected= user.SiteID==y.siteID,
Text = y.siteCode,
Value= y.siteID.ToString()
})
});
}
//
// POST: /Users/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Email,Id,FirstName,LastName,CustomerID,siteID")] EditUserViewModel editUser, params string[] selectedRole)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(editUser.Id);
if (user == null)
{
return HttpNotFound();
}
user.UserName = editUser.Email;
user.Email = editUser.Email;
user.FirstName = editUser.FirstName;
user.LastName = editUser.LastName;
user.CustomerID = editUser.CustomerID;
user.SiteID = editUser.siteID;
var userRoles = await UserManager.GetRolesAsync(user.Id);
selectedRole = selectedRole ?? new string[] { };
var result = await UserManager.AddUserToRolesAsync(user.Id, selectedRole.Except(userRoles).ToList<string>());
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
result = await UserManager.RemoveUserFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToList<string>());
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
editUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
//Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
});
ModelState.AddModelError("", "Something failed.");
return View(editUser);
}
Hi Im using kendo ui grid in my project.
This is my code to insert records in database.
public static void Insert(StudentViewModel student)
{
student.StudentId = All().OrderByDescending(p => p.StudentId).First().StudentId + 1;
//All().Insert(0, student);
UniRegEntities uniRegEntities = new UniRegEntities();
Student stu =new Student();
stu.FName = student.FirstName;
stu.LName = student.LastName;
stu.Gender = uniRegEntities.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
stu.Id = student.StudentId;
uniRegEntities.Students.Add(stu);
uniRegEntities.SaveChanges();
}
And this is my update statement.
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToUpdate = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
studentToUpdate.FName = student.FirstName;
studentToUpdate.LName = student.LastName;
studentToUpdate.Gender = context.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
context.SaveChanges();
}
Anyone can suggest me the delete method?
You can either get an entity from the DB and then delete it or create one and then delete it.
So:
var e = // Get
ctx.DeleteObject(e);
ctx.SaveChanges();
or
var e = new Foo() { FooId = id };
ctx.Entity.Attach(e);
ctx.DeleteObject(e);
ctx.SaveChanges();
Applied to your situation:
You are getting a record so you want to use DeleteObject()
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToDelete = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
context.Students.DeleteObject(studentToUpdate);
context.SaveChanges();
}
context.Students.Remove(context.students.Single(x=>x.Id==student.Id));
Can you please try with below code snippet?
using (var db= new AppContext(ConnectionStr))
{
try
{
con.Configuration.AutoDetectChangesEnabled = false;
var o = new Student { StudentId = student.StudentId };
db.Students.Attach(o);
db.Students.Remove(o);
db.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message);
}
finally
{
con.Configuration.AutoDetectChangesEnabled = true;
}
}
While i build the Project, It have a error like this:
Server Error in '/' Application.
The model item passed into the dictionary is of type
'System.Data.DataTable', but this dictionary requires a model item of
type 'System.Collections.Generic.IList`1[TLayout.Models.DemoTable]'.
This is my Controller
public ActionResult Index()
{
var dm = new DemoTable();
string connstring = "Server=localhost;Port=5432;User Id=postgres;Password=123456;Database=test";
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
string sql = "select * from demo";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
var demoid = dm.demoid.ToString();
var demoname = dm.demoname;
for (int i = 0; i < dt.Rows.Count; i++)
{
List<DataTable> dtb = new List<DataTable>();
demoid = dt.Rows[i]["demoid"].ToString();
demoname = dt.Rows[i]["demoname"].ToString();
dtb.Add(dt);
}
return View(dt);
}
This is my View, to show data to layout:
foreach (var item in Model)
{
fields.Add(Html.X().ModelField().Mapping(#item.demoid.ToString()).Name("grid-alarm"));
fields.Add(Html.X().ModelField().Mapping(#item.demoname.ToString()).Name("grid-check"));
}
var list = dt.AsEnumerable()
.Where(row => (int)row["demoid"] > 5)
.Select(row => new
{
demoid = Convert.ToInt32(row["demoid"]),
demoname = row["demoname"] != null ?
row["demoname"].ToString() :
String.Empty
}).ToList();
Or you can define class:
public class myClass
{
public int demoid;
public string demoname;
}
and then:
List<myClass> list = dt.AsEnumerable()
.Where(row => (int)row["demoid"] > 5)
.Select(row => new myClass
{
demoid = Convert.ToInt32(row["demoid"]),
demoname = row["demoname"] != null ?
row["demoname"].ToString() :
String.Empty
}).ToList<myClass>();
I have one view that used to display the result of my search item. This is its controller :
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
return View();
}
I displayed the content in the view by looping ViewData["EmployeeType"] and I also included one Print label :
<script language="javascript" type="text/javascript">
function printChart() {
var URL = "EvaluatingReport";
var W = window.open(URL);
W.window.print();
}
function printPage(sURL) {
var oHiddFrame = document.createElement("iframe");
oHiddFrame.src = sURL;
oHiddFrame.style.visibility = "hidden";
oHiddFrame.style.position = "fixed";
oHiddFrame.style.right = "0";
oHiddFrame.style.bottom = "0";
document.body.appendChild(oHiddFrame);
oHiddFrame.contentWindow.onload = oHiddFrame.contentWindow.print;
oHiddFrame.contentWindow.onafterprint = function () {
document.body.removeChild(oHiddFrame); };
}
</script>
<span onclick="printPage('/Report/PrintEvaluatingReport');" style="cursor:pointer;text-decoration:none;color:#0000ff;">
<img src="../../Content/images/Print.png" width="35px;" alt="print" style="position:relative;top:6px;"/>
Print Report
</span>
I used function printPage('/Report/PrintEvaluatingReport') to load the print dialog with the action PrintEvaluatingReport. So I want to take the object that I have in EvaluatingReport to the action PrintEvaluatingReport.
Could anyone tell me how could I do that?
Thanks in advanced.
You could use TempData["EmployeeType"]
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
string empType = frm["empType"].ToString();
int totalMonth = 3;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
string Curdate = mon + "/" + yr;
DateTime date = new DateTime();
var result = (from e in context.tblEmployees
join p in context.tblEmployee_Position on e.PositionIDF equals p.PositionID
select new EvaluateEmployee
{
ID = e.Code,
IDCard = e.IDCard,
Name = e.NameEng,
DOB = e.DOB,
Position = p.Position,
Sex = e.Sex,
StartDate = e.StartDate
}).ToList();
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();
ViewData["EmployeeType"] = result;
// Store in TempData to be read by PrintEvaluatingReport
TempData["EmployeeType"] = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = TempData["EmployeeType"] as EmployeeType;
// do stuff
return View();
}
You can use a session variable for that !!
private EmployeeType Result
{
get { return (EmployeeType)this.Session["Result"]; }
set
{
this.Session["Result"] = value;
}
}
[HttpPost]
public ActionResult EvaluatingReport(FormCollection frm)
{
.
.
.
// Store in Session
this.Result = result;
return View();
}
public ActionResult PrintEvaluatingReport()
{
var employeeType = this.Result;
.
.
.
}