Combine model in asp.net mvc - 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.

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

Call WCF Restful POST Method in MVC 5

I have to create simple WCF web service with GET and POST. See bellow source code
public interface ISample
{
[OperationContract]
[WebGet(UriTemplate = "/GetDEPT", RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
Task<IEnumerable<DEPT>> GetDEPT();
[OperationContract]
[WebInvoke(UriTemplate = "UpdateDEPT?Id={Id}&StatusId={StatusId}", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Task<bool> UpdateDEPT(List<DEPT> DEPT, string Id, string StatusId);
}
ISample interface Implementation : Sample
public class Sample: ISample
{
public async Task<IEnumerable<DEPTt>> GetDEPT()
{
return await DEPTBO.GetDEPT();
}
public async Task<bool> UpdateDEPT(List<DEPTt> DEPT, string Id, string StatusId)
{
return await DEPTBO.UpdateDEPTAsync(Id, DEPT, StatusId);
}
}
How to call this WCF Restful service in MVC 5?
Please help me Service integration in MVC Application
Now i found the solution for my question.
I have create class for proxy
namespace WCF.WCFService
{
public static class WebService<T> where T : class
{
public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];
public static IEnumerable<T> GetDataFromService(string Method, string param = "")
{
var client = new WebClient();
var data = client.DownloadData(appSettings + Method + param);
var stream = new System.IO.MemoryStream(data);
var obj = new DataContractJsonSerializer(typeof(IEnumerable<T>));
var result = obj.ReadObject(stream);
IEnumerable<T> Ts = (IEnumerable<T>)result;
return Ts;
}
}
public static class WebServiceUpdate
{
public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];
public static bool GetDataFromService_Update(string Method, List<CNHDataModel.CustomEntities.Port> portData, string param = "")
{
bool _res = false;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<CNHDataModel.CustomEntities.Port>));
MemoryStream mem = new MemoryStream();
serializer.WriteObject(mem, portData);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString(appSettings + Method + param, "POST", data);
_res = true;
bool Ts = (bool)_res;
return Ts;
}
}
}
Bellow, call the service proxy from controller
public class DEPTController : Controller
{
[ActionName("DEPTView")]
public ActionResult DEPTViewAsync()
{
try
{
IEnumerable<DEPT> DEPT = CNHService.WebService<DEPT>.GetDataFromService("GetDEPT");
if (port == null)
{
return HttpNotFound();
}
IEnumerable<Status> Status = CNHService.WebService<Status>.GetDataFromService("GetStatusAsync");
if (port == null || Status == null)
{
return HttpNotFound();
}
}
catch (Exception ex)
{
}
return View();
}
[HttpPost]
[ActionName("DEPTView")]
public ActionResult DEPTViewAsync([Bind(Include = "id,Statusid")] DEPT DEPTMENT)
{
try
{
List<DEPT> objDEPT = Session["DEPTItems"] as List<DEPT>;
List<DEPTStatus> objStatus = Session["DEPTIStatus"] as List<PortStatus>;
ViewBag.DEPTList = new SelectList(objDEPTt, "id", "Name");
ViewBag.DEPTStatusList = new SelectList(objStatus, "id", "Name");
if (ModelState.IsValid)
{
WebServiceUpdate.GetDataFromService_Update("UpdateDEPT", objDEPT, "?Id=" + DEPTMENT.Id + "&StatusId=" + DEPTMENT.Statusid);
setting.Message = true;
}
else
{
return View(setting);
}
}
catch (Exception ex)
{
}
return View(setting);
}
}
I hope this code help to WCF Restful service integration in MVC 5

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'Int32' for method 'Edit(Int32)'

