Пример #1
0
        public static void Main(string[] args)
        {
            var applicationSettings = new ApplicationSettings();
            var bookRepo = new FileSystemStorage<Book>(applicationSettings);
            var customerRepo = new FileSystemStorage<Customer>(applicationSettings);

            var bookShopService = new BookShopService(bookRepo, customerRepo);

            #region data preparation
            var book = new Book
            {
                Price = 21.62,
                Title = "The Twelve : A Novel",
                Author = new Author
                {
                    Id = Guid.NewGuid(),
                    FirstName = "Justin",
                    LastName = "Cronin",
                    Rank = 23
                }
            };

            var customer = new Customer
            {
                Address = "Somewhere over the rainbow",
                CardNumber = "221234324",
                FirstName = "Clark",
                LastName = "Kent"
            };
            #endregion

            bookShopService.BuyOneBook(customer, book);
        }
Пример #2
0
        public void CoordinatorWorksOnFileSystemStorage()
        {
            var storage = new FileSystemStorage(@"c:\temp\netreduce", eraseContents: true) as IStorage;

            storage.Store(Base64.Encode("f1"), "ala ma kota");
            storage.Store(Base64.Encode("f2"), "kota alama");
            storage.Store(Base64.Encode("f3"), "dolan ma");
            var filesToRead = storage.ListFiles();
            var mapperCodeFile = new Uri("file:///SampleMapper.cs");
            var reducerCodeFile = new Uri("file:///SampleReducer.cs");
            TestHelpers.LoadToStorage(@"..\..\SampleMapper.cs", mapperCodeFile, storage);
            TestHelpers.LoadToStorage(@"..\..\SampleReducer.cs", reducerCodeFile, storage);
            var coordinator = new Coordinator<ThreadWorker>(storage);

            coordinator.Start(2, 2, mapperCodeFile, reducerCodeFile, filesToRead);

            string result = string.Empty;
            foreach (var uri in storage.ListFiles())
            {
                var file = this.storage.GetFileName(uri);
                if (file.Contains("REDUCE") && file.Contains(Base64.Encode("kota")))
                {
                    result = storage.Read(file);
                }
            }

            result.ShouldBe("2");
        }
Пример #3
0
        private void diskSpaceCheckTimer_Tick(object sender, EventArgs e)
        {
            string drive = System.IO.Path.GetPathRoot(Properties.Settings.Default.OutputPath);

            var space = FileSystemStorage.GetFreeDiskSpaceBytes(drive);

            long diskQuota = long.Parse(Properties.Settings.Default.DiskQuota) * (1024 * 1024);

            if (space <= diskQuota && !isDeleting)
            {
                isDeleting = true;
                System.Threading.ThreadPool.QueueUserWorkItem((o) =>
                {
                    try
                    {
                        FileSystemStorage.DeleteMostOutDatedDataForDay(1);
                    }
                    catch (System.IO.IOException)
                    {
                    }
                    finally
                    {
                        isDeleting = false;
                    }
                },
                                                              null
                                                              );
            }
        }
        public ActionResult Image(string filename)
        {
            var    stream    = new MemoryStream();
            string Thumbnail = ConfigurationManager.AppSettings["Image"];

            switch (Thumbnail)
            {
            case "Mongo":
                MongoStorage.GetFile(stream, filename, "Image");
                break;

            case "FileSystem":
                stream = FileSystemStorage.GetFile(filename, "Image");
                if (stream == null)
                {
                    return(File(new byte[] { }, "image/jpeg"));
                }
                break;

            case "QiNue":
                //实际上这里直接使用QiNue的URL就可以了
                stream = QiniuStorage.GetFile(filename);
                break;
            }
            if (stream == null)
            {
                return(null);
            }
            return(File(stream.ToArray(), "image/jpeg"));
        }
Пример #5
0
        public void CreateDirectoryTest()
        {
            var tempFolder = GetTempFolder();
            var fs         = new FileSystemStorage();

            var path = fs.Combine(tempFolder, Guid.NewGuid().ToString());

            fs.CreateDirectory(path);

            var result = fs.DirectoryExists(path);

            if (!result)
            {
                Trace.WriteLine($"Failed to create directory: {path}");
                Assert.Fail();
            }

            fs.DeleteDirectory(path);

            result = fs.DirectoryExists(path);
            if (result)
            {
                Trace.WriteLine($"Failed to delete directory: {path}");
                Assert.Fail();
            }
        }
