Castle Core Invocation create a cache key from intercepted method - caching

I'm using a interface interceptor to cache all methods that starts with "Get" but i can't figure out how to generate a unique cache key for every unknown parameter it can be anything and using GetHashCode is not an option as i can't be 100% sure that they have overridden the GetHashCode.
some thoughts was someting in the line of How can I create a unique hashcode for a JObject?
where JSON is used for a JObject i was thinking on JSON serialize every parameter then get the hash code like explained in the link above:
var obj = JToken.Parse(jsonString);
var comparer = new JTokenEqualityComparer();
var hashCode = comparer.GetHashCode(obj);
However i think this will be a performence hit so how can this be solved ?
The code i have so far is this but it wont handle the complex type situation where .ToString won't generate the raw value type like int, string etc.
private string CreateCacheKey(IInvocation invocation)
{
string className = invocation.TargetType.FullName;
string methodName = invocation.Method.Name;
var builder = new StringBuilder(100);
builder.Append(className);
builder.Append(".");
builder.Append(methodName);
for (int i = 0; i < invocation.Arguments.Length; i++)
{
var argument = invocation.Arguments[i];
var argumentValue = invocation.GetArgumentValue(i);
builder.Append("_");
builder.Append(argument);
if (argument != argumentValue)
{
builder.Append(argumentValue);
}
}
return string.Format("{0}-{1}", this.provider.CacheKey, builder);
}

I ended up using GetHashCode as it is the only viable solution if thay dont override the method it will not cache.

Related

Spring ehcache - Not able to retrieve value based on custom key

I am using KeyGenerator to generate custom key while caching a component.
Here is the cacheable method:
#CachePut(value = "cacheOne", keyGenerator = "keyGenerator")
public CachedObject cacheMeta(final Object obj1,
final Object obj2,
final CachedObject cachedObject) {
return cachedObject;
}
Here is KeyGenerator implementation:
public Object generate(Object o, Method m ,Object ... params){
StringBuilder s=new StringBuilder();
return s.append(params[0].hashCode()).append(params[1].hashCode());
}
While retrieving value from cache, i am generating key as :
StringBuilder s= new StringBuilder();
s.append(obj1.hashCode().append(obj2.hashCode()));
Element elt=CacheManager.getInstance("cacheOne").get(s)
But it always returns null.
The problem is that you are using a StringBuilder as the cache key. StringBuilder has no equals or hashCode defined. So it relies on the ones defined on Object.
Which basically means that the get used to get the cache entry doesn't match the one putting the entry.
Using toString() to put
StringBuilder s = new StringBuilder();
return s.append(params[0].hashCode()).append(params[1].hashCode()).toString();
and get
StringBuilder s = new StringBuilder();
s.append("a".hashCode()).append("b".hashCode());
Cache.ValueWrapper wrapper = cache.get(s.toString());
solves it.
But I have to things to say.
First, using a StringBuilder here is useless because using String concatenation will let the compiler add a StringBuilder under the hood but be much nicer to read. So you could do
return params[0].hashCode() + "" + params[1].hashCode();
and
Cache.ValueWrapper wrapper = cache.get("a".hashCode() + "" + "b".hashCode());
which will work perfectly and have the same performance.
Then, relying on hashcodes to create a key is not safe. Hashcodes can have collisions. Even when appending two hashcodes. So you might mix entries on a given key.

How to use Expressions to invoke a method call with a generic list as the parameter?

