My controller is not able to retrieve my session list from a Repository file - asp.net-mvc

I have created a repository in this application and a session list is created in order to keep data in memory. I am not able to retrieve my list from the controller in order to populate a grid view which I have.
This is my Repository
namespace ClientSearch.Repository
{
public class Repo
{
public HttpSessionStateBase session;
public Repo (HttpSessionStateBase session)
{
this.session = session;
}
public void SetClient(ClientInfo client)
{
List<ClientInfo> mylist = new List<ClientInfo>();
mylist = (List<ClientInfo>)this.session["test"];
}
public List<ClientInfo> GetClient()
{
return (List<ClientInfo>)session["list"];
}
}
}
This is my Controller function
public ActionResult SearchClient()
{
HttpSessionStateBase session = HttpContext.Session;
Repo repo = new Repo(session);
var result = repo.GetClient();
return Json(new
{
list = result,
count = result.Count
}, JsonRequestBehavior.AllowGet);
}
my setting control
public JsonResult ClientInformation(ClientInfo client)
{
JsonResult result = new JsonResult();
result.Data = client;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}

Related

WCF---Consuming CRUD operation using Linq in ASP.NET MVC application?

enter image description here
First step...Opened WCF created IService:
namespace CRUDOperationWCFMVC
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
bool CreateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool UpdateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool DeleteDetails(int id);
[OperationContract]
List<EmployeeDetails> GetDetails();
}
public class EmployeeDetails
{
[DataMember]
public int EmpID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public int? Salary { get; set; }
}
}
Step 2: then I implemented service code:
public class Service1 : IService1
{
DataClasses1DataContext dcd = new DataClasses1DataContext();
public bool CreateDetails(EmployeeDetails employeeDetails)
{
Nevint emp = new Nevint();
emp.EmpID= employeeDetails.EmpID;
emp.Name = employeeDetails.Name;
emp.Location = employeeDetails.Location;
emp.Salary = employeeDetails.Salary;
dcd.Nevints.InsertOnSubmit(emp);
dcd.SubmitChanges();
return true;
}
public bool DeleteDetails(int id)
{
var delete = (from v in dcd.Nevints where v.EmpID==id select v).FirstOrDefault();
dcd.Nevints.DeleteOnSubmit(delete);
dcd.SubmitChanges();
return true;
}
public List<EmployeeDetails> GetDetails()
{
List<EmployeeDetails> details = new List<EmployeeDetails>();
var select= (from v in dcd.Nevints select v);
foreach (var i in select)
{
EmployeeDetails emp = new EmployeeDetails();
emp.EmpID = i.EmpID;
emp.Name = i.Name;
emp.Location = i.Location;
emp.Salary = i.Salary;
details.Add(emp);
}
return details;
}
public bool UpdateDetails(EmployeeDetails employeeDetails)
{
var update = (from v in dcd.Nevints.ToList() where employeeDetails.EmpID==v.EmpID select v).FirstOrDefault();
update.EmpID = employeeDetails.EmpID;
update.Name = employeeDetails.Name;
update.Location = employeeDetails.Location;
update.Salary = employeeDetails.Salary;
dcd.SubmitChanges();
return true;
}
}
Step 3: then I add linq to sql, opened my ASP.NET MVC project for consuming, and added a controller and wrote this code:
namespace ConsumingClient.Controllers
{
public class EmpdetailsController : Controller
{
ServiceReference1.Service1Client serobj=new ServiceReference1.Service1Client();
ServiceReference1.EmployeeDetails empdetails=new ServiceReference1.EmployeeDetails();
// GET: Empdetails
public ActionResult Index()
{
List<employee> lstemp = new List<employee>();
var result = serobj.GetDetails();
foreach (var i in result)
{
employee emp = new employee();
empdetails.EmpID = i.EmpID;
empdetails.Name = i.Name;
empdetails.Location = i.Location;
empdetails.Salary = i.Salary;
lstemp.Add(emp);
}
return View(result);
}
// GET: Empdetails/Details/5
public ActionResult Details(int id)
{
Employees emp = new Employees();
return View();
}
// GET: Empdetails/Create
public ActionResult Create()
{
return View();
}
// POST: Empdetails/Create
[HttpPost]
public ActionResult Create(Employees employees)
{
try
{
// TODO: Add insert logic here
empdetails.EmpID=employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.CreateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Empdetails/Edit/5
public ActionResult Edit(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Edit/5
[HttpPost]
public ActionResult Edit(Employees employees)
{
try
{
// TODO: Add update logic here
empdetails.EmpID = employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.UpdateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View(employees);
}
}
// GET: Empdetails/Delete/5
public ActionResult Delete(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
serobj.DeleteDetails(id);
return RedirectToAction("Index");
}
catch
{
return View(id);
}
}
}
}
Data was displaying fine. I can create data.
However, when I click on edit and delete, I'm getting an error:
ERROR Message "Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'ConsumingClient.Controllers.EmpdetailsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
This error is thrown if you attempt to call this controller action and you do not specify the id either in the path portion or as query string parameter. Since your controller action takes an id as parameter you should make sure that you always specify this parameter.
Make sure that when you are requesting this action you have specified a valid id in the url:
http://example.com/somecontroller/Edit/123
If you are generating an anchor, make sure there's an id:
#Html.ActionLink("Edit", "somecontroller", new { id = "123" })
If you are sending an AJAX request, also make sure that the id is present in the url.
If on the other hand the parameter is optional, you could make it a nullable integer:
public ActionResult Edit(int? id)
but in this case you will have to handle the case where the parameter value is not specified.
https://coderedirect.com/questions/197477/mvc-the-parameters-dictionary-contains-a-null-entry-for-parameter-k-of-non-n

How can I call the method that is in my Hub from my controller on ASP.NET Core?

I'm using SignalR and I my hub is on a folder called Hubs. I need to call the method that's in my Hub "PostMarker()" on my controller. So, everytime something is posted, the SignalR updates all windows open. How should I do that?
[HttpPost]
public async Task<IActionResult> PostOcorrencias([FromBody] Ocorrencias ocorrencia, IFormFile UploadImag)
{
ocorrencia.DataOcorrencia = DateTime.Now;
//processar a fotografia
//ocorrencia.Fotografia = "(nome fotografia)";
string caminho = "";
if (UploadImag == null)
{
return BadRequest(ModelState);
}
else
{
if (UploadImag.ContentType == "imagens/jpg" ||
UploadImag.ContentType == "imagens/png")
{
string extensao = Path.GetExtension(UploadImag.FileName).ToLower();
Guid g;
g = Guid.NewGuid();
string nome = g.ToString() + extensao;
caminho = Path.Combine(environment.WebRootPath,"imagens", nome);
ocorrencia.Fotografia = nome;
// Cria o ficheiro no sistema
using (var stream = new FileStream(caminho, FileMode.Create))
{
await UploadImag.CopyToAsync(stream);
}
}
}
_context.Ocorrencias.Add(ocorrencia);
//CALL HUB METHOD PostMarker()
await _context.SaveChangesAsync();
}
return CreatedAtAction("GetOcorrencias", new { id = ocorrencia.Id }, ocorrencia);
}
Here is my Hub:
public class MyHub : Hub
{
public async Task PostMarker()
{
await Clients.All.SendAsync("RedesignMap");
}
}
A SignalR IHubContext provides a means of sending messages to your clients outside of a Hub instance. The sample at https://learn.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-3.1 provides an example. Using the code there as a starting point, you can:
Inject the IHubContext into your controller, assuming that it is named HomeController:
public class HomeController : Controller
{
private readonly IHubContext<MyHub> _hubContext;
public HomeController(IHubContext<MyHub> hubContext)
{
_hubContext = hubContext;
}
}
Use the hub context in your PostOcorrencias controller action:
...
_context.Ocorrencias.Add(ocorrencia);
await _hubContext.Clients.All.SendAsync("RedesignMap");
await _context.SaveChangesAsync();
...

Get recent inserted Id and send in to another controllers view

EDITED:
I have Created CRUD Functions for each Modals and now i am trying to get recent Inserted Id and use it in different view.
Here is what I have tried so far
I have created 2 classes(Layer based) for CRUD function for each ContextEntities db to practice pure OOP recursive approach and following is the code.
1. Access Layer
ViolatorDB
public class ViolatorDB
{
private TPCAEntities db;
public ViolatorDB()
{
db = new TPCAEntities();
}
public IEnumerable<tbl_Violator> GetALL()
{
return db.tbl_Violator.ToList();
}
public tbl_Violator GetByID(int id)
{
return db.tbl_Violator.Find(id);
}
public void Insert(tbl_Violator Violator)
{
db.tbl_Violator.Add(Violator);
Save();
}
public void Delete(int id)
{
tbl_Violator Violator = db.tbl_Violator.Find(id);
db.tbl_Violator.Remove(Violator);
Save();
}
public void Update(tbl_Violator Violator)
{
db.Entry(Violator).State = EntityState.Modified;
Save();
}
public void Save()
{
db.SaveChanges();
}
}
2. Logic Layer
ViolatorBs
public class ViolatorBs
{
private ViolatorDB objDb;
public ViolatorBs()
{
objDb = new ViolatorDB();
}
public IEnumerable<tbl_Violator> GetALL()
{
return objDb.GetALL();
}
public tbl_Violator GetByID(int id)
{
return objDb.GetByID(id);
}
public void Insert(tbl_Violator Violator)
{
objDb.Insert(Violator);
}
public void Delete(int id)
{
objDb.Delete(id);
}
public void Update(tbl_Violator Vioaltor)
{
objDb.Update(Vioaltor);
}
}
And Finally using Logic Layer functions in presentation Layer.Here insertion is performed as:
public class CreateViolatorController : Controller
{
public TPCAEntities db = new TPCAEntities();
private ViolatorBs objBs;
public CreateViolatorController()
{
objBs = new ViolatorBs();
}
public ActionResult Index()
{
var voilator = new tbl_Violator();
voilator=db.tbl_Violator.Add(voilator);
ViewBag.id = voilator.VID;
return View();
}
[HttpPost]
public ActionResult Create(tbl_Violator Violator)
{
try
{
if (ModelState.IsValid)
{
objBs.Insert(Violator);
TempData["Msg"] = "Violator Created successfully";
return RedirectToAction("Index");
}
else
{
return View("Index");
}
}
catch (Exception ex)
{
TempData["Msg"] = "Failed..." + ex.Message + " " + ex.ToString();
return RedirectToAction("Index");
}
}
}
Now here is the main part how do i get perticuller inserted id in another controller named Dues while performing insertion ?
In sqlqery I would have used ##IDENTITY but in Entity Framework I'm not sure.
I'm new to mvc framework any suggestion or help is appreciated Thanks in Advance.
Once you save your db context the id is populated back to your entity by EF automatically.
for example.
using(var context = new DbContext())
{
var employee = new Employee(); //this has an id property
context.Employees.Add(employee);
context.SaveChanges();
var id = employee.id; // you will find the id here populated by EF
}
You dont need to add and save your table as you have done this already in your voilatorDB class just fetch the last id like following
var id = yourTableName.Id;
db.yourTableName.find(id);
Or you can simply write one line code to achive that using VoilatorBs class function
GetbyID(id);

Combine model in asp.net mvc

I combine my tables to Result. İt works with no problem.
public ActionResult Index()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
However, when using multiple actions, i have to write the above code every time.
For instance:
public ActionResult Customer()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
public ActionResult Product()
{
var Result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return View(Result );
}
İ have to combine my tables in every actionresult.
How can i write only one time and use my Result everywhere ?
You may do as follows. I always use this approach:
public Modeller GetResult()
{
var result = new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList(),
};
return result;
}
public ActionResult Customer()
{
var Result = GetResult();
return View(Result);
}
public ActionResult Product()
{
var Result = GetResult();
return View(Result);
}
One option is to just reference a shared class/service. For example:
public class YourService
{
public static Modeller GetCombinedTables()
{
return new Modeller
{
KISALTMALAR = context.KISALTMALAR.ToList(),
FirmaListesiGetir = context.SP_FIRMA_LISTESI_GETIR().ToList()
};
}
}
Then, in your action you can just call that method:
public ActionResult Customer()
{
var Result = YourService.GetCombinedTables();
return View(Result);
}
You can also create the Result variable at controller level, so that way you don't have to assign it for every action.

