Configure Mvc Mini Profiler with Linq DataCotext - asp.net-mvc

I'm using linq-to-sql datacontext for an application.
I have the following class
UserDataContext which I instantiate the table with
var db = new UserDataContext();
How do I make Mvc Mini Profiler insert into that?
I tried to extend UserDataContext with the following partial found at another answer, but the code is never hit.
partial class UserDataContext
{
public static UserDataContext Get()
{
var sqlConnection = new HelpSaudeAPDataContext().Connection;
var profiledConnection = new MvcMiniProfiler.Data.ProfiledDbConnection(new SqlConnection("UserConnectionString"), MiniProfiler.Current);
return new HelpSaudeAPDataContext(profiledConnection);
}
}
Unfortunately there is no single point repository with the var db connection where I could simply pass the mvc mini profiler connection with.
var db = UserDataContext(profilerConnection);

but the code is never hit.
Well, hit it:
var db = UserDataContext.Get();

Related

elastic search setup in asp.net mvc

I am working on an asp.net application where I have huge database. I want to implement elastic search. Here is what I have done in code:
var node = new Uri("http://localhost:9200/");
var setting = new ConnectionSettings(node);
setting.DefaultIndex("businessuser");
client = new ElasticClient(setting);
CanadaBusinessDBEntities db = new CanadaBusinessDBEntities();
client.DeleteIndex("businessuser", null);
var ListofBusiness = db.CanadaTables.ToList();
foreach (var Business in ListofBusiness)
{
var resutl = client.Index(Business, null);
}
This code is written in constructor which gets all records and then index them using elastic search. indexing is taking long time. I want to ask if this is correct way? I am new to elastic search. please suggest better way to do this.
Thanks.
You have to use ElasticsearchContext Class of Nest.
private readonly ElasticsearchContext _elasticsearchContext;
private const string ConnectionString = "http://localhost:9200";
private readonly IElasticsearchMappingResolver _elasticsearchMappingResolver;
_elasticsearchMappingResolver = new ElasticsearchMappingResolver();
_elasticsearchContext = new ElasticsearchContext(ConnectionString, new ElasticsearchSerializerConfiguration(_elasticsearchMappingResolver,true,true));
for Delete purpose you can use like that below
public void DeleteSkill(int Id)
{
_elasticsearchContext.DeleteDocument<Tag>(Id);
_elasticsearchContext.SaveChanges();
}

ASP.NET MVC - Service layer, single or many services in each controller action?

I'm starting to implement a service layer to my MVC project to thin down some bloated controllers (it also has repository / unitofwork pattern).
My question is if you have a complicated view model for a page with lots of child objects etc, and quite a lot of logic going on behind the scenes (to give you an idea the controller the original developer wrote had almost 4000 lines of code!!) is it OK to have multiple services going off doing their thing? or should I just have one big ReportService which does everything?
My controller is starting to look like this? and if I carry on I could end up having quite a lot of different services being called to build up the view model.
Does this look OK or is it starting to go in the wrong direction?
public ViewResult Index(int? reportId)
{
// get the base report object
var reportService = new ReportService();
var report = reportService.GetByReportId(reportId);
var model = Mapper.Map<Report, ReportViewModel>(report);
// get the current active user
var userService = new UserService();
var user = userService.GetCurrentUser();
model.User = Mapper.Map<User, ReportViewModel.UserViewModel>(user);
// get the first unread message
var messageService = new MessageService();
var message = messageService.GetFirstUnread(user.Id);
model.Message = Mapper.Map<Message, ReportViewModel.MessageViewModel>(message);
// get the category navigation
var categoryService = new CategoryService();
var categoryNavigation = categoryService.GetCategoryNavigation(report.Id);
model.CategoryNavigation = Mapper.Map<IEnumerable<Category>, IEnumerable<ReportViewModel.CategoryNavigationViewModel>>(categoryNavigation);
return View(model);
}
It's fine to have multiple small services in your controller. However, there is one thing that's wrong here:
You services should be available through the entire controller and injected through the constructor to achieve loose-coupling.
So something like this:
private readonly IReportService _reportService;
private readonly IUserService _userService;
public SomeConstructor(IReportService reportService, IUserService userService, etc.)
{
_reportService = reportService;
_userService = userService;
// etc
}
That does look like a good approach, an alternative approach would to be split some of this up by using Child Actions - the best solution will depend upon your specific use case though.
If, for example, the ViewModel property CategoryNavigation was being used by the view to create a sort of navigation 'widget' that might be useful in several different Views, you might be better spliting this off into a ChildAction e.g.
[ChildActionOnly]
public ActionResult CategoryNavigationWidget(int reportId)
{
// get the category navigation
var categoryService = new CategoryService();
var categoryNavigation = categoryService.GetCategoryNavigation(report.Id);
return PartialView(categoryNavigation);
}
Any View could then render that ChildAction by going:
#{ Html.RenderAction("CategoryNavigationWidget", "Report",
new { reportId = Model.ReportId }); }
Whether or not this is a good idea will probably depend upon whether or not the 'widget' is reusable.

