Пример #1
0
        public ImageFromCacheService(CacheUpdateService cacheUpdateService,
                                     IMiniLogger logger        = null,
                                     int cacheLifeTimeMilliSec = 2001,
                                     int framesPerSecond       = 5

                                     )
        {
            _cacheUpdateService = cacheUpdateService ?? throw new ArgumentNullException(nameof(cacheUpdateService));
            if (cacheLifeTimeMilliSec < MinValueCacheLifeTimeMilliSec)
            {
                throw new ArgumentException(
                          $"{nameof(cacheLifeTimeMilliSec)} too small: " +
                          $"{cacheLifeTimeMilliSec} < {MinValueCacheLifeTimeMilliSec}");
            }
            if (framesPerSecond < MinValueFramesPerSecond)
            {
                throw new ArgumentException(
                          $"{nameof(framesPerSecond)} too small: " +
                          $"{framesPerSecond} < {MinValueFramesPerSecond}");
            }

            _cacheLifeTimeMilliSec = cacheLifeTimeMilliSec;
            _framesPerSecond       = framesPerSecond;
            _logger = logger;
        }
        //Helpers
        private CacheUpdateService CreateImageCache(byte[] imgBytes, int userId, DateTime dateUpdated)
        {
            var imageCache = new CacheUpdateService();

            imageCache.UpdateImage(imgBytes, userId, dateUpdated);

            return(imageCache);
        }
        public void GetImageAsByteArray_NoParamsAndImageCacheHasNoData_ReturnsNull()
        {
            // Arrange
            var imageCache = new CacheUpdateService();

            // Act
            var imgCacheSvc = new ImageFromCacheService(imageCache);

            // Assert
            Assert.IsNull(imgCacheSvc.GetCurrentImageAsByteArray());
        }
        public void Constructor_ValidParams_HappyPath(int expiration, int fps)
        {
            // Arrange
            var imageCache = new CacheUpdateService();

            // Act
            var imgCacheSvc = new ImageFromCacheService(imageCache, null, expiration, fps);

            // Assert
            Assert.IsNotNull(imgCacheSvc);
        }
        public void Constructor_InvalidParams_Throws(int expiration, int fps)
        {
            // Arrange
            var imageCache = new CacheUpdateService();

            Assert.Throws <ArgumentException>(() => new ImageFromCacheService(
                                                  cacheUpdateService: imageCache,
                                                  logger: null,
                                                  cacheLifeTimeMilliSec: expiration,
                                                  framesPerSecond: fps));
        }
        public void GetImageAsByteArray_NoParamsImageCacheHasData_ReturnsNotNull()
        {
            // Arrange
            var imageCache = new CacheUpdateService();

            imageCache.UpdateImage(new byte[2], 1, DateTime.MaxValue);

            // Act
            var imgCacheSvc = new ImageFromCacheService(imageCache);


            // Assert
            Assert.IsNotNull(imgCacheSvc.GetCurrentImageAsByteArray());
        }
        [TestCase(1, StrCacheLastUpdate, 2000, 5, true, 99, 5000, false)]  // Failure: readerDelay > lifetime
        public void GetNewImageAsByteArray_WithParamsAndFreshData_ReturnNotNull(int cacheUpdaterUserId, string strCacheLastUpdate, int cacheLifeTime,
                                                                                int cacheFps, bool cacheHasData,
                                                                                int cacheReaderUserId, int cacheReaderDelay, bool expectedSuccess)
        {
            // Arrange
            DateTime cacheLastUpdate     = DateTime.ParseExact(s: strCacheLastUpdate, format: "yyyy-MM-dd HH:mm:ss.fff", provider: null);
            DateTime timeWhenCacheIsRead = cacheLastUpdate.AddMilliseconds(cacheReaderDelay);

            byte[]             imageBytes = cacheHasData ? new byte[2] : null;
            CacheUpdateService imageCache = CreateImageCache(imageBytes, cacheUpdaterUserId, cacheLastUpdate);
            var cachingService            = new ImageFromCacheService(cacheUpdateService: imageCache, logger: null, cacheLifeTimeMilliSec: cacheLifeTime, framesPerSecond: cacheFps);

            // Act
            byte[] imgBytes        = cachingService.GetNewImageAsByteArray(userId: cacheReaderUserId, timeRequested: timeWhenCacheIsRead);
            bool   resultIsNotNull = imgBytes != null;

            // Assert
            Assert.AreEqual(resultIsNotNull, expectedSuccess);
        }
        [TestCase(10, StrCacheLastUpdate, 2000, 5, true, 99, -1, 0)]                    // No wait time:  cacheReaderDelay < 0 ms
        public void WaitBeforeGettingNextImageTest_AnyParameters_ReturnExpectedResult(int cacheUpdaterUserId, string strCacheLastUpdate, int cacheLifeTime,
                                                                                      int cacheFps, bool cacheHasData,
                                                                                      int cacheReaderUserId, int cacheReaderDelay, int expectedWaitTimeMilliSec)
        {
            // Arrange
            DateTime cacheLastUpdate     = DateTime.ParseExact(s: strCacheLastUpdate, format: "yyyy-MM-dd HH:mm:ss.fff", provider: null);
            DateTime timeWhenCacheIsRead = cacheLastUpdate.AddMilliseconds(cacheReaderDelay);

            byte[] imageBytes = cacheHasData ? new byte[2] : null;

            CacheUpdateService imageCache       = CreateImageCache(imageBytes, cacheUpdaterUserId, cacheLastUpdate);
            var cachingService                  = new ImageFromCacheService(cacheUpdateService: imageCache, logger: null, cacheLifeTimeMilliSec: cacheLifeTime, framesPerSecond: cacheFps);
            int fpsTimeBetweenTwoFramesMilliSec = 1000 / cacheFps;

            // Act
            (int waitTimeMilliSec, string reason) = cachingService.WaitBeforeGettingNextImage(userId: cacheReaderUserId, timeRequested: timeWhenCacheIsRead);

            // Assert
            Assert.That(waitTimeMilliSec, Is.EqualTo(expectedWaitTimeMilliSec));

            Assert.That(waitTimeMilliSec, Is.LessThanOrEqualTo(fpsTimeBetweenTwoFramesMilliSec));
        }
        [TestCase(10, StrCacheLastUpdate, 2000, 5, true, 99, -1, false)] // Cannot update = new date is in the past
        public void UpdateCachedImage_AnyParameters_ReturnExpectedResult(int oldUpdaterUserId, string strCacheLastUpdate, int cacheLifeTime,
                                                                         int cacheFps, bool cacheHasData,
                                                                         int newCacheUpdaterUserId, int newCacheUpdaterDelay, bool expectedSuccess)
        {
            // Arrange
            DateTime cacheLastUpdate     = DateTime.ParseExact(s: strCacheLastUpdate, format: "yyyy-MM-dd HH:mm:ss.fff", provider: null);
            DateTime timeWhenCacheIsRead = cacheLastUpdate.AddMilliseconds(newCacheUpdaterDelay);
            var      oldImageArraySize   = 2;

            byte[] imageBytes = cacheHasData ? new byte[oldImageArraySize] : null;

            CacheUpdateService imageCache = CreateImageCache(imageBytes, oldUpdaterUserId, cacheLastUpdate);
            var cachingService            = new ImageFromCacheService(cacheUpdateService: imageCache, logger: null, cacheLifeTimeMilliSec: cacheLifeTime, framesPerSecond: cacheFps);
            var newImageArraySize         = 44;

            // Act
            cachingService.UpdateCachedImage(new byte[newImageArraySize], newCacheUpdaterUserId, timeWhenCacheIsRead);

            // Assert
            bool cacheHasBeenUpdated = cachingService.GetCurrentImageAsByteArray().Length == newImageArraySize;

            Assert.That(cacheHasBeenUpdated, Is.EqualTo(expectedSuccess));
        }
