how to create a DAL using petapoco [closed] - petapoco

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to create a DAL and repositories using petapoco. The difficulty that comes in, is that I dont know how it manages its connections.
If I was using dapper I know how the connection process flows because I control it. I don't know what are the best practices in creating a DAL with petapoco.
public class UserRepository
{
public IEnumerable<User> All()
{
var db = new PetaPoco.Database("Sqlite_Connection");//this line
var s = db.Query<User>("SELECT * FROM Users");
return s.ToList();
}
}
I would like to place var db = new PetaPoco.Database("Sqlite_Connection");//this line
in my DALHelper class as a static property but I'm worried about scalability

I don't recommend using a static since you can get errors like "There is already an open DataReader associated with this Command" because the same connection is used by different request accesing the same resource.
Two options:
1. Create the connection in a controller base class
public class BaseController : Controller
{
protected DatabaseWithMVCMiniProfiler _database;
protected override void OnActionExecuting(ActionExecutingContext filterCon )
{
base.OnActionExecuting( filterCon );
_database = new DatabaseWithMVCMiniProfiler( "MainConnectionString");
}
}
2. Static method creating one connection per request
public static class DbHelper {
public static Database CurrentDb() {
if (HttpContext.Current.Items["CurrentDb"] == null) {
var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
HttpContext.Current.Items["CurrentDb"] = retval;
return retval;
}
return (Database)HttpContext.Current.Items["CurrentDb"];
}
}

A static property will be fine for the Initialization.
PetaPoco will open and close the connection each time, unless you are using a transaction. This isn't usually an issue due to connection pooling.
If you are using this in a web application then you should instantiate one PetaPoco database per request.

Related

