Recovering after exception when using a single dbcontext - wpf

I am using entity framework to persist data in a N-tier Wpf application. My dbcontext is shared amongst all repositories and is never disposed. When I persist data I mark an object as modifed and try to save changes. If an error accurs while persisting the object the object is still markted as modifed and if the user aborts the current opperation he will get the same error when saving another object.
I have solved this by overriding SaveChanges in my dbcontext and if any error accurs I accept all changes(see code below). So if an error accurs the object and all objects are marked unchanged even if theyr'e not persited.
This doesn't feel right...
Does anyone agree with this solution?
Another solution would be to new the dbcontext in each method in my repositores and disposing of them right away. That will make my repositories more complicated and "noicy" and I will also lose the ability to lazy load data...
Does anyone have a different solution for me?
//In my repositories
public void UpdateObject(Object object)
{
dbContext.Entry(object).State = EntityState.Modified;
dbContext.SaveChanges();
}
//In my dbcontext class
private ObjectContext ObjectContext()
{
return (this as IObjectContextAdapter).ObjectContext;
}
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (Exception)
{
ObjectContext().AcceptAllChanges();
throw;
}
}

Our team uses an approach similar to below:
Repository:
public class StudentRepository
{
private readonly MyEntities _context;
public StudentRepository(MyEntities context)
{
_context = context;
}
// Basic CRUD methods etc
}
Business Logic:
public AddStudent(Student student)
{
using( var context = new MyEntities())
{
var studentrepo = new StudentRepository(context);
studentrepo.Add(student);
context.SaveChanges();
}
}
This is an oversimplified example, but should give you an idea. To reduce code, we also use a base generic repository class for the CRUD methods.
If the project we are working on includes a web service, we instantiate the dbcontext in the API Controller and override the Dispose method to get rid of it.

Having such a long lived context is not a good idea. It will get large and slow with all the entities and changes being tracked, concurrency related issues may arise and exceptions thrown by your context can impact your entire application.
http://msdn.microsoft.com/en-us/data/jj729737
Another solution would be to new the dbcontext in each method in my
repositores and disposing of them right away. That will make my
repositories more complicated and "noicy" and I will also lose the
ability to lazy load data
In a disconnected scenario I would create and dispose with each request/unit of work. Concerned about your repos getting complicated? Then don't use this extra layer of abstraction. Are the repos really necessary? What do you gain over using the DbContext directly?
As for lazy loading I think in a disconnected n-tier scenario that lazy loading is not really appropriate. You should probably use eager loading of required data for your view or have separate method calls to get the related data.

Related

Static Analysis tool to catch self-invocation bypassing Spring cache #Cacheable method