I am performing CRUD operation using linq to sql. But while clicking on Edit, Details or delete it gives me error i.e. "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 'CRUD_using_LinQ_to_SQL_in_MVC.Controllers.OTDController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
I checked the solution and found that, while running application url didn't get ID parameter. But i dont understand what should i change in my code.. Can you please help me...
My Controller Code:
using System;
namespace CRUD_using_LinQ_to_SQL_in_MVC.Controllers
{
public class OTDController : Controller
{
private IOTddataRepository repository;
public OTDController()
: this(new OtdDataRepository())
{
}
public OTDController(IOTddataRepository _repository)
{
repository = _repository;
}
//-----------------------Index--------------------------
public ActionResult Index()
{
var otddata = repository.Getallotddata();
return View(otddata);
}
//-----------------------Details--------------------------
public ActionResult Details(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
//-----------------------Create--------------------------
public ActionResult Create()
{
return View(new OtdModelClass());
}
[HttpPost]
public ActionResult Create(OtdModelClass otdmodel)
{
try
{
if (ModelState.IsValid)
{
repository.Insertotddata(otdmodel);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in Data Saving");
}
return View(otdmodel);
}
//-----------------------EDIT--------------------------
public ActionResult Edit(int id)
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost]
public ActionResult Edit(OtdModelClass otdclass)
{
try
{
if (ModelState.IsValid)
{
repository.Updateotddata(otdclass);
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Problem in editing and Updating data");
}
return View(otdclass);
}
//-----------------------Delete--------------------------
public ActionResult Delete(int id, bool? savechangeserror)
{
if (savechangeserror.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Problem in Deleting";
}
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
return View(otdmodel);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
try
{
OtdModelClass otdmodel = repository.Getotddatabysrno(id);
repository.Deleteotddata(id);
}
catch (DataException)
{
return RedirectToAction("Delete", new System.Web.Routing.RouteValueDictionary {
{"id",id},
{"SaveChangesError",true}});
}
return RedirectToAction("Index");
}
}
}
My OTD class Code:
public class OtdDataRepository : IOTddataRepository
{
private MVCLoginMasterLogDataClassesDataContext otdcontextobj;
public OtdDataRepository()
{
otdcontextobj = new MVCLoginMasterLogDataClassesDataContext();
}
public IEnumerable<OtdModelClass> Getallotddata()
{
IList<OtdModelClass> otddatalist = new List<OtdModelClass>();
var myselectallquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs select otduser;
var otd = myselectallquery.ToList();
foreach (var otddata in otd)
{
otddatalist.Add(new OtdModelClass()
{
Srno=Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
});
}
return otddatalist;
}
public OtdModelClass Getotddatabysrno(int id)
{
var getotddataquery = from otduser in otdcontextobj.tbl_MVC_Login_Master_Logs
where otduser.Srno == id
select otduser;
var otddata = getotddataquery.FirstOrDefault();
var otdmodel = new OtdModelClass()
{
Srno = Convert.ToInt32(otddata.Srno),
MemberCode = otddata.MemberCode,
LoginID = otddata.LoginID,
OTDPassword = otddata.OTDPassword,
BBSID = otddata.BBSID,
IPAddress = otddata.IPAddress,
ServerType = otddata.ServerType,
OTDStatus = otddata.OTDStatus,
RemoteIP = otddata.RemoteIP,
RemotePort = otddata.RemotePort,
AllowDownload = otddata.AllowDownload,
OTDTimeStamp = otddata.OTDTimeStamp,
MemberType = otddata.MemberType,
EQ = otddata.EQ,
EQD = otddata.EQD,
BFX = otddata.BFX,
SLB = otddata.SLB,
Others = otddata.Others
};
return otdmodel;
}
public void Insertotddata(OtdModelClass otdmodel_obj)
{
var empdata = new tbl_MVC_Login_Master_Log()
{
Srno = Convert.ToInt32(otdmodel_obj.Srno),
MemberCode = otdmodel_obj.MemberCode,
LoginID = otdmodel_obj.LoginID,
OTDPassword = otdmodel_obj.OTDPassword,
BBSID = otdmodel_obj.BBSID,
IPAddress = otdmodel_obj.IPAddress,
ServerType = otdmodel_obj.ServerType,
OTDStatus = otdmodel_obj.OTDStatus,
RemoteIP = otdmodel_obj.RemoteIP,
RemotePort = otdmodel_obj.RemotePort,
AllowDownload = otdmodel_obj.AllowDownload,
OTDTimeStamp = otdmodel_obj.OTDTimeStamp,
MemberType = otdmodel_obj.MemberType,
EQ = otdmodel_obj.EQ,
EQD = otdmodel_obj.EQD,
BFX = otdmodel_obj.BFX,
SLB = otdmodel_obj.SLB,
Others = otdmodel_obj.Others
};
otdcontextobj.tbl_MVC_Login_Master_Logs.InsertOnSubmit(empdata);
otdcontextobj.SubmitChanges();
}
public void Deleteotddata(int id)
{
tbl_MVC_Login_Master_Log otd_deletelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser => otduser.Srno == id).SingleOrDefault();
otdcontextobj.tbl_MVC_Login_Master_Logs.DeleteOnSubmit(otd_deletelog);
otdcontextobj.SubmitChanges();
}
public void Updateotddata(OtdModelClass otdmodel_obj)
{
tbl_MVC_Login_Master_Log otd_updatelog = otdcontextobj.tbl_MVC_Login_Master_Logs.Where(otduser=>otduser.Srno==otdmodel_obj.Srno).SingleOrDefault();
otd_updatelog.Srno = otdmodel_obj.Srno;
otd_updatelog.MemberCode = otdmodel_obj.MemberCode;
otd_updatelog.LoginID = otdmodel_obj.LoginID;
otd_updatelog.OTDPassword = otdmodel_obj.OTDPassword;
otd_updatelog.BBSID = otdmodel_obj.BBSID;
otd_updatelog.IPAddress = otdmodel_obj.IPAddress;
otd_updatelog.ServerType = otdmodel_obj.ServerType;
otd_updatelog.OTDStatus = otdmodel_obj.OTDStatus;
otd_updatelog.RemoteIP = otdmodel_obj.RemoteIP;
otd_updatelog.RemotePort = otdmodel_obj.RemotePort;
otd_updatelog.AllowDownload = otdmodel_obj.AllowDownload;
otd_updatelog.OTDTimeStamp = otdmodel_obj.OTDTimeStamp;
otd_updatelog.MemberType = otdmodel_obj.MemberType;
otd_updatelog.EQ = otdmodel_obj.EQ;
otd_updatelog.EQD = otdmodel_obj.EQD;
otd_updatelog.BFX = otdmodel_obj.BFX;
otd_updatelog.SLB = otdmodel_obj.SLB;
otd_updatelog.Others = otdmodel_obj.Others;
otdcontextobj.SubmitChanges();
}
}
Can you please help me...
The framework is telling you that the link you are clicking on to call the Edit and Delete action methods is not providing an int parameter named id which the action method is expecting to find somewhere in the submitted data. This is usually provided either in the URL, query string or submitted variables.
If that is not enough for you to spot the problem, post your view code specially the section related to the links.

Returning Json data from MVC controller

public ActionResult About()
{
List<Stores> listStores = new List<Stores>();
listStores = this.GetResults("param");
return Json(listStores, "Stores", JsonRequestBehavior.AllowGet);
}
Using the above code I am able to get the below result
[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}},
How would I able to get the result in below format?
{
"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"abc#ac.com",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},
{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"nfnf#ac.com","geo":{"latitude":"12.9876","longitude":"122.376237"}} ]
}
I would like to have the stores at the beginning of the data.
Please help me in this regard.
You will need to create an object that contains the stores within a property named stores:
public ActionResult About()
{
var result = new { stores = this.GetResults("param") };
return Json(result, "Stores", JsonRequestBehavior.AllowGet);
}
I've used an anonymous type for simplicity here, if this result type were required in multiple places you may consider creating a 'proper' class for it.
JavaScriptSerializer can be found from namespace System.Web.Script.Serialization
var ser = new JavaScriptSerializer();
var jsonStores = ser.Serialize(stores);
return Json(new { stores: jsonStores }, "Stores", JsonRequestBehavior.AllowGet);
if you want to send object to client side as Json format
like Data-table,List,Dictionary etc. then need to override jsonResult and ExecuteResult
other wise use linq format to return data
like
using JSON.NET(must need to use override jsonResult and ExecuteResult )
DataTable dt = new DataTable();//some data in table
return json("data",JsonConvert.SerializeObject(dt))
other option using linq
var Qry = (from d in dt.AsEnumerable()
select new
{
value = d.Field<int>("appSearchID"),
text = d.Field<string>("appSaveSearchName"),
type = d.Field<int>("appSearchTypeStatus")
});
return json("Data", Qry);
override methods
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
try
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = int.MaxValue
};
}
catch (Exception)
{
throw;
}
}
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
try
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
using (StringWriter sw = new StringWriter())
{
response.Write(this.Data);
}
}
catch (Exception)
{
throw;
}
}
}
public class StoresViewModel{
public List<Stores> stores {get;set;}
}
public ActionResult About()
{
List<Stores> listStores = new List<Stores>();
listStores = this.GetResults("param");
StoresViewModelmodel = new StoresViewModel(){
stores = listStores;
}
return Json(model, JsonRequestBehavior.AllowGet);
}

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