Deep Module vs SRP [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
i have a message object that i can add content to. The message can also be sent. Is it better to provide a "deep module" that hides the dispatcher from the client, or is it better to have only one responsibility per class?
Example: expose the dispatcher
class Message {
void add(String key, String value) { ... }
}
class Dispatcher {
Result send(Message message) { ... }
}
class DispatcherFactory {
Dispatcher create() { return new DefaultDispatcher(); }
}
Example: Hide the dispatcher
class MessageFactory {
Message create() { return new Message(DefaultDispatcher()); }
}
class Message {
Message(Dispatcher dispatcher) { ... }
void add(String key, String value) { ... }
Result send() {
return dispatcher.dispatch(content);
}
}
In my opinion the latter is easier to use and also testable, but violates the SRP. Which one is better?
In my opinion the latter is easier to use and also testable, but violates the SRP
it does not violate SRP as implementation of Dispatcher class is located in Dispatcher class. If Message class would have implentation of Dispatcher class, then it will be violtion of SRP class.
Which one is better?
In my view, the second implementation is better if you can slightly modify your implementation of MessageFactory Mediator pattern.
Let me show an example:
class MessageFactory {
Message create(DefaultDispatcher defaultDispatcher)
{ return new Message(defaultDispatcher); }
}
UPDATE:
If you want to have relationship publisher and subscriber. I mean publisher send messages to subscribers, then you can use Observer pattern.
As wiki says about Observer pattern:
The observer pattern is a software design pattern in which an object,
named the subject, maintains a list of its dependents, called
observers, and notifies them automatically of any state changes,
usually by calling one of their methods.

How to NUnit test controller with multiple repositories [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a .net core API with a controller that handles multiple tables in the SQL database and I am using repository pattern design for best practice.
My Home controller's constructor injection looks like this:
private IUploadRepository _uploadRepository;
private ISalesRepository _salesRepository;
private ITRSalesRepository _trsalesRepository;
private ILocalPurchaseRepository _localRepository;
public HomeController(
IUploadRepository uploadRepository,
ISalesRepository salesRepository,
ITRSalesRepository trsalesRepository,
ILocalPurchaseRepository localRepository
)
{
this._uploadRepository = uploadRepository;
this._salesRepository= salesRepository;
this._trsalesRepository= trsalesRepository;
this._localRepository= localRepository;
}
[HttpPost]
public IActionResult PostUpload([FromBody] UploadModel upload)
{
uploadRepository.Add(upload); // the uploadRepository will save to db
return Created("Post", upload)
}
I have added the DI for these repositories in the StartUp.cs and I have verified that the Home controller (method) is behaving as expected. It is able to read/write to SQL db.
My question is, how can I use NUnit test to test this Home controller's Post action method? I have multiple CRUD methods that utilize these repository so in general I'd want to NUnit test them all.
I've tried to use constructor injection for the Home-Test-Class but that doesn't work.
Thank you for your help!
Uddate:
I've added a Post method as a test I would like to NUnit test on.
To unit test HomeController, you don't need to instantiate the external dependencies. You can have them as Mock Objects. There are lot of mocking frameworks out there that can do the job for you.
"Your goal is to unit test the HomeController only and test the functionalities related to it." Use mock or stub objects to minimize the number of external dependencies, so the test is focused on testing one thing only.
Following is a simple example to test your controller. I have also created a dummy project, you can see the code here NewEmployeeBuddy.CoreAPI:
using Microsoft.AspNetCore.Mvc;
using Moq;
using System.Collections.Generic;
using Xunit;
namespace UnitTestDemo.Tests.Controllers
{
public class HomeControllerTest
{
#region Properties
protected readonly Mock<IUploadRepository> uploadMockRepository;
protected readonly Mock<ISalesRepository> salesMockRepository;
protected readonly Mock<ITRSalesRepository> trsalesMockRepository;
protected readonly Mock<ILocalPurchaseRepository > localMockRepository;
protected readonly HomeController controllerUnderTest;
#endregion
#region Constructor
public HomeControllerTest()
{
//Don't rely on the dependency injection. Define your mock instances for the dependencies.
uploadMockRepository= new Mock<IUploadRepository>();
uploadMockRepository.Setup(svc => svc.GetAllEmployees()).Returns();
salesMockRepository= new Mock<ISalesRepository>();
trsalesMockRepository= new Mock<ITRSalesRepository>();
localMockRepository= new Mock<ILocalPurchaseRepository>();
controllerUnderTest = new HomeController(
uploadMockRepository.Object,
salesMockRepository.Object,
trsalesMockRepository.Object,
localMockRepository.Object);
}
#endregion
#region Unit Tests
//Add tests
#endregion
}
}
you could use a library like Moq to create mocks of the classes you need
a rough example of using Moq:
Declare the class you are mocking:
public Mock<IUploadRepository> UploadService { get; set; } = new Mock<IUploadRepository>();
Declare what should be returned when a particular method in your class is called.
UploadService.Setup(x => x.ClassMethodIWantToMock("Mock input param"))
.Returns(MyMockObject);
when instantiating your HomeController, you pass in the Mock classes you have created
moq quickstart wiki

How to go about starting a method chain in Object Oriented Programming? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Imagine having two objects, A and B, and B is dependent on A. Now you need to first call a method on object A (let's say checkUpdates), and then call one on object B (relayInfo).
If OOP is your preferred approach is it best practice to
call A.checkUpdates() and then B.relayInfo() from B (or wherever)
OR call A.checkUpdates() which directly calls B.relayInfo() on a reference of B?
In short should you have these objects call methods on each other in a ping-pong-like manner, or should one of them (or a controller object) call methods sequentially for both of them?
Let the dependent object be responsible for this task
public class Main {
public static void main(String[] args) {
B b = new B(new A());
b.relayInfo();
}
}
class A {
void checkUpdates() {
System.out.println("checkUpdates()");
}
}
class B {
final A a;
B(A a) {
this.a = a;
}
void relayInfo() {
if (a == null) {
return;
}
a.checkUpdates();
System.out.println("relayInfo()");
}
}

Is a low number of members in a class considered a code smell? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am currently making a simple to-do list program using the MVC pattern, and thus have a model class for the Notebook. However, something feels "off" as it has a very low number of members.
The Notebook is composed of categories, which are composed of To-do lists, which are composed of Items.
What I cannot place is whether this is a case poor analysis (e.g. there are more members and responsibilities I am just missing them..) or perhaps a code smell that the class is not needed (in that case I'm not sure what to do as I could just have a list of categories in that controller, but then I don't have a notebook entity modelled which seems wrong as well).
Below is the very simple class I have:
class Notebook
{
private String title;
private List<Category> categories;
public Notebook(String title, List<Category> categories)
{
}
public void setCategories(List<Category> categories)
{
}
public List<Category> getCategories()
{
}
}
I often have this issue where it feels like I am making classes for the sake of it and they have a very number of members/responsibilities, so it would be nice to know whether I am stressing for no reason or not.
Not necessarily, there is the concept in Domain Driven Design of what is called a "Standard Type". Which is really a basic primitive wrapped in an object class. The idea is that the primitive contains no information about what information it contains, it's just a string/int/whatever. So by having say an object that surrounds the primitive and ensures that it is always valid ensures that the object has a meaning far beyond just the primitive it contains e.g. a Name is not just a string, it's a Name.
Here's an example taken from the comments of Velocity
public class Velocity
{
private readonly decimal _velocityInKPH;
public static Velocity VelocityFromMPH(decimal mph)
{
return new Velocity(toKph(mph));
}
private Velocity(decimal kph)
{
this._velocityInKPH = kph;
}
public decimal Kph
{
get{ return this._velocityInKPH; }
}
public decimal Mph
{
get{ return toMph(this._velocityInKPH); }
}
// equals addition subtraction operators etc.
private static decimal ToMph(decimal kph){ // conversion code }
private static decimal ToKph(decimal mph){ // conversion code }
}

Accessing Request in Automapper Custom Resolver

I am working on an ASP.NET Web API project.
I use Auto-mapper for mapping from my domain objects to DTOs
How do pass in a request parameters into a Custom ValueResolver ?
I saw a couple of similar questions on stackoverflow posted a TWO years back which mention that this cannot be done. Is this the same situation now or has this been resolved ?
Link to similar question raised a TWO years ago : How to pass values to a Custom Resolver in Automapper?
There is a ConstructedBy method which can be used to inject your own Resolver object , but I don't how to access pass in Request
Thanks
I used the AfterMap() feature for the time being. I am hoping someone has a better solution.
For simplicity if I reduced my source and destination classes to
public class Source {
public string Value {get;set;}
}
public class Destination{
public string Value {get;set;}
private bool _reset;
public Destination(bool reset = false){
_reset = reset;
}
public void TryReset(){
if(!_reset) return;
Value = string.Empty;
}
}
I added a AfterMap() in the Mapping configuration to call the reset method.
Mapper.CreateMap<Source, Destination>()
.AfterMap( (source, dest) => dest.TryReset());
In the controller I pass the reset flag from the Request directly as
var destination = Mapper.Map(new Source { Value ="Hello" },
new Destination(flag));