I understand that this is because of the way proxies are created for handling caching, transaction related functionality in Spring. And the way to fix it is use AspectJ but I donot want to take that route cause it has its own problems. Can I detect self-invocation using any static analyis tools?
#Cacheable(value = "defaultCache", key = "#id")
public Person findPerson(int id) {
return getSession().getPerson(id);
}
public List<Person> findPersons(int[] ids) {
List<Person> list = new ArrayList<Person>();
for (int id : ids) {
list.add(findPerson(id));
}
return list;
}
If it would be sufficient for you to detect internal calls, you could use native AspectJ instead of Spring AOP for that and then throw runtime exceptions or log warnings every time this happens. That is not static analysis, but better than nothing. On the other hand, if you use native AspectJ, you are not limited to Spring proxies anyway and the aspects would work for self-invocation too.
Anyway, here is what an aspect would look like, including an MCVE showing how it works. I did it outside of Spring, which is why I am using a surrogate #Component annotation for demo purposes.
Update: Sorry for targeting #Component classes instead of #Cacheable classes/methods, but basically the same general approach I am showing here would work in your specific case, too, if you simply adjust the pointcut a bit.
Component annotation:
package de.scrum_master.app;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
#Retention(RUNTIME)
#Target(TYPE)
public #interface Component {}
Sample classes (components and non-components):
This component is to be called by other components should not lead to exceptions/warnings:
package de.scrum_master.app;
#Component
public class AnotherComponent {
public void doSomething() {
System.out.println("Doing something in another component");
}
}
This class is not a #Component, so the aspect should ignore self-invocation inside it:
package de.scrum_master.app;
public class NotAComponent {
public void doSomething() {
System.out.println("Doing something in non-component");
new AnotherComponent().doSomething();
internallyCalled("foo");
}
public int internallyCalled(String text ) {
return 11;
}
}
This class is a #Component. The aspect should flag internallyCalled("foo"), but not new AnotherComponent().doSomething().
package de.scrum_master.app;
#Component
public class AComponent {
public void doSomething() {
System.out.println("Doing something in component");
new AnotherComponent().doSomething();
internallyCalled("foo");
}
public int internallyCalled(String text ) {
return 11;
}
}
Driver application:
Please note that I am creating component instances throughout this sample code with new instead of requesting beans from the application context, like I would do in Spring. But you can ignore that, it is just an example.
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
new NotAComponent().doSomething();
new AComponent().doSomething();
}
}
Console log when running without aspect:
Doing something in non-component
Doing something in another component
Doing something in component
Doing something in another component
Now with the aspect, instead of the last message we would expect an exception or a logged warning. Here is how to do that:
Aspect:
Sorry for using native AspectJ syntax here. Of course, you could also use annotation-based syntax.
package de.scrum_master.aspect;
import de.scrum_master.app.*;
public aspect SelfInvocationInterceptor {
Object around(Object caller, Object callee) :
#within(Component) &&
call(* (#Component *).*(..)) &&
this(caller) &&
target(callee)
{
if (caller == callee)
throw new RuntimeException(
"Self-invocation in component detected from " + thisEnclosingJoinPointStaticPart.getSignature() +
" to "+ thisJoinPointStaticPart.getSignature()
);
return proceed(caller, callee);
}
}
Console log when running with aspect:
Doing something in non-component
Doing something in another component
Doing something in component
Doing something in another component
Exception in thread "main" java.lang.RuntimeException: Self-invocation in component detected from void de.scrum_master.app.AComponent.doSomething() to int de.scrum_master.app.AComponent.internallyCalled(String)
at de.scrum_master.app.AComponent.internallyCalled_aroundBody3$advice(AComponent.java:8)
at de.scrum_master.app.AComponent.doSomething(AComponent.java:8)
at de.scrum_master.app.Application.main(Application.java:6)
I think, you can use this solution and maybe rather log warnings instead of throwing exceptions in order to softly guide your co-workers to inspect and improve their AOP-dependent Spring components. Sometimes maybe they do not wish self-invocation to trigger an aspect anyway, it depends on the situation. You could run the Spring application in full AspectJ mode and then, after evaluating the logs, switch back to Spring AOP. But maybe it would be simpler to just use native AspectJ to begin with and avoid the self-invocation problem altogether.
Update: In AspectJ you can also make the compiler throw warnings or errors if certain conditions are met. In this case you could only statically determine calls from components to other components, but without differentiating between self-invocation and calls on other methods from other components. So this does not help you here.
Please also notice that this solution is limited to classes annotated by #Component. If your Spring bean is instantiated in other ways, e.g. via XML configuration or #Bean factory method, this simple aspect does not work. But it could easily be extended by checking if the intercepted class is a proxy instance and only then decide to flag self-invocations. Then unfortunately, you would have to weave the aspect code into all of your application classes because the check can only happen during runtime.
I could explain many more things, such as using self-injection and call internal methods on the injected proxy instance instead of via this.internallyCalled(..). Then the self-invocation problem would be solved too and this approach also works in Spring AOP.
Can I detect self-invocation using any static analysis tools?
In theory you can, but be aware of Rice's theorem. Any such tool would sometimes give false alarms.
You could develop such a tool using abstract interpretation techniques. You may need more than a year of work.
You could subcontract the development of such tools to e.g. the Frama-C team. Then email me to basile.starynkevitch#cea.fr

Asynchronous Begin/End pattern for webservices in silverlight project

I found that the proxy generated with SlSvcUtil.exe (or by adding reference to Web References) only supports Event based async model which is absolutely inappropriate from design point of view (events were 2nd class citizens from the first days).
I'm going to implement F#'s async builder approach and I found "old style" Begin/End are much easier to be generalized. I notices SlSvcUtil.exe generates Begin/End methods pair but marks them both with private keyword?
A couple options on top of my head are:
expose Begin/End methods by updating the proxy class by hand
use wsdl.exe and create wrapper library for missing System.Web classes
use other communication protocols (HttpClient, Tcp)
use third-party proxies (failed to find any so far)
Any ideas?
Say someone created a remote service with one method:
public interface CompressService
{
public byte[] Compress(byte[] inData);
}
After SlSvcUtil I got:
public class CompressServiceSoapClient: ClientBase<CompressServiceSoap...
{
private BeginOperationDelegate onBeginCompressDelegate;
private EndOperationDelegate onEndCompressDelegate;
public event System.EventHandler<CompressCompletedEventArgs> CompressCompleted;
public void CompressAsync(byte[] inData, object userState);
}
While in fact I need:
public class CompressServiceSoapClient: ClientBase<CompressServiceSoap...
{
public IAsyncResult BeginCompress(byte[] inData, System.AsyncCallback callback, object asyncState);
public byte[] EndCompress(IAsyncResult result);
}
Answer
The solution is to declare contract interface with async methods and do not use generated code inherited from ClientBase<>. The article http://msdn.microsoft.com/en-us/library/dd744834(v=vs.95).aspx describes this in more details.
You can access the begin/end methods by using the channel factory for the end point.
Basically just create a new ChannelFactory and pass in a binding and end point. You can use the host source to dynamically update the end point so it's not hard-coded. The resulting instance will expose the begin/end methods for you.

AppDomain.GetData method not accessible?

I am developing a Silverlight 3 application and I would like to delegate all unexpected error handling in a single instance of a class I have named ErrorHandler. This class has one method named HandleApplicationException, plus a couple of other methods to handle more specialized errors.
In my application I am using Unity for dependency injection, but since I want the error handling object to be available even when the Unity container is not yet set up, I register the object as AppDomain global data in the App class constructor, this way:
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
AppDomain.CurrentDomain.SetData("ErrorHandler", new ErrorHandler());
InitializeComponent();
}
And in case of unhandled exception, I retrieve the error handler object and use it this way:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
e.Handled = true;
var errorHandler = AppDomain.CurrentDomain.GetData("ErrorHandler") as ErrorHandler;
Debug.Assert(errorHandler != null, "No ErrorHandler registered.");
errorHandler.HandleApplicationException(e.ExceptionObject);
}
The problem is that the AppDomain.GetData method in the Application_UnhandledException method is throwing a MethodAccessException. I don't understand why, as I am just invoking a public method on the AppDomain class. I have used a similar approach in other applications and it worked fine (anyway these were not Silverlight applications).
So, what's going on? Am I doing something wrong?
Ok, I got it. From MSDN documentation:
This member has a
SecurityCriticalAttribute attribute,
which restricts it to internal use by
the .NET Framework for Silverlight
class library. Application code that
uses this member throws a
MethodAccessException.
I have resorted to storing the error handler in a public property in the App class, then I access it using ((App)Application.Current).ErrorHandler. I don't like doing things this way but I suppose it is ok in this special case.
Why can't you just use a static instance of ErrorHandler? I.e. have something like ErrorHandler.Current?
It looks like you're trying to manually construct a poor man's IoC framework to be honest.
Consider doing some research on Unity/Ninject and see for yourself why strongly-typed decoupling is better.