Пример #6
0
        public void GetDirectoryNameTest()
        {
            var testData = new List <Tuple <string, string> >
            {
                new Tuple <string, string>(@"c:\path1\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"path1\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"\path1\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"\\server:\path1\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"file1.txt", "file1.txt"),
                new Tuple <string, string>("", ""),
                new Tuple <string, string>(@"c:\path1\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"c:\0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"c:\path2\012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.txt", "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.txt"),
                new Tuple <string, string>(@"0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\path2\file1.txt", "file1.txt"),
                new Tuple <string, string>(@"path2\012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.txt", "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.txt"),
                new Tuple <string, string>(@"file1", "file1"),
                new Tuple <string, string>(@"\", ""),
            };

            var fs = new FileSystemStorage();

            foreach (var data in testData)
            {
                var result = fs.GetFileName(data.Item1);
                if (String.Compare(result, data.Item2, true) != 0)
                {
                    Trace.WriteLine($"Input path: {data.Item1}");
                    Trace.WriteLine($"Output file: {result}, Should be: {data.Item2}");
                    Assert.Fail();
                }
            }
        }
Пример #7
0
        public void DeleteFileTest()
        {
            var tempFolder = GetTempFolder();
            var fs         = new FileSystemStorage();

            var path = fs.Combine(tempFolder, Guid.NewGuid().ToString());

            System.IO.File.WriteAllText(path, "test");

            var result = fs.FileExists(path);

            if (!result)
            {
                Trace.WriteLine($"Failed to create file: {path}");
                Assert.Fail();
            }

            fs.DeleteFile(path);
            result = fs.FileExists(path);
            if (result)
            {
                Trace.WriteLine($"Failed to delete file: {path}");
                Assert.Fail();
            }
        }
Пример #8
0
        public void IsFileSameTest()
        {
            var tempFolder = GetTempFolder();
            var fs         = new FileSystemStorage();

            var path1 = fs.Combine(tempFolder, Guid.NewGuid().ToString());
            var path2 = fs.Combine(tempFolder, Guid.NewGuid().ToString());

            System.IO.File.WriteAllText(path1, "test");
            System.IO.File.WriteAllText(path2, "test");

            var result = fs.IsFileSame(path1, path2);

            if (result)
            {
                Trace.WriteLine($"Date signature: Files are the same: {path1}, {path2}");
                Assert.Fail();
            }

            var path3 = fs.Combine(tempFolder, Guid.NewGuid().ToString());

            fs.CopyFile(path1, path3);
            result = fs.IsFileSame(path1, path3);
            if (!result)
            {
                Trace.WriteLine($"Date signature: Files are not the same: {path1}, {path3}");
                Assert.Fail();
            }

            fs.DeleteFile(path1);
            fs.DeleteFile(path2);
            fs.DeleteFile(path3);
        }
Пример #9
0
        public void DirectoryExistsTest()
        {
            var tempFolder = GetTempFolder();
            var fs         = new FileSystemStorage();

            var path   = fs.Combine(tempFolder, Guid.NewGuid().ToString());
            var result = fs.DirectoryExists(path);

            if (result)
            {
                Trace.WriteLine($"Directory {path} exists on file system");
                Assert.Fail();
            }

            path = fs.Combine(tempFolder, Guid.NewGuid().ToString());
            fs.CreateDirectory(path);

            result = fs.DirectoryExists(path);
            if (!result)
            {
                Trace.WriteLine($"Directory {path} does no exist on file system");
                Assert.Fail();
            }

            fs.DeleteDirectory(path);
        }
Пример #10
0
        public void FileExistsTest()
        {
            var tempFolder = GetTempFolder();
            var fs         = new FileSystemStorage();

            var path   = fs.Combine(tempFolder, Guid.NewGuid().ToString());
            var result = fs.FileExists(path);

            if (result)
            {
                Trace.WriteLine($"File {path} exists on file system");
                Assert.Fail();
            }

            path = fs.Combine(tempFolder, Guid.NewGuid().ToString());
            System.IO.File.WriteAllText(path, "test");

            result = fs.FileExists(path);
            if (!result)
            {
                Trace.WriteLine($"File {path} does no exist on file system");
                Assert.Fail();
            }

            fs.DeleteFile(path);
        }
        public List <LifeTimeObject> Get_LifetimePd_And_RedefaultLifetimePD_Result()
        {
            var lifetimePd = new List <LifeTimeObject>();

            switch (_scenario)
            {
            case ECL_Scenario.Best:
                lifetimePd = FileSystemStorage <LifeTimeObject> .ReadCsvData(this._eclId, ECLStringConstants.i.PdLifetimeBests_Table(this._eclType));

                break;

            case ECL_Scenario.Optimistic:
                lifetimePd = FileSystemStorage <LifeTimeObject> .ReadCsvData(this._eclId, ECLStringConstants.i.PdLifetimeOptimistics_Table(this._eclType));

                break;

            case ECL_Scenario.Downturn:
                lifetimePd = FileSystemStorage <LifeTimeObject> .ReadCsvData(this._eclId, ECLStringConstants.i.PdLifetimeDownturns_Table(this._eclType));

                break;

            default:
                return(null);
            }

            return(lifetimePd);
        }
Пример #12
0
        private void SaveSelectedImage()
        {
            if ((this.bestPicListView.Items.Count <= 0) || (this.bestPicListView.FocusedItem == null))
            {
                return;
            }
            string filePath = this.bestPicListView.FocusedItem.Tag as string;

            if (File.Exists(filePath))
            {
                this.pictureBox1.Image = Image.FromFile(filePath);
            }
            ImageDetail imgInfo    = ImageDetail.FromPath(filePath);
            string      bigImgPath = FileSystemStorage.BigImgPathForFace(imgInfo);

            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                saveDialog.RestoreDirectory = true;
                saveDialog.Filter           = "Jpeg 文件|*.jpg";
                //saveDialog.FileName = filePath.Substring(filePath.Length - 27, 27);
                string fileName = Path.GetFileName(filePath);
                saveDialog.FileName = fileName;
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    if (pictureBox1.Image != null)
                    {
                        string path = saveDialog.FileName;
                        pictureBox1.Image.Save(path);
                        path = path.Replace(fileName, Path.GetFileName(bigImgPath));
                        pictureBoxWholeImg.Image.Save(path);
                    }
                }
            }
        }