Unit Testing MVC Controllers

A controller in my ASP.NET MVC application pre-populates form data displayed by my view according to a couple of fairly straight forward rules.
It seems like this would be a good thing to cover in my unit testing. But the only way I could see to verify the correct data is placed in the form, would be to extract the logic from the controller in what feels like an unnatural way.
Can someone suggest ways to approach this?
All the examples I've found of unit testing controllers seemed very trivial, such as verifying it returned the expected type of view. I'm not sure I even see the value in that.
You can test by casting the returned object to the appropriate class, instead of using their base class (which is returned by default)
For example, to test the default AccountController you'd so something like this:
var controller = new AccountController();
var result = controller.LogOn() as ViewResult;
var model = result.Model as LogOnModel;
Assert.IsTrue(model.RememberMe); // assuming you "pre-populated" enabled the checkbox
Checking if the returned object is filled with the right data does not seem "unnatural" to me, or did you meant it differently?
I would agree that testing the type of view returned would be somewhat pointless. However, testing that the expected "view" was returned along with its correct data would be a valid test case IMO.
For example here is a singular edit test case for an edit controller. Note, that this example is making use of Moq and Nunit but that aside it's fairly straight forward.
Note, that that ViewResult is cast to the expected view model and the assertions are then made against the expected contact.
Test:
[Test]
public void Edit_Get_Should_Lookup_Contact_From_Repository_And_Return_Edit_View()
{
// arrange
var _repository = new Mock<IContactRepository>();
var expectedContact = new Contact
{
First = "first",
Last = "last",
Email = "mail#test.com"
};
var mockContext = new Mock<ControllerContext>();
_repository.Setup(x => x.GetById(It.IsAny<int>())).Returns(expectedContact);
var controller = new ContactController(_repository.Object)
{
ControllerContext = mockContext.Object
};
// act
var result = controller.Edit(1) as ViewResult;
var resultData = (Contact)result.ViewData.Model;
// assert
Assert.AreEqual("Edit", result.ViewName);
Assert.AreEqual(expectedContact.First, resultData.First);
Assert.AreEqual(expectedContact.Last, resultData.Last);
Assert.AreEqual(expectedContact.Email, resultData.Email);
}
Controller:
[HttpGet]
public ActionResult Edit(int id)
{
var contact = _repository.GetById(id);
return View("Edit", contact);
}

How to Unit Test JsonResult and Collections in MSTest

