Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            //Debugger.Launch();

            IKernel ninjectKernel = new StandardKernel();
            IRepository iRepository = ninjectKernel.TryGet<IRepository>();

            // this check wouldn't happen in a real consuming application because it would never have reference to the bound runtime type implementation class (or assembly)
            // for the interface; however we cheat in order to peek inside to see what implementation classes Ninject is actually loading at runtime
            if(iRepository.ORM != typeof(DapperAdapter))
                throw new TypeLoadException("Wrong ORM Adapter loaded from Ninject. Verify Ninject.Extensions.Api binding configuration");

            IEnumerable<dynamic> customers    = iRepository.GetAllCustomers();
            IEnumerable<dynamic> addresses    = iRepository.GetAllAddresses();
            IEnumerable<dynamic> phoneNumbers = iRepository.GetAllPhoneNumbers();

            if (customers.ToList().Count == 0)
                throw new ApplicationException("No customers returned");

            if (addresses.ToList().Count == 0)
                throw new ApplicationException("No addresses returned");

            if (phoneNumbers.ToList().Count == 0)
                throw new ApplicationException("No phone numbers returned");

            Console.WriteLine("Everything works great");
            Console.Read();
        }
Ejemplo n.º 2
0
        public static void Configure(HttpConfiguration config)
        {
            config.Filters.Add(new ValidationActionFilter());

            var kernel = new StandardKernel();
            kernel.Bind<ISlechRepository>().ToConstant(new InitialData());
            config.ServiceResolver.SetResolver(
                t => kernel.TryGet(t),
                t => kernel.GetAll(t));
        }
Ejemplo n.º 3
0
        public static void RegisterDependenciesViaNinject(HttpConfiguration httpConfiguration)
        {
            var kernel = new StandardKernel();
            kernel.Bind<IWordRepository>().To<WordRepository>();
            kernel.Bind<IMeaningRepository>().To<MeaningRepository>();

            httpConfiguration.ServiceResolver.SetResolver(
                t => kernel.TryGet(t),
                t => kernel.GetAll(t));
        }
Ejemplo n.º 4
0
		/// <summary>
		/// Set new data source and apply binding for the data source interface.
		/// </summary>
		public void SetDataSource(string sourceType, StandardKernel ninjectKernel)
		{
			var storageType = TryToLoadDll(sourceType);
			var type = storageType;

			var currentObj = ninjectKernel.TryGet<IDataStorage>();
			if (currentObj == null || currentObj.GetType() != type)
			{
				ninjectKernel.Bind<IDataStorage>().To(type);
			}
		}
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);

            DependencyResolver.SetResolver(t => kernel.TryGet(t), t => kernel.GetAll(t));
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

            return kernel;
        }
Ejemplo n.º 6
0
        public static void Configure(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute("def", "bugs/{controller}", new {controller = "Index"});

            config.Formatters.Add(new RazorHtmlMediaTypeFormatter());
            config.MessageHandlers.Add(new EtagMessageHandler());

            var kernel = new StandardKernel();
            kernel.Bind<IBugRepository>().To<StaticBugRepository>();

            config.ServiceResolver.SetResolver(t => kernel.TryGet(t), t => kernel.GetAll(t));

            AutoMapperConfig.Configure();
        }