Пример #13
0
        //以前
        //02_090702150918-0001.jpg -->大图片
        //02_090702152518-0006-0000.jpg--> 小图片

        //现在
        //02_090807144104343.jpg-->大图片
        //02_090807144104343-0000.jpg-->小图片
        private void bestPicListView_ItemActivate(object sender, System.EventArgs e)
        {
            string filePath = this.bestPicListView.FocusedItem.Tag as string;

            //show modify icon
            if (File.Exists(filePath))
            {
                this.pictureBox1.Image = Image.FromFile(filePath);
            }

            //detail infomation
            ImageDetail imgInfo = ImageDetail.FromPath(filePath);

            string captureLoc = string.Format("抓拍地点: {0}", imgInfo.FromCamera);

            this.labelCaptureLoc.Text = captureLoc;

            string captureTime = string.Format("抓拍时间: {0}", imgInfo.CaptureTime);

            this.labelCaptureTime.Text = captureTime;

            string bigImgPath = FileSystemStorage.BigImgPathForFace(imgInfo);

            this.pictureBoxWholeImg.Image = Image.FromFile(bigImgPath);
        }
Пример #14
0
        protected List <LifeTimeObject> GetScenarioRedfaultLifetimePdResult(ECL_Scenario _scenario)
        {
            var redefaultLifetimePd = new List <LifeTimeObject>();

            switch (_scenario)
            {
            case ECL_Scenario.Best:
                redefaultLifetimePd = FileSystemStorage <LifeTimeObject> .ReadCsvData(this._eclId, ECLStringConstants.i.PdRedefaultLifetimeBests_Table(this._eclType));

                break;

            case ECL_Scenario.Optimistic:
                redefaultLifetimePd = FileSystemStorage <LifeTimeObject> .ReadCsvData(this._eclId, ECLStringConstants.i.PdRedefaultLifetimeOptimistics_Table(this._eclType));

                break;

            case ECL_Scenario.Downturn:
                redefaultLifetimePd = FileSystemStorage <LifeTimeObject> .ReadCsvData(this._eclId, ECLStringConstants.i.PdRedefaultLifetimeDownturns_Table(this._eclType));

                break;

            default:
                return(null);
            }
            Log4Net.Log.Info($"LGD_RedefaultLifetimePD - {_scenario}");
            return(redefaultLifetimePd);
        }
Пример #15
0
        protected override void Initialize()
        {
            // create all application services and add to main services container.
            _services = new ServiceContainer();
            ServiceLocator.SetLocatorProvider(() => _services);

            var vfsStorage      = new VfsStorage();
            var pathStorage     = new FileSystemStorage("data");
            var uiAssetsStorage = new ZipStorage(pathStorage, "UI_Assets.zip");

            vfsStorage.MountInfos.Add(new VfsMountInfo(uiAssetsStorage, null));

            // Register the virtual file system as a service.
            _services.Register(typeof(IStorage), null, vfsStorage);

            // The GraphicsDeviceManager needs to be registered in the service container.
            // (This is required by the XNA content managers.)
            _services.Register(typeof(IGraphicsDeviceService), null, _graphicsDeviceManager);
            _services.Register(typeof(GraphicsDeviceManager), null, _graphicsDeviceManager);

            var uiContentManager = new StorageContentManager(_services, uiAssetsStorage);

            _services.Register(typeof(ContentManager), "UIContent", uiContentManager);

            // ----- Initialize Services
            // Register the game class.
            _services.Register(typeof(Microsoft.Xna.Framework.Game), null, this);
            _services.Register(typeof(kbPCB), null, this);

            // Input
            _inputManager = new InputManager(false);
            _services.Register(typeof(IInputService), null, _inputManager);

            // Graphics
            _graphicsManager = new GraphicsManager(GraphicsDevice, Window, uiContentManager);
            _services.Register(typeof(IGraphicsService), null, _graphicsManager);

            // GUI
            _uiManager = new UIManager(this, _inputManager);
            _services.Register(typeof(IUIService), null, _uiManager);

            // Animation
            _animationManager = new AnimationManager();
            _services.Register(typeof(IAnimationService), null, _animationManager);

            // Game logic
            _gameObjectManager = new GameObjectManager();
            _services.Register(typeof(IGameObjectService), null, _gameObjectManager);

            // Profiler
            _profiler = new HierarchicalProfiler("Main");
            _services.Register(typeof(HierarchicalProfiler), "Main", _profiler);

            // add more stuff here
            var editor2D = new Editor2D(this);

            Components.Add(editor2D);

            base.Initialize();
        }
