/// <summary> /// Initializes a new instance of the FileAdapterConnectionFactory class /// </summary> public FileAdapterConnectionFactory(ConnectionUri connectionUri , ClientCredentials clientCredentials , FileAdapter adapter) { this.clientCredentials = clientCredentials; this.adapter = adapter; this.ConnectionUri = connectionUri as FileAdapterConnectionUri; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); ActionBar.Hide(); mFileAlbum = new FileAlbum(); SetFileData(); //Dictionary<string, Permission> users = new Dictionary<string, Permission>(); //users.Add(this.userController.CurrentUser.UserName, Permission.Owner); //byte[] content = new byte[10]; //File testFile = new File(); //testFile.Users = users; //testFile.GUID = "675_2;"; //testFile.Content = content; //testFile.Extension = ".txt"; //testFile.Name = "fileTwo"; //FileController controller = new FileController(); //controller.UploadFile(testFile); // mCommonAlbum = new CommonAlbum(); /* * This code is how to replace the placeholder layout that's part of the CommonLayout. */ FrameLayout frame = FindViewById <FrameLayout>(Resource.Id.Common_FrameLayout); View file = LayoutInflater.Inflate(Resource.Layout.FilePage, null); // Replace the inside of this method call with your desired layout frame.AddView(file.FindViewById <LinearLayout>(Resource.Id.File_Layout)); SetUpNavBar(); Button AddFileBtn = FindViewById <Button>(Resource.Id.FilePage_AddFileButton); AddFileBtn.Click += UploadClick; StudyApp.Assets.Models.File fileOne = new StudyApp.Assets.Models.File(); /* * This method needs to be called on the OnCreate method for any activities inheriting from CommonActivity, * since this is what initializes the navbar */ mRecyclerView = FindViewById <RecyclerView>(Resource.Id.recyclerView); // Plug in the linear layout manager: mLayoutManager = new LinearLayoutManager(this); mRecyclerView.SetLayoutManager(mLayoutManager); // Plug in my adapter: mAdapter = new FileAdapter(mFileAlbum, this, this.userController.CurrentUser); mRecyclerView.SetAdapter(mAdapter); }
void DataRead(GLib.Object obj, GLib.AsyncResult res) { File file = FileAdapter.GetObject(obj); Regex keyValueRegex = new Regex( @"(^(\s)*(?<Key>([^\=^\n]+))[\s^\n]*\=(\s)*(?<Value>([^\n]+(\n){0,1})))", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.CultureInvariant ); using (DataInputStream stream = new DataInputStream(file.ReadFinish(res))) { ulong len; string line; while ((line = stream.ReadLine(out len, null)) != null) { line = line.Trim(); Match match = keyValueRegex.Match(line); if (match.Success) { string key = match.Groups["Key"].Value; string val = match.Groups["Value"].Value; if (key.Equals(NameTag)) { Name = val; } else if (key.Equals(DescTag)) { Description = val; } else if (key.Equals(AppUriTag)) { AppUri = val; } else if (key.Equals(IconTag)) { if (val.StartsWith("./") && val.Length > 2) { IconFile = file.Parent.GetChild(val.Substring(2)); if (IconFile.Exists) { Icon = DockServices.Drawing.LoadIcon(IconFile.Path + ";;extension"); } } else { Icon = DockServices.Drawing.LoadIcon(val + ";;extension", 128); } } } } } OnDataReady(); }
/// <summary> /// Zapisuje plik z danymi wycieczki na dysk /// </summary> public bool SaveFileForTrip(Trip trip, String filename) { /// <summary> /// Opis /// </summary> FileAdapter<Trip> forTrip = new FileAdapter<Trip>(); /// <summary> /// Opis /// </summary> return true; }
public async Task <IActionResult> CreatePost([FromForm] PostDto dto) { var result = await Mediator.Send(new CreatePostRequest { Title = dto.Title, Body = dto.Body, AuthorId = CurrentUserId !.Value, Tags = dto.Tags, PreviewBody = dto.PreviewBody, PreviewImage = new FileAdapter(dto.PreviewImage) });
public void MemoryFileSystem_FolderStruct() { var folderPath = "A:\\TestFolder\\Test"; var content = "This is test string"; using var fileSystem = CreateTestMemoryFile(folderPath, content); fileSystem.PrintTo(Console.Out); var adapter = new FileAdapter(fileSystem); var actual = adapter.GetFileNames(folderPath); Assert.IsTrue(actual.Count > 0); }
public RequestBuilder Handler(string file, string provider, int fileNumber) { ObjectAdapter adapter = FileAdapter.Csv(file); IEnumerable <ValidationRecordCsv> records = adapter.Records <ValidationRecordCsv>(true); if (records.Any(r => !r.IsValid)) { return(new BadRequstBuilder(file, records.Where(r => !r.IsValid))); } return(new ValidationRequestBuilder(file, records.Where(r => r.IsValid), provider, fileNumber, 10000)); }
/// <summary> /// Tömeges törléshez: /// ID alapján törli a megadott mappát és tartalmát /// </summary> /// <param name="ids"></param> public void deleteFolderMulti(HashSet <string> ids) { foreach (string item in ids) { FileAdapter fa = new FileAdapter(item); if (fa.folderExists()) { fa.deleteFolder(); } } }
public void Test_ReturnsList() { // arrange var sut = new FileAdapter(); var expected = 0; // act var actual = fa; // assert Assert.True(expected <= actual.Count()); }
public RequestBuilder Handler(string file, string provider, int fileNumber) { ObjectAdapter adapter = FileAdapter.Load(file, new SpireXlsLoader()); IEnumerable <IdentificationRecordExcel> records = adapter.Records <IdentificationRecordExcel>(true); if (records.Any(r => !r.IsValid)) { return(new BadRequstBuilder(file, records.Where(r => !r.IsValid))); } return(new IdentificationRequestBuilder(file, records.Where(r => r.IsValid), provider, fileNumber, 10000)); }
/// <summary> /// Gets the data. /// </summary> /// <returns></returns> /// <exception cref="PK2NotLoadedException"></exception> /// <exception cref="System.InvalidOperationException">It's impossible to read data from a directory or from a deleted file.</exception> public byte[] GetData() { if (FileAdapter.GetInstance() == null) { throw new PK2NotLoadedException(); } if (Type != PK2EntryType.File) { throw new InvalidOperationException("It's impossible to read data from a directory or from a deleted file."); //TODO: find something better } return(FileAdapter.GetInstance().ReadData((long)Position, (int)Size)); }
/// <summary> /// Extracts the file to the specified destination /// </summary> /// <param name="destination">The destination.</param> /// <exception cref="PK2NotLoadedException"></exception> /// <exception cref="System.InvalidOperationException">Directories can not be extracted.</exception> public void Extract(string destination) { if (FileAdapter.GetInstance() == null) { throw new PK2NotLoadedException(); } if (Type != PK2EntryType.File) { throw new InvalidOperationException("Directories can not be extracted."); //TODO: find something better } File.WriteAllBytes(destination, FileAdapter.GetInstance().ReadData((long)Position, (int)Size)); }
public void Test_ReturnsList() { // arrange, set it up, go find what you are going to test var sut = new FileAdapter(); var expected = 4; // act, run what you want to test var actual = fa; // assert, lets check against what we think it's suppose to happen Assert.True(expected <= actual.Count()); }
public void getNextPageNumberzeroTest() { try { FileAdapter adapter = new FileAdapter("resources\\simple_page.htm"); VideoExtractorAndCommenter extractorAndCommenter = new VideoExtractorAndCommenter(adapter, 20); Assert.IsTrue(extractorAndCommenter.getNextPageNumber(adapter.readPageSource()) == 0); } catch (Exception e) { Assert.IsTrue(false, e.Message); } }
public void ObjectAdapterExample() { string fileName = "adapterTest.log"; ObjectProcessor processor = new ObjectProcessor(); File.Delete(fileName); ILogWriter logWriter = new FileAdapter(fileName); processor.Run(logWriter); Console.WriteLine(File.ReadAllText(fileName)); }
public void getRelatedVideoAddress3Test() { try { FileAdapter adapter = new FileAdapter("resources\\3_video.htm"); VideoExtractorAndCommenter extractorAndCommenter = new VideoExtractorAndCommenter(adapter, 20); Assert.IsTrue(extractorAndCommenter.getRelatedVideoAddress(adapter.getUrl()).Count == 19); } catch (Exception e) { Assert.IsTrue(false, e.Message); } }
public Stream CheckNew(string applicationId) { Application app = BuilderFactory.DefaultBulder().Load <Application, ApplicationPK>(new ApplicationPK { ApplicationId = applicationId }); if (app.ApplicationId == null) { WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; return(new MemoryStream(Encoding.UTF8.GetBytes("无效的AppId"))); } //检查主程序 string exeFileName = app.ApplicationCode; string exeDir = HttpContext.Current.Server.MapPath("~/" + applicationId); string exeFilePath = exeDir + @"\" + exeFileName; if (FileAdapter.Exists(exeFilePath)) { //Assembly asm = Assembly.LoadFile(exeFilePath);会锁定 Assembly asm = Assembly.Load(System.IO.File.ReadAllBytes(exeFilePath)); string version = asm.GetName().Version.ToString(); Product product = new Product { ApplicationId = applicationId, ApplicationName = app.ApplicationName, Version = version, Description = "更新说明" }; string appRoot = GetAppRootPath(); if (appRoot.EndsWith("/")) { appRoot = appRoot.Substring(0, appRoot.Length - 1); } product.FileList = new UpdateFilesInfo { SourcePath = appRoot + "/" + applicationId + "/" }; string[] files = Directory.GetFiles(exeDir, "*", SearchOption.AllDirectories); product.FileList.FileItems = new List <FileItem>(); foreach (string file in files) { string itemName = file.Replace(exeDir + @"\", "").Replace(@"\", "/"); product.FileList.FileItems.Add(new FileItem { Name = itemName }); } product.FileList.Count = product.FileList.FileItems.Count.ToString(); byte[] resultBytes = Encoding.UTF8.GetBytes(XmlSerializeAdapter.Serialize <Product>(product)); WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; return(new MemoryStream(resultBytes)); } return(null); }
public static TerrainData CreateTerrainData(string path, Vector3 size, int hResolution, int bResolution) { TerrainData terrainData = new TerrainData(); terrainData.size = size; terrainData.heightmapResolution = hResolution; terrainData.baseMapResolution = bResolution; terrainData.SetDetailResolution(1024, 16); FileAdapter.RequestFilePath(path); AssetDatabase.CreateAsset(terrainData, path); return(terrainData); }
public void VideoAddressExtractor5Test() { try { FileAdapter adapter = new FileAdapter("resources\\4_page.htm"); VideoExtractorAndCommenter extractorAndCommenter = new VideoExtractorAndCommenter(adapter, 20); IList <string> list = extractorAndCommenter.extractVideoAddresses(adapter.readPageSource()); Assert.IsTrue(list.Count == 16); } catch (Exception e) { Assert.IsTrue(false, e.Message); } }
public OrderRepos() { if (_orderList == null) { try { _orderList = FileAdapter.ReadFromXml <List <OrderDetails> >(_path); } catch { _orderList = new List <OrderDetails>(); Save(); } } }
/// <Docs>If the fragment is being re-created from /// a previous saved state, this is the state.</Docs> /// <summary> /// Raises the activity created event. /// </summary> /// <param name="savedInstanceState">Saved instance state.</param> public override void OnActivityCreated(Bundle savedInstanceState) { base.OnActivityCreated(savedInstanceState); adapter = new FileAdapter(cache); adapter.SetFilter(filter); adapter.emptyView = empty; list.SetAdapter(adapter); if (folder != null) { adapter.SetFolder(folder); } }
public CustomerRepository() { // Initialize(); if (_customerList == null) { try { _customerList = FileAdapter.ReadFromXml <List <Customer> >(_path); } catch { _customerList = new List <Customer>(); Save(); } } }
/// <summary> /// Feltölt az adatbázisba egy új dokumentumot /// </summary> /// <param name="newDocument"></param> public int insertNewDocumentIntoDatabase(Document newDocument) { FileAdapter fa = new FileAdapter("0"); if (newDocument != null) { SQLiteAdapter.insertData(newDocument); } if (fa.folderExists()) { fa.renameFolder(Convert.ToString(SQLiteAdapter.getLastInserItemID())); } return(SQLiteAdapter.getLastInserItemID()); }
private static void Main(string[] args) { //all of these show delegate PlayBook(); // PlayMovie(); // ShowPhoto(); // PlaySong(); // PlaySitcom(); // PlayAudio(); // PlayVideo(); FileAdapter.Write(_ar.List().ToList()); }
//public TripEdit() //{ // InitializeComponent(); //} public TripEdit(Trip trip) { // TODO: Complete member initialization this.trip = trip; FileAdapter<Trip> t = new FileAdapter<Trip>(); Type x = typeof(Trip); t.ForTrip(trip); destDir = t.GetDataBaseLocation(); InitializeComponent(); if (trip.vid == 0) { trip.vorganizer = AuthAdapter.GetInstance().getIdentity().vid; button1.Visible = false; button3.Visible = false; } }
public static void Upgrade() { string updateFolder = AppDomain.CurrentDomain.BaseDirectory + Common.APPLICATION_ID; FileAdapter.EnsurePath(updateFolder); FileAdapter.Copy(Updater.AppName, updateFolder + @"\" + Updater.AppName, true); foreach (var file in Updater.DepandenceFiles) { FileAdapter.Copy(file, AppDomain.CurrentDomain.BaseDirectory + Common.APPLICATION_ID + @"\" + file, true); } string updateEndPoint = INIAdapter.ReadValue(Common.CFG_SECTION_WEB, Common.CFG_KEY_UPDATE_END_POINT, Common.CFG_FILE_PATH); string args = String.Format("-n {0} -v {1} -c {2}", AppAdapter.GetName(), VersionAdapter.GetPureVersion(VersionType.ASSEMBLY), updateEndPoint + "/" + Common.APPLICATION_ID); System.Diagnostics.Process.Start(updateFolder + @"\" + Updater.AppName, args); }
public void MemoryFileSystem_GetFileNames() { //arrange var rootFolderPath = "A:\\TestFolder\\Test"; var content = "This is test string"; using (var fileSystem = CreateTestMemoryFile(rootFolderPath, content)) { var adapter = new FileAdapter(fileSystem); //act var actual = adapter.GetFileNames(rootFolderPath); //assert Assert.IsTrue(actual.Count > 0); } }
public StoreRepos() { if (_storeList == null) { try { _storeList = FileAdapter.ReadFromXml <List <StoreDetails> >(_path); } catch { _storeList = new List <StoreDetails>(); Save(); } } }
private static T LoadJsonConfig <T>(string path, Func <T> emptyConfigurationFactory, Func <string, T> loaderMethod) { var fileAdapter = new FileAdapter(); try { var configContents = fileAdapter.ReadAllText(path); return(loaderMethod(configContents)); } catch (Exception ex) { Log.Warn($"Exception occurred loading JSON configuration file from '{path}' ('{ex.Message}'), assuming an empty configuration."); return(emptyConfigurationFactory()); } }
/// <summary> /// Reads the block. /// </summary> /// <param name="position">The position.</param> /// <param name="currentDirectory">The current directory.</param> private void ReadBlockAt(ulong position, PK2Directory currentDirectory = null) { var currentBlockBuffer = FileAdapter.GetInstance().ReadData((long)position, 2560); var currentBlock = new PK2Block(currentBlockBuffer, position); //Check if the chain continues at another position if (currentBlock.Entries[19].NextChain > 0) { ReadBlockAt(currentBlock.Entries[19].NextChain); } //Read the subfolder chain //The folder "." and ".." are required if you which to use "free-browsing" mode, without reading the whole index at once foreach (var pk2Entry in currentBlock.Entries.Where(entry => !entry.Name.StartsWith(".") && entry.Position > 0)) { switch (pk2Entry.Type) { case PK2EntryType.Directory: if (Config.Mode == PK2Mode.Index) { var subDirectory = new PK2Directory(pk2Entry, currentDirectory?.Path); _directories.Add(subDirectory); ReadBlockAt(pk2Entry.Position, subDirectory); } else { ReadBlockAt(pk2Entry.Position); } break; case PK2EntryType.File: if (Config.Mode == PK2Mode.Index) { _files.Add(new PK2File(pk2Entry, currentDirectory?.Path)); } break; } } if (Config.Mode == PK2Mode.IndexBlocks) { Blocks.Add(currentBlock); } }
public static void LogToJsonFile(this string rawJson, string prefix = "", string suffix = "") { var formattedJson = rawJson.FormatAsJson(); var fileName = DateTime.Now.ToFileTimeUtc().ToString(); if (!string.IsNullOrEmpty(prefix)) { fileName = prefix + "_" + fileName; } if (!string.IsNullOrEmpty(suffix)) { fileName = fileName + "_" + suffix; } FileAdapter.SaveHasUTF8(DEBUG_FOLDER + fileName + ".json", formattedJson); #if UNITY_EDITOR Debug.Log(fileName + ": " + rawJson.FormatAsJson(" ")); #endif //UNITY_EDITOR }
protected override void OnListItemClick(ListView l, View v, int position, long id) { FileAdapter files = (FileAdapter)l.Adapter; var t = files.Items[position]; if (t is DirectoryInfo) { //Folder Behavior : path = t.FullName; folder.Text = "Folder: " + t.Name; ourlist.Adapter = new FileAdapter(t.FullName, this); } else { // File Behavior: (This is where will work will come in!) Android.Widget.Toast.MakeText(this, t.Name, Android.Widget.ToastLength.Short).Show(); } }
private void GlobalEvents_SavingReportInDesigner(object sender, Stimulsoft.Report.Design.StiSavingObjectEventArgs e) { if (!Equals(sender, DesignerControl)) { return; } if (e.SaveAs) { e.Processed = false; var dc = DesignerControl; if (dc == null) { return; } dc.ReportFileName = FileAdapter.removeBadChar(tbReportName.Text); } }
/// <summary> /// Instantiate the adapter. /// </summary> /// <returns></returns> protected override BindingElement CreateBindingElement() { FileAdapter adapter = new FileAdapter(); this.ApplyConfiguration(adapter); return adapter; }
public void Internal_OutputTest(string sourcePath, string destinationFolder, string destinationFile, string expectedPath, string fileContent, OverwriteAction overwriteAction = default(OverwriteAction)) { var adapter = new FileAdapter { OverwriteAction = overwriteAction }; var connectionUri = new FileAdapterConnectionUri { Path = destinationFolder, FileName = destinationFile }; var factory = new FileAdapterConnectionFactory(connectionUri, new ClientCredentials(), adapter); var connection = factory.CreateConnection(); var outputHandler = connection.BuildHandler<FileAdapterOutboundHandler>(null); outputHandler.Execute(CreateMessage(sourcePath, GetTestStream(fileContent)), TimeSpan.MaxValue); Assert.IsTrue(System.IO.File.Exists(expectedPath)); Assert.AreEqual(fileContent, System.IO.File.ReadAllText(expectedPath)); }
public void Setup() { Directory.SetCurrentDirectory(TestContext.CurrentContext.TestDirectory); sut = new FileAdapter(); }
private void RegisterAdapters() { var directoryAdapter = new DirectoryAdapter( Kernel.Resolve<IMapPath>(), !_AllowAccessOutsideRootFolder, RootFolder); Kernel.Register(Component.For<IDirectoryAdapter>().Named("directory.adapter").Instance(directoryAdapter)); var fileAdapter = new FileAdapter( !_AllowAccessOutsideRootFolder, RootFolder); Kernel.Register(Component.For<IFileAdapter>().Named("file.adapter").Instance(fileAdapter)); if (Kernel.HasComponent(typeof(ITransactionManager))) fileAdapter.TxManager = directoryAdapter.TxManager = Kernel.Resolve<ITransactionManager>(); else Kernel.ComponentRegistered += Kernel_ComponentRegistered; }
/// <summary> /// Zwraca nazwy plików dla danej wycieczki /// </summary> public String[] GetFilesForTrip(Trip trip) { FileAdapter<Trip> adapter = new FileAdapter<Trip>(); return new string[] { }; }
/// <summary> /// Zapisuje plik z danymi u¿ytkownika na dysk /// </summary> public bool SaveFileForUser(User user, String filename) { FileAdapter<User> forUser = new FileAdapter<User>(); return true; }
/// <summary> /// Zapisuje plik z danymi danego zdjêcia /// </summary> public Photo SavePhoto(Photo photo) { FileAdapter<Photo> adapter = new FileAdapter<Photo>(); return new Photo("."); }
/// <summary> /// Dodaje zdjêcie do danego albumu i zapisuje na dysku /// </summary> public bool SavePhotoToAlbum(Album album, Photo photo) { FileAdapter<Album> adapter = new FileAdapter<Album>(); return true; }
public void Setup() { sut = new FileAdapter(); }