Ejemplo n.º 7
0
        private static void Main()
        {
            var container = new StandardKernel();

            var token = ConfigurationManager.AppSettings["TOKEN"];
            var account = ConfigurationManager.AppSettings["ACCOUNT_EUR_USD"].SafeParseInt().GetValueOrDefault();

            var adapter = new OandaAdapter("https://api-fxpractice.oanda.com/v1/",
              "https://api-fxpractice.oanda.com/v1/",
              "https://stream-fxpractice.oanda.com/v1/",
              "https://stream-fxpractice.oanda.com/v1/",
              "https://api-fxpractice.oanda.com/labs/v1/",
              token);

            container.Bind<Cobra>()
                .ToConstant(new Cobra(new Adx(14),
                    new Ema(12),
                    new Ema(12),
                    new Sma(72),
                    new Sma(72),
                    new SimpleDateProvider(),
                    "EUR_USD",
                    15,
                    adapter,
                    adapter,
                    account))
                .InSingletonScope();

            container.Bind<IRateProvider>()
                .ToConstant(adapter)
                .InSingletonScope();

            var test = container.TryGet<Cobra>();

            if (test == null)
            {
                throw new Exception("Unable to build Forex System");
            }

            var config = new JobHostConfiguration
            {
                JobActivator = new MyActivator(container)
            };
            config.Tracing.ConsoleLevel = TraceLevel.Info;
            config.UseTimers();

            var host = new JobHost(config);
            host.RunAndBlock();
        }
Ejemplo n.º 8
0
        private static HttpSelfHostServer SetupWebApiServer(string url)
        {
            var ninjectKernel = new StandardKernel();
            ninjectKernel.Bind<IContactRepository>().To<InMemoryContactRepository>();

            var configuration = new HttpSelfHostConfiguration(url);
            configuration.ServiceResolver.SetResolver(
                t => ninjectKernel.TryGet(t),
                t => ninjectKernel.GetAll(t));

            configuration.Routes.MapHttpRoute(
                "Default",
                "{controller}/{id}/{ext}",
                new {id = RouteParameter.Optional, ext = RouteParameter.Optional});

            var host = new HttpSelfHostServer(configuration);

            return host;
        }
Ejemplo n.º 9
0
        public Launcher(params string[] args)
        {
            mConfig = new LauncherConfig(args);

            if (!GlobalConditions.Init()) {
                Logger.Fatal("Unable to initialise Kinect. Exiting.");
                return;
            }

            var settings = new NinjectSettings { LoadExtensions = false };
            IKernel k = new StandardKernel(settings, new XmlExtensionModule());
            if (mConfig.BindingsFile == null) {
                Logger.Warn("Unable to launch. No bindings file specified.");
                return;
            }
            try {
                k.Load(mConfig.BindingsFile);
            } catch (Exception e) {
                Logger.Warn("Unable to launch. Problem loading bindings. " + e.Message);
            }
            if (k.TryGet<IMediaPlayer>() == null)
                k.Bind<IMediaPlayer>().To<DummyPlayer>().InSingletonScope();

            try {
                mCore = k.Get<Core>();
            } catch (Exception e) {
                Logger.Warn("Unable to launch. Problem instantiating coordinator. " + (e.InnerException != null ? e.InnerException.Message :e.Message));
                Logger.Debug("", e);
            }
        }
Ejemplo n.º 10
0
        private static void Main()
        {
            var container = new StandardKernel();

            var token = ConfigurationManager.AppSettings["TOKEN"];
            var account = ConfigurationManager.AppSettings["ACCOUNT_USD_CHF"].SafeParseInt().GetValueOrDefault();

            var adapter = new OandaAdapter("https://api-fxpractice.oanda.com/v1/",
              "https://api-fxpractice.oanda.com/v1/",
              "https://stream-fxpractice.oanda.com/v1/",
              "https://stream-fxpractice.oanda.com/v1/",
              "https://api-fxpractice.oanda.com/labs/v1/",
              token);

            var instrument = "EUR_GBP";
            var periodInMinutes = 15;
            var minNumberOfCandles = 72;
            var lastCandles = adapter.GetLastCandles(instrument,
                   periodInMinutes,
                   minNumberOfCandles).ToList();
            if (lastCandles.Count < minNumberOfCandles)
            {
                Trace.TraceWarning("Not enough candles to check trading, positions can still be closed");
                lastCandles = new List<Candle>();
            }

            container.Bind<IRateProvider>()
              .ToConstant(adapter)
              .InSingletonScope();

            container.Bind<Cobra>()
                .ToConstant(new Cobra(new Adx(14),
                    new Ema(12),
                    new Ema(12),
                    new Sma(72),
                    new Sma(72),
                    new SimpleDateProvider(),
                    instrument,
                    periodInMinutes,
                    adapter,
                    adapter,
                    account,
                    false,
                    lastCandles))
                .InSingletonScope();

            var test = container.TryGet<Cobra>();
            if (test == null)
            {
                throw new Exception("Unable to build Forex System");
            }

            var config = new JobHostConfiguration
            {
                JobActivator = new MyActivator(container)
            };
            config.Tracing.ConsoleLevel = TraceLevel.Verbose;
            config.UseTimers();

            var host = new JobHost(config);
            host.RunAndBlock();
        }