We're using the very Excellent ToStringBuilder in our project as a performant, generic backing for our ToString implementations. It worked fine for debugging until I needed to generate a string representation of an object graph to check if it had changed in between loading and closing. Previously I had used a MemoryStream to write the object out to xml, but this seemed heavyweight so I decided to try out using ToStringBuilder, which is where I hit a showstopper...
Our object graph uses generic typed lists heavily, so when the lists are printed out they look like the following:
PropertyName:{System.Collections.Generic.List`1[Namespace.Path.To.MyClassDto]}
Instead of enumerating through the list and invoking ToString on each object, which is fine as that's default behaviour (btw, ToStringBuilder supports object[], but we don't want to retrofit our entire Dto layer just to fix this problem).
I tried to patch the code in question (ToStringBuilder.cs, line 177) to recognise when the type is a generic list, and then invoke string.Join(", ", list), but I couldn't get my head around how the linq reflection API handles generics.
The first thing I tried was to get a handle to the String.Join(IEnumerable<>) method like this:
var stringJoinMethod = typeof(string).GetMethod("Join", new[] { typeof(string), typeof(IEnumerable<>) });
But GetMethod returned null so that didn't work. I eventually found this StackOverflow question that showed me how to get a generic method by signature (call getmethods() instead and filter the results). That got me the correct method handle, so I tried to do something like this:
private void AppendMember(MemberInfo memberInfo)
{
AppendQuotesIfRequiredForType(memberInfo);
Type type = GetMemberType(memberInfo);
var memberAppendMethod = typeof(StringBuilder).GetMethod("Append", new[] { type });
Expression getMemberValue = Expression.MakeMemberAccess(TargetArgExpression, memberInfo);
if (type.IsValueType)
{
Type appendArgType = memberAppendMethod.GetParameters()[0].ParameterType;
if (type != appendArgType)
{
getMemberValue = Expression.TypeAs(getMemberValue, typeof(object));
}
//my code begins here.
_appendExpressions.Add(Expression.Call(SbArgExpression, memberAppendMethod, getMemberValue));
}
else if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>)))
{
// now to emit some code to do the below, you wouldn't think it'd be this hard...
// string.Join(", ", genericList);
AppendStartOfMembers();
//this returns null, because generics are not well supported by the reflection API, boo!
var stringJoinMethod = typeof(string).GetGenericMethod("Join", new[] { typeof(string), typeof(IEnumerable<>) });
var CommaSpace = Expression.Constant(", ");
// this doesn't work, throws an ArgumentException as below
getMemberValue = Expression.Call(stringJoinMethod, CommaSpace, getMemberValue);
_appendExpressions.Add(Expression.Call(SbArgExpression, memberAppendMethod, getMemberValue));
AppendEndOfMembers();
}
else
{
//primitives like strings
_appendExpressions.Add(Expression.Call(SbArgExpression, memberAppendMethod, getMemberValue));
}
//my code ends here.
AppendQuotesIfRequiredForType(memberInfo);
}
This errors with the following exception:
System.ArgumentException: "Method System.String Join[T](System.String, System.Collections.Generic.IEnumerable`1[T]) is a generic method definition"
at System.Linq.Expressions.Expression.ValidateMethodInfo(MethodInfo method)
at System.Linq.Expressions.Expression.ValidateMethodAndGetParameters(Expression instance, MethodInfo method)
at System.Linq.Expressions.Expression.Call(MethodInfo method, Expression arg0, Expression arg1)
at MyNameSpace.Common.ToStringBuilder`1.AppendMember(MemberInfo memberInfo) in C:\myproject\MyNamespace.Common\ToStringBuilder.cs:line 206
I started googling that error message and found people talking about using Expression.Lamba() to wrap calls to generic methods, at which point I realised I was way out of my depth.
So, assuming I have a List mylist, how do I generate an Expression as above that will do the equivalent of string.Join(", ", mylist); ?
thanks!
To get the "generic type" of your generic list (the type of "T"), you can do
var genericListType= type.GetGenericArguments()[0];
so in your elseif, you could do (it might be easier, I just stay as close as possible to your code)
else if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>)))
{
// now to emit some code to do the below, you wouldn't think it'd be this hard...
// string.Join(", ", genericList);
AppendStartOfMembers();
//this returns null, because generics are not well supported by the reflection API, boo!
var stringJoinMethod = typeof(string).GetGenericMethod("Join", new[] { typeof(string), typeof(IEnumerable<>) });
var CommaSpace = Expression.Constant(", ");
var genericListType= type.GetGenericArguments()[0];
var genericStringJoinMethod = stringJoinMethod.MakeGenericMethod(new[]{genericListType});
// this doesn't work, throws an ArgumentException as below
getMemberValue = Expression.Call(genericStringJoinMethod , CommaSpace, getMemberValue);
_appendExpressions.Add(Expression.Call(SbArgExpression, memberAppendMethod, getMemberValue));
AppendEndOfMembers();
}

How to write inresponse in indesign scripts

I am running this script for getting all form fields of a indd file.
var _ALL_FIELDS = "";
var allFields = myDocument.formFields;
for(var i=0;i<allFields.length;i++){
var tf = allFields[i];
alert(tf.id);
alert(tf.label);
alert(tf.name);
alert(_ALL_FIELDS = _ALL_FIELDS +\",\"+ tf.name);
}
What i have done is, created a soap-java based client and calling the runscript method.
Now i am able to get these fields but how to send these fields back to the client i.e. how to write this in response and then at client side how to read it from response.
Code for calling runscript method is:-
Service inDesignService = new ServiceLocator();
ServicePortType inDesignServer = inDesignService.getService(new URL(parsedArgs.getHost()));
IntHolder errorNumber = new IntHolder(0);
StringHolder errorString = new StringHolder();
DataHolder results = new DataHolder();
inDesignServer.runScript(runScriptParams, errorNumber, errorString, results);
Also I have found in docs that runScript method returns RunScriptResponse but in my case it's returning void.
http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/indesign/sdk/cs6/server/ids-solutions.pdf
It looks like you want to return an array of formField names. You could take advantage of the everyItem() collection interface method in your javascript:
var result = myDocument.formFields.everyItem().name;
result;
The javascript will return the last value in the called script, so just to make it completely obvious, the last line is just the value to be returned.
On the Java side, the runScript method is passing the results variable as the 4th parameter, and that's where you'll find your response. So, after your code snippet, you might have something like this:
List<String> formFieldNames = new ArrayList<String>();
if (results.value.getData() != null) {
Data[] resultsArray = (Data[]) results.value.getData();
for (int i = 0; i < resultsArray.length; i++) {
formFieldNames.add(resultsArray[i].getData().toString());
}
}

Is there an equivalent in Dart of the instance_variable_set method in Ruby?

If not, is there anything like this on the horizon?
This is the one feature of JavaScript, Ruby, and Perl that I can't live without. I know you can fake it with a hash member, but I want to be able to create (arbitrary) "first class" members from a parser.
Currently there's nothing that can set a field that doesn't yet exist. The mirror API can be used to set fields that already exist, and may eventually be extended to support defining new fields dynamically.
You can also use the "noSuchMethod" method on a class to intercept setter / getter, and store the received value in a map.
For example (I can't remember the syntax exactly...):
class Foo {
var _dynamicProperties = new Map<String,Object>();
noSuchMethod(String function_name, List args) {
if (args.length == 0 && function_name.startsWith("get:")) {
// Synthetic getter
var property = function_name.replaceFirst("get:", "");
if (_dynamicProperties.containsKey(property)) {
return _dynamicProperties[property];
}
}
else if (args.length == 1 && function_name.startsWith("set:")) {
// Synthetic setter
var property = function_name.replaceFirst("set:", "");
// If the property doesn't exist, it will only be added
_dynamicProperties[property] = args[0];
return _dynamicProperties[property];
}
super.noSuchMethod(function_name, args)
}
}
And then you can use this in your code as follows:
var foo = new Foo();
foo.bar = "Hello, World!";
print(foo.bar);
Of course, this can lead to typos that will not be checked by the type checker, e.g.:
foo.bar = "Hello";
foo.baz = "Hello, World!"; // Typo, meant to update foo.bar.
There are ways you have type-checker validation by using redirecting factory constructors and an implied interface, but then it starts to get complicated.
Side note: This is what JsonObject uses to convert a JSON map to a class type syntax.

Reflection + Linq + DbSet

I use EF code-first 4.1. in my application. Now I want to get entities through WCF services using generic types.
I'm trying to reflect generic type and invoke the method ToList of DbSet Object.
Here is my code:
public string GetAllEntries(string objectType)
{
try
{
var mdc =
Globals.DbConnection.Create(#"some_db_connection", true);
// Getting assembly for types
var asob = Assembly.GetAssembly(typeof(CrmObject));
// getting requested object type from assembly
var genericType = asob.GetType(objectType, true, true);
if (genericType.BaseType == typeof(CrmObject))
{
// Getting Set<T> method
var method = mdc.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
// Making Set<SomeRealCrmObject>() method
var genericMethod = method.MakeGenericMethod(genericType);
// invoking Setmethod into invokeSet
var invokeSet = genericMethod.Invoke(mdc, null);
// invoking ToList method from Set<> invokeSet
var invokeToList = invokeSet.GetType().GetMember("ToList").Cast<MethodInfo>().FirstOrDefault();
//this return not referenced object as result
return invokeToList.ToString();
}
return null;
}
catch (Exception ex)
{
return ex.Message + Environment.NewLine + ex.StackTrace;
}
}
In fact then I write the code like return mdc.Set<SomeRealCrmObject>().ToList() - works fine for me! But then I use the generic types I cannot find the method ToList in object DbSet<SomeRealCrmObject>().
Eranga is correct, but this is an easier usage:
dynamic invokeSet = genericMethod.Invoke(mdc, null);
var list = Enumerable.ToList(invokeSet);
C# 4's dynamic takes care of the cumbersome generic reflection for you.
ToLIst() is not a member of DbSet/ObjectSet but is an extension method.
You can try this instead
var method = typeof(Enumerable).GetMethod("ToList");
var generic = method.MakeGenericMethod(genericType);
generic.Invoke(invokeSet, null);
I had a similar situation where I needed a way to dynamically load values for dropdown lists used for search criteria on a page allowing users to run adhoc queries against a given table. I wanted to do this dynamically so there would be no code change on the front or backend when new fields were added. So using a dynamic type and some basic reflection, it solved my problem.
What I needed to do was invoke a DbSet property on a DbContext based on the generic type for the DbSet. So for instance the type might be called County and the DbSet property is called Counties. The load method below would load objects of type T (the County) and return an array of T objects (list of County objects) by invoking the DbSet property called Counties. EntityList is just a decorator object that takes a list of lookup items and adds additional properties needed for the grid on the front-end.
public T[] Load<T>() where T : class
{
var dbProperty = typeof(Data.BmpDB).GetProperties().FirstOrDefault(
x => x.GetMethod.ReturnType.GenericTypeArguments[0].FullName == typeof(T).FullName);
if (dbProperty == null)
return null;
dynamic data = dbProperty.GetMethod.Invoke(BmpDb, null);
var list = Enumerable.ToList(data) as List<T>;
var entityList = new Data.EntityList<T>(list);
return entityList.Results;
}

Resources