Convert.ChangeType() on EntityObject - mysql

I'm working on MySQL using .Net Connector 6.3.6 and created Entity models on VS 2010. I'm planning to write a generic method that would add an EntityObject to its corresponding table. Here is how it looks:
public void AddToTable(ObjectContext dataContext, string tableName, EntityObject tableObj)
{
try
{
Type type = dataContext.GetType();
string methodName = "AddTo" + tableName;
MethodInfo methodInfo = type.GetMethod(methodName);
PropertyInfo propInfo = dataContext.GetType().GetProperty(tableName);
Object[] parameters = new Object[] { Convert.ChangeType(tableObj, propInfo.PropertyType) };
methodInfo.Invoke(dataContext, parameters);
}
catch (Exception e)
{
edit://gonna handle it appropriately here!
}
}
ObjectContext will be the actual ObjectContext class.
But I'm getting exception saying "object must implement IConvertible" when I use Covert.ChangeType() on an EntityObject.
How to overcome this problem?
Edit: FYI, my main intention is to make write a method which is as generic as possible so that no casting to a particular table type would be required.
Thanks,
Alerter

You're reinventing the wheel.
public void AddToTable<TEntity>(ObjectContext dataContext, TEntity tableObj)
{
dataContext.CreateObjectSet<TEntity>().AddObject(tableObj);
}
And please don't eat exceptions.

Followed the following generalized repository pattern:
[link]http://www.codeproject.com/Articles/37155/Implementing-Repository-Pattern-With-Entity-Framew[link] It is very intuitive and fits my requirement :)

Related

How to read CSVRecord in apache beam?

I have a Java Iterable object, Iterable records. And I want to pass it to the Beam pipeline. I tried
PCollection csvRecordPC = p.apply("Create collection", Create.of(records));
It caused an error
An exception occured while executing the Java class. Can not determine a default Coder for a 'Create' PTransform that has no elements. Either add elements, call Create.empty(Coder), Create.empty(TypeDescriptor), or call 'withCoder(Coder)' or 'withType(TypeDescriptor)' on the PTransform.
Which Coder should I use? Or how can I write my custom coder?
I found a solution using FileIO.
p.apply(FileIO.match().filepattern(options.getInputFile()))
.apply(FileIO.readMatches())
.apply(ParDo.of(new CsvParser()))
The CsvPaser() is
public class CsvParser extends DoFn<ReadableFile, CSVRecord> {
#DoFn.ProcessElement
public void processElement(#Element ReadableFile element, DoFn.OutputReceiver<CSVRecord> receiver) throws IOException {
InputStream is = Channels.newInputStream(element.open());
Reader reader = new InputStreamReader(is);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(reader);
for (CSVRecord record : records) {
receiver.output(record);
}
}
}

Castle windsor: how to pass arguments to deep dependencies?

I have the following dependency chain:
IUserAppService
IUserDomainService
IUserRepository
IUserDataContext - UserDataContextImpl(string conn)
All interfaces above and implementations are registered in a Windsor Castle container. When I use one connection string, everything works fine.
Now we want to support multiple databases, In UserAppServiceImpl.cs, we want to get different IUserRepository (different IUserDatabaseContext) according to userId as below:
// UserAppServiceImpl.cs
public UserInfo GetUserInfo(long userId)
{
var connStr = userId % 2 == 0 ? "conn1" : "conn2";
//var repo = container.Resolve<IUserRepository>(....)
}
How can I pass the argument connStr to UserDataContextImpl?
Since the connection string is runtime data in your case, it should not be injected directly into the constructor of your components, as explained here. Since however the connection string is contextual data, it would be awkward to pass it along all public methods in your object graph.
Instead, you should hide it behind an abstraction that allows you to retrieve the proper value for the current request. For instance:
public interface ISqlConnectionFactory
{
SqlConnection Open();
}
An implementation of the ISqlConnectionFactory itself could depend on a dependency that allows retrieving the current user id:
public interface IUserContext
{
int UserId { get; }
}
Such connection factory might therefore look like this:
public class SqlConnectionFactory : ISqlConnectionFactory
{
private readonly IUserContext userContext;
private readonly string con1;
private readonly string con2;
public SqlConnectionFactory(IUserContext userContext,
string con1, string con2) {
...
}
public SqlConnection Open() {
var connStr = userContext.UserId % 2 == 0 ? "conn1" : "conn2";
var con = new SqlConnection(connStr);
con.Open();
return con;
}
}
This leaves us with an IUserContext implementation. Such implementation will depend on the type of application we are building. For ASP.NET it might look like this:
public class AspNetUserContext : IUserContext
{
public string UserId => int.Parse(HttpContext.Current.Session["UserId"]);
}
You have to start from the beginning of your dependency resolver and resolve all of your derived dependencies to a "named" resolution.
Github code link:https://github.com/castleproject/Windsor/blob/master/docs/inline-dependencies.md
Example:
I have my IDataContext for MSSQL and another for MySQL.
This example is in Unity, but I am sure Windsor can do this.
container.RegisterType(Of IDataContextAsync, dbEntities)("db", New InjectionConstructor())
container.RegisterType(Of IUnitOfWorkAsync, UnitOfWork)("UnitOfWork", New InjectionConstructor(New ResolvedParameter(Of IDataContextAsync)("db")))
'Exceptions example
container.RegisterType(Of IRepositoryAsync(Of Exception), Repository(Of Exception))("iExceptionRepository",
New InjectionConstructor(New ResolvedParameter(Of IDataContextAsync)("db"),
New ResolvedParameter(Of IUnitOfWorkAsync)("UnitOfWork")))
sql container
container.RegisterType(Of IDataContextAsync, DataMart)(New HierarchicalLifetimeManager)
container.RegisterType(Of IUnitOfWorkAsync, UnitOfWork)(New HierarchicalLifetimeManager)
'brands
container.RegisterType(Of IRepositoryAsync(Of Brand), Repository(Of Brand))
controller code:
No changes required at the controller level.
results:
I can now have my MSSQL context do its work and MySQL do its work without any developer having to understand my container configuration. The developer simply consumes the correct service and everything is implemented.