Ejemplo n.º 11
0
        public async void Test()
        {
            _databaseConnection.Connect();

            /////////////////////////////////////
            // OPERATIONAL, CONTEXUAL SCOPE... //
            /////////////////////////////////////

            // create a Writer to write to the database
            IWriter writer = new Writer(_databaseConnection);
            // create a Reader to read from the database
            IReader reader = new Reader(_databaseConnection);
            // create an Updater to update the database
            IUpdater updater = new Updater(_databaseConnection);

            Entry exampleMongoDBEntry = new Entry();

            exampleMongoDBEntry.Message = "Hello";

            // write the object to the "MyFirstCollection" Collection that exists within the
            // previously referenced "MyFirstDatabase" that was used to create the "writer" object
            writer.Write <Entry>("MyFirstCollection", exampleMongoDBEntry);

            IEnumerable <Entry> readEntrys = reader.Read <Entry>("MyFirstCollection", // within this collection...
                                                                 "Message",           // for the object field "Description"
                                                                 "Hello");            // return matches for 'Hello'

            Assert.AreEqual(1, readEntrys.Count());

            ////////////////////////////////////
            // AND ASYNCHRONOUS OPERATIONS... //
            ////////////////////////////////////

            // read, write and update asynchronously using System.Threading.Task
            IAsyncReader asyncReader = new AsyncReader(reader);

            readEntrys = await asyncReader.ReadAsync <Entry>("MyFirstCollection", "Message", "Hello");

            Assert.AreEqual(1, readEntrys.Count());

            IAsyncWriter  asyncWriter  = new AsyncWriter(writer);
            IAsyncUpdater asyncUpdater = new AsyncUpdater(updater);

            // or delegate call backs
            IAsyncDelegateReader asyncDelegateReader = new AsyncDelegateReader(reader);

            asyncDelegateReader.AsyncReadCompleted += new ReadCompletedEvent(readerCallBack);
            asyncDelegateReader.ReadAsync <Entry>("MyFirstCollection", "Message", "Hello");
            _readerAutoResetEvent.WaitOne();

            Assert.AreEqual(1, _asyncReadResults.Count());

            IAsyncDelegateWriter  asyncDelegateWriter  = new AsyncDelegateWriter(writer);
            IAsyncDelegateUpdater asyncDelegateUpdater = new AsyncDelegateUpdater(updater);

            /////////////////////////////////////////////
            // FOR A SERVER, DATABASE OR COLLECTION... //
            /////////////////////////////////////////////

            // get a little higher level with the EasyMongo.Database namespace to target a database for operations
            IDatabaseReader  databaseReader  = new DatabaseReader(reader, asyncReader);
            IDatabaseWriter  databaseWriter  = new DatabaseWriter(writer, asyncWriter);
            IDatabaseUpdater databaseUpdater = new DatabaseUpdater(updater, asyncUpdater);

            // or a little lower level with the EasyMongo.Collection namespace to target a specific Collection
            ICollectionReader  collectionReader  = new CollectionReader(databaseReader, "MyFirstCollection");
            ICollectionWriter  collectionWriter  = new CollectionWriter(databaseWriter, "MyFirstCollection");
            ICollectionUpdater collectionUpdater = new CollectionUpdater(databaseUpdater, "MyFirstCollection");

            ///////////////////////////////////////////////
            // TO RESTRICT CLIENT SCOPE (LAW OF DEMETER) //
            ///////////////////////////////////////////////

            // operate only against "MyFirstDatabase"'s "MySecondCollection"
            readEntrys = collectionReader.Read <Entry>("Message", "Hello");
            Assert.AreEqual(1, readEntrys.Count());

            /////////////////////
            // GENERIC CLASSES //
            /////////////////////

            // Instead of defining generic type arguments at the method level,
            // you can do it once at the class declaration
            IWriter <Entry> writerT = new Writer <Entry>(writer);

            writerT.Write("MySecondCollection", new Entry()
            {
                Message = "Goodbye World (Generically)"
            });

            ///////////////////////////////
            // SIMPLIFY CREATION VIA IoC //
            ///////////////////////////////

            // because EasyMongo is a componentized framework built with blocks of functionality, EasyMongo
            // works great with DI containers and Inversion of Control.
            // here's an example of using the nuget Ninject extension to load EasyMongo mappings and a conn
            // string from configuration
            Ninject.IKernel            kernel             = new Ninject.StandardKernel();
            ICollectionUpdater <Entry> collectionUpdaterT = kernel.TryGet <ICollectionUpdater <Entry> >();

            // the alternative to this would be:
            IServerConnection   serverConn     = new ServerConnection(LOCAL_MONGO_SERVER_CONNECTION_STRING);
            IDatabaseConnection databaseConnn  = new DatabaseConnection(serverConn, "MyFirstDatabase");
            IDatabaseUpdater    databaseUpdatr = new DatabaseUpdater(updater, asyncUpdater);
            ICollectionUpdater  collectionUpdaterTheHardWay = new CollectionUpdater(databaseUpdater, "MySecondCollection");

            /////////////////////////
            // SIMPLE QUERIES...   //
            /////////////////////////

            databaseReader.Read <Entry>("MyFirstCollection", "Message", "Hello");
            readEntrys = await databaseReader.ReadAsync <Entry>("MyFirstCollection", "Message", "Hello");

            Assert.AreEqual(1, readEntrys.Count());

            /////////////////////////
            // POWERFUL QUERIES... //
            /////////////////////////

            // when more robust querying is needed leverage power of underlying MongoDB driver IMongoQuery
            IMongoQuery query1 = Query.Matches("Message", new BsonRegularExpression("HE", "i"));

            IEnumerable <Entry> queryResults = reader.Execute <Entry>("MyFirstCollection", query1);

            Assert.AreEqual(1, queryResults.Count());
            Assert.AreEqual("Hello", queryResults.ElementAt(0).Message);

            //////////////////////
            // AND COMBINATIONS //
            //////////////////////

            Entry exampleMongoDBEntry2 = new Entry();

            exampleMongoDBEntry2.Message = "Hello Again";

            Entry exampleMongoDBEntry3 = new Entry();

            exampleMongoDBEntry3.Message = "Goodbye";

            writer.Write <Entry>("MyFirstCollection", exampleMongoDBEntry2);
            writer.Write <Entry>("MyFirstCollection", exampleMongoDBEntry3);

            // "AND" multiple IMongoQueries...
            IMongoQuery query2 = Query.Matches("Message", new BsonRegularExpression("Again"));

            queryResults = reader.ExecuteAnds <Entry>("MyFirstCollection", new [] { query1, query2 });
            Assert.AreEqual(1, queryResults.Count());
            Assert.AreEqual("Hello Again", queryResults.ElementAt(0).Message);

            // "OR" multiple IMongoQueries...
            IMongoQuery query3 = Query.Matches("Message", new BsonRegularExpression("Goo"));

            queryResults = reader.ExecuteOrs <Entry>("MyFirstCollection", new[] { query1, query2, query3 });
            Assert.AreEqual(3, queryResults.Count());
            Assert.AreEqual("Hello", queryResults.ElementAt(0).Message);
            Assert.AreEqual("Hello Again", queryResults.ElementAt(1).Message);
            Assert.AreEqual("Goodbye", queryResults.ElementAt(2).Message);
        }