I am very new to unit testing even though i have been coding for a very long time. I want to make this a part of my way of development. I run into blocks on how to unit test things like a collection. I generally have my jQuery script calling ASP.Net Server side methods to get data and populate tables and the like. They look like
Get_*Noun*()
which generally returns a JsonResult. Any ideas on what and how to test these using Unit tests using MSTest?
You should be able to test this just like anything else, provided you can extract the values from the JsonResult. Here's a helper that will do that for you:
private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
{
var property =
jsonResult.Data.GetType().GetProperties()
.Where(p => string.Compare(p.Name, propertyName) == 0)
.FirstOrDefault();
if (null == property)
throw new ArgumentException("propertyName not found", "propertyName");
return (T)property.GetValue(jsonResult.Data, null);
}
Then call your controller as usual, and test the result using that helper.
var jsonResult = yourController.YourAction(params);
bool testValue = GetValueFromJsonResult<bool>(jsonResult, "PropertyName");
Assert.IsFalse(testValue);
(I am using NUnit syntax, but MSUnit shouldn't be far off)
You could test your JsonResult like this:
var json = Get_JsonResult()
dynamic data = json.Data;
Assert.AreEqual("value", data.MyValue)
Then in the project that contains the code to be tested, edit AssemblyInfo.cs file to allow the testing assembly access to the anonymous type:
[assembly: InternalsVisibleTo("Tests")]
This is so the dynamic can determine the type of anonymous object being returned from the json.Data value;
This is the best blog I've found on this subject.
My favorite was the 4th approach using dynamics. Note that it requires you to ensure that the internals are visible to your test project using [assembly:InternalsVisibleTo("TestProject")] which I find is a reasonably good idea in general.
[TestMethod]
public void IndexTestWithDynamic()
{
//arrange
HomeController controller = new HomeController();
//act
var result = controller.Index() as JsonResult;
//assert
dynamic data = result.Data;
Assert.AreEqual(3, data.Count);
Assert.IsTrue(data.Success);
Assert.AreEqual("Adam", data.People[0].Name);
}
You could use PrivateObject to do this.
var jsonResult = yourController.YourAction(params);
var success = (bool)(new PrivateObject(jsonResult.Data, "success")).Target;
Assert.IsTrue(success);
var errors = (IEnumerable<string>)(new PrivateObject(jsonResult.Data, "errors")).Target;
Assert.IsTrue(!errors.Any());
It's uses reflection similar to David Ruttka's answer, however it'll save you a few key strokes.
See http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx for more info.
Here's a small extension to easily convert a Json ActionResult into the object it represents.
using System.Web.Mvc;
public static class WebExtensions
{
public static T ToJson<T>(this ActionResult actionResult)
{
var jsonResult = (JsonResult)actionResult;
return (T)jsonResult.Data;
}
}
With this, your 'act' in the test becomes smaller:
var myModel = myController.Action().ToJson<MyViewModel>();
My suggestion would be to create a model for the data returned and then cast the result into that model. That way you can verify:
the structure is correct
the data within the model is correct
// Assert
var result = action
.AssertResultIs<JsonResult>();
var model = (UIDSearchResults)result.Data;
Assert.IsTrue(model.IsValid);
Assert.AreEqual("ABC", model.UIDType);
Assert.IsNull(model.CodeID);
Assert.AreEqual(4, model.PossibleCodes.Count());

Profiling Entity Framework With MvcMiniProfiler

I've got an Asp.net Mvc 3 Application which is now using the MvcMiniProfiler. I'm also using the Entity Framework to access my database, and I'd like to enable the profiler to work with the entity model. So far I've created the Context factory below:
internal class ProfiledContextFactory : IContextFactory
{
public ModelContainer GetContext()
{
var conn = ProfiledDbConnection.Get(GetConnection());
return ObjectContextUtils.CreateObjectContext<ModelContainer>(conn);
}
private static EntityConnection GetConnection()
{
return new EntityConnection(ConfigurationManager.ConnectionStrings["ModelContainer"].ConnectionString);
}
}
When I run the above code, which is called by my repository layer when I start a unit of work, it gets stuck in an infite loop when calling CreateDbCommandDefinition in the MvcMiniProfiler.ProfiledDbServices class.
Any clues what I'm doing wrong?
The problem was my GetConnection was returning the EntityConnection, not the SqlConnection within the EntityConnection. I've now modified my code so that it reads:
private static SqlConnection GetConnection()
{
var connStr = ConfigurationManager.ConnectionStrings["ModelContainer"].ConnectionString;
var entityConnStr = new EntityConnectionStringBuilder(connStr);
return new SqlConnection(entityConnStr.ProviderConnectionString);
}
And it works fine.
I discovered this while looking at this question: Using mvc-mini-profiler with EF 4.0 and Ninject

Resources