How to check that a List contains only certain unrelated class types using junit's assertThat?

Would appreciate some help with hamcrest and junit matchers... :)
I'm using junit-4.11.jar and hamcrest-core-1.3.jar on Eclipse Kepler with sun's jdk 1.6.0_30.
I have a class that holds an instance of any unknown type like so:
class UnknownClassHolder {
private Class<?> clazz;
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
}
clazz can be any class.
I want to my junit test to be something like this:
class UnknownClassHolderTest {
#Test
public void test() {
ArrayList<UnknownClassHolder> list = new ArrayList<UnknownClassHolder>();
UnknownClassHolder x = new UnknownClassHolder();
//lets add an Integer
x.setClazz(Integer.class);
list.add(x);
UnknownClassHolder y = new UnknownClassHolder();
//lets add a vector
y.setClazz(Vector.class);
list.add(y);
//now check that we added an Integer or a Vector using assertThat
for (UnknownClassHolder u: list) {
assertThat(u.getClazz(), anyOf(isA(Integer.class), isA(Vector.class))));
}
}
}
Junit's assertThat doesn't like this. It doesn't compile due to Integer & Vector Types not being related to each other via sub/super classes:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Class<capture#1-of ?>, AnyOf<Vector>)
Is there a more succinct way to do this other than:
assertThat(u.getClazz().getName(), either(is(Integer.class.getName())).or(is(Vector.class.getName())));
Is there a particular reason for using Matcher<? super T> rather than Matcher<?> in the org.hamcrest.MatcherAssert.assertThat(...) method?
Thanks.
First, you should be using is instead of isA since you're asserting that one class equals another. isA is for testing that an object is an instance of some class. Second, the only thing I can make work is forcing the compiler to see these as raw Objects.
assertThat(u.getClazz(), anyOf(is((Object) Integer.class), is((Object) Vector.class)));

Dependency Injection and JavaScriptConverter.Deserialize

My application needs to combine extensive use of dependency injection with the use of JSON as a public API. This apparently leads to the need for a custom JavaScriptConverter.
Right now, my JavaScriptConverter's Deserialize method looks like this:
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
var result = IocHelper.GetForType(type);
return result;
}
This hands back the appropriate class. Unfortunately, it fails to populate the class members with the applicable values. What I'm missing is a way to tell the Serializer, "Here's the type you asked for. Now fill it in."
The solution I used was to switch from JavaScriptSerializer to Newtonsoft's JSON converter
I was able to get a working round trip by writing a single CustomCreationConverter:
public class JsonDomainConverter : CustomCreationConverter<object>
{
public JsonDomainConverter()
{
}
public override bool CanConvert(Type objectType)
{
return objectType.IsInterface;
}
public override object Create(Type objectType)
{
return IocHelper.GetForType(objectType);
}
}
No doubt this same approach is possible with JavaScriptSerializer, I just couldn't figure out how to make it work. With the Newtonsoft stuff, it took a couple hours at the most, and just a couple lines of code.

Localization using a DI framework - good idea?