Ejemplo n.º 12
0
        public ActionResult GetLikesUsers(int embroideryId)
        {
            IKernel kernel = new StandardKernel(new DataModelCreator());

            var likes = kernel.Get<IRepository<Like>>().GetAll().Where(l => l.EmbroideryId == embroideryId);

            List<Object> result = new List<object>();

            foreach (var item in likes)
            {
                User user = kernel.TryGet<IRepository<User>>().GetById(item.UserId);
                result.Add(new { UserName = user.FirstName + " " + user.LastName, UserId = item.UserId });
            }

            return Json(result);
        }
        public async void Test()
        {
            _databaseConnection.Connect();

            /////////////////////////////////////
            // OPERATIONAL, CONTEXUAL SCOPE... //
            /////////////////////////////////////

            // create a Writer to write to the database
            IWriter writer = new Writer(_databaseConnection);
            // create a Reader to read from the database
            IReader reader = new Reader(_databaseConnection);
            // create an Updater to update the database
            IUpdater updater = new Updater(_databaseConnection);

            Entry exampleMongoDBEntry = new Entry();
            exampleMongoDBEntry.Message = "Hello";

            // write the object to the "MyFirstCollection" Collection that exists within the 
            // previously referenced "MyFirstDatabase" that was used to create the "writer" object
            writer.Write<Entry>("MyFirstCollection", exampleMongoDBEntry);

            IEnumerable<Entry> readEntrys = reader.Read<Entry>("MyFirstCollection", // within this collection...
                                                               "Message",// for the object field "Description"
                                                               "Hello");// return matches for 'Hello'
            Assert.AreEqual(1, readEntrys.Count());

            ////////////////////////////////////
            // AND ASYNCHRONOUS OPERATIONS... //
            ////////////////////////////////////

            // read, write and update asynchronously using System.Threading.Task
            IAsyncReader asyncReader = new AsyncReader(reader);
            readEntrys = await asyncReader.ReadAsync<Entry>("MyFirstCollection", "Message", "Hello");
            Assert.AreEqual(1, readEntrys.Count());

            IAsyncWriter asyncWriter = new AsyncWriter(writer);
            IAsyncUpdater asyncUpdater = new AsyncUpdater(updater);

            // or delegate call backs
            IAsyncDelegateReader asyncDelegateReader = new AsyncDelegateReader(reader);
            asyncDelegateReader.AsyncReadCompleted += new ReadCompletedEvent(readerCallBack);
            asyncDelegateReader.ReadAsync<Entry>("MyFirstCollection", "Message", "Hello");
            _readerAutoResetEvent.WaitOne();

            Assert.AreEqual(1, _asyncReadResults.Count());

            IAsyncDelegateWriter asyncDelegateWriter = new AsyncDelegateWriter(writer);
            IAsyncDelegateUpdater asyncDelegateUpdater = new AsyncDelegateUpdater(updater);

            /////////////////////////////////////////////
            // FOR A SERVER, DATABASE OR COLLECTION... //
            /////////////////////////////////////////////

            // get a little higher level with the EasyMongo.Database namespace to target a database for operations
            IDatabaseReader databaseReader = new DatabaseReader(reader, asyncReader);
            IDatabaseWriter databaseWriter = new DatabaseWriter(writer, asyncWriter);
            IDatabaseUpdater databaseUpdater = new DatabaseUpdater(updater, asyncUpdater);

            // or a little lower level with the EasyMongo.Collection namespace to target a specific Collection
            ICollectionReader collectionReader = new CollectionReader(databaseReader, "MyFirstCollection");
            ICollectionWriter collectionWriter = new CollectionWriter(databaseWriter, "MyFirstCollection");
            ICollectionUpdater collectionUpdater = new CollectionUpdater(databaseUpdater, "MyFirstCollection");

            ///////////////////////////////////////////////
            // TO RESTRICT CLIENT SCOPE (LAW OF DEMETER) //
            ///////////////////////////////////////////////

            // operate only against "MyFirstDatabase"'s "MySecondCollection"
            readEntrys = collectionReader.Read<Entry>("Message", "Hello");
            Assert.AreEqual(1, readEntrys.Count());

            /////////////////////
            // GENERIC CLASSES //
            /////////////////////

            // Instead of defining generic type arguments at the method level,
            // you can do it once at the class declaration
            IWriter<Entry> writerT = new Writer<Entry>(writer);
            writerT.Write("MySecondCollection", new Entry() { Message = "Goodbye World (Generically)" });

            ///////////////////////////////
            // SIMPLIFY CREATION VIA IoC //
            ///////////////////////////////

            // because EasyMongo is a componentized framework built with blocks of functionality, EasyMongo
            // works great with DI containers and Inversion of Control. 
            // here's an example of using the nuget Ninject extension to load EasyMongo mappings and a conn 
            // string from configuration
            Ninject.IKernel kernel = new Ninject.StandardKernel();
            ICollectionUpdater<Entry> collectionUpdaterT = kernel.TryGet<ICollectionUpdater<Entry>>();

            // the alternative to this would be:
            IServerConnection serverConn = new ServerConnection(LOCAL_MONGO_SERVER_CONNECTION_STRING);
            IDatabaseConnection databaseConnn = new DatabaseConnection(serverConn, "MyFirstDatabase");
            IDatabaseUpdater databaseUpdatr = new DatabaseUpdater(updater, asyncUpdater);
            ICollectionUpdater collectionUpdaterTheHardWay = new CollectionUpdater(databaseUpdater, "MySecondCollection");

            /////////////////////////
            // SIMPLE QUERIES...   //
            /////////////////////////

            databaseReader.Read<Entry>("MyFirstCollection", "Message", "Hello");
            readEntrys = await databaseReader.ReadAsync<Entry>("MyFirstCollection", "Message", "Hello");
            Assert.AreEqual(1, readEntrys.Count());

            /////////////////////////
            // POWERFUL QUERIES... //
            /////////////////////////

            // when more robust querying is needed leverage power of underlying MongoDB driver IMongoQuery
            IMongoQuery query1 = Query.Matches("Message", new BsonRegularExpression("HE", "i"));

            IEnumerable<Entry> queryResults = reader.Execute<Entry>("MyFirstCollection", query1);
            Assert.AreEqual(1, queryResults.Count());
            Assert.AreEqual("Hello", queryResults.ElementAt(0).Message);

            //////////////////////
            // AND COMBINATIONS //
            //////////////////////

            Entry exampleMongoDBEntry2 = new Entry();
            exampleMongoDBEntry2.Message = "Hello Again";

            Entry exampleMongoDBEntry3 = new Entry();
            exampleMongoDBEntry3.Message = "Goodbye";

            writer.Write<Entry>("MyFirstCollection", exampleMongoDBEntry2);
            writer.Write<Entry>("MyFirstCollection", exampleMongoDBEntry3);

            // "AND" multiple IMongoQueries...
            IMongoQuery query2 = Query.Matches("Message", new BsonRegularExpression("Again"));
            queryResults = reader.ExecuteAnds<Entry>("MyFirstCollection", new []{ query1, query2});
            Assert.AreEqual(1, queryResults.Count());
            Assert.AreEqual("Hello Again", queryResults.ElementAt(0).Message);

            // "OR" multiple IMongoQueries...
            IMongoQuery query3 = Query.Matches("Message", new BsonRegularExpression("Goo"));
            queryResults = reader.ExecuteOrs<Entry>("MyFirstCollection", new[] { query1, query2, query3 });
            Assert.AreEqual(3, queryResults.Count());
            Assert.AreEqual("Hello", queryResults.ElementAt(0).Message);
            Assert.AreEqual("Hello Again", queryResults.ElementAt(1).Message);
            Assert.AreEqual("Goodbye", queryResults.ElementAt(2).Message);         
        }