Migration from linq2sql to EF4.0 - linq-to-sql

In linq2sql I had this code to implement base class for repository
public abstract class Repository<T> : IRepository<T> where T : class {
protected DataContext context;
protected Table<T> table;
public Repository (DataContext context)
{
this.context = context;
table = context.GetTable<T> ();
}
public IQueryable<T> FindAll ()
{
return table;
}
public IQueryable<T> FindAll(Func<T, bool> exp)
{
return table.Where(exp).AsQueryable();
}
}
Now I need to migrate to EF 4.0
Everything is fine and simple, BUT I can't find GetTable (or similar) method in ObjectContext
Thanks for help

You're looking for CreateObjectSet<T>.

Related

I need to write JUNIT for Apache camel route

I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}

Easymock with dao

Let's assume that i have a Dao class with a method that establishes connection and reads int from database.
public class Dao {
public static final Dao INSTANCE = new Dao();
public int getSomething() {
//connection
return 1;
}
}
And i have a Servlet with such code inside.
int i = Dao.INSTANCE.getSomething();
The problem is that i don't know how to mock this Dao.INSTANCE call...
If it was for example a servlet with session. I could make it like this.
Session s = EasyMock.createMock(Session.class);
expect(request.getSession()).andReturn(s);
but i am not able to make it like this
Dao dao = EasyMock.createMock(Dao.class);
expect(Dao.INSTANCE).andReturn(dao);
Make the dao an instance variable, and then you can easily mock it:
public class MyServlet extends HttpServlet {
Dao dao = Dao.INSTANCE;
}
MyServlet servlet = new MyServlet();
servlet.dao = EasyMock.createMock(Dao.class);
I'd recommend you change the code so calling a method will return a singleton. Such as
public class Dao {
public static Dao singleton;
public static Dao getInstance(){
if(singleton == null){
singleton = new Dao();
}
return singleton;
}
public int getSomething() {
//connection
return 1;
}
}
And after that mock getInstance using PowerMock.
Take a look here for how.

How to define an aspectj pointcut that picks out all constructors of a class that has a specific annotation?

