I am using the mvc mini profiler to profile a NUnit Test suite.
I am just curious whether it would be possible to use the mvc mini profiler's profiling mechanism as an aspect, i.e., rather than having those using statements could I not somehow just provide some attribute above the method I want to profile?
I know that this would kill the kind of granularity we get with the mini profiler but in some cases, it's just more appropriate to use the AOP approach.
Ideas? Suggestions?
Thanks a bunch.
You would need to weave in code, so you would have to look at either PostSharp, Roslyn or some other IL weaving mechanism.
Yes, it is totally possible. In my case I was using Autofac, which implements interception using Castle's DynamicProxy.
But a very basic interceptor for profiling would look something like this (in C#):
public class ProfilerInterceptor : IInterceptor
{
#region Implementation of IInterceptor
public void Intercept(IInvocation invocation)
{
using (MiniProfiler.Current.Step(invocation.TargetType.Name + "." + invocation.Method.Name))
{
invocation.Proceed();
}
}
#endregion
}
NOTE: I know your preference was weaving rather than interception through proxies, but I'm posting it in case anybody else finds it useful.
Related
I was writing app with zend 2 framework. I had not worked with it, some time ago done small app maybe with zend 1.
I see what is not usual to me - public properties. I thought this is bad. But zend is showing such examples:
namespace Album\Model;
class Album
{
public $id;
public $artist;
public $title;
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->artist = (!empty($data['artist'])) ? $data['artist'] : null;
$this->title = (!empty($data['title'])) ? $data['title'] : null;
}
}
https://framework.zend.com/manual/2.3/en/user-guide/database-and-models.html
Is is good for this case? Why?
For the sake of those examples, zend tends to simplify their code, but when you develop your app, your must use your best practises you've learned. So if you think those properties deserve to be at least protected, so be it, it's good and I agree with you.
Sometimes zend, when they explain some stuff and uses the ServiceLocator they use it in controllers, it's not a good practise at all, because the serviceLocator is not mean to be used that way, plus, it was removed from controllers in zf3. Again they do it for explain some concept, and for the sake of tutorials they gave some bad code. The community suffered of this.
I advise you to be suspicious, more, skeptic about what Zend give into their tutorials, they just explain the functionnality but you shall not just blind copy what they provide. Only understand what they mean.
I am getting NPE while mocking EntityManager, below is my code,
#Stateless
public class NodeChangeDeltaQueryBean implements NodeChangeDeltaQueryLocal {
#PersistenceContext
private EntityManager em;
#Override
public String findIdByNaturalKey(final String replicationDomain, final int sourceNodeIndex,
final int nodeChangeNumber) {
List<String> result =
NodeChangeDelta.findIdByNaturalKey(this.em, replicationDomain, sourceNodeIndex,
nodeChangeNumber).getResultList();
return result.isEmpty() ? null : result.get(0);
}
}
My Entity Class
#Entity
public class NodeChangeDelta implements Serializable, Cloneable, GeneratedEntity, KeyedEntity<String> {
public static TypedQuery<String> findIdByNaturalKey(final EntityManager em, final String replicationDomain, final int sourceNodeIndex, final int nodeChangeNumber) {
return em.createNamedQuery("NodeChangeDelta.findIdByNaturalKey", String.class)
.setParameter("replicationDomain", replicationDomain)
.setParameter("sourceNodeIndex", sourceNodeIndex)
.setParameter("nodeChangeNumber", nodeChangeNumber);
}
}
My Test Class
#RunWith(MockitoJUnitRunner.class)
public class NodeChangeDeltaQueryBeanTest {
#InjectMocks
NodeChangeDeltaQueryBean nodeChangeDeltaQueryBean;
#Mock
EntityManager em;
#Test
public void testFindIdByNaturalKey() {
this.addNodeChangeDelta();
this.nodeChangeDeltaQueryBean.findIdByNaturalKey(this.REPLICATION_DOMAIN,
this.SOURCE_NODE_INDEX, this.NODE_CHANGE_NUMDER);
}
}
While debugging em is not null (also other arguments REPLICATION_DOMAIN,
SOURCE_NODE_INDEX, NODE_CHANGE_NUMDER not null) in Entity class, whereas em.createNamedQuery("NodeChangeDelta.findIdByNaturalKey", String.class) is null.
On the mockito wiki : Don't mock types you don't own !
This is not a hard line, but crossing this line may have repercussions! (it most likely will.)
Imagine code that mocks a third party lib. After a particular upgrade of a third library, the logic might change a bit, but the test suite will execute just fine, because it's mocked. So later on, thinking everything is good to go, the build-wall is green after all, the software is deployed and... Boom
It may be a sign that the current design is not decoupled enough from this third party library.
Also another issue is that the third party lib might be complex and require a lot of mocks to even work properly. That leads to overly specified tests and complex fixtures, which in itself compromises the compact and readable goal. Or to tests which do not cover the code enough, because of the complexity to mock the external system.
Instead, the most common way is to create wrappers around the external lib/system, though one should be aware of the risk of abstraction leakage, where too much low level API, concepts or exceptions, goes beyond the boundary of the wrapper. In order to verify integration with the third party library, write integration tests, and make them as compact and readable as possible as well.
Mock type that you don't have the control can be considered a (mocking) anti-pattern. While EntityManager is pretty much standard, one should not consider there won't be any behavior change in upcoming JDK / JSR releases (it already happened numerous time in other part of the API, just look at the JDK release notes). Plus the real implementations may have subtleties in their behavior that can hardly be mocked, tests may be green but the production tomcats are on fire (true story).
My point is that if the code needs to mock a type I don't own, the design should change asap so I, my colleagues or future maintainers of this code won't fall in these traps.
Also the wiki links to other blogs entries describing issues they had when they tried to mock type they didn't have control.
Instead I really advice everyone to don't use mock when testing integration with another system. I believe for database stuff, Arquillian is the thing to go, the project appears to be quite active.
Adapted from my answer : https://stackoverflow.com/a/28698223/48136
In Mockito, any method invocation on a mock that is not explicitly configured, always returns null. Therefore in findIdByNaturalKey, em.createNamedQuery is returning null and so NPE on setParameter. You need to configure it to RETURN_MOCKS.
Also, I am not sure if #InjectMocks supports #PersistenceContext. If it does not then em is probably null. If it does, please let me know and the above is your issue.
I need to MOQ wcfClientService while calling the SomeMethod().
Class ABC : IABC
{
internal WcfClientService wcfClientService = new WcfClientService();
public void SomeMethod(object pqr)
{
using(wcfClientService)
{
wcfClientService.Save(some parameters)
}
}
}
With the current implementation, you cannot isolate the "ABC" class as it is tightly coupled with wcfClientService. I would strongly suggest things mentioned below:
Extract an interface IClientService. This makes your "ABC" class depend on an abstraction instead of a concrete implementation. It will help in short term to isolate "ABC" better for unit testing. In long term, your "ABC" class would not have to be changed if a "RestfulClientService" was to be used.
Consider introducing a Dependency Injection framework. Anything like a Spring.Net, Unity or Autofac should serve the purpose. Ideally, your production code should never instantiate a dependency. Let the framework take care of it.
Now, register and resolve a mock implementation of the interface using the DI framework and start unit testing the "ABC" class.
I'm not so sure the title is a good match for this question I want to put on the table.
I'm planning to create a web MVC framework as my graduation dissertation and in a previous conversation with my advisor trying to define some achivements, he convinced me that I should choose a modular design in this project.
I already had some things developed by then and stopped for a while to analyze how much modular it would be and I couldn't really do it because I don't know the real meaning of "modular".
Some things are not very cleary for me, like for example, just referencing another module blows up the modularity of my system?
Let's say I have a Database Access module and it OPTIONALY can use a Cache module for storing results of complex queries. As anyone can see, I at least will have a naming dependency for the cache module.
In my conception of "modular design", I can distribute each component separately and make it interact with others developed by other people. In this case I showed, if someone wants to use my Database Access module, they will have to take the Cache as well, even if he will not use it, just for referencing/naming purposes.
And so, I was wondering if this is really a modular design yet.
I came up with an alternative that is something like creating each component singly, without don't even knowing about the existance of other components that are not absolutely required for its functioning. To extend functionalities, I could create some structure based on Decorators and Adapters.
To clarify things a little bit, here is an example (in PHP):
Before
interface Cache {
public function isValid();
public function setValue();
public function getValue();
}
interface CacheManager {
public function get($name);
public function put($name, $value);
}
// Some concrete implementations...
interface DbAccessInterface {
public doComplexOperation();
}
class DbAccess implements DbAccessInterface {
private $cacheManager;
public function __construct(..., CacheManager $cacheManager = null) {
// ...
$this->cacheManager = $cacheManager;
}
public function doComplexOperation() {
if ($this->cacheManager !== null) {
// return from cache if valid
}
// complex operation
}
}
After
interface Cache {
public function isValid();
public function setValue();
public function getValue();
}
interface CacheManager {
public function get($name);
public function put($name, $value);
}
// Some concrete implementations...
interface DbAccessInterface {
public function doComplexOperation();
}
class DbAccess implements DbAccessInterface {
public function __construct(...) {
// ...
}
public function doComplexQuery() {
// complex operation
}
}
// And now the integration module
class CachedDbAcess implements DbAccessInterface {
private $dbAccess;
private $cacheManager;
public function __construct(DbAccessInterface $dbAccess, CacheManager $cacheManager) {
$this->dbAccess = $dbAccess;
$this->cacheManager = $cacheManager;
}
public function doComplexOperation() {
$cache = $this->cacheManager->get("Foo")
if($cache->isValid()) {
return $cache->getValue();
}
// Do complex operation...
}
}
Now my question is:
Is this the best solution? I should do this for all the modules that do not have as a requirement work together, but can be more efficient doing so?
Anyone would do it in a different way?
I have some more further questions involving this, but I don't know if this is an acceptable question for stackoverflow.
P.S.: English is not my first language, maybe some parts can get a little bit confuse
Some resources (not theoretical):
Nuclex Plugin Architecture
Python Plugin Application
C++ Plugin Architecture (Use NoScript on that side, they have some weird login policies)
Other SO threads (design pattern for plugins in php)
Django Middleware concept
Just referencing another module blows up the modularity of my system?
Not necessarily. It's a dependency. Having a dependencies is perfectly normal. Without dependencies modules can't interact with each other (unless you're doing such interaction indirectly which in general is a bad practice since it hides dependencies and complicates the code). Modular desing implies managing of dependencies, not removing them.
One tool - is using interfaces. Referencing module via interface makes a so called soft dependency. Such module can accept any implementation of an interface as a dependency so it is more independant and as a result - more maintainable.
The other tool - designing modules (and their interfaces) that have only single responcibility. This also makes them more granular, independant and maintainable.
But there is a line which you should not cross - blindly applying these tools may leed to a too modular and too generic desing. Making things too granular makes the whole system more complex. You should not solve universe problems, making generic modules, that all developers can use (unless it is your goal). First of all your system should solve your domain tasks and make things generic enough, but not more than that.
I came up with an alternative that is something like creating each component singly, without don't even knowing about the existance of other components that are not absolutely required for its functioning
It is great if you came up with this idea by yourself. The statement itself, is a key to modular programming.
Plugin architecture is the best in terms of extensibility, but imho it is hard to maintenance especially in intra application. And depending the complexity of plugin architecture, it can make your code more complex by adding plugin logics, etc.
Thus, for intra modular design, I choose the N-Tier, interface based architecture. Basically, the architecture relays on those tiers:
Domain / Entity
Interface [Depend on 1]
Services [Depend on 1 and 2]
Repository / DAL [Depend on 1 and 2]
Presentation Layer [Depend on 1,2,3,4]
Unfortunately, I don't think this is achieveable neatly in php projects as it need separated project / dll references in each tier. However, following the architecture can help to modularize the application.
For each modules, we need to do interface-based design. It can help to enhance the modularity of your code, because you can change the implementation later, but still keep the consumer the same.
I have provided an answer similiar to this interface-based design, at this stackoverflow question.
Lastly but not least, if you want to make your application modular to the UI, you can do Service Oriented Architecture. This is simply make your application as bunch of services, and then make the UI to consume the service. This design can help to separate your UI with your logic. You can later use different UI such as desktop app, but still use the same logic. Unfortunately, I don't have any reliable source for SOA.
EDIT:
I misunderstood the question. This is my point of view about modular framework. Unfortunately, I don't know much about Zend so I will give examples in C#:
It consist of modules, from the smallest to larger modules. Example in C# is you can using the Windows Form (larger) at your application, and also the Graphic (smaller) class to draw custom shapes in the screen.
It is extensible, or replaceable without making change to base class. In C# you can assign FormLoad event (extensible) to the Form class, inherit the Form or List class (extensible) or overridding form draw method to create a custom window graphic (replaceable).
(optional) it is easy to use. In normal DI interface design, we usually inject smaller modules into a larger (high level) module. This will require an IOC container. Refer to my question for detail.
Easy to configure, and does not involve any magical logic such as Service Locator Pattern. Search Service Locator is an Anti Pattern in google.
I don't know much about Zend, however I guess that the modularity in Zend can means that it can be extended without changing the core (replacing the code) inside framework.
If you said that:
if someone wants to use my Database Access module, they will have to take the Cache as well, even if he will not use it, just for referencing/naming purposes.
Then it is not modular. It is integrated, means that your Database Access module will not work without Cache. In reference of C# components, it choose to provide List<T> and BindingList<T> to provide different functionality. In your case, imho it is better to provide CachedDataAccess and DataAccess.
I've JPA entities and need to perform logic with them. Until now a huge static database class did the job. It's ugly because every public interface method had an private equivalent that used the EntityManager, to perform transactions. But I could solve that having a static em too!
However i'm wondering if that's an appropriate design, especially as the class is responsible for many things.
Not surprisingly, the code i found online of real projects was not easy to understand (i might then as well remeain with my code).
The code here is easy to understand, although maybe over generic? Anyway, on top of JDBC. Yet, insightful, why use factories and singletons for DAOs?
I've though of singletoning the em instance as follows:
private static final Map<String, EntityManager> ems = new HashMap<String, EntityManager>();
private final EntityManager em;
private final EntityManagerFactory emf;
public void beginTransaction() {
em.getTransaction().begin();
}
public void commitTransaction() {
em.getTransaction().commit();
}
public Database(final String persistenceUnitName) {
if(ems.containsKey(persistenceUnitName)){
em = ems.get(persistenceUnitName);
}else{
ems.put(persistenceUnitName, em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager());
}
emf = em.getEntityManagerFactory();
this.persistenceUnitName = persistenceUnitName;
}
This way creation of instances is standard, still maintaining a singleton Connection/EntityManager.
On the otherhand I wondered whether there was the need to singleton ems in the first place?
The advantage is with multiple ems I run into locking problems (not using em.lock()).
Any feedback? Any real-world or tutorial code that demonstrates DAO with JPA2 and eclipselink?
Personally, I don't see the added value of shielding the EntityManager (which is an implementation of the Domain Store pattern) with a DAO and I would use it directly from the services, unless switching from JPA is a likely event. But, quoting An interesting debate about JPA and the DAO:
Adam said that he met only very few cases in which a project switched the database vendor, and no cases in which the persistence moved to a different thing than a RDBMs. Why should you pay more for a thing that it's unlikely to happen? Sometimes, when it happens, a simpler solution might have paid for itself and it might turn out to be simpler to rewrite a component.
I totally share the above point of view.
Anyway, the question that remains open is the lifecycle of the EntityManager and the answer highly depends on the nature of your application (a web application, a desktop application).
Here are some links that might help to decide what would be appropriate in your case:
Re: JPA DAO in Desktop Application
Using the Java Persistence API in Desktop Applications
Eclipselink in J2SE RCP Applications
Developing Applications Using EclipseLink JPA (ELUG)
An interesting debate about JPA and the DAO
And if you really want to go the DAO way, you could:
use Spring JPA support,
use some generic DAO library like generic-dao, krank, DAO Fusion,
roll your own generic DAO.
You could consider using Spring 3. Just follow their documentation for a clean design.