I have stored all subfolder names and it's corresponding file names(from local folder) in a class. Now I want to display it in a good way. And also need to access that files when user selects it. What is the best way to achieve it?
public class SubFolders
{
public string ItemName { get; set; }
public ObservableCollection<SubFolderFiles> SubItemsList { get; set; }
}
public class SubFolderFiles
{
public string SubItemName { get; set; }
}
Best way to show all subfolders and its files in uwp.
For this requirement, you need to create a relatively complete model like the following Illustration.
The above is recursive model, and I have make a class to match it.
public class Folder
{
public string FolderName { get; set; }
private ObservableCollection<File> _subFiles;
public ObservableCollection<File> SubFiles
{
get { return _subFiles ?? (_subFiles = new ObservableCollection<File>()); }
set
{
_subFiles = value;
}
}
private ObservableCollection<Folder> _subFolder;
public ObservableCollection<Folder> SubFolders
{
get { return _subFolder ?? (_subFolder = new ObservableCollection<Folder>()); }
set
{
_subFolder = value;
}
}
public Folder()
{
}
}
public class File
{
public string FileName { get; set; }
}
As you know, if you want to display the folders and files where in one folder on the ListView, you need to converter them into abstract listview items.
public class Item
{
public string ItemName { get; set; }
public ItemType IType { get; set; }
}
public enum ItemType
{
File,
Folder
}
Usage
FolderService.cs
public class FolderService
{
// private Folder FolderModel;
public async static Task<Folder> GetFolderInfoAsync(StorageFolder SelectFolder)
{
var FolderModel = new Folder();
FolderModel.FolderName = SelectFolder.Name;
IReadOnlyList<StorageFile> fileList = await SelectFolder?.GetFilesAsync();
foreach (StorageFile file in fileList)
{
var subFile = new File();
subFile.FileName = file.Name;
FolderModel.SubFiles.Add(subFile);
}
IReadOnlyList<StorageFolder> folderList = await SelectFolder?.GetFoldersAsync();
foreach (StorageFolder folder in folderList)
{
var subFolder = new Folder();
subFolder.FolderName = folder.Name;
FolderModel.SubFolders.Add(subFolder);
}
return FolderModel;
}
public async static Task<ObservableCollection<Item>>GetItems(StorageFolder SelectFolder)
{
var Model = await GetFolderInfoAsync(SelectFolder);
var Items = new ObservableCollection<Item>();
foreach (var file in Model.SubFiles)
{
var item = new Item
{
ItemName = file.FileName,
IType = ItemType.File
};
Items.Add(item);
}
foreach (var folder in Model.SubFolders)
{
var item = new Item
{
ItemName = folder.FolderName,
IType = ItemType.Folder
};
Items.Add(item);
}
return Items;
}
}
ManPageViewModel.cs
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
}
public Command PickCommand => new Command(() => this.BtnClick());
private async void BtnClick()
{
StorageFolder Selectfolder = ApplicationData.Current.LocalFolder;
this.Items = await FolderService.GetItems(Selectfolder);
}
private ObservableCollection<Item> _items;
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string PropertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
public ObservableCollection<Item> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged();
}
}
}
Related
I have in ViewModel
public string SearchPattern
{
get
{
return searchPattern;
}
set
{
searchPattern = value;
}
}
private bool UserFilter(object item)
{
return (item as Node).Name.Contains(SearchPattern);
}
public ICollectionView YourFilteredCollection
{
get
{
var source = CollectionViewSource.GetDefaultView(model.Items);
source.Filter = UserFilter;
return source;
}
}
YourFilteredCollection depends on Model property
public ObservableCollection<Node> Items { get; set; }
Than I decided to filter Node sub items YourFilteredCollectionNodes
public class Node
{
public string Name { get; set; }
public ObservableCollection<Node> Nodes { get; set; }
public ICollectionView YourFilteredCollectionNodes
{
get
{
var source = CollectionViewSource.GetDefaultView(Nodes);
if (source != null)
{
source.Filter = UserFilter;
}
return source;
}
}
private bool UserFilter(object item)
{
//return (item as Node).Name.Contains(SearchPattern);
return true;
}
}
But in this case how it is possible to pass SearchPattern from ViewModel in ObservableCollection item that is in Model??
I'm having a problem with my UWP app and creating a favorites page which allows the user to reorder and save the data on the page. i'm getting the same error on two occasions
CS0120 An object reference is required for the non-static field, method, or property 'Group.Title'
CS0120 An object reference is required for the non-static field, method, or property 'Group.Items'
could anyone explain to me why this is happening,
thanks.
CS File
using App1.Common;
using App1.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace App1
{
public sealed partial class test : Page
{
public ObservableCollection<ItemData> Items { get; set; }
private ObservableDictionary defaultViewModel = new
ObservableDictionary();
private NavigationHelper navigationHelper;
private RootObject jsonLines;
private StorageFile fileFavourites;
private Dictionary<string, ItemData> ItemData = new Dictionary<string,
ItemData>();
public test()
{
loadJson();
getFavoritesFile();
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
}
void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
// Navigate to the appropriate destination page, configuring the new
page
// by passing required information as a navigation parameter
var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
this.Frame.Navigate(typeof(GroupedItemsPage), itemId);
}
private void setupObservableCollection()
{
Items = new ObservableCollection<ItemData>(ItemData.Values);
itemGridView.ItemsSource = Items;
}
private async void loadJson()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new
Uri("ms-appx:///DataModel/SampleData.json"));
var lines = await FileIO.ReadTextAsync(file);
jsonLines = JsonConvert.DeserializeObject<RootObject>(lines);
feedItems();
}
private async void getFavoritesFile()
{
Windows.Storage.StorageFolder storageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
fileFavourites = await storageFolder.GetFileAsync("Fav.txt");
}
private async void feedItems()
{
if (await FileIO.ReadTextAsync(fileFavourites) != "")
{
foreach (var line in await
FileIO.ReadLinesAsync(fileFavourites))
{
foreach (var Group in jsonLines.Groups)
{
foreach (var Item in Group.Items)
{
if (Item.UniqueId == line)
{
var storage = new ItemData()
{
Title = Item.Title,
UniqueID = Item.UniqueId,
ImagePath = Item.ImagePath,
Group = Group.Title
};
ItemData.Add(storage.UniqueID, storage);
}
}
}
}
}
else
{//if favourites file is empty, use?
foreach (var Group in jsonLines.Groups) ;
{
foreach (var Item in Group.Items)
{
var storage = new ItemData()
{
Title = Item.Title,
UniqueID = Item.UniqueId,
ImagePath = Item.ImagePath,
Group = Group.Title
};
ItemData.Add(storage.UniqueID, storage);
await FileIO.AppendTextAsync(fileFavourites,
Item.UniqueId + "\r\n");
}
}
}
setupObservableCollection();
}
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
#region NavigationHelper loader
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
private async void MessageBox(string Message)
{
MessageDialog dialog = new MessageDialog(Message);
await dialog.ShowAsync();
}
private async void navigationHelper_LoadState(object sender,
LoadStateEventArgs e)
{
var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
this.defaultViewModel["Groups"] = sampleDataGroups;
}
#endregion NavigationHelper loader
#region NavigationHelper registration
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
#endregion NavigationHelper registration
}
public class ItemData
{
public string UniqueID { get; set; }
public string Title { get; set; }
public string Group { get; set; }
public string ImagePath { get; set; }
}
}
RootObject File
using App1.Data;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace App1
{
public class Item
{
public string UniqueId { get; set; }
public string Title { get; set; }
public string Subtitle { get; set; }
public string ImagePath { get; set; }
public string Description { get; set; }
public string Content { get; set; }
}
public class Group
{
public string UniqueId { get; set; }
public string Title { get; set; }
public string Subtitle { get; set; }
public string ImagePath { get; set; }
public string Description { get; set; }
public List<Item> Items { get; set; }
}
public class RootObject
{
public List<Group> Groups { get; set; }
}
}
The problem occures in your foreach loop. Actually, there are two problems:
You use Group as iteration variable, which is possible, but leads to confusion with the class name Group.
When instantiating new ItemData, you suddenly use Group.Title instead of Item.Title
So a corrected version of the loop could look like this:
foreach (var group in jsonLines.Groups) ;
{
foreach (var item in group.Items)
{
var storage = new ItemData()
{
Title = item.Title,
UniqueID = item.UniqueId,
ImagePath = item.ImagePath,
Group = item.Title
};
ItemData.Add(storage.UniqueID, storage);
await FileIO.AppendTextAsync(fileFavourites,
Item.UniqueId + "\r\n");
}
}
I changed the loop variable Group to the lower-case group. And I changed the second loop variable Item also to lower-case, which is not necessary in your case, but better complies with C# naming conventions.
in your foreach you should use other names instead of Group, because it conflicts with the class's name. A lowercase group would work.
I'm tring to create a ListView which is fed data from an SQLite Database (pre-existing db file). The ListView uses a custom row which is one of the aspects which baffle me; How do I extract the data and then assign it to a TextView in the custom row?
I'm new to Xamarin, so would really appreciate any guidance you can give me on this, Thank you!
Current Dialog Box Error When Run:
Java.Lang.ClassNotFoundException: Didn't find class "md5c4f65b5cf99ab8e97737acf0f8ec7efd.DBHelper" on path: DexPathList[[zip file "/data/app/AppName.Droid-1/base.apk"],nativeLibraryDirectories=[/data/app/AppName.Droid-1/lib/arm, /system/fake-libs, /data/app/AppName.Droid-1/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]
'MainActivity':
public class EateriesActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Find An Eatery";
SetContentView(Resource.Layout.Eateries);
DBHelper db = new DBHelper();
db.CreateDatabase();
db.CreateTable();
var items = db.GetData();
var listView = FindViewById<ListView>(Resource.Id.EateryList_ListView);
listView.Adapter = new ArrayAdapter<string>(this, Resource.Layout.Eatery_ListView_Row, items);
}
}
ListViewAdapter (is this necessary?):
class ListViewAdapter : BaseAdapter<Eatery>
{
private List<Eatery> myItems;
private Context myContext;
public ListViewAdapter(Context context, List<Eatery> items)
{
myItems = items;
myContext = context;
}
public override int Count
{
get { return myItems.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override Eatery this[int position]
{
get
{
return myItems[position];
}
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(myContext).Inflate(Resource.Layout.Eatery_ListView_Row, null, false);
}
TextView placeName = row.FindViewById<TextView>(Resource.Id.placeName);
placeName.Text = myItems[position].Name;
TextView placeTown = row.FindViewById<TextView>(Resource.Id.placeTown);
placeTown.Text = myItems[position].Town;
return row;
}
}
Eatery:
public class Eatery
{
[PrimaryKey]
public string ID { get; set; }
public string Image { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Address1 { get; set; }
public string Town { get; set; }
public string PostCode { get; set; }
public string Cuisine { get; set; }
}
DBHelper:
public class DBHelper
{
private static string DB_PATH = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
private static string DB_NAME = "EateryDB.db";
public void CreateDatabase()
{
string dbPath = Path.Combine(DB_PATH, DB_NAME);
var db = new SQLiteConnection(new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(), dbPath);
}
public void CreateTable()
{
string dbPath = Path.Combine(DB_PATH, DB_NAME);
var db = new SQLiteConnection(new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(), dbPath);
db.CreateTable<Eatery>();
}
public List<string> GetData()
{
string dbPath = Path.Combine(DB_PATH, DB_NAME);
var db = new SQLiteConnection(new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(), dbPath);
List<string> data = new List<string>();
foreach (var item in db.Table<Eatery>())
{
var place = item.Name.ToString(); item.Town.ToString();
data.Add(place);
}
return data;
}
Based on your two version of code, I think what you need is adding data from your database to the myItems.
Then you can for example code like this:
List<Eatery> data = new List<Eatery>();
foreach (var item in db.Table<Eatery>())
{
var place = item.Name.ToString();
var location = item.Location.ToString();
var rating = item.Rating;
item.Town.ToString();
data.Add(new Eatery() { PlaceName = place, PlaceLocation = location, PlaceRating = rating });
}
And finally add this data to your adapter as you did when you hard code:
MyListViewAdapter adapter = new MyListViewAdapter(this, data);
I made an application to download files into a folder inside another folder.
The name for the folder obtained from DataFile name from database and match the name of the image that has been downloaded.
I'm having a problem, that when downloading to a folder for the first bundle of data is fine, but at the time of downloading the data bundle again the previous folder and the new folder also download both files.
When downloading the files that differ it will create a new folder again and the two previous folders are also downloaded the file. For more details, can see in the image below:
And should one folder contains two files.
JSON:
RHData Class:
[PrimaryKey]
public string SKU { get; set; }
public string Judul { get; set; }
public string Tipe { get; set; }
public string Harga { get; set; }
public string Gratis { get; set; }
public string DataFile { get; set; }
RHViewModel class:
class RHViewModel
{
private string sku = string.Empty;
public string SKU
{
get { return sku; }
set
{
if (sku == value)
return;
sku = value;
RaisePropertyChanged("SKU");
}
}
private string judul = string.Empty;
public string Judul
{
get { return judul; }
set
{
if (judul == value)
return;
judul = value;
RaisePropertyChanged("Judul");
}
}
private string tipe = string.Empty;
public string Tipe
{
get { return tipe; }
set
{
if (tipe == value)
return;
tipe = value;
RaisePropertyChanged("Tipe");
}
}
private string harga = string.Empty;
public string Harga
{
get { return harga; }
set
{
if (harga == value)
return;
harga = value;
RaisePropertyChanged("Harga");
}
}
private string cover = string.Empty;
private string gratis = string.Empty;
public string Gratis
{
get { return gratis; }
set
{
if (gratis == value)
return;
gratis = value;
RaisePropertyChanged("Gratis");
}
}
private string dataFile = string.Empty;
public string DataFile
{
get { return dataFile; }
set
{
if (dataFile == value)
return;
dataFile = value;
RaisePropertyChanged("DataFile");
}
}
public RHViewModel GetItem(string itemSku)
{
var item = new RHViewModel();
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var _item = (db.Table<RHData>().Where(
c => c.SKU == itemSku)).Single();
item.SKU = _item.SKU;
item.Judul = _item.Judul;
item.Tipe = _item.Tipe;
item.Harga = _item.Harga;
item.Gratis = _item.Gratis;
item.DataFile = _item.DataFile;
}
return item;
}
public string SaveItem(RHViewModel item)
{
string result = string.Empty;
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
try
{
var existingItem = (db.Table<RHData>().Where(
c => c.SKU == item.sku)).SingleOrDefault();
if (existingItem != null)
{
existingItem.SKU = item.SKU;
existingItem.Judul = item.Judul;
existingItem.Tipe = item.Tipe;
existingItem.Harga = item.Harga;
existingItem.Gratis = item.Gratis;
existingItem.DataFile = item.DataFile;
int success = db.Update(existingItem);
}
else
{
int success = db.Insert(new RHData()
{
SKU = item.SKU,
Judul = item.Judul,
//Deskripsi = item.Deskripsi,
Tipe = item.Tipe,
Harga = item.Harga,
Gratis = item.Gratis,
//Cover = item.Cover,
//File = item.File,
DataFile = item.DataFile
});
}
result = "Success";
}
catch
{
result = "This item was not saved.";
}
}
return result;
}
public string DeleteItem(string itemDataFile)
{
string result = string.Empty;
using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var existingItem = dbConn.Query<RHData>("select * from RH where DataFile =" + itemDataFile).FirstOrDefault();
if (existingItem != null)
{
dbConn.RunInTransaction(() =>
{
dbConn.Delete(existingItem);
if (dbConn.Delete(existingItem) > 0)
{
result = "Success";
}
else
{
result = "This item was not removed";
}
});
}
return result;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
RHItemsViewModel Class:
class RHItemsViewModel : RHViewModel
{
private ObservableCollection<RHViewModel> items;
public ObservableCollection<RHViewModel> Items
{
get
{
return items;
}
set
{
items = value;
RaisePropertyChanged("Items");
}
}
public ObservableCollection<RHViewModel> GetItems()
{
items = new ObservableCollection<RHViewModel>();
using (var db = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var query = db.Table<RHData>().OrderBy(c => c.SKU);
foreach (var _item in query)
{
var item = new RHViewModel()
{
//SKU = _item.SKU,
SKU = _item.SKU,
Judul = _item.Judul,
//Deskripsi = _item.Deskripsi,
Tipe = _item.Tipe,
Harga = _item.Harga,
Gratis = _item.Gratis,
//Cover = _item.Cover,
//File = _item.File,
DataFile = _item.DataFile
};
items.Add(item);
}
}
return items;
}
}
}
App.Xaml.CS
public static string DB_PATH = Path.Combine(ApplicationData.Current.LocalFolder.Path, "RH.sqlite");
public static SQLite.Net.Platform.WinRT.SQLitePlatformWinRT SQLITE_PLATFORM;
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
SQLITE_PLATFORM = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
if (!CheckFileExists("RH.sqlite").Result)
{
using (var db = new SQLiteConnection(SQLITE_PLATFORM, DB_PATH))
{
db.CreateTable<RHData>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
}
return false;
}
Code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//GC.Collect();
BukuAudio dlList = e.Parameter as BukuAudio;
if (dlList != null)
{
Queue<DownloadOperation> downloadOperationList = new Queue<DownloadOperation>();
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadProgress.Visibility = Visibility.Visible;
downloadfilename.Visibility = Visibility.Visible;
statusdownload.Visibility = Visibility.Visible;
deleteBtn.Visibility = Visibility.Collapsed;
viewBtn.Visibility = Visibility.Collapsed;
foreach (var path in dlList.BundlePath)
{
DownloadBuku(path);
for (int i = 0; i<dlList.BundlePath.Count;i++)
{
downloadfilename.Text = dlList.BundleName.ElementAt(i);
Uri uri = new Uri(path);
string filename = path.Substring(uri.LocalPath.LastIndexOf("/") + 1);
downloadfilename.Text = String.Format("Unduh '{0}'", filename);
}
}
DownloadGambar(dlList.Cover);
}
else
{
DownloadProgress.Visibility = Visibility.Collapsed;
downloadfilename.Visibility = Visibility.Collapsed;
statusdownload.Visibility = Visibility.Collapsed;
deleteBtn.Visibility = Visibility.Visible;
viewBtn.Visibility = Visibility.Visible;
}
bookAudio = e.Parameter as BookAudio;
}
private async void downloadClicked(object sender, RoutedEventArgs e)
{
Uri uri = new Uri(itemDetail.BundlePath.First());
string filename = System.IO.Path.GetFileName(uri.LocalPath);
string statustext = String.Format("Download Buku '{0}'?", itemDetail.Judul);
string sudahada = String.Format("Buku '{0}' sudah ada/sedang didownload", itemDetail.Judul);
MessageDialog messageDialog;
try
{
StorageFolder library = await ApplicationData.Current.LocalFolder.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
var file = await library.GetFileAsync(filename);
messageDialog = new MessageDialog(sudahada, "Buku sudah ada");
messageDialog.Commands.Add(new UICommand("Library", (command) =>
{
this.Frame.Navigate(typeof(library.LibraryPage));
}));
messageDialog.Commands.Add(new UICommand("Batal", (command) =>
{
//rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
}));
}
catch (FileNotFoundException ex)
{
//file not exists show download dialog
// Create the message dialog and set its content and title
messageDialog = new MessageDialog(statustext, "Download");
// Add commands and set their callbacks
messageDialog.Commands.Add(new UICommand("Download", (command) =>
{
itemsViewModel = new RHItemsViewModel();
itemsViewModel.SaveItem(new RHViewModel()
{
SKU = itemDetail.SKU.ToString(),
Judul = itemDetail.Judul.ToString(),
Tipe = itemDetail.Tipe.ToString(),
Harga = itemDetail.Harga.ToString(),
Gratis = itemDetail.Gratis.ToString(),
DataFile = itemDetail.DataFile.ToString()
});
this.Frame.Navigate(typeof(library.LibraryPage), itemDetail);
}));
messageDialog.Commands.Add(new UICommand("Batal", (command) =>
{
//rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
}));
}
// Show the message dialog
await messageDialog.ShowAsync();
}
}
Library Page:
private async void DownloadBuku(string fileLocation)
{
itemsViewModel = new RHItemsViewModel();
items = new ObservableCollection<RHViewModel>();
using (var dbConn = new SQLiteConnection(App.SQLITE_PLATFORM, App.DB_PATH))
{
var existingItem = dbConn.Table<RHData>().OrderBy(c => c.DataFile);
if (existingItem != null)
{
foreach (var _item in existingItem)
{
var item = new RHViewModel()
{
DataFile = _item.DataFile
};
items.Add(item);
var uri = new Uri(fileLocation);
var downloader = new BackgroundDownloader();
StorageFolder library = await installedLocation.CreateFolderAsync("library", CreationCollisionOption.OpenIfExists);
StorageFolder pdf = await library.CreateFolderAsync(item.DataFile.ToString(), CreationCollisionOption.OpenIfExists);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
StorageFile file = await pdf.CreateFileAsync(filename,
CreationCollisionOption.ReplaceExisting);
DownloadOperation download = downloader.CreateDownload(uri, file);
await StartDownloadAsync(download);
}
}
}
}
BukuAudio Class:
class BukuAudio
{
public string SKU { get; set; }
public string Judul { get; set; }
public string Deskripsi { get; set; }
public string Tipe { get; set; }
public string NamaTipe { get; set; }
public string Harga { get; set; }
public string Cover { get; set; }
public string File { get; set; }
public string Gratis { get; set; }
public string Tanggal { get; set; }
public string DataFile { get; set; }
public JsonArray Bundle_file { get; set; }
public List<string> BundleName { get; set; }
public List<string> BundlePath { get; set; }
}
How to handle it?
Note:
First Bundle File downloaded in the folder "bundle.24b"
Second Bundle file downloaded files in the folder "bundle.23b"
Third Bundle downloaded file in the folder "bundle.22b
Supposedly the file name "bundle.24b ....." downloaded in folder bundle.24b, the file name "bundle.23b ....." downloaded in folder bundle.23b, the file name "bundle.22b ....." downloaded in folder bundle.22b
I'm creating a tree structure of a given folder (only folders no files)
also i return the security permission of each folder and add it to a list
Now how can i Loop through this composite and get all items and sub items
public abstract class FolderComponent:IEnumerable
{
public string FullName { get; set; }
public string Name { get; set; }
public List<string[]> Rules { get; set; }
public abstract void AddFolder(FolderComponent folderComponent);
public abstract IEnumerator GetEnumerator();
public abstract void AssignRules();
}
public class Folder : FolderComponent
{
public IList<FolderComponent> FolderComponents { get; set; }
public Folder(string path)
{
FullName = path;
FolderComponents = new List<FolderComponent>();
Rules = new List<string[]>();
}
public override void AddFolder(FolderComponent folderComponent)
{
FolderComponents.Add(folderComponent);
}
public override IEnumerator GetEnumerator()
{
return FolderComponents.GetEnumerator();
}
public override void AssignRules()
{
// some code
string[] rules = new string[]{"Read","Write","Execute"};
Rules.Add(rules);
}
}
public class Program
{
private static FolderComponent GetFolders(string path)
{
FolderComponent folder = new Folder(path);
folder.AssignRules();
foreach (var directory in Directory.GetDirectories(path))
{
folder.AddFolder(GetFolders(directory));
}
return folder;
}
public static void Main()
{
FolderComponent folder = GetFolders(#"C\:Test");
// How can i loop though all folder structure inside folder?
}
}
If you want to do something like this with your Folder class:
FolderComponent folders = GetFolders(#"C\:Test");
foreach (var folder in folders) { Console.WriteLine(folder.FullName); }
and get the full directory tree printed, then the GetEnumerator method needs to have logic to traverse the tree. For example
public override IEnumerator<FolderComponent> GetEnumerator()
{
// Return the current element
yield return this;
// Work through the collection of components in this folder ...
foreach (var component in FolderComponents)
{
// ... and traverse all the subfolders in each component.
// Note that this recursively calls this GetEnumerator
// method on the subfolders to work down the tree.
foreach (var subfolder in component)
{
yield return subfolder;
}
}
}
I added a method to your FolderComponent class and implement that
see if that can do the thing:
public abstract class FolderComponent : IEnumerable
{
public string FullName { get; set; }
public string Name { get; set; }
public List<string[]> Rules { get; set; }
public abstract void AddFolder(FolderComponent folderComponent);
public abstract IEnumerator GetEnumerator();
public abstract void AssignRules();
public abstract List<FolderComponent> GetAllItems();
}
public class Folder : FolderComponent
{
public IList<FolderComponent> FolderComponents { get; set; }
public Folder(string path)
{
FullName = path;
FolderComponents = new List<FolderComponent>();
Rules = new List<string[]>();
}
public override void AddFolder(FolderComponent folderComponent)
{
FolderComponents.Add(folderComponent);
}
public override IEnumerator GetEnumerator()
{
return FolderComponents.GetEnumerator();
}
public override void AssignRules()
{
// some code
string[] rules = new string[] { "Read", "Write", "Execute" };
Rules.Add(rules);
}
public override List<FolderComponent> GetAllItems()
{
var resultItems = new List<FolderComponent> {this};
foreach (var folderComponent in FolderComponents)
{
resultItems.AddRange(folderComponent.GetAllItems());
}
return resultItems;
}
}
public class Program
{
private static FolderComponent GetFolders(string path)
{
FolderComponent folder = new Folder(path);
folder.AssignRules();
foreach (var directory in Directory.GetDirectories(path))
{
folder.AddFolder(GetFolders(directory));
}
return folder;
}
public static void Main()
{
FolderComponent rootfolder = GetFolders(#"D:\4Share");
var allItems = rootfolder.GetAllItems();
foreach (var folderComponent in allItems)
{
Console.WriteLine(folderComponent.FullName);
}
Console.ReadLine();
}
you should add a list of folder type (children).
FolderComponent Parent;
List<FolderComponent> children;
And add a child when u find a folder inside specific folder. You can add parent for backward processing as well.
var directoryInfo = new DirectoryInfo(folderPath);
foreach (var directory in directoryInfo)
{
FolderComponent newSubFolder = new FolderComponent();
newSubFolder.Parent = this;
// get whatever you want like name, permissions etc.
children.Add(newSubFolder);
}
You need something like this in your code (depends on implementation)
PrintFolders()
{
foreach(var child in children)
child.PrintFolders();
Console.WriteLine(FolderName);
}