Here is the annotation:
#Target(value = ElementType.TYPE)
#Retention(value = RetentionPolicy.RUNTIME)
#Inherited
public #interface MyAnnotation {
String name();
}
Here is one annotated class:
#MyAnnotation(name="foo")
public class ClassA {
public ClassA() {
// Do something
}
}
Here is a second annotated class:
#MyAnnotation(name="bar")
public class ClassB {
public ClassB(String aString) {
// Do something
}
}
I am looking for an aspectj pointcut that correctly matches the constructors for ClassA and ClassB while not matching any other constructor for any other class NOT annotated by MyAnnotation.
Your pointcut should look like this:
execution((#MyAnnotation *).new(..))
If the annotation is in another package:
execution((#de.scrum_master.aop.demo.MyAnnotation *).new(..))
Or if you do not want to fully qualify the package:
execution((#*..MyAnnotation *).new(..))
Edit: Okay, some more info about your question in the comment:
Constructor executions have no return value which you could capture in
after() returning(Object myObject) : myJoinpoint()
This only works for methods. So please use
after(Object myObject) returning : myJoinpoint() && this(myObject)
instead if you do need the constructed object for any purpose.
Here is the working solution from kriegaex in its entirety:
public aspect AnnotationTests {
public aspect AnnotationTests {
after(Object myObject) returning : execution((#MyAnnotation *).new(..))
&& this(myObject) {
System.out.println("Object class name: " + myObject.getClass().getName());
}
}
}
#MyAnnotation(name="foo")
public class ClassA {
public ClassA() {
// Do something
}
public static void main(String[] args) {
ClassA classA = new ClassA();
ClassB classB = new ClassB("");
if (classA.getClass().getName().equals(classB.getClass().getName())) {
throw new RuntimeException("Big problems!");
}
}
}
#MyAnnotation(name="bar")
public class ClassB {
private final String aString;
public ClassB(String aString) {
this.aString = aString;
}
}
THE FOLLOWING WORKS, BUT IS NOT RECOMMENDED BY kriegaex. PROVIDED HERE AS POSSIBLE MATERIAL THAT COULD BE REPURPOSED IF THE NEED ARISES.
This was my first working solution to the problem which uses in part the initialization() pointcut primitive.
public aspect AnnotationTests {
private pointcut genericConstructor(): initialization(*.new(..));
private pointcut withinMyAnnotation(): #within(MyAnnotation);
private pointcut constructorInAnnotatedClass(): genericConstructor()
&& withinMyAnnotation();
before(): constructorInAnnotatedClass() && !cflowbelow(constructorInAnnotatedClass()) {
final Object objectInstance = thisJoinPoint.getTarget();
System.out.println("Object class name at join point: "
+ objectInstance.getClass().getName());
}
}
#MyAnnotation(name="foo")
public class ClassA {
public ClassA() {
// Do something
}
public static void main(String[] args) {
ClassA classA = new ClassA();
ClassB classB = new ClassB("");
if (classA.getClass().getName().equals(classB.getClass().getName())) {
throw new RuntimeException("Big problems!");
}
}
}
#MyAnnotation(name="bar")
public class ClassB {
private final String aString;
public ClassB(String aString) {
this.aString = aString;
}
}

Castle Scoped Lifestyle not working

Trying to find the real cause of this and not having much fun!
Type is not resolved for member 'Castle.MicroKernel.Lifestyle.Scoped.CallContextLifetimeScope+SerializationReference,Castle.Windsor, Version=3.1.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'.
This looks like a bug considering I have nothing register with the container using this lifestyle.
Faced same issue while doing MSTest. Adding Castle.Windsor.dll to GAC worked for me.
gacutil.exe /if "C:\Castle.Windsor.3.1.0\lib\net40\Castle.Windsor.dll"
I'm not sure what you are trying to do, but if your goal is implementing an IDependencyResolver (which looks like it since you are using scopes):
If you are implementing an IDependencyResolver, don't try to be clever and inherit from your IDependencyScope implementation. Create the Resolver from scratch. This is how I implemented my dependency resolver (which works):
public class WindsorDependencyResolver : IDependencyResolver {
private readonly IWindsorContainer _container;
public WindsorDependencyResolver(IWindsorContainer container)
{
_container = container;
}
public IDependencyScope BeginScope()
{
return new WindsorDependencyScope(_container);
}
public object GetService(Type serviceType)
{
return _container.Kernel.HasComponent(serviceType)
? _container.Resolve(serviceType)
: null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType).Cast<object>();
}
public void Dispose()
{
}
}
public class WindsorDependencyScope : IDependencyScope {
private readonly IWindsorContainer _container;
private readonly IDisposable _scope;
private bool _disposed;
public WindsorDependencyScope(IWindsorContainer container)
{
_container = container;
_scope = _container.BeginScope();
}
public object GetService(Type serviceType)
{
EnsureNotDisposed();
return _container.Kernel.HasComponent(serviceType)
? _container.Kernel.Resolve(serviceType)
: null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
EnsureNotDisposed();
return _container.ResolveAll(serviceType).Cast<object>();
}
public void Dispose()
{
if(_disposed) return;
_scope.Dispose();
_disposed = true;
GC.SuppressFinalize(this);
}
private void EnsureNotDisposed()
{
if(_disposed) throw new ObjectDisposedException("WindsorDependencyScope");
}
}
And this was my first attempt (which produced your error):
public class WindsorDependencyResolver : WindsorDependencyScope, IDependencyResolver {
private readonly IWindsorContainer _container;
public WindsorDependencyResolver(IWindsorContainer container)
: base(container)
{
_container = container;
}
public IDependencyScope BeginScope()
{
return new WindsorDependencyScope(_container);
}
}

In GWT, how can I serialize/unserialize a Place using JSON in its tokenizer?

I would like to create a standard Tokenizer for my places in GWT.
To do so, I would like to use the json format. Something like this :
public String getToken(T place) {
return transformToJSON(place);
}
public T getPlace(String token) {
return (T)transformJSONToObject(token);
}
I can't find a way to implements transformToJSON and transformJSONToObject. I've tried to use the JSONParser of GWT but it's quite limited to JavascriptObject (and Places are not JavascriptObject).
How can I achieve it ?
You really want to put JSON into your URLs?!
Anyway:
public String getToken(MyPlace place) {
JSONObject obj = new JSONObject();
obj.put("id", new JSONString(place.getId());
return obj.toString();
}
public MyPlace getPlace(String token) {
JSONObject obj = JSONParser.parseStrict(token).isObject();
return new MyPlace(obj.get("id").isString().stringValue());
}
You can achieve the same using AutoBeans; in any case: copy things in and out of your place.
As an alternative, you can of course have your Place be backed by a JSONObject/AutoBean:
class MyPlace extends Place {
public static class Tokenizer implements PlaceTokenizer<MyPlace> {
public String getToken(MyPlace place) {
return myPlace.jsonObject.toString();
}
public Place getPlace(String token) {
return new MyPlace(JSONParser.parseStrict(token).isObject());
}
}
private final JSONObject jsonObject;
public MyPlace() {
this(new JSONObject());
}
public MyPlace(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
public String getId() { return jsonObject.get("id").isString().stringValue(); }
public void setId(String id) { jsonObject.put("id", new JSONString(id)); }
}
Note: All of the above works much better with AutoBeans; error handling is a PITA with JSONObject, and it doesn't make for very readable code either.
Some kind of code-generator can help here if you have a lot of places.
Here is the way how to (de)serialize any objects to JSON with GWT.
1) Define class extending JavaScriptObject with protected constructor
public class PlaceData extends JavaScriptObject {
public PlaceData () {
}
}
2) Add native getters and setter for fields
public final native String getId() /*-{
return this.id;
}-*/;
public final native String getToken() /*-{
return this.token;
}-*/;
3) Define somewhere mapping methods like those
public static getPlace(PlaceData placeData) {
Place place = new Place();
place.setToken(placeData.getToken());
place.setId(placeData.getId());
return place; }
public static getPlaceData(Place place) {
PlaceData placeData = new PlaceData();
placeData.setToken(place.getToken());
placeData.setId(place.getId());
return placeData; }
4) And for converting string to JavaScriptObject use native eval() function.
public static native JsArray<PlaceData> jobs(String jsonArray) /*-{
return eval(json);
}-*/;
public static native PlaceData objects(String jsonPlace) /*-{
return eval(json);
}-*/;