Using app.config from F# Script - configuration

I have seen several related questions here on stack overflow, however none appear to have answers. I will pose the question and then include links to related SO questions I have found.
I have a Core domain library written in C# that leverages Entity Framework. As such, EF requires the dbcontext to pass a connection string to the base (dbcontext). In my case the connection string lives in the app.config (or web.config) depends on top level project of course and the name is "AnnotatorModel".
I need to instantiate the DBContext from within my F# script to test a few queries and analytics.
I have added this to the app.config in my F# project and tried a few of the answers on SO with no success. Does anybody know a good easy straight forward way to accomplish this?
Here is the code, realize it breaks on attempting to instantiate the dbcontext, AnnotatorModel.
let PredictBestEntities (number:int) (tokens:string seq) =
let db = new AnnotatorModel()
tokens
|> Seq.map ...etc etc
Thanks,
~David
Related questions:
Get and use connection string from App.config F# AppSettings provider
App.config and F# Interactive not working
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5b4dba22-28ec-4bbd-bc53-c5102d0b938f/using-fsi-and-an-appconfig?forum=fsharpgeneral

This is not what you're asking, but I'll add this answer anyway:
Add a constructor overload to AnnotatorModel that enables you to pass a connection string. This will enable you to write:
let db = new AnnotatorModel("some connection string")
Relying exclusively on a connection string in app.config tightly couples a library to that single source of configuration. This isn't good library design. Not only are you having trouble with using it from FSI, but it also makes it difficult to change 'configuration values' at run-time, load them from a database instead of a file, etc.
Libraries shouldn't be coupled to app.config. Only applications should use app.config.

Related

.Net Core 1.0.0, multiple projects, and IConfiguration

TL;DR version:
What's the best way to use the .Net Core IConfiguration framework so values in a single appsettings.json file can be used in multiple projects within the solution? Additionally, I need to be able to access the values without using constructor injection (explanation below).
Long version:
To simply things, lets say we have a solution with 3 projects:
Data: responsible for setting up the ApplicationDbContext, generates migrations
Services: class library with some business logic
WebApi: REST API with a Startup.cs
With this architecture, we have to use a work-around for the "add-migration" issue that remains in Core 1.0.0. Part of this work-around means that we have a ApplicationDbContextFactory class that must have a parameterless constructor (no DI) in order for the migration CLI to use it.
Problem: Right now we have connection strings living in two places;
ApplicationDbContextFactory for the migration work-around
in the WebApi's "appsettings.json" file
Prior to .Net Core, we could use ConfigurationManager to pull connection strings for all solution projects from one web.config file based on the startup project. How do we use this new IConfiguration framework to store connection strings in one place that need to be used all over the solution? Additionally, I can't inject into the ApplicationDbContextFactory class' constructor... so that further complicates things (more-so since they changed how the [FromServices] attribute works).
Side note: I would like to avoid implementing an entire DI middleware just to get attribute injection, since Core includes it's own DI framework. If I can avoid that and still access appsettings.json values, that would be ideal.
If I need to add code let me know, this post was already long enough, so I'll hold off on examples until requested. ;)

J2EE Application/Bean configuration Best Practices?

What is the best way to manage property sets to apply to EJB, and easily be able to vary them between machines/environments (e.g. DEV, TEST, PROD)? For example, is there a way to configure your EJB properties on the App Server (which guarantees you can vary them by machine/environment).
Specifically:
1) I have a Singleton EJB which needs certain properties set (environment) specific. Is there annotation(s) which are used to tell the EJB Container where to look up those properties and will automatically apply them to the bean?
2) What is the best way to manage different property sets, i.e. dev, test, prod, so that the J2EE app is portable between servers, and you can seamlessly manage the properties specific to each server?
If there are any good documentation links - let me know. I've Googled around and seen nothing directly to the points above.
I use a singleton helper class "PropertiesHelper" which has a Properties member and reads from an xml configuration file upon the first property access attempt. The helper encapsulates the entire set of configuration settings and prevents them from being read from disk more than once.
The file location is specified in my java opts and read in by PropertiesHelper using System.getProperty()
As for system properties annotations, I don't believe Java supports this natively, but if you're so inclined you may want to look at some AOP/Dependency Injection frameworks like Google Guice which are better at this "cross-cutting".