Пример #16
0
        private void MainForm_Shown(object sender, EventArgs e)
        {
            diskSpaceCheckTimer.Enabled = true;

            FaceRecognition.FaceRecognizer.InitData(Program.ImageSampleCount, Program.ImageLen, Program.EigenNum);

            Camera c = config.FindCameraByID(Properties.Settings.Default.LastSelCamID);

            if (c == null)
            {
                return;
            }

            if (FileSystemStorage.DriveRemoveable(Properties.Settings.Default.OutputPath))
            {
                DialogResult result = MessageBox.Show(this,
                                                      "输出目录位于可移动介质!继续吗?", "警告",
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.No)
                {
                    return;
                }
            }


            this.StartCamera(c);
        }
Пример #17
0
 public void Setup()
 {
     _folder      = Guid.NewGuid().ToString();
     _storage     = new FileSystemStorage(_folder);
     _dict        = new Dictionary <string, object>();
     _tokenSource = new CancellationTokenSource();
 }
Пример #18
0
        /// <summary>
        ///     Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" /> fires that is associated with the <see
        ///     cref="T:Quartz.IJob" /> .
        /// </summary>
        /// <remarks>
        ///     The implementation may wish to set a result object on the JobExecutionContext before this method exits. The result itself is meaningless to Quartz, but may be informative to <see
        ///     cref="T:Quartz.IJobListener" /> s or <see cref="T:Quartz.ITriggerListener" /> s that are watching the job's execution.
        /// </remarks>
        /// <param name="context"> The execution context. </param>
        public void Execute(IJobExecutionContext context)
        {
            try{
                Dictionary <string, IList <Tweet> > groupedTweets = new Dictionary <string, IList <Tweet> >();

                IStorage storage = new FileSystemStorage();

                IList <Tweet> tweets = storage.GetTweets(DateTime.Today);

                foreach (Tweet tweet in tweets)
                {
                    string category = GetCategoryName(tweet);

                    if (groupedTweets.ContainsKey(category))
                    {
                        IList <Tweet> tws = groupedTweets[category];
                        tws.Add(tweet);

                        groupedTweets.Remove(category);
                        groupedTweets.Add(category, tws);
                    }
                    else
                    {
                        var tws = new List <Tweet>();
                        tws.Add(tweet);
                        groupedTweets.Add(category, tws);
                    }
                }

                if (!tweets.Any())
                {
                    return;
                }

                var sortedGroupTweet = groupedTweets.OrderBy(entry => entry.Key).ToDictionary(pair => pair.Key, pair => pair.Value);

                string pageTitle = string.Format(LinkfloodConfiguration.TitleFormat, DateTime.Today.ToString("dd-MMM-yyyy"));

                StringBuilder body = new StringBuilder();

                foreach (var groupedTweet in sortedGroupTweet)
                {
                    body.AppendFormat("<h2>{0} ({1})</h2><br />", groupedTweet.Key, groupedTweet.Value.Count);

                    body.Append("<ul>");

                    foreach (var tweet in groupedTweet.Value)
                    {
                        body.AppendFormat("<li>- <strong>{0}</strong></li>", ParseText(tweet.Text));
                    }

                    body.Append("</ul>");
                }

                Post(pageTitle, body.ToString());
            }
            catch (Exception e) {
                logger.Error("[Scheduler] Error posting", e);
            }
        }
Пример #19
0
        public async Task WithEmptyFile_ReturnsSavedFileLocation()
        {
            const string relativeLocation           = "./bin/helloworld.txt";
            var          mockLocationTemplateParser = new Mock <ILocationTemplateParser>();
            var          mockLogger = new Mock <ILogger <FileSystemStorage> >();

            mockLocationTemplateParser.Setup(x => x.SetBase(relativeLocation, It.IsAny <string>()))
            .Returns(relativeLocation);

            var locationTemplateParser = mockLocationTemplateParser.Object;

            var storageOptions = new FileSystemStorageOptions
            {
                BasePath = ""
            };

            var fileSystemStorage = new FileSystemStorage(Options.Create(storageOptions), locationTemplateParser, mockLogger.Object);

            var stream = new MemoryStream();

            var location = await fileSystemStorage.SaveAsync(relativeLocation, stream);

            Assert.Equal(relativeLocation, location);
            Assert.True(File.Exists(location));
        }