How to write a test for accounts controller for forms authenticate

Trying to figure out how to adequately test my accounts controller. I am having problem testing the successful logon scenario.
Issue 1) Am I missing any other tests.(I am testing the model validation attributes separately)
Issue 2) Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() and Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() test are not passing. I have narrowed it down to the line where i am calling _membership.validateuser(). Even though during my mock setup of the service i am stating that i want to return true whenever validateuser is called, the method call returns false.
Here is what I have gotten so far
AccountController.cs
[HandleError]
public class AccountController : Controller
{
private IMembershipService _membershipService;
public AccountController()
: this(null)
{
}
public AccountController(IMembershipService membershipService)
{
_membershipService = membershipService ?? new AccountMembershipService();
}
[HttpGet]
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (_membershipService.ValidateUser(model.UserName,model.Password))
{
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Overview");
}
ModelState.AddModelError("*", "The user name or password provided is incorrect.");
}
return View(model);
}
}
AccountServices.cs
public interface IMembershipService
{
bool ValidateUser(string userName, string password);
}
public class AccountMembershipService : IMembershipService
{
public bool ValidateUser(string userName, string password)
{
throw new System.NotImplementedException();
}
}
AccountControllerFacts.cs
public class AccountControllerFacts
{
public static AccountController GetAccountControllerForLogonSuccess()
{
var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
var controller = new AccountController(membershipServiceStub);
membershipServiceStub
.Stub(x => x.ValidateUser("someuser", "somepass"))
.Return(true);
return controller;
}
public static AccountController GetAccountControllerForLogonFailure()
{
var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>();
var controller = new AccountController(membershipServiceStub);
membershipServiceStub
.Stub(x => x.ValidateUser("someuser", "somepass"))
.Return(false);
return controller;
}
public class LogOn
{
[Fact]
public void Get_ReturnsViewResultWithDefaultViewName()
{
// Arrange
var controller = GetAccountControllerForLogonSuccess();
// Act
var result = controller.LogOn();
// Assert
Assert.IsType<ViewResult>(result);
Assert.Empty(((ViewResult)result).ViewName);
}
[Fact]
public void Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven()
{
// Arrange
var controller = GetAccountControllerForLogonSuccess();
var user = new LogOnModel();
// Act
var result = controller.LogOn(user, null);
var redirectresult = (RedirectToRouteResult) result;
// Assert
Assert.IsType<RedirectToRouteResult>(result);
Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
Assert.Equal("Index", redirectresult.RouteValues["action"]);
}
[Fact]
public void Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven()
{
// Arrange
var controller = GetAccountControllerForLogonSuccess();
var user = new LogOnModel();
// Act
var result = controller.LogOn(user, "someurl");
var redirectResult = (RedirectResult) result;
// Assert
Assert.IsType<RedirectResult>(result);
Assert.Equal("someurl", redirectResult.Url);
}
[Fact]
public void Put_ReturnsViewIfInvalidModelState()
{
// Arrange
var controller = GetAccountControllerForLogonFailure();
var user = new LogOnModel();
controller.ModelState.AddModelError("*","Invalid model state.");
// Act
var result = controller.LogOn(user, "someurl");
var viewResult = (ViewResult) result;
// Assert
Assert.IsType<ViewResult>(result);
Assert.Empty(viewResult.ViewName);
Assert.Same(user,viewResult.ViewData.Model);
}
[Fact]
public void Put_ReturnsViewIfLogonFailed()
{
// Arrange
var controller = GetAccountControllerForLogonFailure();
var user = new LogOnModel();
// Act
var result = controller.LogOn(user, "someurl");
var viewResult = (ViewResult) result;
// Assert
Assert.IsType<ViewResult>(result);
Assert.Empty(viewResult.ViewName);
Assert.Same(user,viewResult.ViewData.Model);
Assert.Equal(false,viewResult.ViewData.ModelState.IsValid);
}
}
}
Figured out how to fix my tests.
[Fact]
public void Put_ReturnsRedirectToRouteResultForOverviewIfLogonSuccessAndNoReturnUrlGiven()
{
// Arrange
var mocks = new MockRepository();
var mockMembershipService = mocks.StrictMock<IMembershipService>();
using (mocks.Record())
{
Expect.Call(mockMembershipService.ValidateUser("", "")).IgnoreArguments().Return(true).Repeat.Any();
}
var controller = new AccountController(mockMembershipService);
var user = new LogOnModel();
// Act
ActionResult result;
using (mocks.Playback()){
result = controller.LogOn(user, null);
}
// Assert
Assert.IsType<RedirectToRouteResult>(result);
var redirectresult = (RedirectToRouteResult)result;
Assert.Equal("Overview", redirectresult.RouteValues["controller"]);
Assert.Equal("Index", redirectresult.RouteValues["action"]);
}

Resources