Silverlight serialisation/deserialisation problem

I'm looking for a way to persist Silverlight objects to a user's PC, then re-hydrate them so the user can finish editing them.
Serialising with DataContractSerializer and persisting to IsolatedStorageFile works fine. However, deserialising causes a problem. Here's the code that causes the failure:
private string _FirstNames = string.Empty;
public string FirstNames
{
get { return _FirstNames; }
set
{
new PersonNameValidator().Validate(value); //<-- BOOM 8(
Set(ref _FirstNames, value, () => this.FirstNames);
}
}
The deserialiser calls the property setter, which in turn throws an exception and aborts the deserialisation.
I've tried explicitly applying DataContract/DataMember/IgnoreDataMember attributes, but then it doesn't play nicely with private fields:
System.Security.SecurityException
occurred Message="The data contract
type
'Trident.Model.Journey.JourneyApplication'
cannot be serialized because the
member '_TravellerSavingsAmount' is
not public. Making the member public
will fix this error. Alternatively,
you can make it internal, and use the
InternalsVisibleToAttribute attribute
on your assembly in order to enable
serialization of internal members -
see documentation for more details. Be
aware that doing so has certain
security implications."
How can I bypass the property setters during deserialisation?
I'd like to keep my classes focused on the domain, and not too polluted with infrastructure concerns.
A couple of ideas:
serialize a property that is used only for serialization thereby bypassing any validation
serialize a parent class and use a derived class for validation

DeSerialized attribute in Silverlight

I have reasonably limited data to move between silverlight and a WCF service. So I have set up some datacontracts. I was hoping to be able to use the same classes to use for some limited data validation on the client side, without needing the overhead of DTOs and stuff.
I have a contract something like this:
[DataContract]
class MyObject
{
private String _id;
[DataMember]
public String ID
{
get
{
return _id;
}
set
{
_id = value;
DoStuff();
}
}
Now when I deserialize the object the setter will be run. This will set the private variable _id which is good. But I don't want the DoStuff() to be run on deserialization.
I had hoped to use the [OnDeserializing] and [OnDeserialized] attributes. I could have defined a bool flag that I could use to control what gets run in the setter. This actually works on the server side but Silverlight doesn't have those attributes.
Any suggestions?
I would recommend not overloading the usage of these classes to perform logic. This is your service data contract. You shouldn't touch the Silverlight proxy classes that get generated. I recommend that you put your validation logic into other classes that you invoke after deserialization is complete. Otherwise, you might start getting errors in your serialization code when your errors are actually in your data.

Resources