Пример #20
0
        void BypassDetectMotion()
        {
            while (true)
            {
                Frame f = this.GetNewFrame();

                if (f.image != IntPtr.Zero)
                {
                    IplImage ipl = new IplImage(f.image);
                    ipl.IsEnabledDispose = false;
                    f.searchRect.Width   = ipl.Width;
                    f.searchRect.Height  = ipl.Height;

                    motionFrames.Enqueue(f);
                    FileSystemStorage.SaveFrame(f);

                    if (motionFrames.Count == 6)
                    {
                        Frame[] frames = motionFrames.ToArray();
                        motionFrames.Clear();
                        lock (locker) framesQueue.Enqueue(frames);
                        goSearch.Set();
                    }
                }
                else
                {
                    goDetectMotion.WaitOne();
                }
            }
        }
Пример #21
0
        unsafe ImageDetail[] SaveImage(Target[] targets)
        {
            IList <ImageDetail> imgs = new List <ImageDetail>();

            foreach (Target t in targets)
            {
                Frame frame = t.BaseFrame;

                DateTime dt = DateTime.FromBinary(frame.timeStamp);

                for (int j = 0; j < t.FaceCount; ++j)
                {
                    IntPtr * f     = ((IntPtr *)(t.FaceData)) + j;
                    IplImage aFace = new IplImage(*f);
                    aFace.IsEnabledDispose = false;

                    string facePath = FileSystemStorage.GetFacePath(frame, dt, j);

                    aFace.SaveImage(facePath);

                    imgs.Add(ImageDetail.FromPath(facePath));
                }
            }

            ImageDetail[] details = new ImageDetail[imgs.Count];
            imgs.CopyTo(details, 0);

            return(details);
        }
 /// <summary>
 /// Inicializa a instancia.
 /// </summary>
 /// <param name="properties"></param>
 public void Initialize(IDictionary properties)
 {
     try
     {
         string rootDir = null;
         if (properties.Contains("root-dir"))
         {
             rootDir = Convert.ToString(properties["root-dir"]);
         }
         string dataFolder = null;
         if (properties.Contains("persistence-key"))
         {
             dataFolder = Convert.ToString(properties["persistence-key"]);
         }
         int num = 60000;
         if (properties.Contains("persistence-interval"))
         {
             num = Convert.ToInt32(properties["persistence-interval"]);
             num = Math.Max(1000, num);
         }
         _internalStore = new FileSystemStorage(rootDir, dataFolder);
         if (_internalStore.DataFolder != null)
         {
             ((IPersistentCacheStorage)this).LoadStorageState();
             TimerCallback callback = new TimerCallback(this.OnPersistStateTimer);
             _persistenceTimer = new Timer(new TimerCallback(callback.Invoke), num, num, num);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
        public void Search()
        {
            var selectedCamera = this._screen.SelectedCamera;

            if (selectedCamera == null)
            {
                return;
            }

            var range = this._screen.TimeRange;
            var type  = this._screen.SearchScope;

            DTRange         = range;
            typeSearchScope = type;

            Core.Video[] videos =
                new FileSystemStorage(Properties.Settings.Default.OutputPath).VideoFilesBetween(selectedCamera.Id, range.From, range.To);
            TotalVideos = videos;
            if (videos.Length == 0)
            {
                return;
            }
            TotalCount = TotalVideos.Length;
            if ((TotalCount % PageSize) > 0)
            {
                TotalPage = ((int )(TotalCount / PageSize)) + 1;
            }
            else
            {
                TotalPage = ((int)(TotalCount / PageSize));
            }
            currentPage = 0;
            NavigateToFirst();
        }
Пример #24
0
        static void Main()
        {
            var dataFolder = "./data";

            var matcher = new Medina2012Matcher();

            var fs = new FileSystemStorage <MtripletsFeature>(dataFolder, "dat");

            foreach (var f in Directory.GetFiles(dataFolder, "*.tif"))
            {
                var candidateName = Path.GetFileNameWithoutExtension(f);

                if (!fs.ContainsCandidate(candidateName))
                {
                    matcher.Store(fs, new Bitmap(f), candidateName);
                }
            }


            Console.WriteLine($"Searching between {fs.CandidatesCount} candidates");

            var ts = Stopwatch.StartNew();

            var matches = matcher.Match(fs, new Bitmap(Path.Combine(dataFolder, "101_1.tif")), 0, (int)fs.CandidatesCount);

            ts.Stop();

            foreach (var m in matches)
            {
                Console.WriteLine($"{m.EntryId},");
            }

            Console.WriteLine($"Found in {ts.ElapsedMilliseconds} ms");
            Console.ReadLine();
        }
Пример #25
0
        public void Test()
        {
            DateTime dt = DateTime.Parse("2010-1-22 17:55");

            bool result = FileSystemStorage.FaceImagesCapturedWhen(2, dt);

            Assert.IsTrue(result);
        }
Пример #26
0
        void videoFileCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime time = DateTime.Now.AddMinutes(-2);

            if (!FileSystemStorage.MotionImagesCapturedWhen(2, time))
            {
                DeleteVideoFileAt(time);
            }
        }
        public void FileSystemStorageStorageCreate()
        {
            // Arrange

            // Act
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Assert
            Assert.NotNull(storage);
        }
Пример #28
0
        public void FileSystemStorageStorageCreate()
        {
            // Arrange

            // Act
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Assert
            Assert.NotNull(storage);
        }
Пример #29
0
        public void ReadDir()
        {
            FileSystemStorage fStore = new FileSystemStorage();
            LocalFileData     fDat   = fStore.GetData("/test") as LocalFileData;

            Console.WriteLine("名称:{0}", fDat.Name);
            Console.WriteLine("标识:{0}", fDat.IdentityName);
            Console.WriteLine("创建时间:{0}", fDat.CreateDateTimeUTC.ToLocalTime());
            Console.WriteLine("修改时间:{0}", fDat.ModifiedDateTimeUTC.ToLocalTime());
        }
Пример #30
0
        public async Task DesktopStorageCreateContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Act
            var container = await storage.CreateOrGetContainerAsync("FileSystemStorageCreateContainer", ContainerPermission.Public, failIfExists : true);

            // Assert
            Assert.NotNull(container);
        }
Пример #31
0
        public async Task DesktopStorageGetExisingContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Act
            var container = await storage.GetContainerAsync(FileSystemStorageTests._precreatedContainerName);

            // Assert
            Assert.NotNull(container);
        }
