I get an memory exception while loading a 4GB file. i have to do that twice but i have enougth memmory to load them. the memmory exception occures when i have 3gb left or more.:(.
Method:
public TableModel LoadTable(string path) {
TableModel model = new TableModel();
using (FileStream filestream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8)) {
string line = "";
bool isHeader = true;
int counter = 0;
List<string> rows = new List<string>();
while ((line = reader.ReadLine()) != null) {
if (isHeader) {
model.Columns = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
isHeader = false;
continue;
} else {
if (Settings.Default.RonudSet != 0) {
rows.Add(RoundDecimals(line));
} else {
rows.Add(line);
}
}
counter++;
}
model.RowCount = counter;
model.ColumnsCount = model.Columns.Length;
model.Keys = new HashSet<string>(rows);
}
}
return model;
}
Exception:
System.OutOfMemoryException was unhandled
The function evaluation was disabled because of an out of memory exception.
TableModel:
class TableModel {
private string tableName;
private string[] columns;
private HashSet<string> keys;
public int ColumnsCount { get; set; }
public int RowCount { get; set; }
public string TableName { get { return tableName; } set { this.tableName = value; } }
public string[] Columns { get { return columns; } set { this.columns = value; } }
public HashSet<string> Keys { get { return keys; } set { this.keys = value; } }
}
Start Compare:
if (newFile.Name.Equals(currFile.Name)) {
FileLoader loader = new FileLoader();
TableModel newModel = loader.LoadTable(newFile.ToString());
TableModel currentModel = loader.LoadTable(currFile.ToString());
newModel.TableName = newFile.Name;
currentModel.TableName = currFile.Name;
new Compare(newModel, currentModel, currFile.Directory.Name);
break;
}
Compare:
private void CheckColumns() {
bool sameColumnCount = CheckColumnsCount();
int counter = 0;
currentContent = new HashSet<string>(currentModel.Columns);
newContent = new HashSet<string>(newModel.Columns);
foreach (string header in currentContent) {
if (!newContent.Contains(header)) {
headersNotFoundInN.Add(header);
}
}
foreach (string header in newContent) {
if (!currentContent.Contains(header)) {
headersNotFoundInC.Add(header);
}
}
if (currentModel.ColumnsCount == newModel.ColumnsCount) {
for (int i = 0; i < currentModel.ColumnsCount; i++) {
if (currentModel.Columns[i] == newModel.Columns[i]) {
counter++;
}
}
if (counter == currentModel.ColumnsCount) {
headerSequence = true;
} else {
headerSequence = false;
}
} else {
headerSequence = false;
}
bool emptyNotFoundIn = false;
if (headersNotFoundInC.Count == 0 && headersNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameColumnCount, headerSequence, emptyNotFoundIn);
}
private void CheckRows() {
bool sameRowCount = CheckRowCount();
currentContent = new HashSet<string>(currentModel.Keys);
newContent = new HashSet<string>(newModel.Keys);
foreach (string key in currentContent) {
if (!newContent.Contains(key)) {
rowNotFoundInN.Add(key);
}
}
foreach (string key in newContent) {
if (!currentContent.Contains(key)) {
rowNotFoundInC.Add(key);
}
}
bool emptyNotFoundIn = false;
if (rowNotFoundInC.Count == 0 && rowNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameRowCount, emptyNotFoundIn);
}
Its a table with many rows that i have to compare with a similar table. at the end i have to give a report about the diffrences. but i fail here where i have to load this massive file.
try using BufferedStream
using (BufferedStream bs = new BufferedStream(filestream))
{
}
Related
In my case, while calling API (GET Method), I should send the below query as part of the body.
URI : GET XXX/_search
Body:
{
"query":
{
"match_all":
{
}
}
}
As of now, I'm hard-coding the string and appending to the resource body.
hopefully below code snippet can help you.
Consumer:
JsonField jsn1 = new JsonField() { Name = "_id"};
jsn1.AddValue("1234");
JsonField jsn2 = new JsonField() { Name = "_name" };
jsn2.AddValue("CDE");
JsonField jsn0 = new JsonField(true) { Name = "match" };
JsonField jsn = new JsonField(true) { Name = "query" };
JsonConverter.MapField(jsn0, jsn1);
JsonConverter.MapField(jsn, jsn0);
JsonConverter jsonconverter = new JsonConverter();
jsonconverter.Add(jsn);
JsonField jsn3 = new JsonField() { Name = "name" };
jsn3.AddValue("temp");
jsonconverter.Add(jsn3);
Console.WriteLine(jsonconverter.GetJsonFormat());
Check logic below.
public class JsonConverter
{
LinkedList<JsonField> jsonlinking = new LinkedList<JsonField>();
public void Add(JsonField jsonfield)
{
LinkedListNode<JsonField> jsonelement = jsonlinking.Last;
if (jsonelement != null)
{
jsonelement.Value.SpecialChar = ",";
}
jsonlinking.AddLast(jsonfield);
}
public string GetJsonFormat()
{
jsonformat = string.Empty;
jsonformat += "{" + Environment.NewLine;
foreach (var item in jsonlinking)
{
ReadJson(item);
}
jsonformat += Environment.NewLine + "}" + Environment.NewLine;
return jsonformat;
}
public static void MapField(JsonField primary, JsonField relative)
{
primary.Next = relative;
}
public static void MapField(Queue<JsonField> linksource)
{
JsonField primary = null;
JsonField relative = null;
foreach (var item in linksource)
{
if (primary == null)
{
primary = item;
}
else if (relative == null)
{
relative = null;
}
else
{
JsonConverter.MapField(primary, relative);
primary = null;
relative = null;
}
}
}
private string jsonformat = string.Empty;
private void ReadJson(JsonField field)
{
if (field != null)
{
jsonformat += #"""";
jsonformat += field.Name;
jsonformat += #"""";
if (field.isContainer)
{
jsonformat += #":{" + Environment.NewLine;
int count = field.ChildNodes.Count();
if (count > 0)
{
foreach (var item in field.ChildNodes)
{
ReadJson(item);
}
}
jsonformat = (jsonformat.Substring(jsonformat.Length - 1, 1) == ",") ? jsonformat.Substring(0, jsonformat.Length - 1) : jsonformat;
jsonformat += #"}" + field.SpecialChar + Environment.NewLine;
}
else
{
jsonformat += #":";
jsonformat += field.GetValues();
}
}
}
}
public class JsonField
{
private int Size = 1;
private int CurrentIndex = 0;
public string Name { get; set; }
private string[] _value;
public string[] Value { get { return _value; } private set { _value = value; } }
public bool isContainer{get;set;}
public JsonField()
{
this.Value = new string[this.Size];
}
private Queue<JsonField> _next = new Queue<JsonField>();
public JsonField Next {
set
{
if (this._next.Count>0)
{
foreach (var item in this._next)
{
item.SpecialChar = ",";
}
}
this._next.Enqueue(value);
}
}
public IEnumerable<JsonField> ChildNodes { get { return this._next; } }
public JsonField(int valuesize)
{
this.Size = valuesize;
this.Value = new string[this.Size];
}
public JsonField(bool iscontainer)
{
this.isContainer = iscontainer;
}
public void AddValue(string value)
{
if (CurrentIndex >= this.Value.Length)
{
throw new ArgumentException("Index Out of Range over Value Array");
return;
}
this.Value[CurrentIndex] = value;
CurrentIndex++;
}
public void ClearValue()
{
this.Value = null;
this.Value = new string[this.Size];
}
public string GetValues()
{
if (this.Value.Length == 1)
{
return #"""" + this.Value[0] + #"""";
}
string returns=string.Empty;
for (int index = 0; index < this.Value.Length; index++)
{
returns += #"""" + this.Value[index] + #"""";
if ((index +1) < this.Value.Length)
{
returns += ",";
}
}
return "[" + returns+ "]";
}
public string SpecialChar { get; set; }
}
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.
I have two task which work as producer and consumer, but they don't run in parallel. Second one waits for the first one to compelete. Can you explain why and how can I correct this? I want both of them run at the same time. (I try many varians, but all of them don't work well)
class DirectoryReader
{
private readonly string _dir ;
private Processor[] _processors;
private string[] _files;
private readonly Regex _rx = new Regex(#"([^.\\]+)\.cs");
private Queue<Processor> queue = new Queue<Processor>();
private bool isOff;
private AutoResetEvent isAvailable = new AutoResetEvent(false);
private StreamWriter log = new StreamWriter("Log.txt");
public DirectoryReader(string dir)
{
_dir = dir;
}
public Container[] ProcessAllFiles()
{
_files = Directory.GetFiles(_dir, "*.cs", SearchOption.AllDirectories);
_processors = new Processor[_files.Length];
var thread = Task.Run(() => Compute());
var thread2 = Task.Run(() => Read());
thread.Wait();
}
public void Read()
{
for (var i = 0; i < _files.Length; i++)
{
try
{
var matches = _rx.Matches(_files[i]);
foreach (var match in matches)
{
//Console.WriteLine(match);
lock (log)
{
log.WriteLine(match);
}
}
_processors[i] = new Processor(matches[matches.Count - 1].ToString(), File.ReadAllText(_files[i]));
lock (queue)
{
queue.Enqueue(_processors[i]);
isAvailable.Set();
}
}
catch (IOException ex)
{
Console.WriteLine(ex.Message + _files[i]);
}
}
isOff = true;
}
public void Compute()
{
Processor proc = null;
int ccount = 0;
while (true)
{
lock (queue)
{
if ((ccount = queue.Count) > 0)
{
proc = queue.Dequeue();
}
}
if (ccount == 0)
{
if (isOff)
{
return;
}
else
{
isAvailable.WaitOne();
}
}
if (proc != null)
{
//Some calculations on proc
lock (log)
{
log.WriteLine("+++++" + proc.FileName);
}
}
}
}
}
UPD1: I rewrite this code with using BlockingCollection, but is still doesn't work correct
class DirectoryReader
{
private readonly string _dir ;
private Processor[] _processors;
private string[] _files;
private readonly Regex _rx = new Regex(#"([^.\\]+)\.cs");
private List<Container> answer = new List<Container>();
BlockingCollection<FileContainer> dataItems = new BlockingCollection<FileContainer>();
public DirectoryReader(string dir)
{
_dir = dir;
}
public void ProcessAllFiles()
{
_files = Directory.GetFiles(_dir, "*.cs", SearchOption.AllDirectories);
_processors = new Processor[_files.Length];
var task = Task.Factory.StartNew(Compute);
var task2 = Task.Factory.StartNew(Read);
Task.WaitAll(task, task2);
}
public void Read()
{
for (var i = 0; i < _files.Length; i++)
{
try
{
var matches = _rx.Matches(_files[i]);
dataItems.Add(new FileContainer{
Name = matches[matches.Count - 1].ToString(),
Content = File.ReadAllText(_files[i])});
}
catch (IOException ex)
{
Console.WriteLine(ex.Message + _files[i]);
}
}
dataItems.CompleteAdding();
}
public void Compute()
{
FileContainer proc = null;
while (!dataItems.IsCompleted)
{
try
{
proc = dataItems.Take();
}
catch (InvalidOperationException) { }
if (proc != null)
{
//Some calculations
}
}
}
}
I am storing multiple items into one session variable: which is 4 different words.
I need to be able to take those 4 different wordsin the one session, and store them into separate variables so i can use them, is this possible? and if so how?
_application just holds text from a series of text from text boxes.
Here is my session class.
public class JobApplicantSession
{
public JobApplication ApplicationSession
{
get {if (HttpContext.Current.Session["Application"] != null)
return (JobApplication)HttpContext.Current.Session["Application"];
return null; }
set{ HttpContext.Current.Session["Application"] = value; }
}
Job application: Job application holds information from a list of textboxes thats it.
JobApplication _application;
_application = new JobApplication(jobID);
if (i < _applicant.Fields.Count)
_applicant.AddAnswer((_controlsList[i] as TextBox).Text);
else
_application.AddAnswer((_controlsList[i] as TextBox).Text);
add to the session:
_sessions.ApplicationSession = _application;
I can get the session:
JobApplication application;
var jas = new JobApplicantSession();
application = jas.ApplicationSession;
Job application:
public class JobApplication
{
private int _jobID = -1;
public JobApplication(int jobID)
{
_jobID = jobID;
}
List<String> _answers = new List<String>();
List<JobApplicationField> _fields = new List<JobApplicationField>();
public List<JobApplicationField> Fields
{
get { return _fields; }
}
public int JobID()
{
return _jobID;
}
public List<String> Answers
{
get { return _answers; }
set { _answers = value; }
}
public void AddAnswer(String answer)
{
_answers.Add(answer);
}
public void AddField(JobApplicationField field)
{
if (field.HasFieldID)
{
for (int i = 0; i < _fields.Count(); i++)
{
if (_fields[i].FieldID == field.FieldID)
{
_fields[i] = field;
return;
}
}
}
_fields.Add(field);
}
public void PopulateFromDatabase()
{
JobPositionSystemDAL dal = new JobPositionSystemDAL();
DataSet data = dal.OpenJobOpeningByID(_jobID);
foreach (DataRow row in data.Tables[0].Rows)
{
JobApplicationField field = new JobApplicationField(Convert.ToInt32(row["QUESTIONID"]), row["QUESTIONTEXT"].ToString(), Convert.ToBoolean(row["HASCORRECTANSWER"]), row["CORRECTANSWER"].ToString(), Convert.ToBoolean(row["ISREQUIRED"]));
AddField(field);
}
}
public bool Verify()
{
if (_fields.Count != Answers.Count)
throw new Exception("Number of answers != number of fields");
for (int i = 0; i < _fields.Count; i++)
{
if (_fields[i].HasCorrectAnswer == true && _fields[i].CorrectAnswer != _answers[i])
return false;
}
return true;
}
public void Save()
{
JobPositionSystemDAL database = new JobPositionSystemDAL();
foreach(JobApplicationField field in _fields)
{
field.Save(_jobID, ref database);
}
//reload to get the Field/question ID for any new fields
Reload();
}
public void Reload()
{
_fields = new List<JobApplicationField>();
Load(_jobID);
}
public void Load(int jobID)
{
_jobID = jobID;
DataSet ds = DB.OpenJobOpeningByID(jobID);
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
int questionID = 0;
object obj = row["QUESTIONID"];
Int32.TryParse(obj.ToString(), out questionID);
//int jobApplicationID = Int32.Parse(row["JOBAPPLICATIONID"] as String);
string questionText = row["QUESTIONTEXT"] as String;
int type = Int32.Parse(row["TYPEID"].ToString());
bool hasCorrectAnswer = (row["HASCORRECTANSWER"] as String == "0") ? false : true;
string correctAnswer = row["CORRECTANSWER"] as String;
bool required = ((row["ISREQUIRED"] as String) == "0") ? false : true;
JobApplicationField field = new JobApplicationField(questionID, questionText, hasCorrectAnswer, correctAnswer, required);
AddField(field);
}
}
private JobPositionSystemDAL _db;
private JobPositionSystemDAL DB
{
get
{
if (null == _db)
_db = new JobPositionSystemDAL();
return _db;
}
}
}
}
How can i loop through and store each item into its own variable?
i will need 4 variables.
Hope it is what you are asking. If you want to store array of objects in session state you can either sotre array directly:
HttpContext.Current.Session["data"] = new int[32];
or dynamically create names based on element index (strange, but possible):
var data = new int[3];
HttpContext.Current.Session["data" + 0.ToString()] = data[0];
HttpContext.Current.Session["data" + 1.ToString()] = data[1];
HttpContext.Current.Session["data" + 2.ToString()] = data[2];
Read in reverse order:
var dataArray = (int[])(HttpContext.Current.Session["data"]);
or
var data = new int[3];
data[0] = (int)HttpContext.Current.Session["data" + + 0.ToString()];