I have been working on ASP.NET MVC project Visual Studio 2012 Ultimate with Entity Framework. I have to include a Unit Test project into my solution. My problem is in that the test method (called Index()) can't recognize the application connection string in app.config. My Unit test method is:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ELSORegistry;
using ELSORegistry.DataAccess;
using ELSORegistry.Controllers;
namespace ELSORegistryUnitTests
{
[TestClass]
public class FirstControllerTest
{
[TestMethod]
public void Index()
{
//Arange
HomeController controller = new HomeController();
//Act
Guid? myGuid = new Guid("941b1615-f21b-4e2c-8fa8-0ed0d3f2de53");
ViewResult result = controller.Index(myGuid) as ViewResult;
//Assert
Assert.IsNotNull(result);
}
}
}
My Index() action in the Home Controller is:
using System;
using System.Diagnostics.Contracts;
using System.Web.Mvc;
using ELSORegistry.DataAccess;
using ELSORegistry.Models;
using Kendo.Mvc.UI;
using WebGrease.Css.Extensions;
using ELSORegistry.Extensions;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using Kendo.Mvc.Extensions;
using System.Diagnostics;
using ELSORegistry.Helpers;
using Newtonsoft.Json;
namespace ELSORegistry.Controllers
{
[Authorize]
public class HomeController : Controller
{
[Authorize(Roles = "ECLS Center Data Manager, ECLS Center Administrator,ECLS Center Data Viewer, ECLS Center Data Entry")]
//[RequireHttps] // Enable for production
public ActionResult Index(Guid? CenterId)
{
//----------------------------------------
// Remove references to previous patients
//----------------------------------------
Session.Remove("Patient");
Session.Remove("PatientSummary");
Session.Remove("Run");
Session.Remove("RunDetail");
Session.Remove("Addendum");
// if user have this session then he will get edit forms. // Yes if Add new
Session.Remove("AddNewMode");
Session.Remove("AddNewRunId");
Center center;
if (CenterId == null)
{
center = Session["Center"] as Center;
Contract.Assert(center != null);
}
else
{ // set center by selected centerId from dropdownlist
center = new Repository().GetCenter(new Guid(CenterId.ToString()));
Session["Center"] = center;
center = Session["Center"] as Center;
Contract.Assert(center != null);
}
ViewBag.RunCounts = Session["RunCounts"];
ViewBag.ChartSummaries = Session["ChartSummaries"];
return View(new QuickAdd());
}
The bug is in the line:
center = new Repository().GetCenter(new Guid(CenterId.ToString()));
of the controller. The method GetCenter is:
public Center GetCenter(Guid centerId)
{
try
{
using (var context = new ELSORegistryEntities())
{
var center = context.Centers.FirstOrDefault(c => c.CenterId == centerId);
return center;
}
}
catch (InvalidOperationException ex)
{
throw new DataException(string.Format("Error retrieving center for CenterId {0}", centerId), ex);
}
}
and app.config is in the ELSORegistry.DataAccess project which is included in the test. The class ELSORegistryEntities() is:
namespace ELSORegistry.DataAccess
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
public partial class ELSORegistryEntities : DbContext
{
public ELSORegistryEntities()
: base("name=ELSORegistryEntities")
{
}
The connection string is:
<connectionStrings>
<add name="ELSORegistryEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=NELAPC\NELA2014;initial catalog=ELSORegistry2;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
The bug is : "Test method ELSORegistryUnitTests.FirstControllerTest.Index throw exception:System.Data.DataException:Error retrieving center for CenterId 941b1615-f21b-4e2c-8fa8-0ed0d3f2de53->System.InvalidOperationException: No connection string named'ELSORegistryEntities' could be found in the application config file". How can I solve this? Thank you in advance for any help.
You need to include an app.config file inside you unit test project. Only the running project's (in this case the unit test project) app.config is respected/used.
Related
I'm trying to create a very simple C# program for insert the data.
Here is the service file :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DataAccess;
using DataAccess.UoW;
using Model;
namespace ClassLibrary1
{
public class Service
{
private readonly Unit _uow;
public Service()
{
_uow = new Unit();
}
public bool CreateEmp(Mdl insertEntity)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Mdl, Table_1>();
});
IMapper mapper = config.CreateMapper();
var Empinsert = mapper.Map<Mdl, Table_1>(insertEntity);
_uow.Register.Insert(Empinsert);
_uow.Save(); //this line shows error
return false;
}
}
}
Unit of Work:
using DataAccess.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.UoW
{
public class Unit
{
private guruEntities _context = null;
private Repository<Table_1> _register;
public Unit()
{
_context = new guruEntities();
}
public Repository<Table_1> Register
{
get
{
if (this._register == null)
this._register = new Repository<Table_1>(_context);
return _register;
}
}
}
}
And this is the error I get :
C# 'Unit' does not contain a definition for 'Save' and no accessible extension method 'Save' accepting a first argument of type 'Unit' could be found (are you missing a using directive or an assembly reference?)
You have to add save method in your Unit Class like this
public void Save()
{
context.SaveChanges();
}
for better understand you can refer Unitofwork class from below link
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
I am an experienced programmer but relatively new to c# mvc. I am attempting to create my first viewmodel to combine two models into one so a view can access members from both. I have followed instructions on combining distinct models into one view model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ViApplication.Models;
using System.ComponentModel.DataAnnotations;
namespace ViApplication.ViewModel
{
public class TemplateMTMQuestionViewModel
{
public TemplateVISpdat ThisTemplate { get; set; }
public MtmTemplateViSpdatQuestion ThisMTMQuestion { get; set; }
}
}
I have created a controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViApplication.ViewModel;
using ViApplication.Models;
using System.Net;
namespace ViApplication.Controllers
{
public class TemplatesMTMQuestions : Controller
{
private VulnerabilityIndexDatabaseEntities db = new VulnerabilityIndexDatabaseEntities();
public ActionResult AddQuestionToTemplate(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TemplateVISpdat templateVISpdat = GetTemplateByID(id);
if (templateVISpdat == null)
{
return HttpNotFound();
}
TemplateMTMQuestionViewModel TMTMQVM = new TemplateMTMQuestionViewModel();
TMTMQVM.ThisTemplate = GetTemplateByID(id);
TMTMQVM.ThisMTMQuestion = GetBlankMtmTemplateViSpdatQuestion();
return View(TMTMQVM);
}
public TemplateVISpdat GetTemplateByID(long? id)
{
TemplateVISpdat templateVISpdat = db.TemplateVISpdats.Find(id);
return templateVISpdat;
}
public MtmTemplateViSpdatQuestion GetBlankMtmTemplateViSpdatQuestion()
{
MtmTemplateViSpdatQuestion TMTMQVM = new MtmTemplateViSpdatQuestion();
return TMTMQVM;
}
}
}
This compiles fine. But when I try to create a view from AddQuestionToTemplate and select Empty and my ViewModel I get:
Unable to retrieve metadata for
ViApplication.ViewMdoel.TemplateMTMQuestionViewModel. One or more
validation errors were detected during model generation.
TemplateMTMQuestionViewModel::EntityType TemplateMTMQuestionViewModel
has no key defined
The only difference between this project and other projects is that I am using database first.
Any help would be greatly appreciated.
I have the following:
public class StripeController : Controller
{
private readonly UserService _userService;
public StripeController(UserService userService)
{
_userService = userService;
}
[HttpPost]
public ActionResult StripeWebook()
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
[HttpPost]
[Route("api/stripewebhook")]
public async Task<ActionResult> Index(CancellationToken ct)
{
var json = new StreamReader(Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
And requests from stripe generate an error:
The controller for path '/api/stripewebhook' was not found or does not implement IController
Any idea why this is happening when I test from the stripe portal?
Using WebApi 2 it works with no problem.
Here is the smallest WebApi controller to begin with:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
return Ok();
}
}
}
if you execute this from VS you can access it from http://localhost:(port)/api/stripewebhook
Now you only need to extend this to include the stripe code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return Ok();
}
}
}
I've been working on a small MVC-project which since I converted to more of an MVC-approach has stopped working.
The program consuming the web-service is a simple console-application with its own controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication.ServiceReference1;
namespace ConsoleApplication
{
class ConsoleController
{
ServiceReference1.WebService2SoapClient webservice = new ServiceReference1.WebService2SoapClient();
public List<Employee> GetEmployees()
{
return webservice.GetEmployees().ToList();
}
}
}
The web-service consists of a Employee-class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webservice
{
public class Employee
{
public string _socialSN { get; set; }
public string _lastName { get; set; }
public string _firstName { get; set; }
public Employee(string socialSN, string firstName, string lastName)
{
this._firstName = firstName;
this._lastName = lastName;
this._socialSN = socialSN;
}
}
}
A data access layer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace webservice
{
public class DAL
{
private SqlConnection con;
private SqlCommand cmd;
public void GetConnection()
{
con = new SqlConnection("Data Source=****;Initial Catalog=DB2015;Persist Security Info=True;User ID=****;Password=***********");
}
public List<Employee> GetEmployees()
{
GetConnection();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "SELECT SocialSN, Name, Surname FROM Employee";
SqlDataReader reader = cmd.ExecuteReader();
List<Employee> employeeList = new List<Employee>();
if (reader.HasRows)
{
while (reader.Read())
{
employeeList.Add(new Employee(reader.GetString(0), reader.GetString(1), reader.GetString(2)));
}
}
else
{
employeeList = null;
}
reader.Close();
con.Close();
reader.Dispose();
con.Dispose();
return employeeList;
}
}
}
A BackController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webservice
{
class BackController
{
DAL dal = new DAL();
public List<Employee> GetEmployees()
{
return dal.GetEmployees();
}
}
}
And finally the webservice-code itself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace webservice
{
/// <summary>
/// Summary description for WebService2
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService
{
BackController bcontroller = new BackController();
[WebMethod]
public List<Employee> GetEmployees()
{
return bcontroller.GetEmployees();
}
}
}
Whenever I try to add a new service-reference to my console-application I get this error:
Error part 1 http://i.imgur.com/UVw1cAO.png
Error part 2 http://i.imgur.com/N0dF159.png
I cannot figure out what is wrong. It worked fine before I changed to MVC. I've tried to clean the projects, rebuild them and create them all from scratch again and just simply won't work.
Please let me know if you've got any ideas what could be wrong or if you need additional information.
Thanks!
It sounds like you've upgraded some components but the code is still trying to latch onto the old version. Essentially something in your code is looking for say version 1.1.0.1 and you've got version 2.1.0.1. or something like that. You'll need to either redirect to the correct assembly in your web config or find another way to get your application to accept the newer version.
Here are some links you can check out for some tips but these can be elusive bugs to sort out.
From stackoverflow:
The located assembly's manifest definition does not match the assembly reference.
that link has this one inside it:
http://blogs.msdn.com/b/junfeng/archive/2004/03/25/95826.aspx
And here is an independent blogger's take on it:
http://www.codingdefined.com/2014/10/error-located-assemblys-manifest.html
I am trying to create a web api with forms based authentication. I want to login from a client and retrieve data from there. When I log in, user gets authenticated and can retrieve data by giving http request direct into adressbar like localhost:1393/api/Game. But when i try to get it from client I am getting a 401 (Unauthorized error). I have enabled CORS in server side. This is the controller to handle data
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using Cheeky_backend.Models;
using System.Web.Http.WebHost;
namespace Cheeky_backend.Controllers
{
public class Demo
{
public List<Teams> team { get; set; }
public List<Hole> hole { get; set; }
}
[Authorize]
public class GameController : ApiController
{
private Cheeky_backendContext db = new Cheeky_backendContext();
// GET api/Game
public IEnumerable<Hole> GetHoles()
{
return db.Holes.AsEnumerable();
}
}
}
This is the authenticating controler
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Security;
using System.Web.Http;
using Cheeky_backend.Models;
namespace Cheeky_backend.Controllers
{
public class UserController : ApiController
{
private Cheeky_backendContext db = new Cheeky_backendContext();
// GET api/Default1
// GET api/Default1/5
// PUT api/Default1/5
// POST api/Default1
public HttpResponseMessage CreateUser(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
// response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.ID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
// DELETE api/Default1/5
public HttpResponseMessage Login(User user)
{
var userfound = from user2 in db.Users
where user.username == user2.username && user.password == user2.password
select user2;
if( userfound.Any())
{
FormsAuthentication.SetAuthCookie(user.username, true);
return Request.CreateResponse(HttpStatusCode.OK,user);
}
return Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
Source
In your Authentication Handler
Don't set the Principal on the Thread.CurrentPrinicipal any more.
Use the Principal on the HttpRequestContext.
Take a look at here