Пример #32
0
        public void ReadFile()
        {
            FileSystemStorage fStore = new FileSystemStorage();
            LocalFileData     fDat   = fStore.GetData("test.html") as LocalFileData;

            Console.WriteLine("名称:{0}", fDat.Name);
            Console.WriteLine("标识:{0}", fDat.IdentityName);
            Console.WriteLine("创建时间:{0}", fDat.CreateDateTimeUTC.ToLocalTime());
            Console.WriteLine("修改时间:{0}", fDat.ModifiedDateTimeUTC.ToLocalTime());
            Console.WriteLine("文本内容:{0}", System.Text.Encoding.Default.GetString(fDat.RawData));
        }
        public async Task DesktopStorageGetExisingContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Act
            var container = await storage.GetContainerAsync(FileSystemStorageTests._precreatedContainerName);

            // Assert
            Assert.NotNull(container);
        }
Пример #34
0
        public void FileSystemStoragCleanMethodDeletesAllFiles()
        {
            var storage = new FileSystemStorage(@"c:\temp\netreduce", eraseContents: true);
            storage.Store("a", "aa");
            storage.Store("b", "bb");

            storage.Clean();
            var noOfFiles = storage.ListFiles().Count();

            noOfFiles.ShouldBe(0);
        }
Пример #35
0
        public void SelectedImageChanged()
        {
            ImageDetail img = this.screen.SelectedImage;

            if (img != null && !string.IsNullOrEmpty(img.Path))
            {
                string      bigPicPathName = FileSystemStorage.BigImgPathFor(img);
                ImageDetail bigImageDetail = ImageDetail.FromPath(bigPicPathName);
                this.screen.BigImage = bigImageDetail;
            }
        }
        public async Task DesktopStorageGetListOfContainers()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Act
            var list = await storage.GetContainersListAsync(null);

            // Assert
            Assert.NotNull(list);
            Assert.True(list.Any(l => string.Equals(FileSystemStorageTests._precreatedContainerName, l)));
        }
Пример #37
0
        public void FileSystemStorageRemoveDeletesGivenFile()
        {
            var storage = new FileSystemStorage(@"c:\temp\netreduce", eraseContents: true);
            storage.Store("a", "aa");
            storage.Store("b", "bb");
            var fileToRemove = storage.ListFiles().First(u => u.OriginalString.Contains("a"));

            storage.Remove(fileToRemove);

            var noOfFiles = storage.ListFiles().Count();
            noOfFiles.ShouldBe(1);
            storage.ListFiles().First().OriginalString.ShouldContain("b");
        }
        public FormLicensePlateQuery(ConfigurationManager configurationManager, FileSystemStorage videoRepository)
        {
            if (configurationManager == null) throw new ArgumentNullException("configurationManager");
            if (videoRepository == null) throw new ArgumentNullException("videoRepository");

            _configurationManager = configurationManager;
            _videoRepository = videoRepository;
            InitializeComponent();

            InitLicenseplateDataTable();

            var now = DateTime.Now;
            to.EditValue = now;
            from.EditValue = now.AddHours(-1);
        }
