I'm working on an mvc .net web application and I'm using Entity Framework.
In my model, I have an entity called "utisateur" (user) and every user has one or more users that supervise him. What I want to do is generate a multi select list box that contains the list of all users inorder to select the new users' supervisors.
I tried to to that but i got this error :
Object reference not set to an instance of an object.
Here is my model class :
public class util
{
public util()
{
user = new utilisateur();
listesups = Getutilisateurs(null);
}
public utilisateur user { get; set; }
public int[] selectedusers;
public MultiSelectList listesups { get; set; }
public MultiSelectList Getutilisateurs(int[] selectedValues)
{
var db = new BDGestionEntities();
List<utilisateur> utilisateurs = db.utilisateurs.ToList();
return new MultiSelectList(utilisateurs, "id", "login", selectedValues);
}
}
And here is the part of the view that contains the list box :
#Html.ListBoxFor(model => model.selectedusers, Model.listesups)
Here is the controller
public ActionResult Create2()
{
return View();
}
[HttpPost]
public ActionResult Create2(util model)
{
utilisateur u = new utilisateur();
if (model.selectedusers != null)
{
foreach (var selecteduse in model.selectedusers)
{
int selecteduseId = selecteduse;
utilisateur utilisateur = db.utilisateurs.Where(c => c.id == selecteduseId).FirstOrDefault();
u.superieur.Add(utilisateur);
}
}
u.nom = model.user.nom;
u.prenom = model.user.prenom;
u.solde_conge = model.user.solde_conge;
u.email = model.user.email;
u.login = model.user.login;
u.pwd = model.user.pwd;
role role = new role();
//role.nom_role = model.nom_role;
role = db.roles.Where(c => c.nom_role == model.nom_role).FirstOrDefault();
u.role = role;
db.utilisateurs.AddObject(u);
db.SaveChanges();
ViewBag.id_role = new SelectList(db.roles, "id", "nom_role", model.user.id_role);
return RedirectToAction("index");
}
And here is the error message
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 44: <tr><td><label><b>Role : </b></label></td><td>#Html.DropDownListFor(model => model.nom_role, values)</td></tr>
Line 45: <tr>
Line 46: <td><label><b>Liste des supérieurs : </b></label></td><td>#Html.ListBoxFor(model => model.selectedusers, Model.listesups)</td></tr>
Line 47: </table>
Line 48: <p>
I solved this by editing my Create2() method like this :
public ActionResult Create2()
{
string login = User.Identity.Name;
utilisateur ut = new utilisateur();
var q = from j in db.utilisateurs where j.login == login select j;
foreach (var i in q)
ut = i;
if ((ut.role.nom_role == "Stagiaire") || (ut.role.nom_role == "Developpeur"))
return Redirect("~/Erreur");
util u = new util();
u.listesups = new MultiSelectList (db.utilisateurs, "id", "login");
return View(u);
}
[HttpPost]
public ActionResult Create2(FormCollection collection, util model)
{
var sups = collection["selectedusers"];
string login = User.Identity.Name;
utilisateur u = new utilisateur();
List<int> nums = new List<int>();
var q = from j in db.utilisateurs where j.login == login select j;
utilisateur courant = new utilisateur();
try
{
foreach (var i in q)
{
courant = i;
}
foreach (var s in sups.Split(','))
{
nums.Add(int.Parse(s));
}
}
catch(Exception ex)
{
Logger.Warning(ex.Message, "aucun superieur selectionné");
}
try
{
foreach (var selecteduse in nums)
{
utilisateur utilisateur = db.utilisateurs.Where(c => c.id == (int)selecteduse).FirstOrDefault();
u.superieur.Add(utilisateur);
}
}
catch(Exception ex)
{
Logger.Error(ex.Message, "Erreur ajout supérieurs");
}
//}
if ((model.user.nom != null) && (model.user.prenom != null) && (model.user.login != null) && (model.user.email != null))
{
u.nom = model.user.nom;
u.prenom = model.user.prenom;
u.solde_conge = model.user.solde_conge;
u.email = model.user.email;
u.login = model.user.login;
u.pwd = model.user.pwd;
role role = new role();
role = db.roles.Where(c => c.nom_role == model.nom_role).FirstOrDefault();
u.role = role;
try
{
db.utilisateurs.AddObject(u);
db.SaveChanges();
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
ViewBag.id_role = new SelectList(db.roles, "id", "nom_role", model.user.id_role);
return RedirectToAction("index");
}
Related
There are two tables: KindergartenIssues_Users and Users. Now I'm getting fileds of first table.However I could not get full name of user by UserId from 'Users' table.
I got data from 'Kindergartenissues_Users' table. How to correctly write incude to get full name by foreign key of UserId field?
public static async Task<List<KindergartenIssues_UsersView>> GetKinderGartenIssues()
{
List<KindergartenIssues_UsersView> users = new List<KindergartenIssues_UsersView>();
try
{
using (var entities = new WebPortalEntities())
{
users = await entities.KindergartenIssues_Users
.Where(k => k.DeletedDate == null)
.Select(k => new KindergartenIssues_UsersView()
{
ID = k.ID,
UserId = k.UserId,
RegDateWithFoundation = k.RegDateWithFoundation,
Year = k.Year,
AuthorId = k.AuthorId,
CreatedDate = k.CreatedDate,
ModifiedDate = k.ModifiedDate,
EditorId = k.EditorId,
DeletedDate = k.DeletedDate,
Description = k.Description,
ChildBirthYear = k.ChildBirthYear,
isHistory = k.isHistory
}).ToListAsync();
}
}
catch (Exception ex)
{
CommonHelper.WriteError($"GetKinderGartenIssues ERROR: {JsonConvert.SerializeObject(ex)}");
}
return users;
}
Try this
public static async Task<List<object>> GetKinderGartenIssues()
{
try
{
var users = new List<object>();
using (var entities = new WebPortalEntities())
{
users = await entities.KindergartenIssues_Users
.Where(k => k.DeletedDate == null)
.Join(entities.Users, o => o.UserId, i => i.UserId, (ki, u) => {
// You can obviously define your class somewhere instead of using anonymous object...
return new {
ID = ki.ID,
UserId = ki.UserId,
FullName = u.FullName
// etc...
};
}).ToListAsync();
}
}
catch (Exception ex)
{
CommonHelper.WriteError($"GetKinderGartenIssues ERROR: {JsonConvert.SerializeObject(ex)}");
}
return users;
}
I would like to pass the model bind to devexpress gridview back to controller during callback but failed.
Models
public class UploadExcelError
{
public int rowNumber { get; set; }
public string errorMessage { get; set; }
}
public class UploadViewModel
{
public List<UploadExcelError> UploadExcelErrors { get; set; }
public UploadFile UploadFile { get; set; }
}
UploadErrorPartial.cshtml
#using ControlTower2.Models
#model ControlTower2.Models.UploadViewModel
#if (Model != null)
{
if (Model.UploadExcelErrors != null)
{
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gridViewExcelError";
settings.CallbackRouteValues = new { Controller = "PurchaseOrder", Action = "FilteringError", xyz = Model };
settings.SettingsBehavior.AllowSort = false;
settings.SettingsPager.Mode = GridViewPagerMode.ShowAllRecords;
settings.Columns.Add(column => { column.FieldName = "rowNumber"; column.Caption = "Excel Row#"; });
settings.Columns.Add(column => { column.FieldName = "errorMessage"; column.Caption = "Error Message"; });
settings.Settings.ShowHeaderFilterButton = true;
var headerFilterMode = GridHeaderFilterMode.List;
foreach (GridViewDataColumn column in settings.Columns)
column.SettingsHeaderFilter.Mode = headerFilterMode;
}
).Bind(Model.UploadExcelErrors).GetHtml()
}
}
Controller
public ActionResult FilteringError(UploadViewModel xyz)
{
return PartialView("UploadErrorPartial", xyz);
}
xyz is null in code above.
I also tried:
settings.CallbackRouteValues = new { Controller = "PurchaseOrder", Action = "FilteringError", xyz = Model.UploadExcelErrors };
public ActionResult FilteringError(List<UploadExcelError> xyz)
{
UploadViewModel uploadViewModel = new UploadViewModel();
uploadViewModel.UploadExcelErrors = xyz;
return PartialView("UploadErrorPartial", uploadViewModel);
}
xyz is not null but count is zero. But It has show 4 rows of data on UploadErrorPartial.cshtml
I tried ViewData too:
UPDATE - ViewData only transfers data from controller to view, that's why this won't work.
if (Model.UploadExcelErrors != null)
{
ViewData["xyz"] = Model;
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gridViewExcelError";
settings.CallbackRouteValues = new { Controller = "PurchaseOrder", Action = "FilteringError" };
settings.SettingsBehavior.AllowSort = false;
settings.SettingsPager.Mode = GridViewPagerMode.ShowAllRecords;
settings.Columns.Add(column => { column.FieldName = "rowNumber"; column.Caption = "Excel Row#"; });
settings.Columns.Add(column => { column.FieldName = "errorMessage"; column.Caption = "Error Message"; });
settings.Settings.ShowHeaderFilterButton = true;
var headerFilterMode = GridHeaderFilterMode.List;
foreach (GridViewDataColumn column in settings.Columns)
column.SettingsHeaderFilter.Mode = headerFilterMode;
}
).Bind(Model.UploadExcelErrors).GetHtml()
}
public ActionResult FilteringError()
{
UploadViewModel uploadViewModel = (UploadViewModel)ViewData["xyz"];
return PartialView("UploadErrorPartial", uploadViewModel);
}
uploadViewModel get null from (UploadViewModel)ViewData["xyz"].
I use session to store Model.UploadExcelErrors and it solves my problem.
I've been develop a site for sometime but recently had this problem ,home/index page always redirect to login page ,and you can't see it unless you're logged in,Home Controller is surrounded with [AllowAnonymous]
my defulat route is still the same .
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I don't what can cause this problem ,I've never had this before, I've tried adding and removing [AllowAnonymous] ,still the same problem ,but the weird thing is Index is the only action in home controller require login,else work fine
[AllowAnonymous]
public class HomeController : Controller
{
public ActionResult Index()
{
try
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var types = (from r in db.FeedBack
select new FeedBackView { ID = r.ID, Name = r.Name, Jop = r.Jop, Body = r.Body }).Take(7).ToList();
var SlidersList = (from r in db.Sliders
select new SliderView { Description = r.Description, Title = r.Title, ImageURL = r.ImageURL }).ToList();
var FeaturesList = (from r in db.Features
select new FeatureView { Description = r.Description, Title = r.Title, ImageURL = r.ImageURL }).ToList();
var AccordionList = (from r in db.Accordion
select new AccordionView { Description = r.Description, Title = r.Title, ImageURL = r.ImageURL }).ToList();
var ServicesList = (from r in db.Services
select new ServiceView { Body = r.Body, Name = r.Name, ImageURL = r.ImageURL, Glaphicon = r.Glaphicon, ID = r.ID }).Take(6).ToList();
var portfolioTypesList = (from r in db.PortfolioTypes
select new PortfolioTypeView { Name = r.Name, ID = r.ID, filter = r.filter }).Take(5).ToList();
List<PortfolioView> Portfolios = new List<PortfolioView>();
List<PortfolioView> toadd = new List<PortfolioView>();
portfolioTypesList.ForEach(r =>
{
//Portfolios.AddRange((from s in db.Portfolios
// where s.PortfolioTypeID == r.ID
// select new PortfolioView { TypeName = r.Name, ID = s.ID, filter = r.filter, ProjectName = s.ProjectName }
// ).Take(6).ToList());
toadd = (from s in db.Portfolios
where s.PortfolioTypeID == r.ID
select new PortfolioView { TypeName = r.Name, ID = s.ID, filter = r.filter, ProjectName = s.ProjectName }).Take(6).ToList();
Portfolios.AddRange(toadd);
});
var x = new List<PortfolioView>();
PortfolioImage im = new PortfolioImage();
Portfolios.ForEach(r =>
{
im = db.PortfolioImages.Where(s => s.PortfolioID == r.ID).FirstOrDefault();
if (im != null)
{
x.Add(new PortfolioView()
{
ID = r.ID,
TypeName = r.TypeName,
ProjectName = r.ProjectName,
URL = im.ImageURL,
filter = r.filter
});
}
else
{
x.Add(new PortfolioView()
{
ID = r.ID,
TypeName = r.TypeName,
ProjectName = r.ProjectName,
URL = "",
filter = r.filter
});
}
}
);
var Articels = (from e in db.Articles
select new ArticleViewModel
{
Body = e.Body,
Title = e.Title,
ImageURL = e.ImageURL,
ID = e.ID
}).Take(3).ToList();
//var Social = db.Others.FirstOrDefault();
//ViewBag.Social = SocialMedia.convert(Social);
ViewBag.Articels = Articels;
ViewBag.portfolioTypesList = portfolioTypesList;
ViewBag.Portfolios = x;
ViewBag.ServicesList = ServicesList;
ViewBag.AccordionList = AccordionList;
ViewBag.SliderList = SlidersList;
ViewBag.FeaturesList = FeaturesList;
ViewBag.FeedBackGo = types;
return View();
}
}
catch (Exception ex)
{
return RedirectToAction("Error");
}
}
}
Have you tried custom attributes?
For instance let's create an attribute called CustomAuthorize
public class CustomAuthorize: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext
filterContext)
{
if (IsUserAuthenticated(filterContext.HttpContext))
{
filterContext.Result = new RedirectResult("/Account/InvalidRole");
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
private bool IsUserAuthenticated(HttpContextBase context)
{
return context.User != null && context.User.Identity != null &&
context.User.Identity.IsAuthenticated;
}
}
By default the Authorize attribute lead to the login page if the user is not in the right role to access some part of your application.
Now to implement this you should do the following.
[CustomAuthorize(Roles="Admin,Manager")]
public class MyController
{
// Everyone has access
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
// Only Admin and Manager roles have access, everyone else is denied
public ActionResult About()
{
return View();
}
}
Remember to put the attribute [AllowAnonymous] in cases where everyone can access the Action method. Inside the 'public' method you can include the following to allow role-specific implementations:
if(this.User.IsInRole("Administrator"))
{
}
With that you will be redirected to /Account/InvalidRole if you don't have the required role. And if you are good to go the page should render normally.
Having trouble update users in AD
My Model:
public class UserModel
{
....
[ScaffoldColumn(false)]
[DisplayName("Fødselsdag")]
[DataType(DataType.Date)]
[NotMapped]
public DateTime extensionAttribute1_date
{
get
{
try
{
return DateTime.Parse(extensionAttribute1);
}
catch (Exception e)
{
return new DateTime();
}
}
set { }
}
}
My Controller:
[HttpPost]
public ActionResult Edit(string sAMAccountName, FormCollection collection, UserModel data)
{
if (ModelState.IsValid)
{
var config = new LdapConfiguration();
config.ConfigureFactory("domain.local").AuthenticateAs(new NetworkCredential("xxxx", "xxxxx"));
using (var context = new DirectoryContext(config))
{
var user = context.Query(new UserModel(), "OU=users,OU=xxx,DC=xxx,DC=dk", "User").FirstOrDefault(d => d.sAMAccountName == sAMAccountName);
if (user == null) return RedirectToAction("Index");
user.title = data.title;
user.mobile = data.mobile;
user.homePhone = data.homePhone;
user.streetAddress = data.streetAddress;
user.postalCode = data.postalCode;
user.l = data.l;
user.department = data.department;
user.physicalDeliveryOfficeName = data.physicalDeliveryOfficeName;
user.extensionAttribute1 = data.extensionAttribute1_date.ToLongDateString();
context.Update(user);
}
return RedirectToAction("Index");
}
return View();
}
When i submit to Edit Action i results in an error:
The requested attribute does not exist.
If i remove extensionAttribute1_date from the model i updates fine.
How do i exclude my calculated attributes from the update?
I have other attributes in the model such as Age which is calculated! Is this the wrong procedure for this?
/Michael
Getting this error when try to add an item to my repositories/context:
Collection has been modified. Possibly the inventory operation is not performed.
What I'm trying to do
Campaign c = Campaignrepository.FindById(id);
if (c.LandingPage == null)
{
c.LandingPage = new Page() { Campaign = c, CampaignID = c.Campaignid };
PageRepository.Add(c.LandingPage);
}
if (c.RedeemPage == null)
{
c.RedeemPage = new RedeemPage() { Campaign = c, CampaignID = c.Campaignid };
PageRepository.Add(c.RedeemPage);
}
The Repository Add method:
public void Add(Page p)
{
pages.Add(p);
context.SaveChanges();
}
Update: still same error.
After applying the suggestions:
public ActionResult Edit(int id)
{
Campaign c = Campaignrepository.FindById(id);
Campaign newreferenceC = Campaignrepository.FindById(id);
if (c.LandingPage == null)
{
c.LandingPage = new Page() { Campaign = newreferenceC, CampaignID = newreferenceC.Campaignid };
PageRepository.Add(c.LandingPage);
}
if (c.RedeemPage == null)
{
c.RedeemPage = new RedeemPage() { Campaign = newreferenceC, CampaignID = newreferenceC.Campaignid };
PageRepository.Add(c.RedeemPage);
}
return View("Edit", Campaignrepository.FindById(id));
}
Manged to fix it with:
Page landingPage = new Page(c);
RedeemPage redeemPage = new RedeemPage(c);
PageRepository.Add(landingPage);
PageRepository.Add(redeemPage);
c.LandingPage = landingPage;
c.RedeemPage = redeemPage;
Campaignrepository.Update(c);