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);
}
}
Related
There is a way to get all items selected with the mouse in a list view when virtual mode is enabled for this winform.
Example of an working code in use, I can retrieve only one selected file for now. Not too much examples finded on the web and could be identified as duplicate but is not conclusive for me, or the answer is to simple.
private void FilesFoundList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
try
{
if (e.ItemIndex >= 0 && e.ItemIndex < ListFilesInfos.Count)
{
try
{
var acc = ListFilesInfos[e.ItemIndex];
//with colors
e.Item = new ListViewItem(new string[] { acc.TagItem, acc.FileName, acc.FilePath.ToString() })
{ Tag = acc,
BackColor = SearchLabColor(0, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
ForeColor = SearchLabColor(1, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
UseItemStyleForSubItems = false
}; // Set Tag object property to our actual AccountInfo object
}
catch { this.Refresh(); }
}
}
catch
{
}
}
private void ShowItemsVirtual(List<SearchFilesInfo> infos)
{
try
{
FilesFoundList.VirtualListSize = infos.Count; // Set number of items in list view
}
catch { this.Refresh(); }
}
private void FilesFoundList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
SelectedFiles.GlobalVar = (e.Item.SubItems[2]).Text.ToString() + (e.Item.SubItems[1]).Text.ToString();
}
}
You could abbreviate your code to:
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect=
FilesFoundList.SelectedIndices
.Select(i=> new multiSearchSelect()
{
fileName = FilesFoundList.Items[i].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
I will post my solution that fits to my purpose. I have added ItemsSelectionRangeChanged event and get the list of file selected.
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect.Clear();
ListView.SelectedIndexCollection col = FilesFoundList.SelectedIndices;
if (col.Count > 1)
{
foreach (int item in col)
{
multiSearchSelect.Add(new multiSearchSelect
{
fileName = FilesFoundList.Items[item].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
I'm sorry if my title is bad, its 1:30am and I'm all out of coffee. I've tried a few solutions suggested on similar questions but I can't figure it out as my case is a little different.
I'm trying to use a separate form to select parameters for the method I use to format data which is passed to a DataGridView in the original form, however its not populating the DataGridView. I have set the new form to be a dialog, it receives the original form reference when its called, on the form there is a DateTimePicker and a button, when the button is clicked it calls a method that gets the datetime value, then it calls a method on the original form with the datetime parameters being passed to it and closes the dialog. The method on the original form runs with the parameters that where passed to get the data for the DataGridView and then calls the datasource method passing the bindinglist to it.
This method of filling the DataGridView using a dialog is my best interpretation of how its been explained in similar questions on this site but its not populating my DataGridView. Any help would be greatly appreciated.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SearchDialog search = new SearchDialog(this);
search.Show();
}
)button2 is a cancel button(
public partial class SearchDialog : Form
{
static DirectoryInfo DexFolder = new DirectoryInfo(Properties.Settings.Default.DexFolderPath);
static DirectoryInfo ExcelFile = new DirectoryInfo(Properties.Settings.Default.ExcelFilePath);
public SearchDialog(Main form)
{
InitializeComponent();
fromDateSelector.Checked = false;
toDateSelector.Checked = false;
MainForm = form;
}
public Main MainForm {get; set;}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
SearchParameters();
Close();
}
private void SearchParameters()
{
DateTime allTime = DateTime.Now.AddYears(-150);
DateTime current = DateTime.Now;
if (fromDateSelector.Checked == true)
{
allTime = fromDateSelector.Value;
}
if (toDateSelector.Checked == true)
{
current = toDateSelector.Value;
}
MainForm.GetFiles(DexFolder, current, allTime);
}
}
(back on Main form)
public void GetFiles(DirectoryInfo FilePath, DateTime from, DateTime to)
{
List<string> DexFileNames = new List<string>();
List<string> DexData = new List<string>();
IList<FileManagerView> fileManagerData = new BindingList<FileManagerView>();
string[] ExcelData = File.ReadAllLines(ExcelFile.ToString());
foreach (FileInfo fileInfo in FilePath.GetFiles("*.dex"))
{
DexFileNames.Add(fileInfo.Name);
}
foreach (string DexFileName in DexFileNames)
{
DateTime dexDate = File.GetCreationTime(FilePath + DexFileName);
string[] NameData = DexFileName.Split('_', '-', '.');
if (NameData.Length > 2)
{
dexDate = DateTime.ParseExact(NameData[1] + NameData[2], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
}
string DexPHYSID = NameData[0];
string machineNumber = "";
string machineLocation = "";
string telemetryDevice = "";
string routeNumber = "";
string machinePHYSID = "";
string driverName = "";
foreach (string line in ExcelData)
{
string[] lineData = line.Split(',');
if (DexPHYSID == lineData[14].Trim('"'))
{
machinePHYSID = lineData[14].Trim('"');
machineNumber = lineData[0].Trim('"');
machineLocation = lineData[2].Trim('"');
string RouteNumberFull = lineData[17].Trim('"');
string[] DriverName = lineData[18].Trim('"').Split('(');
telemetryDevice = lineData[8].Trim('"');
string[] RouteNumberData = RouteNumberFull.Split(' ');
driverName = DriverName[0];
try
{
routeNumber = RouteNumberData[1] + " " + RouteNumberData[2];
}
catch
{
}
}
}
if (DexPHYSID == machinePHYSID)
{
FileManagerView fileManagerView = new FileManagerView();
if (dexDate.ToString("dd-MM-yy") == from.ToString("dd-MM-yy") && dexDate.ToString("dd-MM-yy") == to.ToString("dd-MM-yy"))
{
fileManagerView.machineNumber = machineNumber;
fileManagerView.machineLocation = machineLocation;
fileManagerView.telemetryDevice = telemetryDevice;
fileManagerView.physid = DexPHYSID;
fileManagerView.routeNumber = routeNumber;
fileManagerView.date = dexDate;
fileManagerView.driver = driverName;
fileManagerData.Add(fileManagerView);
}
}
}
FileManagerPopulate(fileManagerData);
}
public class FileManagerView
{
public string machineNumber { get; set; }
public string machineLocation { get; set; }
public string telemetryDevice { get; set; }
public string physid { get; set; }
public string routeNumber { get; set; }
public string driver { get; set; }
public DateTime date { get; set; }
}
public void FileManagerPopulate(IList<FileManagerView> data)
{
dataGridView1.DataSource = data;
}
So the problem was the use of == operands instead of > and < when the GetFiles() method was checking if the file date was within the selected range.
I'm going to leave this here as it may help someone else looking for answers.
I am making an application which will save and load products. These products have three properties of a product name, customer name and firmware location. However, when I try to save them, it will only save one and keeps overwriting with the most recent product saved. The following is my code for the product class:
public class Product
{
//private product data
private string productName;
public string getProductName()
{
return this.productName;
}
public void setProductName (string inProductName)
{
this.productName = inProductName;
}
private string customerName;
public string getCustomerName()
{
return this.customerName;
}
public void setCustomerName (string inCustomerName)
{
this.customerName = inCustomerName;
}
private string firmwareLocation;
public string getFirmwareLocation()
{
return this.firmwareLocation;
}
public void setFirmwareLocation (string inFirmwareLocation)
{
this.firmwareLocation = inFirmwareLocation;
}
//constructor
public Product (string inProductName, string inCustomerName, string inFirmwareLocation)
{
productName = inProductName;
customerName = inCustomerName;
firmwareLocation = inFirmwareLocation;
}
//save method
public void Save (System.IO.TextWriter textOut)
{
textOut.WriteLine(productName);
textOut.WriteLine(customerName);
textOut.WriteLine(firmwareLocation);
}
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
At the end is my save methods.
Here is the code for when the user presses the add product button:
private void Add_Click(object sender, RoutedEventArgs e)
{
//get input from user
string inputCustomerName = customerNameTextBox.Text;
string inputProductName = productNameTextBox.Text;
string inputFirmwareLocation = firmwareTextBox.Text;
try
{
Product newProduct = new Product(inputProductName, inputCustomerName, inputFirmwareLocation);
newProduct.Save("products.txt");
MessageBox.Show("Product added");
}
catch
{
MessageBox.Show("Product could not be added");
}
}
You are not appending the text to your file, thats why it keeps overwriting the last entry over and over again.
Try to change your save method to:
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename, true);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
Notice the "true" as the second parameter in the StreamWriter constructor. This tells the StreamWriter to append the new line.
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've got the following code , where i define some operations to be done within a class and its variables:
namespace PPF_Converter_v10
{
public class ProgramStuff
{
protected List<String> OpenedFiles { get; private set; }
protected List<String> ValidFiles { get; private set; }
protected List<String> InvalidFiles { get; private set; }
protected List<String> FileData { get; private set; }
protected string FileContents { get; private set; }
public ProgramStuff()
{
OpenedFiles = new List<string>();
ValidFiles = new List<string>();
InvalidFiles = new List<string>();
FileData = new List<string>();
FileContents = string.Empty;
}
public void SelectFiles()
{
using (var FileSelect = new OpenFileDialog())
{
FileSelect.Multiselect = true;
FileSelect.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
FileSelect.Filter = "PPF Files (*.ppf)|*.ppf|CIP Files (*.cip)|*.cip";
FileSelect.Title = "Seclect a PPF or CIP File";
DialogResult dr = FileSelect.ShowDialog();
if (dr == DialogResult.OK)
{
foreach(var File in FileSelect.FileNames)
{
OpenedFiles.Add(File);
}
}
}
}
public void ReadFiles()
{
foreach(var File in OpenedFiles)
{
using (var fs = new FileStream(File, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
FileContents = string.Empty;
var len = (int)fs.Length;
var bits = new byte[len];
fs.Read(bits, 0, len);
// Dump 1024 bytes per line
for (int ix = 0; ix < len; ix += 1024)
{
//drawTextProgressBar(ix, (int)fs.Length);
var cnt = Math.Min(1024, len - ix);
var line = new byte[cnt];
Array.Copy(bits, ix, line, 0, cnt);
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
//Creating a big string with output
FileContents += Encoding.ASCII.GetString(line);
}
FileData.Add(FileContents);
}
}
}
public void FileDefiniton()
{
foreach(var File in FileData)
{
bool b = File.Contains("/HDMZoneCoverageValue") && File.Contains("/CIP3AdmInkColors");
if(b)
{
ValidFiles.Add(File);
}
else
{
InvalidFiles.Add(File);
}
}
}
public string XMLOutputFolder()
{
string XMLOutput = string.Empty;
using (var XMLOut = new FolderBrowserDialog())
{
XMLOut.ShowNewFolderButton = true;
XMLOut.RootFolder = Environment.SpecialFolder.MyComputer;
DialogResult dr = XMLOut.ShowDialog();
if(dr == DialogResult.OK)
{
XMLOutput = XMLOut.SelectedPath;
}
return XMLOutput;
}
}
public void ConvertedPPFFolder(string ConvertedPPF)
{
using (var ConvFolder = new FolderBrowserDialog())
{
ConvFolder.ShowNewFolderButton = true;
ConvFolder.RootFolder = Environment.SpecialFolder.MyComputer;
DialogResult dr = ConvFolder.ShowDialog();
if (dr == DialogResult.OK)
{
ConvertedPPF = ConvFolder.SelectedPath;
}
}
}
}//Closing class ProgramStuff
//Creating a child class called FileManipulation - manipulate files
public class FileManipulation: ProgramStuff
{
protected string PPFColors;
protected string[] ColorsNames;
public void ColorExtraction()
{
MessageBox.Show(ValidFiles.Count.ToString());
foreach (var data in ValidFiles)
{
Regex ColorNameRegex = new Regex("CIP3AdmSeparationNames(.*)CIP3AdmPSExtent");
var RegexAux = ColorNameRegex.Match(data);
PPFColors = RegexAux.Groups[1].ToString();
PPFColors = PPFColors.Replace("] def./", "").Replace("[", "").Replace(" (", "(").Replace("(", "").Replace(")", "|");
PPFColors = PPFColors.Remove(PPFColors.Length - 1, 1);
ColorsNames = PPFColors.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
}
Then, i have my form declaration, where i instantiate both and use them:
public partial class Form1 : Form
{
private FileManipulation FileOp;
private ProgramStuff GetFiles;
public Form1()
{
InitializeComponent();
FileOp = new FileManipulation();
GetFiles = new ProgramStuff();
}
private void button1_Click(object sender, EventArgs e)
{
GetFiles.SelectFiles();
GetFiles.ReadFiles();
GetFiles.FileDefiniton();
}
The question is: i can do all operations i need using the instantiated class ProgramStuff (called GetFiles). But, right here, when i call a method from the child class:
private void button5_Click(object sender, EventArgs e)
{
FileOp.ColorExtraction();
}
I can't acess data stored on the parent class. When debugging, the List called ValidFiles has 0 elements ; and there were elements added to it on the parent class. Is there way for me access those elements ? Thats the main point of my question.
Thanks !
I think the issue you have is that you are instantiating Child and Parent Class:
FileOp = new FileManipulation();
GetFiles = new ProgramStuff();
and you are trying to use data stored in two different objects.
As I see it, you only have to instantiate Child Class:
FileOp = new FileManipulation();
Then you will have to use FileOp on your code calling child and parents methods.
I hope it helps.