I am working on a web application which I need to localize and internationalize. It occurred to me that I could do this using a dependency injection framework. Let's say I declare an interface ILocalResources (using C# for this example but that's not really important):
interface ILocalResources {
public string OkString { get; }
public string CancelString { get; }
public string WrongPasswordString { get; }
...
}
and create implementations of this interface, one for each language I need to support. I would then setup my DI framework to instantiate the proper implementation, either statically or dynamically (for example based on the requesting browsers preferred language).
Is there some reason I shouldn't be using a DI framework for this sort of thing? The only objection I could find myself is that it might be a bit overkill, but if I'm using a DI framework in my web app anyway, I might as well use it for internationalization as well?
A DI framework is built to do dependency injection and localization could just be one of your services, so in that case there's no reason not to use a DI framework IMO. Perhaps we should start discussing the provided ILocalResources interface. While I'm a favor of having compile time support, I'm not sure the supplied interface will help you, because that interface will be probably the type in your system that will change the most. And with that interface the type/types that implement it. Perhaps you should go with a different design.
When we look at most localization frameworks/providers/factories (or whatever), they're all string based. Because of this, think about the following design:
public interface ILocalResources
{
string GetStringResource(string key);
string GetStringResource(string key, CultureInfo culture);
}
This would allow you to add keys and cultures to the underlying message data store, without changing the interface. Downside is of course that you should never change a key, because that will probably be a hell.
Another approach could be an abstract base type:
public abstract class LocalResources
{
public string OkMessage { get { return this.GetString("OK"); } }
public string CancelMessage { get { return this.GetString("Cancel"); } }
...
protected abstract string GetStringResource(string key,
CultureInfo culture);
private string GetString(string key)
{
Culture culture = CultureInfo.CurrentCulture;
string resource = GetStringResource(key, culture);
// When the resource is not found, fall back to the neutral culture.
while (resource == null && culture != CultureInfo.InvariantCulture)
{
culture = culture.Parent;
resource = this.GetStringResource(key, culture);
}
if (resource == null) throw new KeyNotFoundException(key);
return resource;
}
}
And implementation of this type could look like this:
public sealed class SqlLocalResources : LocalResources
{
protected override string GetStringResource(string key,
CultureInfo culture)
{
using (var db = new LocalResourcesContext())
{
return (
from resource in db.StringResources
where resource.Culture == culture.Name
where resource.Key == key
select resource.Value).FirstOrDefault();
}
}
}
This approach takes best of both worlds, because the keys won't be scattered through the application and adding new properties just has to be done in one single place. Using your favorite DI library, you can register an implementation like this:
container.RegisterSingleton<LocalResources>(new SqlLocalResources());
And since the LocalResources type has exactly one abstract method that does all the work, it is easy to create a decorator that adds caching to prevent requesting the same data from the database:
public sealed class CachedLocalResources : LocalResources
{
private readonly Dictionary<CultureInfo, Dictionary<string, string>> cache =
new Dictionary<CultureInfo, Dictionary<string, string>>();
private readonly LocalResources decoratee;
public CachedLocalResources(LocalResources decoratee) { this.decoratee = decoratee; }
protected override string GetStringResource(string key, CultureInfo culture) {
lock (this.cache) {
string res;
var cultureCache = this.GetCultureCache(culture);
if (!cultureCache.TryGetValue(key, out res)) {
cultureCache[key] = res= this.decoratee.GetStringResource(key, culture);
}
return res;
}
}
private Dictionary<string, string> GetCultureCache(CultureInfo culture) {
Dictionary<string, string> cultureCache;
if (!this.cache.TryGetValue(culture, out cultureCache)) {
this.cache[culture] = cultureCache = new Dictionary<string, string>();
}
return cultureCache;
}
}
You can apply the decorator as follows:
container.RegisterSingleton<LocalResources>(
new CachedLocalResources(new SqlLocalResources()));
Do note that this decorator caches the string resources indefinitely, which might cause memory leaks, so you wish to wrap the strings in WeakReference instances or have some sort of expiration timeout on it. But the idea is that you can apply caching without having to change any existing implementation.
I hope this helps.
If you cannot use an existing resource framework (like that built into ASP.Net) and would have to build your own, I will assume that you at some point will need to expose services that provide localized resources.
DI frameworks are used to handle service instantiation. Your localization framework will expose services providing localization. Why shouldn't that service be served up by the framework?
Not using DI for its purpose here is like saying, "I'm building a CRM app but cannot use DI because DI is not built for customer relations management".
So yes, if you're already using DI in the rest of your application, IMO it would be wrong to not use it for the services handling localization.
The only disadvantage I can see is that for any update to "resources", you would have to recompile the assembly containing resources. And depending on your project, this disadvantage may be a good advise to only use a DI framework for resolving a ResourceService of some kind, rather than the values itself.