How can I get a datastore with NeDB using typescrip classes syntax?
namespace NamespaceName {
"use strict";
export class Persistence {
private attrs: Type;
public static $inject: Array<string> = [];
constructor(
) {
this.attr1 = "";
}
// Public Methods
public method1() {
...
}
// Private Methods
private method1() {
...
}
}
}
Where should I create and instantiate my datastore?
I was spinning my wheels on this myself for a while and I was able to do get the database to generate with the following:
import NeDB = require('nedb');
//test class
class duck{
body: string;
constructor(body: string)
{
this.body = body;
}
}
//method from where I init my database.
testdb() {
var db:any = new NeDB("./file.db");
var obj:duck= new duck("A normal duck body");
db.loadDatabase();
db.insert(obj);
}
Notes:
I do have the #typings installed for NeDB see NeDB
Typings
If you look at the above link they provide the tests they used to verify the typings.
Related
I have some problem with cascade all (orphan) and delete the old objcet from the database.
Example:
I have an class A which contains an object of class B. Now, when I create an object of class A and save it, everything works fine. When I call the method SetValueOfB(int i) and save the object A again, the old object B is still in the database.
Must the association between the classes always be directional (for every HasMany/Reference/HasOne...)? (But object b has nothing to know about object a)
Is there a way to solve the problem with unidirectional association?
Do I need a one-to-one mapping? Because the object B can only belong to object A (A is a parameter and B is a value).
Here is a failing test:
using System.Collections.Generic;
using System.Data;
using System.IO;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Mapping;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
namespace ReferenceCascade.Test
{
public class CascadeTest
{
private const string DbFile = "firstProject.db";
[Test]
public void checkCascadeAll()
{
var sessionFactory = CreateSessionFactory();
A testee = new A(new B(1));
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(testee);
transaction.Commit();
}
}
testee.SetValueOfB(2);
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(testee);
transaction.Commit();
}
}
using (var session = sessionFactory.OpenSession())
{
using (session.BeginTransaction())
{
IList<B> stores = session.CreateCriteria(typeof(B))
.List<B>();
Assert.That(stores.Count, Is.EqualTo(1));
}
}
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFile(DbFile).IsolationLevel(IsolationLevel.ReadCommitted))
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<CascadeTest>())
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
private static void BuildSchema(Configuration config)
{
// delete the existing db on each run
if (File.Exists(DbFile))
{
File.Delete(DbFile);
}
// this NHibernate tool takes a configuration (with mapping info in)
// and exports a database schema from it
new SchemaExport(config)
.Create(false, true);
}
}
public abstract class Entity
{
public const long InitialId = 0;
private readonly long _id;
protected Entity()
{
_id = InitialId;
}
public virtual long Id
{
get { return _id; }
}
}
public class A : Entity
{
private B _b;
public A()
{
}
public A(B b)
{
_b = b;
}
public virtual void SetValueOfB(int i)
{
_b = new B(i);
}
public virtual B B
{
get { return _b; }
}
}
public class B : Entity
{
private readonly int _i;
public B()
{
}
public B(int i)
{
_i = i;
}
public virtual int I
{
get { return _i; }
}
}
public class EntityMap<T> : ClassMap<T> where T : Entity
{
public EntityMap()
{
Id(x => x.Id).GeneratedBy.HiLo("33878").Access.CamelCaseField(Prefix.Underscore);
}
}
public class AMap : EntityMap<A>
{
public AMap()
{
Table("A");
References(x => x.B).Not.LazyLoad().Cascade.All().Access.CamelCaseField(Prefix.Underscore);
}
}
public class BMap : EntityMap<B>
{
public BMap()
{
Table("B");
Map(x => x.I).Not.LazyLoad().Access.CamelCaseField(Prefix.Underscore);
}
}
}
Or here is the project: vs project
We haven't found a way to solve the problem. In NHibernate version 4.1, the problem will be fixed and it is possible to use cascade=all-delete-orphan with many-to-one. See here: https://nhibernate.jira.com/browse/NH-1262
Let's get straight.
I have interface and class like this:
public interface IDataBase
{
DataTable GetSomeTableData();
}
My class:
public class DataBase : IDataBase
{
private readonly string _connectionString;
public DataBase(string connectionString)
{
this._connectionString = connectionString;
}
public DataTable GetSomeTableData()
{
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
// some select
}
}
}
I'm using Autofac to inject that class:
var builder = new ContainerBuilder();
builder.RegisterType<DataBase>().As<IDataBase>).WithParameter("connectionString", "my connection string");
var container = builder.Build();
var database = container.Resolve<IDataBase>();
var tableData1 = database.GetSomeTableData();
// change connection string ?????????????????
var tableData2 = database.GetSomeTableData();
I need to get table data from one DB and another DB. How can I change connection string after have registered class? You may give another exapmle..
There are many ways to do it. One would be to create and inject a service instead of just plain connection string.
public interface IConnectionStringProvider
{
public string ConnectionString { get; set }
}
public class ConnectionStringProvider
{
public string ConnectionString { get; set }
}
var builder = new ContainerBuilder();
builder.RegisterType<DataBase>()
.As<IDataBase>);
builder.RegisterType<ConnectionStringProvider>)
.As<IConnectionStringProvider>
.SingleInstance();
var container = builder.Build();
var database = container.Resolve<IDataBase>();
var connStringProvider = container.Resolve<IConnectionStringProvider>();
var tableData1 = database.GetSomeTableData();
connStringProvider.ConnectionString = "...";
var tableData2 = database.GetSomeTableData();
The DataBase would then use that service:
public class DataBase : IDataBase
{
private readonly IConnectionStringProvider _connectionStringProvider;
public DataBase(IConnectionStringProvider connectionStringProvider)
{
this._connectionStringProvider = connectionStringProvider;
}
public DataTable GetSomeTableData()
{
using (SqlConnection cn = new SqlConnection(_connectionStringProvider.ConnectionString))
{
cn.Open();
// some select
}
}
}
I have generic Result<T> generic class which I use often in methods to return result like this
public Result<User> ValidateUser(string email, string password)
There is ILoggingService interface in Result class for logging service injection but I do not find a way to inject actual implementation.
I tried to execute the code below but TestLoggingService intance is not injected into LoggingService property. It always return null. Any ideas how to solve it?
using (var kernel = new StandardKernel())
{
kernel.Bind<ILoggingService>().To<TestLoggingService>();
var resultClass = new ResultClass();
var exception = new Exception("Test exception");
var testResult = new Result<ResultClass>(exception, "Testing exception", true);
}
public class Result<T>
{
[Inject]
public ILoggingService LoggingService{ private get; set; } //Always get null
protected T result = default(T);
//Code skipped
private void WriteToLog(string messageToLog, object resultToLog, Exception exceptionToLog)
{
LoggingService.Log(....); //Exception here, reference is null
}
You are creating the instance manually using new. Ninject will only inject objects created by kernel.Get(). Furthermore it seems you try to inject something into a DTO which is not recommended. Better do the the logging in the class that created the result:
public class MyService
{
public MyService(ILoggingService loggingService) { ... }
public Result<T> CalculateResult<T>()
{
Result<T> result = ...
_loggingService.Log( ... );
return result;
}
}
In the below if I am trying to inject a constructor parameter in one of the dependencies of the model at runtime, it doesn't take with Parameter Override option. Is there any thing else that we need to do?
public class Test: ITest
{
ITestChild _testChild ;
public Test(ITestChild testChild)
{
_testChild = testChild;
}
}
public class TestChild: ITestChild
{
ITestChildChild _testChildChild ;
public Test(ITestChildChild testChildChild)
{
_testChildChild = testChildChild;
}
}
public class TestChildChild: ITestChildChild
{
public TestChildChild()
{
}
}
Mapping Unity:
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITest, Test>(new ContainerControlledLifetimeManager());
unityContainer.RegisterType<ITestChild TestChild>();
unityContainer.RegisterType<ITestChildChild, TestChildChild>();
Main()
{
var testChildChild = new TestChildChild();
var testObject = UnityContainer.Resolve<ITest>(new ParameterOverride("testChildChild", testChildChild));
}
Main()
{
var testChildChild = new TestChildChild();
var testObject = UnityContainer.Resolve<ITest>(new DependencyOverride("testChildChild", testChildChild));
}
I'm trying to find a clean way to accomplish MvvmLight's IDataService pattern with async/await.
Originally I was using the callback Action method to work similar to the template's but that doesn't update the UI either.
public interface IDataService
{
void GetData(Action<DataItem, Exception> callback);
void GetLocationAsync(Action<Geoposition, Exception> callback);
}
public class DataService : IDataService
{
public void GetData(Action<DataItem, Exception> callback)
{
// Use this to connect to the actual data service
var item = new DataItem("Location App");
callback(item, null);
}
public async void GetLocationAsync(Action<Geoposition, Exception> callback)
{
Windows.Devices.Geolocation.Geolocator locator = new Windows.Devices.Geolocation.Geolocator();
var location = await locator.GetGeopositionAsync();
callback(location, null);
}
}
public class MainViewModel : ViewModelBase
{
private readonly IDataService _dataService;
private string _locationString = string.Empty;
public string LocationString
{
get
{
return _locationString;
}
set
{
if (_locationString == value)
{
return;
}
_locationString = value;
RaisePropertyChanged(LocationString);
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
_dataService.GetLocation(
(location, error) =>
{
LocationString = string.Format("({0}, {1})",
location.Coordinate.Latitude,
location.Coordinate.Longitude);
});
}
}
I'm trying to databind against gps coordinates but since the async fires and doesn't run on main thread it doesn't update the UI.
Might be unrelated, but AFAICT you're missing some quotes
RaisePropertyChanged(LocationString);
You pass the name of the property that changed, not its value.