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
Related
I receive an array of messages with attachments from the API and create on their basis Models for UserControls. In model I call Initial method for download image in local storage.But if I open dialog(recieve array from the API) as soon as i run the app, I get an error message System.NotSupportedException in PresentationCore.dll
Additional Information: No pixel format information found.
Here is code of Model:
Most interesting i have catch on it but still get
public class MediaMessageAttachment : ViewModelBase
{
public string FullImageURI { get; set; }
public string VideoURI { get; set; }
public string Title { get; set; }
public bool HasVideo => VideoURI != null;
public bool HasImage => FullImageURI != null;
public string Duration { get; set; }
public bool IsLoading
{
get { return isLoading; }
set
{
isLoading = value;
RaisePropertyChanged("IsLoading");
}
}
private BitmapImage image;
private string previewImageURI;
private bool isLoading;
public string PreviewImageURI { get { return previewImageURI; } set { previewImageURI = value; RaisePropertyChanged("PreviewImageURI"); Initial(); } }
public BitmapImage Image
{
get { return image; }
set
{
image = value;
RaisePropertyChanged("Image");
}
}
public RelayCommand OpenImageCommand
{
get;
private set;
}
public MediaMessageAttachment()
{
OpenImageCommand = new RelayCommand(() => OpenImage());
}
private void OpenImage()
{
if (HasImage)
PopupVM.ShowPopup(FullImageURI);
else if (HasVideo)
PopupVM.ShowPopup(VideoURI);
}
public async Task Initial()
{
IsLoading = true;
if (!Directory.Exists(Environment.CurrentDirectory + "\\temp"))
{
Directory.CreateDirectory(Environment.CurrentDirectory + "\\temp");
}
using (WebClient client = new WebClient())
{
var path = Environment.CurrentDirectory + "\\temp\\" + PreviewImageURI.Substring(PreviewImageURI.LastIndexOf('/') + 1);
if (File.Exists(path))
DownloadFileCompleted(null, null);
else
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
await client.DownloadFileTaskAsync(new Uri(PreviewImageURI), path);
}
}
}
private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
try
{
var path = Environment.CurrentDirectory + "\\temp\\" + PreviewImageURI.Substring(PreviewImageURI.LastIndexOf('/') + 1);
Image = new BitmapImage();
Image.BeginInit();
Image.UriSource = new Uri(path);
Image.CacheOption = BitmapCacheOption.OnLoad;
Image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
Image.EndInit();
Image.Freeze();
IsLoading = false;
}
catch (System.NotSupportedException)
{
Initial();
}
}
}
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();
}
}
}
I have:
private void Tab2KsiazkiBTSzczegoly_Click(object sender, EventArgs e)
{
string KodKsiazki;
KodKsiazki = DataWyszukajKsiazki.Rows[DataWyszukajKsiazki.CurrentCell.RowIndex].Cells[2].Value.ToString();
TSzczegolyDb _szczegoly = new TSzczegolyDb();
Global.listSzczegoly = _szczegoly.GetSZCZEGOLY(KodKsiazki);
//StringBuilder sb = new StringBuilder();
//foreach (DataGridViewCell cell in DataWyszukajKsiazki.SelectedCells)
//{
// sb.AppendLine(cell.Value.ToString());
//}
//MessageBox.Show(sb.ToString());
//}
MessageBox.Show(_szczegoly.ToString());
}
class like that:
public class TSzczegolyDb : Core.CoreMSSQL
{
static string connectionString = TconStrDb.GetConectionString();
public TSzczegolyDb()
: base(connectionString)
{
}
public List<TSzczegolyDto> GetSZCZEGOLY(string co)
{
List<TSzczegolyDto> list = null;
list = new List<TSzczegolyDto>();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT Tytul, Autorzy, ISBN10, ISBN13, IlStron, Wydawnictwo, Gatunek, Opis FROM dbo.TKsiazki WHERE dbo.TKsiazki.KodKsiazki = '" + co + "'";
SqlDataReader reader = ExecuteQuery(command);
while (reader.Read())
{
TSzczegolyDto message = new TSzczegolyDto();
if (!reader.IsDBNull(0))
{
message.Tytuł = reader.GetString(0);
}
if (!reader.IsDBNull(1))
{
message.Autorzy = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
message.ISBN10 = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
message.ISBN13 = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
message.IlStron = reader.GetInt32(4);
}
if (!reader.IsDBNull(5))
{
message.Wydawnictwo = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
message.Gatunek = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
message.Opis = reader.GetString(7);
}
list.Add(message);
}
return list;
}
and second:
public class TSzczegolyDto
{
private string _tytul;
public string Tytuł
{
get { return _tytul; }
set { _tytul = value; }
}
private string _autorzy;
public string Autorzy
{
get { return _autorzy; }
set { _autorzy = value; }
}
private string _ISBN10;
public string ISBN10
{
get { return _ISBN10; }
set { _ISBN10 = value; }
}
private string _ISBN13;
public string ISBN13
{
get { return _ISBN13; }
set { _ISBN13 = value; }
}
private long _ilstron;
public long IlStron
{
get { return _ilstron; }
set { _ilstron = value; }
}
private string _wydawnictwo;
public string Wydawnictwo
{
get { return _wydawnictwo; }
set { _wydawnictwo = value; }
}
private string _gatunek;
public string Gatunek
{
get { return _gatunek; }
set { _gatunek = value; }
}
private string _opis;
public string Opis
{
get { return _opis; }
set { _opis = value; }
}
}
I want show _szczegoly on MessageBox but when I try to MessageBox.Show(_szczegoly.ToString()); then is wrong. In _szczegoly I have string and long type data.
How to create messagebox with this data?
I think you are trying to show an Object with a MessageBox, you need to override the ToString() method to show propertly:
class TSzczegolyDb
{
public override string ToString()
{
return this.Property1 + this.Property2 /*....*/;
}
}
I have huge problem with saveing and restore ObservableCollection to IsolatedData.
I'm trying with this code.
Helper class for Observable
public class ListItem {
public String Title { get; set; }
public bool Checked { get; set; }
public ListItem(String title, bool isChecked=false) {
Title = title;
Checked = isChecked;
}
private ListItem() { }
}
IsoHelper
public class IsoStoreHelper {
private static IsolatedStorageFile _isoStore;
public static IsolatedStorageFile IsoStore {
get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
}
public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class {
if (!IsoStore.DirectoryExists(folderName)) {
IsoStore.CreateDirectory(folderName);
}
if (IsoStore.FileExists(folderName + "\\" + dataName+".dat")) {
IsoStore.DeleteFile(folderName + "\\" + dataName + ".dat");
}
string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
try {
using (var stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore)) {
var dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
dcs.WriteObject(stream, dataList);
}
} catch (Exception e) {
Debug.WriteLine(e.Message);
}
}
public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class {
var retval = new ObservableCollection<T>();
if (!IsoStore.DirectoryExists(folderName) || !IsoStore.FileExists(folderName + "\\" + dataName + ".dat")) {
return retval;
}
string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
var isf = IsoStore;
try {
var fileStream = IsoStore.OpenFile(fileStreamName, FileMode.OpenOrCreate);
if (fileStream.Length > 0) {
var dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
retval = dcs.ReadObject(fileStream) as ObservableCollection<T>;
}
} catch {
retval = new ObservableCollection<T>();
}
return retval;
}
}
And I'm trying to use it this way
public partial class MainPage : PhoneApplicationPage{
public ObservableCollection<ListItem> ListItems = new ObservableCollection<ListItem>();
bool isListSaved;
private void Panorama_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
if (strTag.Equals("list") ) {
isListSave = false;
ListItems = IsoStoreHelper.LoadList<ListItem>("settings", "ListItems");
} else if (!isListSave) {
IsoStoreHelper.SaveList<ListItem>("settings", "ListItems", ListItems);
}
}
}
I keep getting A first chance exception of type 'System.Security.SecurityException' occurred in System.Runtime.Serialization.ni.dll when I try read saved file at line ReadObject(fileStream) but the FileAccess looks fine.
Any conclusion will be appreciated.
SOLVED:
Like Dmytro Tsiniavskyi said I totaly forgot about [DataContract] and [DataMember] in ListItem. Whats more I found better solution for saving and loading data. I end up with this code for ListItem
[DataContract]
public class ListItem {
[DataMember]
public String Title { get; set; }
[DataMember]
public bool Checked { get; set; }
public ListItem(String title, bool isChecked=false) {
Title = title;
Checked = isChecked;
}
private ListItem() { }
}
And this code for save/load collection which was originally founded here and modified a litte bit for better useage.
public partial class IsolatedRW {
public static void SaveData<T>(string fileName, T dataToSave) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
try {
if (store.FileExists(fileName)) {
store.DeleteFile(fileName);
}
if (!store.DirectoryExists("Settings")) store.CreateDirectory("Settings");
IsolatedStorageFileStream stream;
using (stream = store.OpenFile("Settings/"+fileName+".xml", System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, dataToSave);
}
stream.Close();
} catch (System.Security.SecurityException e) {
//MessageBox.Show(e.Message);
return;
}
Debug.WriteLine(store.FileExists("Settings/" + fileName + ".xml"));
}
}
public static T ReadData<T>(string fileName) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
Debug.WriteLine(store.FileExists("Settings/" + fileName + ".xml"));
if (store.FileExists("Settings/" + fileName + ".xml")) {
IsolatedStorageFileStream stream;
using (stream = store.OpenFile("Settings/"+fileName+".xml", FileMode.OpenOrCreate, FileAccess.Read)) {
try {
var serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(stream);
} catch (Exception) {
return default(T);
}
}
stream.Close();
}
return default(T);
}
}
}
Try to add [DataContract] attribute for your ListItem class.
[DataContract]
public class ListItem {
[DataMember]
public String Title { get; set; }
[DataMember]
public bool Checked { get; set; }
public ListItem(String title, bool isChecked=false) {
Title = title;
Checked = isChecked;
}
private ListItem() { }
}
I've a problem. In my code I'm looking for all xml files in one directory. Finally it works but I don't know how to read them. A single one is loaded with the string xmlFile. I think I need to replace or edit that in this way that my code now that xmlFile is not only one file, but all files who are found in the directory.
What should I be doing?
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
private const string xmlFile = "C:\Games\games.xml"; // single xml file works
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.LoadDataFromXml();
listView.Items.AddRange(Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray());
}
private void LoadDataFromXml()
{
if (File.Exists(xmlFile))
{
XDocument document = XDocument.Load(xmlFile);
if (document.Root != null)
{
foreach (XElement gameElement in document.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string uninstallpath = gameElement.Element("uninstallpath").Value;
string publisher = gameElement.Element("publisher").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, uninstallpath, publisher);
AddGameToListView(game);
}
}
}
}
private void AddGameToListView(Game game)
{
ListViewItem item = CreateGameListViewItem(game);
this.listView.Items.Add(item);
}
private ListViewItem CreateGameListViewItem(Game game)
{
ListViewItem item = new ListViewItem(game.Gamename);
item.SubItems.Add(game.Launchpath);
item.SubItems.Add(game.Uninstallpath);
item.SubItems.Add(game.Publisher);
item.Tag = game;
return item;
}
private void InitializeListView()
{
this.listView.View = View.Details;
this.listView.GridLines = true;
this.listView.MultiSelect = false;
this.listView.FullRowSelect = true;
this.listView.Columns.AddRange(new[]
{
new ColumnHeader{Text = "Gamename", Width = 200},
new ColumnHeader{Text = "Launchpath"},
new ColumnHeader{Text = "Uninstallpath"},
new ColumnHeader{Text = "Publisher"}
});
this.listView.MouseDoubleClick += ListViewOnMouseDoubleClick;
}
private void ListViewOnMouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && this.listView.SelectedItems.Count > 0)
{
Game game = (Game)((this.listView.SelectedItems[0].Tag);
try
{
Process.Start(game.Launchpath);
}
catch (Exception ex)
{
MessageBox.Show("Can not start game.\nDetails:\n" + ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
internal class Game
{
public Game()
{
}
public Game(string gamename, string launchpath, string uninstallpath, string publisher)
{
this.Gamename = gamename;
this.Launchpath = launchpath;
this.Uninstallpath = uninstallpath;
this.Publisher = publisher;
}
public string Gamename { get; set; }
public string Launchpath { get; set; }
public string Uninstallpath { get; set; }
public string Publisher { get; set; }
}
}
UPDATE:
This is my current code. how can i send f to LoadDataFromXml ?
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
var files = Directory.GetFiles(#"C:\Games\", "*.xml").Select(f => new ListViewItem(f)).ToArray(); listView.Items.AddRange(files);
foreach (var f in files)
{
this.LoadDataFromXml(f);
}
}
private void LoadDataFromXml(//What Do I need to enter here?)
{
foreach (XElement gameElement in f.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string portablesave = gameElement.Element("portablesave").Value;
string publisher = gameElement.Element("publisher").Value;
string gameid = gameElement.Element("gameID").Value;
string update = gameElement.Element("update").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, portablesave, publisher, gameid, update);
AddGameToListView(game);
}
}
Simple use Directory functions to get all your XML files, and loop through them, by calling LoadDataFromXml for each file. Note: You will need to refactor your code a little bit.
You need to modify your LoadDataFromXml to take file as a parameter. And change your Form1 constructor to something like this
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
var files = Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray();
listView.Items.AddRange(files);
foreach(var f in files)
{
this.LoadDataFromXml(f);
}
}