Пример #39
0
        public ImagePair GetFace(string path)
        {
            Bitmap face = (Bitmap)Damany.Util.Extensions.MiscHelper.FromFileBuffered(path);

            string bigImgPath = new FileSystemStorage(Properties.Settings.Default.OutputPath).BigImgPathForFace(Core.ImageDetail.FromPath(path));

            Bitmap big = (Bitmap)Damany.Util.Extensions.MiscHelper.FromFileBuffered(bigImgPath);

            ImagePair ip = new ImagePair();
            ip.Face = face;
            ip.FacePath = path;

            ip.BigImage = big;
            ip.BigImagePath = bigImgPath;

            return ip;
        }
Пример #40
0
        public PicQueryForm(FileSystemStorage videoRepository, ConfigurationManager manager)
        {
            _videoRepository = videoRepository;
            _manager = manager;

            InitializeComponent();

            navigator.NavigatableControl = new NullNavigator();

            var now = DateTime.Now;
            this.timeFrom.EditValue = now.AddMinutes(-10);
            this.timeTo.EditValue = now;

            galleryControl1.Gallery.ItemCheckedChanged += Gallery_ItemCheckedChanged;

            this.PageSize = 50;
        }
Пример #41
0
		public void CompressAndDecompressOnFileSystem()
		{
			var storage = new FileSystemStorage();

			var contents = "This is a compression test. With accent è." + new string('c', 100);

			const string Source = @"Decompressed.txt";

			storage.WriteAllText(Source, contents);

			const string Compressed = @"Source.txt.gz";
			storage.CompressFile(Source, Compressed);
			storage.File(Compressed).Length.Should().Be.EqualTo(63);

			const string Decompressed = "Destination.txt";
			storage.DecompressFile(Compressed, Decompressed);
			storage.File(Decompressed).Length.Should().Be.EqualTo(contents.Length);
		}
        public async Task DesktopStorageGetNonExisingContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);
            StorageException ex = null;

            // Act
            try {
                await storage.GetContainerAsync(FileSystemStorageTests._precreatedContainerName + "-NOT-EXISTS");
            }
            catch (StorageException e) {
                ex = e;
            }

            // Assert
            Assert.NotNull(ex);
            Assert.Equal(StorageExceptionReason.ContainerNotFound, ex.Reason);
        }
        public async Task DesktopStorageTryToDeleteContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);
            const string containerName = "DesktopStorageTryToDeleteContainer";

            await storage.CreateOrGetContainerAsync(containerName, ContainerPermission.Public, failIfExists: false);
            var storages1 = await storage.GetContainersListAsync(containerName);

            // Act

            await storage.DeleteContainerAsync(containerName);
            var storages2 = await storage.GetContainersListAsync(containerName);

            // Assert
            Assert.NotNull(storages1);
            Assert.NotNull(storages2);
            Assert.True(storages1.All(c => string.Equals(c, containerName)));
            Assert.False(storages2.Any());
        }
        public async Task DesktopStorageCreateContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);

            // Act
            var container = await storage.CreateOrGetContainerAsync("FileSystemStorageCreateContainer", ContainerPermission.Public, failIfExists: true);

            // Assert
            Assert.NotNull(container);
        }
        public async Task DesktopStorageTryCreateContainer()
        {
            // Arrange
            IStorage storage = new FileSystemStorage(this._storagePath);
            StorageException ex = null;

            // Act
            try {
                await storage.CreateOrGetContainerAsync(FileSystemStorageTests._precreatedContainerName, ContainerPermission.Public, failIfExists: true);
            }
            catch (StorageException e) {
                ex = e;
            }

            // Assert
            Assert.NotNull(ex);
            Assert.Equal(StorageExceptionReason.ContainerExistAlready, ex.Reason);
        }
        private List<Video> FindFirstVideo()
        {
            var videos =
                new FileSystemStorage(
                    Properties.Settings.Default.OutputPath).
                    VideoFilesBetween(_selectedCamera.Id,
                                      _range.From, _range.To).ToList();

            return videos;
        }
        private void DoSearch()
        {
            var videos =
            new FileSystemStorage(
                Properties.Settings.Default.OutputPath).
                VideoFilesBetween(_selectedCamera.Id,
                                  _currentRange.From, _currentRange.To).ToList();

            var watch = System.Diagnostics.Stopwatch.StartNew();
            var range = new DateTimeRange(_currentRange.From, _currentRange.To.AddMinutes(1));

            watch.Stop();
            System.Diagnostics.Debug.WriteLine("frames search took " + watch.Elapsed);

            watch.Start();

            _portraits = new XPCollection<Portrait>();
            var cretia = CriteriaOperator.Parse("CaptureTime >= ? and CaptureTime < ?",
                                                            range.From, range.To);
            _portraits.Criteria = cretia;
            _portraits.Load();

            var gq = from  item in _portraits
                     group item by item.CaptureTime.Date.AddHours(item.CaptureTime.Hour).AddMinutes(item.CaptureTime.Minute) into g
                     orderby g.Key ascending
                     select g;

            watch.Stop();
            System.Diagnostics.Debug.WriteLine("portraits search took " + watch.Elapsed);

            this._screen.ClearAll();

            foreach (var v in videos)
            {
                if (v.CapturedAt.Ticks < _currentRange.From.Ticks || v.CapturedAt.Ticks > _currentRange.To.Ticks)
                {
                    continue;
                }

                v.HasFaceCaptured = gq.Where(g => g.Key == v.CapturedAt).Count() != 0;

                if ((_scope & SearchScope.FaceCapturedVideo)
                    == SearchScope.FaceCapturedVideo)
                {
                    if (v.HasFaceCaptured)
                    {
                        _screen.AddVideo(v);
                    }
                }

                if ((_scope & SearchScope.MotionWithoutFaceVideo)
                    == SearchScope.MotionWithoutFaceVideo)
                {
                    if (v.HasMotionDetected && !v.HasFaceCaptured)
                    {
                        _screen.AddVideo(v);
                    }
                }

                if ((_scope & SearchScope.MotionLessVideo)
                    == SearchScope.MotionLessVideo)
                {
                    if (!v.HasFaceCaptured &&
                        !v.HasMotionDetected)
                    {
                        _screen.AddVideo(v);
                    }
                }

            }
        }
        public void Search()
        {
            var selectedCamera = this._screen.SelectedCamera;
            if (selectedCamera == null)
            {
                return;
            }

            var range = this._screen.TimeRange;
            var type = this._screen.SearchScope;
            DTRange = range;
            typeSearchScope = type;

            Core.Video[] videos =
                new FileSystemStorage(Properties.Settings.Default.OutputPath).VideoFilesBetween(selectedCamera.Id, range.From, range.To);
            TotalVideos = videos;
            if (videos.Length == 0) return;
            TotalCount = TotalVideos.Length;
            if ((TotalCount % PageSize) > 0)
            {
                TotalPage =((int )(TotalCount / PageSize))+1;
            }
            else
            {
                TotalPage = ((int)(TotalCount / PageSize)) ;
            }
            currentPage = 0;
            NavigateToFirst();
        }
Пример #49
0
        public Video[] SearchVideos(int cameraID, DateTime from, DateTime to)
        {
            RemoteImaging.Core.Video[] videos = new FileSystemStorage(Properties.Settings.Default.OutputPath).VideoFilesBetween(cameraID, from, to).ToArray();

            Video[] serviceVideos = new Video[videos.Length];

            for (int i = 0; i < videos.Length; ++i)
            {
                serviceVideos[i] = new Video()
                {
                    HasFaceCaptured = videos[i].HasFaceCaptured,
                    HasMotionDected = videos[i].HasMotionDetected,
                    Path = videos[i].Path,
                };
            }

            return serviceVideos;
        }
Пример #50
0
        public MainForm(Func<IPicQueryPresenter> picQueryPresenterCreator,
            Func<IVideoQueryPresenter> createVideoQueryPresenter,
            Func<FaceComparePresenter> createFaceCompare,
            Func<OptionsForm> createOptionsForm,
            Func<TargetPersonEditForm> targetsEditorFactory,
            Func<OptionsPresenter> createOptionsPresenter,
            Func<FullVideoScreen> fullScreenMethod,
            IMessageBoxService messageBoxService,
            ConfigurationManager configurationManager,
            FileSystemStorage videoRepository
            )
            : this()
        {
            if (targetsEditorFactory == null) throw new ArgumentNullException("targetsEditorFactory");
            if (fullScreenMethod == null) throw new ArgumentNullException("fullScreenMethod");
            if (messageBoxService == null) throw new ArgumentNullException("messageBoxService");

            CreateFaceCompare = createFaceCompare;
            this.picPresenterCreator = picQueryPresenterCreator;
            _createVideoQueryPresenter = createVideoQueryPresenter;
            _createFaceCompare = createFaceCompare;
            this._createOptionsPresenter = createOptionsPresenter;
            _fullScreenMethod = fullScreenMethod;
            _messageBoxService = messageBoxService;
            _configurationManager = configurationManager;
            this._createOptionsForm = createOptionsForm;
            _targetsEditorFactory = targetsEditorFactory;
            _videoRepository = videoRepository;

            configurationManager.ConfigurationChanged += configurationManager_ConfigurationChanged;

            #if DEBUG
            barButtonItemTest.Visibility = BarItemVisibility.Always;
            #endif
        }