Can a class derived from a Linq to SQL entity still be saved?

Say "Foo" is a Linq to SQL entity created in the Linq to SQL designer.
I then have "Bar" which derives from "Foo".
Should I be able to save "Bar" using Linq to SQL (assuming I don't care abut saving any of the extra properties on Bar).
using (myDataContext ctx = new myDataContext())
{
ctx.Foos.InsertOnSubmit(instanceOfBar);
ctx.SubmitChanges();
}
Is this supposed to be supported?
Thanks much,
Jon
I've tried to do this once upon a time and couldn't get it to work. Can't remember what the error that was thrown, but to get around it, i basically had to go through all the properties using reflection and copy the properties marked with ColumnAttribute into a new base class instance and then insert that instead. It's not pretty, but it works. I haven't reinvestigated the issue since i implemented it, so if there's a better way, i'd love to know.
I'm not sure, but why are you doing it? The entities are all implemented as partial classes, so why don't you just implement what you want in a partial class?
I'm a stickler for the repository pattern which means that I define my models in an isolated dll (project.Models.dll) and then create a LinqToSql implementation of my IRepository.
The linq classes only exist within the LinqToSql implementation dll and I create extension methods to convert from my models to the linq entities and vice versa.
I've found that this enables you to test more parts of the system without being overly reliant on the database. It is a bit of a pain though, but you only do it once per project.
Which then means that you have full control over the serialization of your objects, and can do pretty much whatever you like with them

How can I connect to a MySQL database using Scala?

I'm working on a little project where I'd like to parse some data, and then put it into a database. I'm not working with Lift, and I haven't been able to find a standard way to do this.
I'm fine writing the queries myself, but I'm not sure what to use to actually connect to the DB.
You can use JDBC - the standard means of getting Java to talk to databases. You'll need the appropriate MySQL JDBC driver. Apache DbUtils provides some utility classes surrounding JDBC and would be useful.
If you want a higher level API which takes some of the boilerplate out, then check out Spring's JDBC integration.
If you want an ORM (object-relational mapping), then Hibernate is a good choice.
I've used all three in Scala with success.
Off course you can use all Java version compatible with JDBC (Hibernate, Spring, etc), but for better use of Scala language, I recommend using a Scala specific framework, which have a better DSL.
ScalaQuery is an API / DSL (domain specific language) built on top of JDBC for accessing relational databases in Scala. It was designed with the following goals in mind:
Squeryl is a Scala ORM and DSL for talking with Databases with minimum verbosity and maximum type safety
SORM is a Scala ORM-framework designed to eliminate boilerplate code and solve the problems of scalability with a high level abstraction and a functional programming style
Slick - Typesafe backed project with Functional Relational Mapping
Check out more about these frameworks at https://stackoverflow.com/questions/1362748/looking-for-a-comparison-of-scala-persistence-frameworks
I've actually written a SQL command shell, in Scala, that talks to any arbitrary database for which a JDBC driver exists. As Brian Agnew notes, it works perfectly. In addition, there are tools like Querulous, SQueryL and OR/Broker that provide Scala-friendly database layers. They sit on top of JDBC, but they provide some additional semantics (via DSLs, in some cases) to make things easier for you.
Try O/R Broker:
case class MyObj(name: String, year: Int)
val ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource
// set properties on ds
import org.orbroker._
val builder = new BrokerBuilder(ds)
val broker = builder.build
val myObj: MyObj = // Parse stuff to create MyObj instance
broker.transaction() { session =>
session.execute("INSERT INTO MYTABLE VALUES(:obj.name, :obj.year)", "obj"->myObj)s
}
val myObjs: Seq[MyObj] = // Parse stuff to create sequence of MyObj instances
broker.transaction() { session =>
session.executeBatch("INSERT INTO MYTABLE VALUES(:obj.name, :obj.year)", "obj"->myObjs)
}
For completeness, also check out RichSQL. It's demo code showing how to wrap JDBC to make more Scala-like operations, but it's actually quite usable. It has the advantage of being simple and small, so you can easily study the source to see what's going on. Don't forget to close() your PreparedStatements.
I just discovered ScalikeJDBC which offers a Scala like API wrapper for JDBC.
(I found ScalikeJDBC when researching how to use ScalaAnorm without Play Framework. Now it looks like I won't be needing Anorm for my project.)
Here is a simple example, though it offers many interesting features not shown here:
import scalikejdbc._
Class.forName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource")
ConnectionPool.singleton("jdbc:mysql://localhost:3306/myschema", "user", "password")
DB.localTx { implicit conn =>
val data = sql"select mystringcol, myintcolumn from mytable".map {
rs => (rs.string("mystringcol"), rs.int("myintcolumn"))
}.list().apply()
println(data)
}
Some documentation links:
Documentation on running queries
Connection pool and loan pattern

Singleton for Application Configuration

In all my projects till now, I use to use singleton pattern to access Application configuration throughout the application. Lately I see lot of articles taking about not to use singleton pattern , because this pattern does not promote of testability also it hides the Component dependency.
My question is what is the best way to store Application configuration, which is easily accessible throughout the application without passing the configuration object all over the application ?.
Thanks in Advance
Madhu
I think an application configuration is an excellent use of the Singleton pattern. I tend to use it myself to prevent having to reread the configuration each time I want to access it and because I like to have the configuration be strongly typed (i.e, not have to convert non-string values each time). I usually build in some backdoor methods to my Singleton to support testability -- i.e., the ability to inject an XML configuration so I can set it in my test and the ability to destroy the Singleton so that it gets recreated when needed. Typically these are private methods that I access via reflection so that they are hidden from the public interface.
EDIT We live and learn. While I think application configuration is one of the few places to use a Singleton, I don't do this any more. Typically, now, I will create an interface and a standard class implementation using static, Lazy<T> backing fields for the configuration properties. This allows me to have the "initialize once" behavior for each property with a better design for testability.
Use dependency injection to inject the single configuration object into any classes that need it. This way you can use a mock configuration for testing or whatever you want... you're not explicitly going out and getting something that needs to be initialized with configuration files. With dependency injection, you are not passing the object around either.
For that specific situation I would create one configuration object and pass it around to those who need it.
Since it is the configuration it should be used only in certain parts of the app and not necessarily should be Omnipresent.
However if you haven't had problems using them, and don't want to test it that hard, you should keep going as you did until today.
Read the discussion about why are they considered harmful. I think most of the problems come when a lot of resources are being held by the singleton.
For the app configuration I think it would be safe to keep it like it is.
The singleton pattern seems to be the way to go. Here's a Setting class that I wrote that works well for me.
If any component relies on configuration that can be changed at runtime (for example theme support for widgets), you need to provide some callback or signaling mechanism to notify about the changed config. That's why it is not enough to pass only the needed parameters to the component at creation time (like color).
You also need to provide access to the config from inside of the component (pass complete config to component), or make a component factory that stores references to the config and all its created components so it can eventually apply the changes.
The former has the big downside that it clutters the constructors or blows up the interface, though it is maybe fastest for prototyping. If you take the "Law of Demeter" into account this is a big no because it violates encapsulation.
The latter has the advantage that components keep their specific interface where components only take what they need, and as a bonus gives you a central place for refactoring (the factory). In the long run code maintenance will likely benefit from the factory pattern.
Also, even if the factory was a singleton, it would likely be used in far fewer places than a configuration singleton would have been.
Here is an example done using Castale.Core >> DictionaryAdapter and StructureMap