Пример #10
0
        /// <summary>
        /// Registers the type mappings with the Unity container (IoC container).
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();

            // Register interfaces
            AppConfiguration configuration = AppConfiguration.Instance;

            container.RegisterInstance(
                configuration,
                new ContainerControlledLifetimeManager()                 //Singleton
                );

            container.RegisterType <IDateTimeProvider, DateTimeProvider>(
                new ContainerControlledLifetimeManager()                 //Singleton
                );

            container.RegisterType <IMiniLogger, MiniLogger>(
                new InjectionConstructor(
                    container.Resolve <IDateTimeProvider>(),
                    container.Resolve <AppConfiguration>().UserIPsLogPath,
                    container.Resolve <AppConfiguration>().UserPtzCmdLogPath,
                    container.Resolve <AppConfiguration>().ErrorsLogPath,
                    container.Resolve <AppConfiguration>().CacheStatsLogPath
                    ));

            var imageCache = new CacheUpdateService();

            container.RegisterInstance(imageCache);

            container.RegisterType <IImageFromCacheService, ImageFromCacheService>(
                new InjectionConstructor(
                    container.Resolve <CacheUpdateService>(),
                    container.Resolve <IMiniLogger>(),
                    container.Resolve <AppConfiguration>().CacheLifeTimeMilliSec,
                    container.Resolve <AppConfiguration>().CameraFps
                    ));

            container.RegisterType <IImageFromWebCamService, ImageFromWebCamService>(
                new InjectionConstructor(
                    container.Resolve <AppConfiguration>().CameraConnectionInfo
                    ));

            var cacheUpdater = new CacheUpdaterInfo();

            container.RegisterInstance(
                cacheUpdater,
                new ContainerControlledLifetimeManager()                 //Singleton
                );

            container.RegisterType <IImageProviderService, ImageProviderService>(
                new InjectionConstructor(
                    container.Resolve <IImageFromCacheService>(),
                    container.Resolve <IImageFromWebCamService>(),
                    container.Resolve <IDateTimeProvider>(),
                    container.Resolve <IMiniLogger>(),
                    container.Resolve <AppConfiguration>().CacheUpdaterExpirationMilliSec,
                    container.Resolve <CacheUpdaterInfo>(),
                    container.Resolve <AppConfiguration>().ErrorImageLogPath
                    ));


            //// Register controllers - not needed
            //container.RegisterType<BaseApiController>();
            //container.RegisterType<ImageController>();
            //container.RegisterType<PtzController>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }