static void Main(string[] args) { const string baseUrl = "https://api.themoviedb.org/3/movie/popular/?api_key=50bfb202877fce6b0d15c9d434cbd1e2"; const string baseImageUrl = "https://image.tmdb.org/tY/p/w370"; var storage = new FileStorage(@"c:\temp\Movies.API"); const string completeUrl = baseUrl + "&page=1"; using (var webClient = new WebClient()) { webClient.Encoding = Encoding.UTF8; var resultString = webClient.DownloadString(completeUrl); var movieResults = JsonConvert.DeserializeObject<MovieResults>(resultString); foreach (var movie in movieResults.results.Select(movieResult => new Movie(movieResult.id, movieResult.title) { Overview = movieResult.overview, Popularity = movieResult.popularity, PosterPath = baseImageUrl + movieResult.poster_path })) { storage.Store(movie); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Stored movies! We got em!"); Console.ResetColor(); } }
public void TestSystemTemplates() { FileStorage fs = new FileStorage ( Path.Combine (Path.GetTempPath (), "TestTemplatesService")); TemplatesService ts = new TemplatesService (fs); // Start service ts.Start (); ICategoriesTemplatesProvider ctp = ts.CategoriesTemplateProvider; // We must have at least one template provider called 'Default' Dashboard dash = ctp.Load ("Default dashboard"); Assert.AreNotSame (dash, null); // Test we dont have a template bool found = ctp.Exists ("NonExistingTemplate"); Assert.AreEqual (found, false); // Test saving the default template dash.Name = "NewDefault"; ctp.Save (dash); // Test loading a template from a file Dashboard newDefault = ctp.Load ("NewDefault"); Assert.AreEqual (newDefault.Name, "NewDefault"); }
private static void FileStorageTest() { const string fileName = "foo.yml"; try { using (var fs = new FileStorage(fileName, FileStorage.Mode.Write | FileStorage.Mode.FormatYaml)) { fs.Write("int", 123); fs.Write("double", Math.PI); using (var tempMat = new Mat("data/lenna.png")) { fs.Write("mat", tempMat); } } using (var fs = new FileStorage(fileName, FileStorage.Mode.Read)) { Console.WriteLine("int: {0}", fs["int"].ReadInt()); Console.WriteLine("double: {0}", (double) fs["double"]); using (var window = new Window("mat")) { window.ShowImage(fs["mat"].ReadMat()); Cv2.WaitKey(); } } } finally { File.Delete(fileName); } }
public App() { // Load Embedded DLLs from Resources. emdll = new EmbeddedDLL(); siteExtensions = new DLL_Manager<ISiteExtension, ISiteExtensionCollection>(); databaseExtensions = new DLL_Manager<IDatabaseExtension, IDatabaseExtensionCollection>(); assemblyInfo = new AssemblyInformation(); AppDomain.CurrentDomain.AssemblyResolve += emdll.ResolveAssembly; SiteExtensions.DLLAppDomain.AssemblyResolve += emdll.ResolveAssembly; DatabaseExtensions.DLLAppDomain.AssemblyResolve += emdll.ResolveAssembly; // Handle unhandled exceptions DispatcherUnhandledException += App_DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Initialize Collections mangaArchiveCacheCollection = new ObservableCollection<MangaArchiveCacheObject>(); // Create a File System Watcher for Manga Objects mangaObjectArchiveWatcher = new FileSystemWatcher(MANGA_ARCHIVE_DIRECTORY, MANGA_ARCHIVE_FILTER); mangaObjectArchiveWatcher.EnableRaisingEvents = false; // Create a File System Watcher for Manga Chapter Objects chapterObjectArchiveWatcher = new FileSystemWatcher(CHAPTER_ARCHIVE_DIRECTORY, CHAPTER_ARCHIVE_FILTER); chapterObjectArchiveWatcher.IncludeSubdirectories = true; chapterObjectArchiveWatcher.EnableRaisingEvents = false; // Create IO class objects fileStorage = new Core.IO.Storage.Manager.BaseInterfaceClasses.FileStorage(); zipStorage = new Core.IO.Storage.Manager.BaseInterfaceClasses.ZipStorage(); downloadManager = new IO.Network.DownloadManager(); Startup += App_Startup; InitializeComponent(); }
internal static extern FileNode cvGetRootFileNode(FileStorage fs, int stream_index);
internal static extern void cvWriteRawData(FileStorage fs, IntPtr src, int len, string dt);
internal static extern void cvWrite(FileStorage fs, string name, CVHandle ptr, AttrList attributes);
static void Main(string[] args) { #region Mat[] splitall; Mat src; Mat channel_depth = new Mat(); Mat channel_gray = new Mat(); Mat channel_three = new Mat(); Mat element3 = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 1)); Mat element5 = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3)); FileStorage cld_date = new FileStorage("0924.yaml", FileStorage.Mode.Read); //101161kk.yaml using (var fs = new FileStorage("0924.yaml", FileStorage.Mode.Read)) //0924.yaml { src = fs["vocabulary"].ReadMat(); } Cv2.Split(src, out splitall); splitall[2].ConvertTo(channel_depth, MatType.CV_32FC1); //var window1 = new Window("depth",channel_depth); //Cv2.WaitKey(); splitall[3].ConvertTo(channel_gray, MatType.CV_8UC1); //using (var window = new Window("原始图", WindowMode.Normal, channel_gray)) //{ // Cv2.WaitKey(); //} int imgcols = channel_depth.Cols, imgrows = channel_depth.Rows; Mat model_calc_gray = Mat.Zeros(channel_depth.Rows, channel_depth.Cols, MatType.CV_32FC1); Mat model_gray = Mat.Zeros(channel_depth.Rows, channel_depth.Cols, MatType.CV_8UC1); Mat model_step1 = Mat.Zeros(channel_depth.Rows, channel_depth.Cols, MatType.CV_32FC1); for (int i = 0; i < channel_depth.Rows; i++) { for (int j = 0; j < channel_depth.Cols; j++) { if (channel_depth.At <float>(i, j) < 900) //900时为临界 ==》 0943 { model_calc_gray.Set <float>(i, j, channel_gray.At <Byte>(i, j)); //= channel_gray.At<short>(i, j);//char convert to float that could calcaulate }//方便后面sigmoid计算 else { continue; } } } Mat Edge_one = model_calc_gray.Clone(); for (int i = 0; i < 100; i++) { for (int j = 0; j < model_calc_gray.Cols; j++) { Edge_one.Set <float>(i, j, 0); } } //取反 Mat Edge = Mat.Zeros(channel_depth.Rows, channel_depth.Cols, MatType.CV_32FC1); Edge = new Scalar(255) - Edge_one; // int zero_cout = Cv2.CountNonZero(Edge); //返回矩阵中的非零值个数 Scalar zero_sum = Cv2.Sum(Edge); //对mat类四个通道求和 float matMean = (float)(zero_sum[0] / zero_cout); //对非0像素求均值 float angle = 0.2f; for (int i = 0; i < imgrows; i++) { for (int j = 0; j < imgcols; j++) { if (Edge.At <float>(i, j) != 0) { model_step1.Set <float>(i, j, sigmod(Edge.At <float>(i, j), matMean, angle)); } } } Mat show_change_two = Mat.Zeros(channel_depth.Rows, channel_depth.Cols, MatType.CV_8UC1); Cv2.Normalize(model_step1, show_change_two, 0, 255, NormTypes.MinMax, MatType.CV_8UC1); using (var window = new Window("转换展示图", WindowMode.Normal, show_change_two)) { Cv2.WaitKey(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Cv2.MorphologyEx(show_change_two, show_change_two, MorphTypes.Close, element5, new Point(-1, -1), 10); using (var window = new Window("5次模糊", WindowMode.Normal, show_change_two)) { Cv2.WaitKey(); } Cv2.MorphologyEx(show_change_two, show_change_two, MorphTypes.Dilate, element5, new Point(-1, -1), 8); using (var window = new Window("5次模糊", WindowMode.Normal, show_change_two)) { Cv2.WaitKey(); } #region 注释代码 //Cv2.MorphologyEx(show_change_two, show_change_two, MorphTypes.Erode, element5, new Point(-1, -1), 2); //using (var window = new Window("5次模糊", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //Cv2.MorphologyEx(show_change_two, show_change_two, MorphTypes.Open, element5, new Point(-1, -1), 10); //using (var window = new Window("5次模糊", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //for (int num1 = 0; num1 < 5; num1++) // //Cv2.MedianBlur(show_change_two, show_change_two, 5); // Cv2.GaussianBlur(show_change_two, show_change_two, new Size(3, 1), MatType.CV_8UC1); //using (var window = new Window("10次中值", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //Cv2.MorphologyEx(show_change_two, show_change_two, MorphTypes.Close, element5, new Point(-1, -1), 3); //using (var window = new Window("5比原算", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //for (int num1 = 0; num1 < 10; num1++) // Cv2.GaussianBlur(show_change_two, show_change_two, new Size(1, 3), MatType.CV_8UC1); //using (var window = new Window("5次模糊", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //Cv2.MorphologyEx(show_change_two, show_change_two, MorphTypes.Dilate, element3, new Point(-1, -1), 3); ////调试结果较好,二值化之前都不要对图像进行滤波,会丧失边界 //Cv2.Dilate(show_change_two, show_change_two, element3, new Point(-1, -1), 5); //using (var window = new Window("5膨胀", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} // Cv2.Dilate(show_change_two, show_change_two, element5, new Point(-1, -1), 5); //using (var window = new Window("5次腐蚀", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} // for (int num1 = 0; num1 < 10; num1++) // Cv2.MedianBlur(show_change_two, show_change_two, 5); //// Cv2.GaussianBlur(show_change_two, show_change_two, new Size(1, 3), MatType.CV_8UC1); // using (var window = new Window("10次中值", WindowMode.Normal, show_change_two)) // { // Cv2.WaitKey(); // } // int a = 0; //Cv2.Threshold(show_change_two, show_change_two, 0, 255,ThresholdTypes.Otsu); //PixelConnectivity pixelConnectivity =new PixelConnectivity(); //Cv2.ConnectedComponents(show_change_two, show_change_two, 4); //////Cv2.MedianBlur(show_change_two, show_change_two, 5); //using (var window = new Window("结果二值", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //for (int num1 = 0; num1 < 10; num1++) // Cv2.MedianBlur(show_change_two, show_change_two, 5); //// Cv2.GaussianBlur(show_change_two, show_change_two, new Size(1, 3), MatType.CV_8UC1); //using (var window = new Window("10次中值", WindowMode.Normal, show_change_two)) //{ // Cv2.WaitKey(); //} //int a = 0; #endregion #endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Mat Sobel_Edge = new Mat(); Mat Sobel_result = Mat.Zeros(imgrows, imgcols, MatType.CV_8UC1); Cv2.Sobel(show_change_two, Sobel_Edge, MatType.CV_16SC1, 4, 0, 5, 1, 0, BorderTypes.Default); Cv2.ConvertScaleAbs(Sobel_Edge, Sobel_result); Cv2.Threshold(Sobel_result, Sobel_result, 20, 255, ThresholdTypes.Otsu); using (var window = new Window("sobel结果二值", WindowMode.Normal, Sobel_result)) { Cv2.WaitKey(); } //for (int num1 = 0; num1 < 3; num1++) ////Cv2.MedianBlur(Sobel_result, Sobel_result, 3); // Cv2.GaussianBlur(Sobel_result, Sobel_result, new Size(1, 3), MatType.CV_8UC1); //using (var window = new Window("10次模糊", WindowMode.Normal, Sobel_result)) //{ // Cv2.WaitKey(); //} //Mat img_step2 = new Mat(); //Cv2.MorphologyEx(Sobel_result, Sobel_result, MorphTypes.Open, element5, new Point(-1, -1), 1); //using (var window = new Window("sobel5后膨胀", WindowMode.Normal, Sobel_result)) //{ // Cv2.WaitKey(); //} Mat result = Mat.Zeros(imgrows, imgcols, MatType.CV_8UC1); Point[][] contours_one; HierarchyIndex[] hierarchy_one; Cv2.FindContours(Sobel_result.Clone(), out contours_one, out hierarchy_one, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new Point(0, 0)); List <Point[]> afterFilter = new List <Point[]>(); Console.WriteLine("轮廓数量" + contours_one.Length); for (int c = 0; c < contours_one.Length; c++) { Console.WriteLine("轮廓" + c + "长度" + contours_one[c].Length); } //vector<vector<Point>>::iterator itc = contours_one.begin(); for (int c = 0; c < contours_one.Length; c++) { double area = Cv2.ContourArea(contours_one[c]); Console.WriteLine(area); if (area > 800) { afterFilter.Add(contours_one[c]); } } Cv2.DrawContours(result, afterFilter, -1, new Scalar(255), -1); using (var window = new Window("去除小面积结果图", WindowMode.Normal, result)) { Cv2.WaitKey(); } ////for (int num = 0; num < 5; num++) //// Cv2.Dilate(result, result, element3); //using (var window = new Window("连接下面的部分5次膨胀结果图", WindowMode.Normal, result)) //{ // Cv2.WaitKey(); //} Cv2.MorphologyEx(result, result, MorphTypes.Close, element3, new Point(-1, -1), 5); using (var window = new Window("闭运算再次迭代10次结果图", result)) { Cv2.WaitKey(); } Mat result1 = Mat.Zeros(imgrows, imgcols, MatType.CV_8UC1); Point[][] contours_one1; HierarchyIndex[] hierarchy_one1; Cv2.FindContours(result.Clone(), out contours_one1, out hierarchy_one1, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new Point(0, 0)); List <Point[]> afterFilter1 = new List <Point[]>(); Console.WriteLine(contours_one1.Length); //vector<vector<Point>>::iterator itc = contours_one.begin(); for (int c = 0; c < contours_one1.Length; c++) { double area = Cv2.ContourArea(contours_one1[c]); Console.WriteLine(area); if (area > 3000) { afterFilter1.Add(contours_one1[c]); } } Cv2.DrawContours(result1, afterFilter1, -1, new Scalar(255), -1); using (var window = new Window("再次去除小面积结果图", WindowMode.Normal, result1)) { Cv2.WaitKey(); } Mat result_uchar = Mat.Zeros(imgrows, imgcols, MatType.CV_8UC1); result1.ConvertTo(result_uchar, MatType.CV_8UC1); Point[][] contours_three; HierarchyIndex[] hierarchy_three; Cv2.FindContours(result_uchar.Clone(), out contours_three, out hierarchy_three, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new Point(0, 0)); Mat rectangle_one = Mat.Zeros(imgrows, imgcols, MatType.CV_8UC3); Rect[] boundRect_one = new Rect[contours_three.Length]; //定义外接矩形集合 RotatedRect[] box_one = new RotatedRect[contours_three.Length]; Point2f[] rect_one = new Point2f[4]; Console.WriteLine("最终边界数量:" + contours_three.Length); List <Point2f[]> rec_vec = new List <Point2f[]>(contours_three.Length); float[] center_one_x = new float[contours_three.Length]; float[] center_one_y = new float[contours_three.Length]; for (int i = 0; i < contours_three.Length; i++) { box_one[i] = Cv2.MinAreaRect(contours_three[i]); //计算外接旋转矩形 boundRect_one[i] = Cv2.BoundingRect(contours_three[i]); //计算每个轮廓最小外接矩形 Cv2.Circle(rectangle_one, new Point(box_one[i].Center.X, box_one[i].Center.Y), 5, new Scalar(0, 255, 0), -1); //绘制最旋转矩形的中心点 rect_one = box_one[i].Points(); //把最小外接矩形四个端点复制给rect数组 复制构造 Cv2.Rectangle(rectangle_one, boundRect_one[i], new Scalar(0, 255, 0), 5); //画最小外接矩形 center_one_x[i] = box_one[i].Center.X; center_one_y[i] = box_one[i].Center.Y; //cout << "end" <<center_one.size() << endl; for (int j = 0; j < 4; j++) { Cv2.Line(rectangle_one, (Point)rect_one[j], (Point)rect_one[(j + 1) % 4], new Scalar(0, 0, 255), 2); //绘制旋转矩形每条边 // rec_vec[i].push_back(rect_one[j]); /*cout << "第"<<j<<"个角点"<< rect[j] << endl;*/ } using (var window = new Window("绘制最小外接矩形结果图", WindowMode.Normal, rectangle_one)) { Cv2.WaitKey(); } } int[] ind = new int[center_one_x.Length]; BubbleSort(center_one_x, ind); for (int i = 0; i < contours_three.Length - 1; i++) { // cout << "ind" << ind[i] << endl; Point point_one; point_one.X = boundRect_one[ind[i]].X + boundRect_one[ind[i]].Width / 2; point_one.Y = boundRect_one[ind[i]].Y; Point point_two; point_two.X = boundRect_one[ind[i + 1]].X + boundRect_one[ind[i + 1]].Width / 2; point_two.Y = boundRect_one[ind[i + 1]].Y + boundRect_one[ind[i + 1]].Height; Point point_three; point_three = point_two - point_one; point_three.X = Math.Abs(point_three.X); point_three.Y = Math.Abs(point_three.Y); Rect rect = new Rect(point_one.X, point_one.Y, point_three.X, point_three.Y); Mat capture_one = channel_gray[rect]; //imshow("截图第一幅图结果图", capture_one); using (var window = new Window("截图第一幅图结果图", WindowMode.Normal, capture_one)) { Cv2.WaitKey(); } Point point_four; point_four.X = point_one.X + point_three.X / 2; point_four.Y = point_one.Y + 100; Cv2.Circle(channel_gray, point_four, 9, new Scalar(0, 0, 255)); Console.WriteLine("贴标X:" + splitall[0].At <float>(point_four.Y, point_four.X)); Console.WriteLine("贴标Y:" + splitall[1].At <float>(point_four.Y, point_four.X)); Console.WriteLine("贴标Z:" + splitall[2].At <float>(point_four.Y, point_four.X)); using (var window = new Window("截图第一幅圈圈", WindowMode.Normal, channel_gray)) { Cv2.WaitKey(); } Point point_five; point_five.X = point_one.X + point_three.Y / 2; point_five.Y = point_one.Y + 200; Cv2.Circle(channel_gray, point_five, 9, new Scalar(0, 0, 255)); Console.WriteLine("喷码X:" + splitall[0].At <float>(point_five.Y, point_five.X)); Console.WriteLine("喷码Y:" + splitall[1].At <float>(point_five.Y, point_five.X)); Console.WriteLine("喷码Z:" + splitall[2].At <float>(point_five.Y, point_five.X)); using (var window = new Window("截图第二幅圈圈", WindowMode.Normal, channel_gray)) { Cv2.WaitKey(); } } }
public void CreateStorage() { fs = new FileStorage (Path.Combine (Path.GetTempPath (), "TestFileStorage")); }
public async Task BackgroundActionStorageTest() { IStorage foregroundStorage = storage; await foregroundStorage.InitStorage(); IStorage backgroundStorage = new FileStorage() { Background = true }; await backgroundStorage.InitStorage(); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); IList <HistoryAction> historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(4, historyActions.Count, "Not 4 actions"); HistoryAction action = historyActions.First(t => t.Trigger == (int)BeaconEventType.Enter); Assert.AreEqual("1", action.BeaconId, "not same pid"); Assert.AreEqual("1", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T12:00:00.000+00:00", action.ActionTime, "not same date"); action = historyActions.First(t => t.Trigger == (int)BeaconEventType.Exit); Assert.AreEqual("2", action.BeaconId, "not same pid"); Assert.AreEqual("2", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T13:00:00.000+00:00", action.ActionTime, "not same date"); historyActions = await foregroundStorage.GetUndeliveredActions(); await foregroundStorage.SetActionsAsDelivered(historyActions); historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "not all actions as delivered marked"); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("5", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(4, historyActions.Count, "Not 4 actions"); action = historyActions.First(t => t.Trigger == (int)BeaconEventType.Enter); Assert.AreEqual("1", action.BeaconId, "not same pid"); Assert.AreEqual("4", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T12:00:00.000+00:00", action.ActionTime, "not same date"); action = historyActions.First(t => t.Trigger == (int)BeaconEventType.Exit); Assert.AreEqual("2", action.BeaconId, "not same pid"); Assert.AreEqual("5", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T13:00:00.000+00:00", action.ActionTime, "not same date"); historyActions = await backgroundStorage.GetUndeliveredActions(); await backgroundStorage.SetActionsAsDelivered(historyActions); historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "not all actions as delivered marked"); }
public FilesController() { fileStorage = new FileStorage(); }
public NumberServiceTests() { FileStorage fileStorage = new FileStorage(); _numbersService = new NumbersService(fileStorage); }
private void button4_Click(object sender, EventArgs e) { FileStorage fs = new FileStorage("cameraMat.txt", FileStorage.Mode.Read); Mat cameraMat = new Mat(); fs.GetFirstTopLevelNode().ReadMat(cameraMat); fs = new FileStorage("distort.txt", FileStorage.Mode.Read); Mat distortMat = new Mat(); fs.GetFirstTopLevelNode().ReadMat(distortMat); cameraPar = new float[9]; double[] cameraParDouble = new Double[9]; cameraMat.CopyTo(cameraParDouble); for (int i = 0; i < 9; i++) { cameraPar[i] = (float)cameraParDouble[i]; } const int width = 5; //5 //width of chessboard no. squares in width - 1 const int height = 5; //5 // heght of chess board no. squares in heigth - 1 Size patternSize = new Size(width, height); //size of chess board to be detected MCvPoint3D32f[] corners_object_list = new MCvPoint3D32f[width * height]; PointF[] corners_points_list = new PointF[width * height]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { corners_object_list[5 * i + j] = new MCvPoint3D32f((4 - i) * 29, (4 - j) * 29, 0); } } var output = new Emgu.CV.Util.VectorOfPointF(); Size smallerPicSize = new Size(816, 612); Mat imgCam = new Mat("1.jpg", LoadImageType.Unchanged);//load picture of chessboard Mat smallerPic = new Mat(); Size PicSize = new Size(3264, 2448); CvInvoke.Resize(imgCam, smallerPic, smallerPicSize); bool found = CvInvoke.FindChessboardCorners(smallerPic, patternSize, output);//find chessboard Console.WriteLine("found:" + found); corners_points_list = output.ToArray(); Mat rotationVec = new Mat(); Mat translationVec = new Mat(); CvInvoke.SolvePnP(corners_object_list, corners_points_list, cameraMat, distortMat, rotationVec, translationVec); //1 by 3 array of rotate Matrix rotateArr = new float[9]; Mat rotationMatrix = new Mat(); CvInvoke.Rodrigues(rotationVec, rotationMatrix); double[] rotateArrDouble = new double[9]; rotationMatrix.CopyTo(rotateArrDouble); for (int i = 0; i < 9; i++) { rotateArr[i] = (float)rotateArrDouble[i]; } //1 by 3 array of translate Matrix translateArr = new float[3]; double[] translateArrDouble = new double[3]; translationVec.CopyTo(translateArrDouble); for (int i = 0; i < 3; i++) { translateArr[i] = (float)translateArrDouble[i]; } }
private void button2_Click(object sender, EventArgs e) { const int width = 5; //5 //width of chessboard no. squares in width - 1 const int height = 5; //5 // heght of chess board no. squares in heigth - 1 Size patternSize = new Size(width, height); //size of chess board to be detected MCvPoint3D32f[][] corners_object_list = new MCvPoint3D32f[6][]; PointF[][] corners_points_list = new PointF[6][]; for (int k = 0; k < 6; k++) { corners_object_list[k] = new MCvPoint3D32f[width * height]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { corners_object_list[k][5 * i + j] = new MCvPoint3D32f((4 - i) * 29, (4 - j) * 29, 0); } } } var output = new Emgu.CV.Util.VectorOfPointF(); Size smallerPicSize = new Size(816, 612); for (int k = 1; k <= 6; k++) { Mat imgCam = new Mat(k + ".jpg", LoadImageType.Unchanged);//load picture of chessboard Mat smallerPic = new Mat(); Size PicSize = new Size(3264, 2448); CvInvoke.Resize(imgCam, smallerPic, smallerPicSize); if (k == 1) { smallerPic.Save("small1.jpg"); } //CvInvoke.Imshow("small", smallerPic); bool found = CvInvoke.FindChessboardCorners(smallerPic, patternSize, output);//find chessboard Console.WriteLine("found:" + found); corners_points_list[k - 1] = output.ToArray(); } for (int i = 0; i < output.Size; i++) { Console.WriteLine(corners_points_list[0].GetValue(i)); } Mat cameraMat = new Mat(); Mat distorCoef = new Mat(); Mat[] rotationVec = new Mat[6]; Mat[] translationVec = new Mat[6]; for (int k = 0; k < 6; k++) { translationVec[k] = new Mat(); rotationVec[k] = new Mat(); } MCvTermCriteria criteria = new MCvTermCriteria(); double rms = CvInvoke.CalibrateCamera(corners_object_list, corners_points_list, smallerPicSize, cameraMat, distorCoef, CalibType.RationalModel, criteria, out rotationVec, out translationVec); cameraPar = new float[9]; double[] cameraParDouble = new Double[9]; cameraMat.CopyTo(cameraParDouble); for (int i = 0; i < 9; i++) { cameraPar[i] = (float)cameraParDouble[i]; } //1 by 14 array of distortion coeff, only first 8 important double[] distortArr = new double[14]; distorCoef.CopyTo(distortArr); //1 by 3 array of rotate Matrix rotateArr = new float[9]; Mat rotationMatrix = new Mat(); //need to flip stuff //double[] rv = new double[3]; //rotationVec[0].CopyTo(rv); //rv[1] = -1.0f * rv[1]; rv[2] = -1.0f * rv[2]; //rotationVec[0].SetTo(rv); CvInvoke.Rodrigues(rotationVec[0], rotationMatrix); double[] rotateArrDouble = new double[9]; rotationMatrix.CopyTo(rotateArrDouble); for (int i = 0; i < 9; i++) { rotateArr[i] = (float)rotateArrDouble[i]; } //1 by 3 array of translate Matrix translateArr = new float[3]; double[] translateArrDouble = new double[3]; translationVec[0].CopyTo(translateArrDouble); for (int i = 0; i < 3; i++) { translateArr[i] = (float)translateArrDouble[i]; } for (int i = 0; i < 3; i++) { Console.WriteLine(rotateArr[i]); } for (int i = 0; i < 3; i++) { Console.WriteLine(translateArr[i]); } //CvInvoke.Imshow("chessboard", imgCam); Console.WriteLine(rms); FileStorage fs = new FileStorage("cameraMat.txt", FileStorage.Mode.Write); fs.Write(cameraMat); fs.ReleaseAndGetString(); fs = new FileStorage("distort.txt", FileStorage.Mode.Write); fs.Write(distorCoef); fs.ReleaseAndGetString(); }
public void TestFile() { var localFileStorage = new FileStorage <string>(); TestStrategy(localFileStorage); }
public async Task GetBackgroundActionsFromBackgroundinForegroundTest() { IStorage foregroundStorage = storage; await foregroundStorage.InitStorage(); IStorage backgroundStorage = new FileStorage() { Background = true }; await backgroundStorage.InitStorage(); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue( await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "31231231"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, null))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("5", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue( await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "31231231"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, null))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("5", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); TaskCompletionSource <bool> source = new TaskCompletionSource <bool>(); ((FileStorage)foregroundStorage).ForegroundHistoryActionWriter.QueueEmpty += () => source.SetResult(true); await source.Task; IList <HistoryAction> historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(16, historyActions.Count, "Not 16 actions"); historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(16, historyActions.Count, "Not 16 actions"); // HistoryAction dbHistoryAction = await backgroundStorage.GetAction("5"); // Assert.AreEqual((int) BeaconEventType.Exit, dbHistoryAction.Trigger, "not same type"); // Assert.AreEqual("2", dbHistoryAction.BeaconId, "not same pid"); // Assert.AreEqual("5", dbHistoryAction.EventId, "not same eid"); // Assert.AreEqual(DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), DateTimeOffset.Parse(dbHistoryAction.ActionTime), "not same date"); // dbHistoryAction = await foregroundStorage.GetAction("5"); // Assert.AreEqual((int) BeaconEventType.Exit, dbHistoryAction.Trigger, "not same type"); // Assert.AreEqual("2", dbHistoryAction.BeaconId, "not same pid"); // Assert.AreEqual("5", dbHistoryAction.EventId, "not same eid"); // Assert.AreEqual(DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), DateTimeOffset.Parse(dbHistoryAction.ActionTime), "not same date"); // IList<HistoryAction> dbHistoryActions = await backgroundStorage.GetActions("6"); // Assert.AreEqual(4, dbHistoryActions.Count, "Not 4 actions"); // dbHistoryActions = await foregroundStorage.GetActions("6"); // Assert.AreEqual(4, dbHistoryActions.Count, "Not 4 actions"); historyActions = await backgroundStorage.GetUndeliveredActions(); await foregroundStorage.SetActionsAsDelivered(historyActions); historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "not all actions as delivered marked"); }
internal static extern FileNode cvGetFileNodeByName(FileStorage fs, FileNode map, string name);
internal static extern void cvReadRawData(FileStorage fs, FileNode src, IntPtr dst, string dt);
/// <summary> /// There are no comments for FileStorage in the schema. /// </summary> public void AddToFileStorage(FileStorage fileStorage) { base.AddObject("FileStorage", fileStorage); }
public async Task TestBackgroundActionsTest() { ServiceManager.ReadOnlyForTests = false; ServiceManager.LayoutManager = new LayoutManagerExtend(); Layout resp = JsonConvert.DeserializeObject<Layout>( await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/raw/mock/mock_layout.json", UriKind.RelativeOrAbsolute))), new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); resp?.FromJson(await FileIO.ReadTextAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/raw/mock/layout_request_header.txt", UriKind.RelativeOrAbsolute))), DateTimeOffset.Now); ((LayoutManagerExtend) ServiceManager.LayoutManager).SetLayout(resp); ServiceManager.ReadOnlyForTests = true; FileStorage storage = new FileStorage {Background = true}; await storage.InitStorage(); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("9ded63644e424d758b0218f7c70f2473", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3f30be2605524f82a9bf0ccb4a81618f", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("312a8594e07542bd814ecdd17f76538e", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("959ea393e3424ab7ad53584a8b789197", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)); IStorageService storageService = ServiceManager.StorageService; List<BeaconAction> beaconActions = await storageService.GetActionsForForeground(); Assert.AreEqual(4, beaconActions.Count, "Not 4 actions found"); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("9ded63644e424d758b0218f7c70f2473", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3f30be2605524f82a9bf0ccb4a81618f", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("312a8594e07542bd814ecdd17f76538e", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("959ea393e3424ab7ad53584a8b789197", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)); beaconActions = await storageService.GetActionsForForeground(); Assert.AreEqual(4, beaconActions.Count, "Not 4 actions found"); StorageService service = (StorageService) ServiceManager.StorageService; IStorage foregroundStorage = service.Storage; await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")); await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")); await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")); await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)); IList<HistoryAction> historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(12, historyActions.Count, "Not 12 history actions found"); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("9ded63644e424d758b0218f7c70f2473", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3f30be2605524f82a9bf0ccb4a81618f", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("312a8594e07542bd814ecdd17f76538e", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("959ea393e3424ab7ad53584a8b789197", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)); await foregroundStorage.SetActionsAsDelivered(historyActions); historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(4, historyActions.Count, "Not 4 history actions found"); beaconActions = await storageService.GetActionsForForeground(); Assert.AreEqual(4, beaconActions.Count, "Not 4 actions found"); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("9ded63644e424d758b0218f7c70f2473", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3f30be2605524f82a9bf0ccb4a81618f", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("312a8594e07542bd814ecdd17f76538e", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "")); await storage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("959ea393e3424ab7ad53584a8b789197", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null)); historyActions = await foregroundStorage.GetUndeliveredActions(); await foregroundStorage.SetActionsAsDelivered(historyActions); historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "Not 0 history actions found"); beaconActions = await storageService.GetActionsForForeground(); Assert.AreEqual(4, beaconActions.Count, "Not 4 actions found"); }
/// <summary> /// Create a new FileStorage object. /// </summary> /// <param name="ID">Initial value of Id.</param> /// <param name="location">Initial value of Location.</param> public static FileStorage CreateFileStorage(int ID, string location) { FileStorage fileStorage = new FileStorage(); fileStorage.Id = ID; fileStorage.Location = location; return fileStorage; }
public string ConvertHTMLToMHTML(String HTMLString, String outputFilePath, FileStorage st) { _HtmlFile.setDownLoadedBytes(HTMLString); ValidateFilename(outputFilePath, ".mht"); _HtmlFile.DownloadPath = outputFilePath; _HtmlFile.UseHtmlTitleAsFilename = true; //-- if set to permanent disk storage, make a local copy of the HTML if (st == FileStorage.DiskPermanent) { _HtmlFile.SaveToFile(Path.ChangeExtension(_HtmlFile.DownloadPath, ".htm")); } //-- download all references _HtmlFile.DownloadExternalFiles(st, _AllowRecursion); //-- build the Mht AppendMhtHeader(_HtmlFile); AppendMhtFiles(); FinalizeMht(Path.ChangeExtension(_HtmlFile.DownloadPath, ".mht")); //-- possibly destroy temporary resources if (st == FileStorage.DiskTemporary) { foreach (DictionaryEntry de in WebFiles) { WebFile ef = (WebFile)de.Value; if (ef.Storage == FileStorage.DiskTemporary) { File.Delete(ef.DownloadPath); } //-- if the temp folder is empty, kill that too if (Directory.GetFileSystemEntries(ef.DownloadFolder).Length == 0) { Directory.Delete(ef.DownloadFolder); } } } WebFiles.Clear(); return Path.ChangeExtension(_HtmlFile.DownloadPath, ".mht"); }
/// <summary> /// Saves the file. /// </summary> /// <param name="file">The file.</param> /// <param name="isRootFile">if set to <c>true</c> [is root file].</param> protected virtual void SaveFile(IWebFile file, bool isRootFile) { FileStorage.SaveFile(file, isRootFile); }
private void CreateFileWithRandomDataAndFinishActivity (string fileName, FileStorage storage, string sizeInBytes) { long size = Convert.ToInt32 (sizeInBytes); string filePath = null; try { switch (storage) { case FileStorage.Internal: filePath = Path.Combine (FilesDir.AbsolutePath, fileName); break; case FileStorage.External: if (!Utils.IsExternalStorageAvailable ()) { DisplayShortCenteredToast ("The external storage is not available"); } else { string externalAppDir = GetExternalFilesDir (null).Path; filePath = Path.Combine (externalAppDir, fileName); } break; case FileStorage.DoNotBackup: filePath = Path.Combine (NoBackupFilesDir.AbsolutePath, fileName); break; } if (filePath == null) { Log.Debug (TAG, "Unable to locate file destination path!"); // Returning back to the caller activity. SetResult (Result.Canceled); Finish (); return; } byte[] randomBytes = new byte[size]; var random = new Random (); for (int i = 0; i < randomBytes.Length; i++) randomBytes[i] = (byte)(255 * random.NextDouble ()); File.WriteAllBytes (filePath, randomBytes); string message = string.Format ("File created: {0}, size: {1} bytes", filePath, sizeInBytes); DisplayShortCenteredToast (message); Log.Debug (TAG, message); // Returning back to the caller activity. SetResult (Result.Ok); Finish (); } catch (Exception e) { Log.Error (TAG, e.Message, e); // Returning back to the caller activity. SetResult (Result.Canceled); Finish (); } }
public async Task GetEventInForegroundFromBackgroundStorageTest() { IStorage foregroundStorage = storage; await foregroundStorage.InitStorage(); IStorage backgroundStorage = new FileStorage() {Background = true}; await backgroundStorage.InitStorage(); Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T15:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("1", DateTimeOffset.Parse("2016-04-16T16:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("2", DateTimeOffset.Parse("2016-04-16T17:00:00.000+0000"), BeaconEventType.Enter, null))); Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("3", DateTimeOffset.Parse("2016-04-15T14:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("3", DateTimeOffset.Parse("2016-04-15T15:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("3", DateTimeOffset.Parse("2016-04-15T16:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryEvents(FileStorageHelper.ToHistoryEvent("4", DateTimeOffset.Parse("2016-04-15T17:00:00.000+0000"), BeaconEventType.Enter, null))); //verify every storage api accesses every data IList<HistoryEvent> historyEvents = await backgroundStorage.GetUndeliveredEvents(); HistoryEvent historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-15T15:00:00.000+00:00"); Assert.AreEqual("3", historyEvent.BeaconId, "Wrong pid"); Assert.AreEqual("2016-04-15T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date"); Assert.AreEqual((int) BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger"); historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-16T15:00:00.000+00:00"); Assert.AreEqual("1", historyEvent.BeaconId, "Wrong pid"); Assert.AreEqual("2016-04-16T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date"); Assert.AreEqual((int) BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger"); historyEvents = await foregroundStorage.GetUndeliveredEvents(); historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-15T15:00:00.000+00:00"); Assert.AreEqual("3", historyEvent.BeaconId, "Wrong pid"); Assert.AreEqual("2016-04-15T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date"); Assert.AreEqual((int) BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger"); historyEvent = historyEvents.FirstOrDefault(h => h.EventTime == "2016-04-16T15:00:00.000+00:00"); Assert.AreEqual("1", historyEvent.BeaconId, "Wrong pid"); Assert.AreEqual("2016-04-16T15:00:00.000+00:00", historyEvent.EventTime, "Wrong date"); Assert.AreEqual((int) BeaconEventType.Exit, historyEvent.Trigger, "Wrong trigger"); await backgroundStorage.SetEventsAsDelivered(historyEvents); historyEvents = await backgroundStorage.GetUndeliveredEvents(); Assert.AreEqual(0, historyEvents.Count, "not all events as delivered marked - background"); historyEvents = await foregroundStorage.GetUndeliveredEvents(); Assert.AreEqual(0, historyEvents.Count, "not all events as delivered marked - foreground"); }
internal static extern void cvWriteComment(FileStorage fs, string comment, int eol_comment);
public async Task BackgroundActionStorageTest() { IStorage foregroundStorage = storage; await foregroundStorage.InitStorage(); IStorage backgroundStorage = new FileStorage() {Background = true}; await backgroundStorage.InitStorage(); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); IList<HistoryAction> historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(4, historyActions.Count, "Not 4 actions"); HistoryAction action = historyActions.First(t => t.Trigger == (int) BeaconEventType.Enter); Assert.AreEqual("1", action.BeaconId, "not same pid"); Assert.AreEqual("1", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T12:00:00.000+00:00", action.ActionTime, "not same date"); action = historyActions.First(t => t.Trigger == (int) BeaconEventType.Exit); Assert.AreEqual("2", action.BeaconId, "not same pid"); Assert.AreEqual("2", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T13:00:00.000+00:00", action.ActionTime, "not same date"); historyActions = await foregroundStorage.GetUndeliveredActions(); await foregroundStorage.SetActionsAsDelivered(historyActions); historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "not all actions as delivered marked"); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("5", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(4, historyActions.Count, "Not 4 actions"); action = historyActions.First(t => t.Trigger == (int) BeaconEventType.Enter); Assert.AreEqual("1", action.BeaconId, "not same pid"); Assert.AreEqual("4", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T12:00:00.000+00:00", action.ActionTime, "not same date"); action = historyActions.First(t => t.Trigger == (int) BeaconEventType.Exit); Assert.AreEqual("2", action.BeaconId, "not same pid"); Assert.AreEqual("5", action.EventId, "not same eid"); Assert.AreEqual("2016-04-16T13:00:00.000+00:00", action.ActionTime, "not same date"); historyActions = await backgroundStorage.GetUndeliveredActions(); await backgroundStorage.SetActionsAsDelivered(historyActions); historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "not all actions as delivered marked"); }
internal static extern void cvStartNextStream(FileStorage fs);
public async Task GetBackgroundActionsFromBackgroundinForegroundTest() { IStorage foregroundStorage = storage; await foregroundStorage.InitStorage(); IStorage backgroundStorage = new FileStorage() {Background = true}; await backgroundStorage.InitStorage(); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue( await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "31231231"))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, null))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("5", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, ""))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); Assert.IsTrue(await backgroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("1", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, "1"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("2", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, "2"))); Assert.IsTrue( await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, "31231231"))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("3", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("4", "1", DateTimeOffset.Parse("2016-04-16T12:00:00.000+0000"), BeaconEventType.Enter, null))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("5", "2", DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), BeaconEventType.Exit, ""))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "3", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); Assert.IsTrue(await foregroundStorage.SaveHistoryAction(FileStorageHelper.ToHistoryAction("6", "2", DateTimeOffset.Parse("2016-04-16T14:00:00.000+0000"), BeaconEventType.EnterExit, null))); TaskCompletionSource<bool> source = new TaskCompletionSource<bool>(); ((FileStorage)foregroundStorage).ForegroundHistoryActionWriter.QueueEmpty += () => source.SetResult(true); await source.Task; IList<HistoryAction> historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(16, historyActions.Count, "Not 16 actions"); historyActions = await foregroundStorage.GetUndeliveredActions(); Assert.AreEqual(16, historyActions.Count, "Not 16 actions"); // HistoryAction dbHistoryAction = await backgroundStorage.GetAction("5"); // Assert.AreEqual((int) BeaconEventType.Exit, dbHistoryAction.Trigger, "not same type"); // Assert.AreEqual("2", dbHistoryAction.BeaconId, "not same pid"); // Assert.AreEqual("5", dbHistoryAction.EventId, "not same eid"); // Assert.AreEqual(DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), DateTimeOffset.Parse(dbHistoryAction.ActionTime), "not same date"); // dbHistoryAction = await foregroundStorage.GetAction("5"); // Assert.AreEqual((int) BeaconEventType.Exit, dbHistoryAction.Trigger, "not same type"); // Assert.AreEqual("2", dbHistoryAction.BeaconId, "not same pid"); // Assert.AreEqual("5", dbHistoryAction.EventId, "not same eid"); // Assert.AreEqual(DateTimeOffset.Parse("2016-04-16T13:00:00.000+0000"), DateTimeOffset.Parse(dbHistoryAction.ActionTime), "not same date"); // IList<HistoryAction> dbHistoryActions = await backgroundStorage.GetActions("6"); // Assert.AreEqual(4, dbHistoryActions.Count, "Not 4 actions"); // dbHistoryActions = await foregroundStorage.GetActions("6"); // Assert.AreEqual(4, dbHistoryActions.Count, "Not 4 actions"); historyActions = await backgroundStorage.GetUndeliveredActions(); await foregroundStorage.SetActionsAsDelivered(historyActions); historyActions = await backgroundStorage.GetUndeliveredActions(); Assert.AreEqual(0, historyActions.Count, "not all actions as delivered marked"); }
internal static extern StringHashNode cvGetHashedKey( FileStorage fs, string name, int len, int create_missing);
/// <summary> /// Write detector to FileStorage. /// </summary> /// <param name="fs">FileStorage for output</param> public void Write(FileStorage fs) { XObjdetectInvoke.cveWBDetectorWrite(_ptr, fs); }
internal static extern FileNode cvGetFileNode( FileStorage fs, FileNode map, StringHashNode key, int create_missing);
private async Task <ContentItem> RefreshContentFromFile(string fileName, ContentItem cachedItem, TimeSpan expiresIn) { using (Trace.Activity("Downloading Content Item: " + fileName)) { IFileReference reference = await FileStorage.GetFileReferenceAsync( CoreConstants.Folders.ContentFolderName, fileName, ifNoneMatch : cachedItem?.ContentId); if (reference == null) { Trace.Error("Requested Content File Not Found: " + fileName); return(null); } // Check the content ID to see if it's different if (cachedItem != null && String.Equals(cachedItem.ContentId, reference.ContentId, StringComparison.Ordinal)) { Trace.Verbose("No change to content item. Using Cache"); // Update the expiry time cachedItem.ExpiryUtc = DateTime.UtcNow + expiresIn; Trace.Verbose($"Updating Cache: {fileName} expires at {cachedItem.ExpiryUtc}"); return(cachedItem); } // Retrieve the content Trace.Verbose("Content Item changed. Trying to update..."); try { using (var stream = reference.OpenRead()) { if (stream == null) { Trace.Error("Requested Content File Not Found: " + fileName); return(null); } else { using (Trace.Activity("Reading Content File: " + fileName)) { using (var reader = new StreamReader(stream)) { string text = await reader.ReadToEndAsync(); string content; if (fileName.EndsWith(".md")) { content = new Markdown().Transform(text); } else { content = text; } IHtmlString html = new HtmlString(content.Trim()); // Prep the new item for the cache var expiryTime = DateTime.UtcNow + expiresIn; return(new ContentItem(html, expiryTime, reference.ContentId, DateTime.UtcNow)); } } } } } catch (Exception) { Debug.Assert(false, "owchy oochy - reading content failed"); Trace.Error("Reading updated content failed. Returning cached content instead."); return(cachedItem); } } }
internal static extern IntPtr cvRead(FileStorage fs, FileNode node, IntPtr attributes);
/// <summary> /// Creates a transaction to transfers funds from an old federation to a new federation. /// </summary> /// <param name="isSideChain">Indicates whether the <paramref name="network"/> is the sidechain.</param> /// <param name="network">The network that we are creating the recovery transaction for.</param> /// <param name="counterChainNetwork">The counterchain network.</param> /// <param name="dataDirPath">The root folder containing the old federation.</param> /// <param name="redeemScript">The new redeem script.</param> /// <param name="password">The password required to generate transactions using the federation wallet.</param> /// <param name="txTime">Any deposits beyond this UTC date will be ignored when selecting coin inputs.</param> /// <returns>A funds recovery transaction that moves funds to the new redeem script.</returns> public FundsRecoveryTransactionModel CreateFundsRecoveryTransaction(bool isSideChain, Network network, Network counterChainNetwork, string dataDirPath, Script redeemScript, string password, DateTime txTime) { var model = new FundsRecoveryTransactionModel() { Network = network, IsSideChain = isSideChain, RedeemScript = redeemScript }; // Get the old redeem script from the wallet file. PayToMultiSigTemplateParameters multisigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript); string theChain = isSideChain ? "sidechain" : "mainchain"; var nodeSettings = new NodeSettings(network, args: new string[] { $"datadir={dataDirPath}", $"redeemscript={redeemScript}", $"-{theChain}" }); var walletFileStorage = new FileStorage <FederationWallet>(nodeSettings.DataFolder.WalletPath); FederationWallet wallet = walletFileStorage.LoadByFileName("multisig_wallet.json"); Script oldRedeemScript = wallet.MultiSigAddress.RedeemScript; PayToMultiSigTemplateParameters oldMultisigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(oldRedeemScript); model.oldMultisigAddress = oldRedeemScript.Hash.GetAddress(network); model.newMultisigAddress = redeemScript.Hash.GetAddress(network); // Create dummy inputs to avoid errors when constructing FederatedPegSettings. var extraArgs = new Dictionary <string, string>(); extraArgs[FederatedPegSettings.FederationIpsParam] = oldMultisigParams.PubKeys.Select(p => "0.0.0.0".ToIPEndPoint(nodeSettings.Network.DefaultPort)).Join(","); var privateKey = Key.Parse(wallet.EncryptedSeed, password, network); extraArgs[FederatedPegSettings.PublicKeyParam] = privateKey.PubKey.ToHex(network); (new TextFileConfiguration(extraArgs.Select(i => $"{i.Key}={i.Value}").ToArray())).MergeInto(nodeSettings.ConfigReader); model.PubKey = privateKey.PubKey; var dBreezeSerializer = new DBreezeSerializer(network.Consensus.ConsensusFactory); var blockStore = new BlockRepository(network, nodeSettings.DataFolder, nodeSettings.LoggerFactory, dBreezeSerializer); blockStore.Initialize(); var chain = new ChainRepository(nodeSettings.LoggerFactory, new ChainStore(), network); Block genesisBlock = network.GetGenesis(); ChainedHeader tip = chain.LoadAsync(new ChainedHeader(genesisBlock.Header, genesisBlock.GetHash(), 0)).GetAwaiter().GetResult(); var chainIndexer = new ChainIndexer(network, tip); var nodeLifetime = new NodeLifetime(); IDateTimeProvider dateTimeProvider = DateTimeProvider.Default; var federatedPegSettings = new FederatedPegSettings(nodeSettings); var opReturnDataReader = new OpReturnDataReader(nodeSettings.LoggerFactory, new CounterChainNetworkWrapper(counterChainNetwork)); var walletFeePolicy = new WalletFeePolicy(nodeSettings); var walletManager = new FederationWalletManager(nodeSettings.LoggerFactory, network, chainIndexer, nodeSettings.DataFolder, walletFeePolicy, new AsyncProvider(nodeSettings.LoggerFactory, new Signals(nodeSettings.LoggerFactory, new DefaultSubscriptionErrorHandler(nodeSettings.LoggerFactory)), nodeLifetime), nodeLifetime, dateTimeProvider, federatedPegSettings, new WithdrawalExtractor(nodeSettings.LoggerFactory, federatedPegSettings, opReturnDataReader, network), blockStore); walletManager.Start(); walletManager.EnableFederationWallet(password); if (!walletManager.IsFederationWalletActive()) { throw new ArgumentException($"Could not activate the federation wallet on {network}."); } // Retrieves the unspent outputs in deterministic order. List <Stratis.Features.FederatedPeg.Wallet.UnspentOutputReference> coinRefs = walletManager.GetSpendableTransactionsInWallet().ToList(); // Exclude coins (deposits) beyond the transaction (switch-over) time! coinRefs = coinRefs.Where(r => r.Transaction.CreationTime < txTime).ToList(); if (!coinRefs.Any()) { throw new ArgumentException($"There are no coins to recover from the federation wallet on {network}."); } Money fee = federatedPegSettings.GetWithdrawalTransactionFee(coinRefs.Count()); var builder = new TransactionBuilder(network); builder.AddKeys(privateKey); builder.AddCoins(coinRefs.Select(c => ScriptCoin.Create(network, c.Transaction.Id, (uint)c.Transaction.Index, c.Transaction.Amount, c.Transaction.ScriptPubKey, oldRedeemScript))); // Split the coins into multiple outputs. Money amount = coinRefs.Sum(r => r.Transaction.Amount) - fee; const int numberOfSplits = 10; Money splitAmount = new Money((long)amount / numberOfSplits); var recipients = new List <Stratis.Features.FederatedPeg.Wallet.Recipient>(); for (int i = 0; i < numberOfSplits; i++) { Money sendAmount = (i != (numberOfSplits - 1)) ? splitAmount : amount - splitAmount * (numberOfSplits - 1); builder.Send(redeemScript.PaymentScript, sendAmount); } builder.SetTimeStamp((uint)(new DateTimeOffset(txTime)).ToUnixTimeSeconds()); builder.CoinSelector = new DeterministicCoinSelector(); builder.SendFees(fee); model.tx = builder.BuildTransaction(true); File.WriteAllText(Path.Combine(dataDirPath, $"{network.Name}_{model.PubKey.ToHex(network).Substring(0, 8)}.hex"), model.tx.ToHex(network)); // Merge our transaction with other transactions which have been placed in the data folder. Transaction oldTransaction = model.tx; string namePattern = $"{network.Name}_*.hex"; int sigCount = 1; foreach (string fileName in Directory.EnumerateFiles(dataDirPath, namePattern)) { Transaction incomingPartialTransaction = network.CreateTransaction(File.ReadAllText(fileName)); // Don't merge with self. if (incomingPartialTransaction.GetHash() == oldTransaction.GetHash()) { continue; } // Transaction times must match. //if (incomingPartialTransaction is PosTransaction && incomingPartialTransaction.Time != model.tx.Time) //{ // Console.WriteLine($"The locally generated transaction is time-stamped differently from the transaction contained in '{fileName}'. The imported signature can't be used."); // continue; //} // Combine signatures. Transaction newTransaction = SigningUtils.CheckTemplateAndCombineSignatures(builder, model.tx, new[] { incomingPartialTransaction }); if (oldTransaction.GetHash() == newTransaction.GetHash()) { Console.WriteLine($"The locally generated transaction is not similar to '{fileName}'. The imported signature can't be used."); continue; } model.tx = newTransaction; sigCount++; } Console.WriteLine($"{sigCount} of {multisigParams.SignatureCount} signatures collected for {network.Name}."); if (sigCount >= multisigParams.SignatureCount) { if (builder.Verify(model.tx)) { // Write the transaction to file. File.WriteAllText(Path.Combine(dataDirPath, $"{(txTime > DateTime.Now ? "Preliminary " : "")}{network.Name}Recovery.txt"), model.tx.ToHex(network)); } else { Console.WriteLine("Could not verify the transaction."); } } // Stop the wallet manager to release the database folder. nodeLifetime.StopApplication(); walletManager.Stop(); return(model); }
Stream IDataServiceStreamProvider.GetWriteStream(object entity, string Etag, bool? checkETagForEquality, DataServiceOperationContext host) { //Debug.Assert(entity is InternalPicture, "Unexpected entity type!"); InternalPicture pict = entity as InternalPicture; if (pict != null) { string filename = host.RequestHeaders.AllKeys.Contains("Slug") ? host.RequestHeaders["Slug"] : string.Format("{0}.txt", Guid.NewGuid()); if (filename.Contains(@"FAIL")) throw new InvalidOperationException("'FAIL' in Slug :: Test hook for exception!"); string contentType = host.RequestHeaders.AllKeys.Contains("Content-Type") ? host.RequestHeaders["Content-Type"] : null; if (this.GetEntityState(pict) != EntityState.Added) { this.LoadFileStorageIfItsNotLoaded(pict, "PT.FK_FileStorage_InternalPictures1", "FileStorage"); if (pict.FileStorage != null) { if (checkETagForEquality != null) { // the value of checkETagForEquality should be "True" (if-match header). This code does not understand "False" value (if-none-match header). if (!(bool)checkETagForEquality) throw new NotSupportedException("The service does not support if-none-match header !"); // if etag does not match, return 412 -> Precondition failed // ETag value is timestamp of the storage file var creationTime = System.Data.Test.Astoria.FullTrust.TrustedMethods.GetFileCreationTime(DataPath(pict.FileStorage.Location)); string fileCreationTimeStamp = string.Concat("\"", creationTime.ToString("dd MMMM yyyy hh:mm:ss.ffffff", System.Globalization.DateTimeFormatInfo.InvariantInfo), "\""); if (fileCreationTimeStamp != Etag) { throw new DataServiceException(412, string.Format("Etag values does not match, expected: {0}, actual: {1}", Etag, fileCreationTimeStamp)); } } pict.FileStorage.ContentType = contentType; pict.FileStorage.Location = filename; } else { // else - trouble, incosistent data - 500(internal error) throw new DataServiceException("Inconsistent data found, giving up!"); } } else { FileStorage fs = new FileStorage { ContentType = contentType, Location = filename, Picture = pict }; entityContext.AddObject("FileStorage", fs); } return new System.Data.Test.Astoria.FullTrust.TrustedFileStream(DataPath(filename), FileMode.Create, FileAccess.Write, FileShare.Write); } else { throw new NotSupportedException("Unexpected entity type!"); } }
public void Cs1GameInit() { int CurrentProgress = 0; int TotalProgress = 4; bool shouldAutoCloseWindow = true; try { Progress.Message("Checking Sen1Launcher.exe...", CurrentProgress++, TotalProgress); using (var fs = new HyoutaUtils.Streams.DuplicatableFileStream(Sen1LauncherPath)) { SHA1 hash = ChecksumUtils.CalculateSHA1ForEntireStream(fs); if (hash != new SHA1(0x8dde2b39f128179aul, 0x0beb3301cfd56a98ul, 0xc0f98a55u)) { Progress.Error("Selected file does not appear to be Sen1Launcher.exe of version 1.6."); Progress.Finish(false); return; } } } catch (Exception ex) { Progress.Error("Error while validating Sen1Launcher.exe: " + ex.Message); Progress.Finish(false); return; } try { Path = System.IO.Path.GetDirectoryName(Sen1LauncherPath); Progress.Message("Checking if we have encoding errors in filenames...", CurrentProgress++, TotalProgress); if (FilenameFix.FixupIncorrectEncodingInFilenames(Path, 1, false, Progress)) { if (!FilenameFix.FixupIncorrectEncodingInFilenames(Path, 1, true, Progress)) { Progress.Error("Failed to fix encoding errors in filenames, attempting to proceed anyway..."); shouldAutoCloseWindow = false; } } Progress.Message("Initializing patch data...", CurrentProgress++, TotalProgress); var files = Sen1KnownFiles.Files; Progress.Message("Initializing game data...", CurrentProgress++, TotalProgress); var storageInit = FileModExec.InitializeAndPersistFileStorage(Path, files, Progress); Storage = storageInit?.Storage; if (storageInit == null || storageInit.Errors.Count != 0) { shouldAutoCloseWindow = false; } } catch (Exception ex) { Progress.Error("Error while initializing CS1 patch/game data: " + ex.Message); Progress.Finish(false); return; } ShouldProceedToPatchOptionWindow = Path != null && Storage != null; if (shouldAutoCloseWindow) { Progress.Message("Initialized CS1 data, proceeding to patch options...", CurrentProgress, TotalProgress); } else { Progress.Message("", CurrentProgress, TotalProgress); if (ShouldProceedToPatchOptionWindow) { Progress.Error( "Encountered problems while initializing CS1 data. " + "Closing this window will proceed to the patch options anyway, but be aware that some patches may not work correctly. " + "It is recommended to verify the game files using Steam or GOG Galaxy's build-in feature to do so, or to reinstall the game. " + "Please also ensure you're trying to patch a compatible version of the game. (XSEED release version 1.6; other game versions are not compatible)" ); } else { Progress.Error( "Unrecoverable issues while initializing CS1 data. " + "Please ensure SenPatcher has read and write access to the selected game directory, then try again." ); } } Progress.Finish(shouldAutoCloseWindow); }
/// <summary> /// Serializes this object to a given cv::FileStorage. /// </summary> /// <param name="fs"></param> public virtual void Save(FileStorage fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); NativeMethods.face_FaceRecognizer_save2(ptr, fs.CvPtr); }
/// <summary> /// Deserializes this object from a given cv::FileStorage. /// </summary> /// <param name="fs"></param> public virtual void Load(FileStorage fs) { if (fs == null) throw new ArgumentNullException("fs"); NativeMethods.face_FaceRecognizer_load2(ptr, fs.CvPtr); }
public IEnumerable <FileModResult> TryApply(FileStorage storage) { var s = storage.TryGetDuplicate(GetExecutableHash()); if (s == null) { return(null); } MemoryStream ms = s.CopyToMemoryAndDispose(); Sen1ExecutablePatchState PatchInfo = new Sen1ExecutablePatchState(IsJp); PatchInfo.InitCodeSpaceIfNeeded(ms); if (RemoveTurboSkip) { Sen1ExecutablePatches.PatchJumpBattleAnimationAutoSkip(ms, PatchInfo); Sen1ExecutablePatches.PatchJumpBattleResultsAutoSkip(ms, PatchInfo); } if (AllowR2NotebookShortcut) { Sen1ExecutablePatches.PatchJumpR2NotebookOpen(ms, PatchInfo); Sen1ExecutablePatches.PatchJumpR2NotebookSettings(ms, PatchInfo); } if (TurboKey >= 0 && TurboKey <= 0xF) { Sen1ExecutablePatches.PatchButtonBattleAnimationAutoSkip(ms, PatchInfo, (byte)TurboKey); Sen1ExecutablePatches.PatchButtonBattleResultsAutoSkip(ms, PatchInfo, (byte)TurboKey); Sen1ExecutablePatches.PatchButtonTurboMode(ms, PatchInfo, (byte)TurboKey); } if (FixTextureIds) { Sen1ExecutablePatches.PatchThorMasterQuartzString(ms, PatchInfo); } if (CorrectLanguageVoiceTables) { Sen1ExecutablePatches.PatchLanguageAppropriateVoiceTables(ms, PatchInfo); } if (DisableMouseCapture) { Sen1ExecutablePatches.PatchDisableMouseCapture(ms, PatchInfo); } if (DisablePauseOnFocusLoss) { Sen1ExecutablePatches.PatchDisablePauseOnFocusLoss(ms, PatchInfo); } // add indicator to the title screen that we're running a modified executable ms.Position = PatchInfo.Mapper.MapRamToRom(PatchInfo.PushAddressVersionString); uint addressVersionString = ms.ReadUInt32(EndianUtils.Endianness.LittleEndian); ms.Position = PatchInfo.Mapper.MapRamToRom(addressVersionString); string versionString = ms.ReadAsciiNullterm(); string newVersionString = versionString + " SenPatcher " + Version.SenPatcherVersion; MemoryStream newVersionStringStream = new MemoryStream(); newVersionStringStream.WriteAsciiNullterm(newVersionString); byte[] newVersionStringBytes = newVersionStringStream.CopyToByteArrayAndDispose(); var regionStrings = PatchInfo.RegionScriptCompilerFunctionStrings; uint addressNewVersionString = regionStrings.Address; ms.Position = PatchInfo.Mapper.MapRamToRom(regionStrings.Address); ms.Write(newVersionStringBytes); regionStrings.TakeToAddress(PatchInfo.Mapper.MapRomToRam(ms.Position), "SenPatcher version string"); ms.Position = PatchInfo.Mapper.MapRamToRom(PatchInfo.PushAddressVersionString); ms.WriteUInt32(addressNewVersionString, EndianUtils.Endianness.LittleEndian); ms.Position = 0; return(new FileModResult[] { new FileModResult(IsJp ? "ed8jp.exe" : "ed8.exe", ms) }); }
/// <summary> /// <para> /// Initializes a new <see cref="HelloWorldTrigger"/> instance. /// </para> /// <para></para> /// </summary> /// <param name="storage"> /// <para>A git hub api.</para> /// <para></para> /// </param> /// <param name="fileStorage"> /// <para>A file storage.</para> /// <para></para> /// </param> /// <param name="fileSetName"> /// <para>A file set name.</para> /// <para></para> /// </param> public HelloWorldTrigger(GitHubStorage storage, FileStorage fileStorage, string fileSetName) { this._storage = storage; this._fileStorage = fileStorage; this._fileSetName = fileSetName; }
internal static extern void cvStartWriteStruct( FileStorage fs, string name, StructStorageFlags struct_flags, string type_name, AttrList attributes);
internal static extern void cvEndWriteStruct(FileStorage fs);
/// <summary> /// Saves URL to disk as a single file Mht archive /// if a folder is provided instead of a filename, the TITLE tag is used to name the file /// </summary> /// <param name="outputFilePath">path to generate to, or filename to generate</param> /// <param name="st">type of storage to use when generating the Mht archive</param> /// <param name="url">fully qualified URL you wish to save as Mht</param> /// <returns>the complete path of the Mht archive file that was generated</returns> public string SavePageArchive(String outputFilePath, FileStorage st, params String[] url) { String URL = String.Empty; if (url.Length > 0) URL = url[0]; ValidateFilename(outputFilePath, ".mht"); // check this to see wotDownloadHtmlFile(URL)does if URL == null if (URL != null) { DownloadHtmlFile(URL); } _HtmlFile.DownloadPath = outputFilePath; _HtmlFile.UseHtmlTitleAsFilename = true; //-- if set to permanent disk storage, make a local copy of the HTML if (st == FileStorage.DiskPermanent) { _HtmlFile.SaveToFile(Path.ChangeExtension(_HtmlFile.DownloadPath, ".htm")); } //-- download all references _HtmlFile.DownloadExternalFiles(st, _AllowRecursion); //-- build the Mht AppendMhtHeader(_HtmlFile); AppendMhtFiles(); FinalizeMht(Path.ChangeExtension(_HtmlFile.DownloadPath, ".mht")); //-- possibly destroy temporary resources if (st == FileStorage.DiskTemporary) { foreach (DictionaryEntry de in WebFiles) { WebFile ef = (WebFile)de.Value; if (ef.Storage == FileStorage.DiskTemporary) { File.Delete(ef.DownloadPath); } //-- if the temp folder is empty, kill that too if (Directory.GetFileSystemEntries(ef.DownloadFolder).Length == 0) { Directory.Delete(ef.DownloadFolder); } } } WebFiles.Clear(); return Path.ChangeExtension(_HtmlFile.DownloadPath, ".mht"); }
internal static extern void cvWriteInt(FileStorage fs, string name, int value);
public void Initialize() { storage = new FileStorage(); }
internal static extern void cvWriteReal(FileStorage fs, string name, double value);
private void InitFileStorageSpinner () { var spinner = FindViewById<Spinner> (Resource.Id.storage_spinner); var adapter = ArrayAdapter.CreateFromResource (this, Resource.Array.file_storage_array, Android.Resource.Layout.SimpleSpinnerItem); adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = adapter; spinner.ItemSelected += delegate (object sender, AdapterView.ItemSelectedEventArgs e) { fileStorage = (FileStorage) e.Position; }; }
internal static extern void cvWriteString(FileStorage fs, string name, string str, int quote);
protected override void OnResume () { base.OnResume (); // If an intent has extra parameters, create the file and finish the activity. if (Intent.HasExtra (FILE_NAME) && Intent.HasExtra (FILE_SIZE_IN_BYTES)) { string fileName = Intent.GetStringExtra (FILE_NAME); string sizeInBytesParamValue = Intent.GetStringExtra (FILE_SIZE_IN_BYTES); string fileStorageParamValue = FileStorage.Internal.ToString (); if (Intent.HasExtra (FILE_STORAGE)) fileStorageParamValue = Intent.GetStringExtra (FILE_STORAGE); if (TextUtils.IsEmpty (fileName) || DoesFileExist (fileName) || !IsSizeValid (sizeInBytesParamValue) || !IsFileStorageParamValid (fileStorageParamValue)) { SetResult (Result.Canceled); Finish (); return; } fileStorage = (FileStorage)Enum.Parse (typeof (FileStorage), fileStorageParamValue); if (fileStorage == FileStorage.External && !Utils.IsExternalStorageAvailable ()) { SetResult (Result.Canceled); Finish (); return; } CreateFileWithRandomDataAndFinishActivity (fileName, fileStorage, sizeInBytesParamValue); } }
public void ReadAndWriteInMemory() { var sequence = new[] { "image1.jpg", "myfi.png", "../data/baboon.jpg" }; var map = new { @int = 12345, @double = 3.14159, @string = "foo" }; var mapSequence = new { vec2b = new Vec2b(255, 128), rect = new Rect(1, 2, 3, 4), size = new Size(10, 20), point = new Point(300, 400) }; // write string yaml; using (var fs = new FileStorage("yml", FileStorage.Mode.Write | FileStorage.Mode.Memory)) { fs.Add("sequence").Add("["); foreach (var s in sequence) { fs.Add(s); } fs.Add("]"); fs.Add("empty_sequence").Add("[").Add("]"); fs.Add("map").Add("{") .Add("int").Add(map.@int) .Add("double").Add(map.@double) .Add("string").Add(map.@string) .Add("}"); fs.Add("map_sequence").Add("[") .Add("{") .Add("vec2b").Add(mapSequence.vec2b) .Add("rect").Add(mapSequence.rect) .Add("}").Add("{") .Add("size").Add(mapSequence.size) .Add("point").Add(mapSequence.point) .Add("}") .Add("]"); using (Mat r = Mat.Eye(3, 3, MatType.CV_64FC1)) using (Mat t = Mat.Ones(3, 1, MatType.CV_64FC1)) using (Mat lenna = Image("lenna.png")) { fs.Write("R", r); fs.Write("T", t); fs.Write("lenna", lenna); } yaml = fs.ReleaseAndGetString(); } // check truncation because of StringBuilder capacity Assert.EndsWith("]", yaml.TrimEnd()); // read using (var fs = new FileStorage(yaml, FileStorage.Mode.Read | FileStorage.Mode.Memory)) { Assert.True(fs.IsOpened()); // sequence using (FileNode node = fs["sequence"]) { Assert.NotNull(node); Assert.Equal(FileNode.Types.Seq, node.Type); // C++ style sequence reading FileNodeIterator it = node.Begin(), end = node.End(); for (int i = 0; !it.Equals(end); it.MoveNext(), i++) { var s = it.Current.ReadString(); Assert.Equal(sequence[i], s); } // C# style int j = 0; foreach (var n in node) { var s = n.ReadString(); Assert.Equal(sequence[j++], s); } } // empty_sequence using (FileNode node = fs["empty_sequence"]) { Assert.NotNull(node); Assert.Equal(FileNode.Types.Seq, node.Type); var children = node.ToArray(); Assert.Empty(children); } // map using (FileNode node = fs["map"]) { Assert.NotNull(node); Assert.Equal(FileNode.Types.Map, node.Type); Assert.Equal(map.@int, node["int"].ReadInt()); Assert.Equal(map.@double, node["double"].ReadDouble()); Assert.Equal(map.@string, node["string"].ReadString()); } // map_sequence using (FileNode node = fs["map_sequence"]) { Assert.NotNull(node); Assert.Equal(FileNode.Types.Seq, node.Type); using (var elem0 = node.ElementAt(0)) using (var elem1 = node.ElementAt(1)) { Assert.Equal(mapSequence.vec2b, elem0["vec2b"].ReadVec2b()); Assert.Equal(mapSequence.rect, elem0["rect"].ReadRect()); Assert.Equal(mapSequence.size, elem1["size"].ReadSize()); Assert.Equal(mapSequence.point, elem1["point"].ReadPoint()); } } // mat using (Mat r = fs["R"].ReadMat()) using (Mat t = fs["T"].ReadMat()) { Console.WriteLine("R = {0}", r); Console.WriteLine("T = {0}", t); Assert.Equal(1.0, r.Get <double>(0, 0)); Assert.Equal(0.0, r.Get <double>(0, 1)); Assert.Equal(0.0, r.Get <double>(0, 2)); Assert.Equal(0.0, r.Get <double>(1, 0)); Assert.Equal(1.0, r.Get <double>(1, 1)); Assert.Equal(0.0, r.Get <double>(1, 2)); Assert.Equal(0.0, r.Get <double>(2, 0)); Assert.Equal(0.0, r.Get <double>(2, 1)); Assert.Equal(1.0, r.Get <double>(2, 2)); Assert.Equal(1.0, t.Get <double>(0)); Assert.Equal(1.0, t.Get <double>(1)); Assert.Equal(1.0, t.Get <double>(2)); } using (Mat storedLenna = fs["lenna"].ReadMat()) using (Mat lenna = Image("lenna.png")) { ImageEquals(storedLenna, lenna); } } }