Monotorrent does not download files - c#

I'm developing an application that needs to download a directory (11 GB in size), via torrent, but it only creates 0 byte files. When testing with a small volume (~ 100 MB) - everything is fine. I tried torrent files from different trackers, nothing happened. What's wrong? Help...
public void InitTorrent(string savePath)
{
this.engine = new ClientEngine(new EngineSettings());
this.savePath = savePath;
CPBMax = 100;
CPBMin = 0;
CPBVal = 0;
}
public void DownloadTorrent(string path)
{
Torrent torrent = Torrent.Load(path);
TorrentManager manager = new TorrentManager(torrent, savePath, new TorrentSettings());
engine.Register(manager);
double TorrentSize = manager.Torrent.Size;
TorrentSize = Math.Round(TorrentSize/(1024 * 1024), 1);
double TorrentProcess = 0;
double TorrentDowload = 0;
string HashSumm = manager.InfoHash.ToString();
TProcess = "Проверка мода";
if (HashSumm != Hash)
{
// Запуск
manager.Start();
bool _running = true;
TProcess = "Загрузка мода";
while (_running)
{
if (manager.State == TorrentState.Stopped)
{
_running = false;
}
BTNPlayEn = 0;
TorrentDowload = manager.Monitor.DataBytesDownloaded;
TorrentProcess = Math.Round(manager.Progress, 1);
if (manager.Progress > 0.0 ^ engine.TotalDownloadSpeed > 0.0)
{
CPBIndet = 0;
}
CPBVal = TorrentProcess;
Version = "Загружено: " + Math.Round((TorrentSize * TorrentProcess)/100, 1) + "/" + TorrentSize + " Mb" + " ⇓ " + Math.Round(engine.TotalDownloadSpeed / 1024.0, 1) + " kB/sec";
}
Version = "Завершено";
//CPBIndet = 0;
if (TorrentProcess == 100)
{
Hash = HashSumm;
TProcess = "Готов к запуску";
BTNPlayContent = "Играть";
BTNPlayEn = 1;
// CPBIndet = 0;
}
SetSettings();
}
else
{
TProcess = "Готов к запуску";
//CPBIndet = 0;
}
}

Related

Reading /proc/stat values to get cpu usage throws DivideByZeroException

I have been following this stack overflow article :
Accurate calculation of CPU usage given in percentage in Linux?
It is written in different language so I decided to follow the logic and convert it to C#.
public class HardwareInfoManager : IHardwareInfoManager
{
private IConfiguration Configuration;
private List<long> oldCpuStatistics;
private List<long> newCpuStatistics;
public HardwareInfoManager(IConfiguration Configuration)
{
this.Configuration = Configuration;
oldCpuStatistics = new List<long>();
newCpuStatistics = new List<long>();
}
private decimal GetCPUUsage()
{
string cpuUsagePath = "//proc//stat";
StringBuilder sb = new StringBuilder();
if (File.Exists(cpuUsagePath) && oldCpuStatistics.IsNullOrEmpty())
{
SaveIntsFromFilePath(cpuUsagePath, oldCpuStatistics);
Task.Delay(200);
GetCPUUsage();
}
if (File.Exists(cpuUsagePath) && !oldCpuStatistics.IsNullOrEmpty())
{
SaveIntsFromFilePath(cpuUsagePath, newCpuStatistics);
var prevIdle = oldCpuStatistics[3] + oldCpuStatistics[4];
decimal idle = newCpuStatistics[3] + newCpuStatistics[4];
var prevNonIdle = oldCpuStatistics[0] + oldCpuStatistics[1] + oldCpuStatistics[2] + oldCpuStatistics[5] + oldCpuStatistics[6] + oldCpuStatistics[7];
decimal nonIdle = newCpuStatistics[0] + newCpuStatistics[1] + newCpuStatistics[2] + newCpuStatistics[5] + newCpuStatistics[6] + newCpuStatistics[7];
var prevTotal = prevIdle + prevNonIdle;
decimal total = idle + nonIdle;
var totalDifference = total - prevTotal;
var idleDifference = idle - prevIdle;
decimal cpuPercentage = (totalDifference - idleDifference / totalDifference) * 100;
cpuPercentage = Math.Round(cpuPercentage, 2);
return cpuPercentage;
}
else
{
return 0;
}
}
private List<long> SaveIntsFromFilePath(string path, List<long> longList)
{
var firstLineOfCPUFile = File.ReadAllLines(path).First();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < firstLineOfCPUFile.Length; i++)
{
//take first index of a number until it reaches a whitespace, add to an int array
if (Char.IsNumber(firstLineOfCPUFile[i]))
{
sb.Append(firstLineOfCPUFile[i]);
//start with this index until it reaches whitespace
}
if (Char.IsWhiteSpace(firstLineOfCPUFile[i]) && i > 5)
{
longList.Add(long.Parse(sb.ToString()));
sb.Clear();
//start with this index until it reaches whitespace
}
}
sb.Clear();
return longList;
}
}
Unable to debug this as it runs on a remote raspberry machine , it throws this error:
Job HardwareInfo.HardwareInfo threw an exception.
Quartz.SchedulerException: Job threw an unhandled exception. --->
System.DivideByZeroException: Attempted to divide by zero.
95% of the time it throws the exception because of the totaldifference being 0. In the other cases it works and throws the whole info such as this:
"TenantId":null,"Hostname":"DEV1\n","Temperature":66.218,"MemoryStats":{"MemoryTotal":"1985984
kB","MemoryFree":"1072468 kB","MemoryAvailable":"1438552
kB"},"CPUUsage":0.0
Please advise, I am stuck for 2 days on this now.
This is how I solved it.
public class HardwareInfoManager : IHardwareInfoManager
{
private IConfiguration Configuration;
private List<long> oldCpuStatistics;
private List<long> newCpuStatistics;
public HardwareInfoManager(IConfiguration Configuration)
{
this.Configuration = Configuration;
oldCpuStatistics = new List<long>();
newCpuStatistics = new List<long>();
}
public HardwareInfoDto GetHardWareInfo()
{
return new HardwareInfoDto()
{
TenantId = Configuration.GetValue<string>("TenantId"),
Hostname = GetHostName(),
Temperature = GetTemperature(),
MemoryStats = GetMemoryStats(),
CPUUsage = GetCPUUsage()
};
}
private string GetHostName()
{
string hostNameFilePath = "//etc//hostname";
if (File.Exists(hostNameFilePath))
{
return (File.ReadAllText(hostNameFilePath));
}
else
{
return "";
}
}
private decimal GetTemperature()
{
string temperatureFilePath = "//sys//class//thermal//thermal_zone0//temp";
if (File.Exists(temperatureFilePath))
{
decimal output = Convert.ToDecimal(File.ReadAllText(temperatureFilePath));
output /= 1000;
//string temperature = output.ToString() + "°C";
return output;
//var file= File.ReadAllLines();
}
else
{
return 0.00M;
}
}
private MemoryStatsDto GetMemoryStats()
{
MemoryStatsDto memoryStatsDto = new MemoryStatsDto();
string memoryStatsPath = "//proc//meminfo";
if (File.Exists(memoryStatsPath))
{
var file = File.ReadAllLines(memoryStatsPath);
//Skipping all lines we are not interested in
for (int i = 0; i < 3; i++)
{
int firstOccurenceOfDigit = 0;
var memoryLine = file[i];
//index of first number , start the string until the end and store it
for (int j = 0; j < memoryLine.Length; j++)
{
if (Char.IsNumber(memoryLine[j]))
{
firstOccurenceOfDigit = j;
break;
}
}
var memoryValue = memoryLine.Substring(firstOccurenceOfDigit);
switch (i)
{
case 0:
memoryStatsDto.MemoryTotal = memoryValue;
break;
case 1:
memoryStatsDto.MemoryFree = memoryValue;
break;
case 2:
memoryStatsDto.MemoryAvailable = memoryValue;
break;
default: break;
}
}
return memoryStatsDto;
}
else
{
memoryStatsDto.MemoryAvailable = "";
memoryStatsDto.MemoryFree = "";
memoryStatsDto.MemoryTotal = "";
return memoryStatsDto;
}
}
private decimal GetCPUUsage()
{
string cpuUsagePath = "//proc//stat";
StringBuilder sb = new StringBuilder();
if (File.Exists(cpuUsagePath) && oldCpuStatistics.IsNullOrEmpty())
{
oldCpuStatistics = SaveIntsFromFilePath(cpuUsagePath, oldCpuStatistics);
Thread.Sleep(10000);
GetCPUUsage();
}
if (File.Exists(cpuUsagePath) && !oldCpuStatistics.IsNullOrEmpty())
{
newCpuStatistics = SaveIntsFromFilePath(cpuUsagePath, newCpuStatistics);
var prevIdle = oldCpuStatistics[3] + oldCpuStatistics[4];
decimal idle = newCpuStatistics[3] + newCpuStatistics[4];
var prevNonIdle = oldCpuStatistics[0] + oldCpuStatistics[1] + oldCpuStatistics[2] + oldCpuStatistics[5] + oldCpuStatistics[6] + oldCpuStatistics[7];
decimal nonIdle = newCpuStatistics[0] + newCpuStatistics[1] + newCpuStatistics[2] + newCpuStatistics[5] + newCpuStatistics[6] + newCpuStatistics[7];
var prevTotal = prevIdle + prevNonIdle;
decimal total = idle + nonIdle;
var totalDifference = total - prevTotal;
var idleDifference = idle - prevIdle;
decimal cpuPercentage = 0;
Log.Logger.Information($"TotalDifference is {totalDifference}");
Log.Logger.Information($"IdleDifference is {idleDifference}");
cpuPercentage = (totalDifference - idleDifference) * 100M / (totalDifference);
cpuPercentage = Math.Round(cpuPercentage, 2);
return cpuPercentage;
}
else
{
return 0;
}
}
private List<long> SaveIntsFromFilePath(string path, List<long> longList)
{
var firstLineOfCPUFile = File.ReadAllLines(path).First();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < firstLineOfCPUFile.Length; i++)
{
//take first index of a number until it reaches a whitespace, add to an int array
if (Char.IsNumber(firstLineOfCPUFile[i]))
{
sb.Append(firstLineOfCPUFile[i]);
//start with this index until it reaches whitespace
}
if (Char.IsWhiteSpace(firstLineOfCPUFile[i]) && i > 5)
{
longList.Add(long.Parse(sb.ToString()));
sb.Clear();
//start with this index until it reaches whitespace
}
}
sb.Clear();
for (int i = 0; i < longList.Count; i++)
{
Log.Logger.Information($"LongList index {i} value is {longList[i]}");
}
return longList;
}
}

C# I create a new Picturebox and now my Textboxes won't give me any values back

I'm creating a new Picturebox via code, but now my TextBoxes don't give me any values. I think they went out of focus, or their controls aren't working anymore, here's the code so far:
private void button1_Click(object sender, EventArgs e)
{
int ErrorCode = 0;
string NewName = NewPointName.Text;
int X, Y;
Application.DoEvents();
if (NewPointName.Text == "")
ErrorCode = 1;
else
for (int i = 0; i < Names + 1; i++)
{
if (PointName[i] == NewName)
ErrorCode = 2;
}
if (ErrorCode > 0)
MessageBox.Show("Error " + ErrorCode);
else
{
if (Convert.ToInt32(NewPointXBox.Text) > 60)
X = 60;
else if (Convert.ToInt32(NewPointXBox.Text) < -60)
X = -60;
else if (NewPointXBox.Text == "")
X = 0;
else
X = Convert.ToInt32(NewPointXBox.Text);
if (Convert.ToInt32(NewPointYBox.Text) > 60)
Y = 60;
else if (Convert.ToInt32(NewPointYBox.Text) < -60)
Y = -60;
else if (NewPointYBox.Text == "")
Y = 0;
else
Y = Convert.ToInt32(NewPointYBox.Text);
Punkt.GiveName(NewName, Names);
Punkt.GiveCoordinates(X, Y, Names);
PointName[Names] = NewName;
NewPointName.Text = "";
NewPointXBox.Text = "";
NewPointYBox.Text = "";
Application.DoEvents();
UpdatePoint();
CreatePoint(X, Y, NewName, Names);
Names++;
ErrorCode = 0;
NewName = "";
}
}
public void CreatePoint(int X, int Y, string name, int i)
{
int StartPointX = 450, StartPointY = 450, Factor = 7;
if (RadioG6060.Checked)
{
StartPointX = 454;
StartPointY = 449;
Factor = 7;
}
Dot[i] = new PictureBox();
this.Controls.Add(Dot[i]);
Dot[i].Name = "PB_" + name;
Dot[i].Size = new Size(10, 10);
Dot[i].Image = Image.FromFile("../Dot.png");
Dot[i].Anchor = AnchorStyles.Left;
Dot[i].Location = new Point(StartPointX, StartPointY);
Dot[i].Visible = true;
InitializeComponent();
Dot[i].BringToFront();
Dot[i].Location = new Point(Dot[i].Location.X + (X * Factor), Dot[i].Location.Y - (Y * Factor));
Application.DoEvents();
}
I think it's the this.controls.Add(Dot[i]) that throws it off, because now I can't access the text in my NewPointName textbox.
How can I focus the program back on the form or do generally anything that could activate the boxes again?
I just solved the problem, I just had to leave out the InitializeComponent(), then it worked. Turns out that if you do that, the already existing components get blocked and can't be changed in any options of themselves anymore.

C# How can I get timer to tick properly?

Making an application that can take Youtube links and add them to a queue and then play them until the queue is empty. Currently my timer1_Tick doesn't seem to be executing and I'm not sure why :(
//timer1_Tick
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
Video.Movie = "";
q.Dequeue();
qq.Dequeue();
}
Here is the meat and potatoes
if (e.ChatMessage.Message.StartsWith("!songrequest"))
{
var myString = e.ChatMessage.Message.ToString();
var newString = myString.Remove(0, myString.IndexOf(' ') + 1);
var getID = newString.Remove(0, newString.IndexOf('=') + 1);
var vUrl = "https://www.youtube.com/v/" + getID + "&autoplay=1";
var vUrlString = vUrl.ToString();
q.Enqueue(vUrlString);
qq.Enqueue(getID.ToString());
string[] array = new string[q.Count];
string[] array2 = new string[qq.Count];
q.CopyTo(array, 0);
qq.CopyTo(array2, 0);
if (timer1.Enabled == false)
{
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
else
{
client.SendMessage("It's still running somehow.");
}
here you are checking disabled timer and only if it is not enabled it will go into condition..
if (timer1.Enabled == false)
{
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
so if you are starting timer, on timer1.Start(), you need to enable it first.
try
if (timer1.Enabled == false)
{
timer1.Enabled = true;
for (int i = 0; i < array.Length; i++)
{
YouTubeVideo video = new Helix.YouTubeVideo(array2[i]);
var gDur = getDuration(video.duration);
string[] time = gDur.ToString().Split(' ');
int min = int.Parse(time[0]);
int sec = int.Parse(time[1]);
int msm = min * 60000;
int mss = sec * 1000;
int dur = msm + mss;
timer1.Interval = dur;
Video.Movie = array[i];
timer1.Start();
client.SendMessage("Now playing: " + video.title + ".");
client.SendMessage($"Timer set to { dur } ms.");
}
}
You need to enable the timer, its defaulted to false.

Odd C# behavior

I'm a hobby programmer.
I tried to ask this question earlier on a very unstructured way (Sorry again), now I try to ask on the proper way.
I wrote the following code that seems to work unreliably.
The code was written like this for several reasons. I know it's messy but it should still work. To explain why I wrote it like this would mean that I need to explain several weeks' of work that is quite extensive. Please accept that this is at least the least worse option I could figure out. In the below sample I removed all sections of the code that are not needed to reproduce the error.
What this program does in a nutshell:
The purpose is to check a large number of parameter combinations for a program that receives streaming data. I simulate the original process to test parameter combinations.
First data is read from files that represents recorded streaming data.
Then the data is aggregated.
Then I build a list of parameters to test for.
Finally I run the code for each parameter combination in parallel.
Inside the parallel part I calculate a financial indicator called the bollinger bands. This is a moving average with adding +/- standard deviation. This means the upper line and the lower line should only be equal when variable bBandDelta = 0. However sometimes it happens that CandleList[slot, w][ctr].bollingerUp is equal to CandleList[slot, w][ctr].bollingerDown even when bBandDelta is not 0.
As a result I don't understand how can line 277 kick in. It seems that sometimes the program fails to write to the CandleList[slot, w][ctr]. However this should not be possible because (1) I lock the list and (2) I use ConcurrentBag. Could I have some help please?
Source files are here.
The code is:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Justfortest
{
class tick : IComparable<tick> //Data element to represent a tick
{
public string disp_name; //ticker ID
public DateTime? trd_date; //trade date
public TimeSpan? trdtim_1; //trade time
public decimal trdprc_1; //price
public int? trdvol_1; //tick volume
public int CompareTo(tick other)
{
if (this.trdprc_1 == other.trdprc_1)
{
return other.trdprc_1.CompareTo(this.trdprc_1); //Return the later item
}
return this.trdprc_1.CompareTo(other.trdprc_1); //Return the earlier item
}
}
class candle : IComparable<candle> //Data element to represent a candle and all chart data calculated on candle level
{
public int id = 0;
public DateTime? openDate;
public TimeSpan? openTime;
public DateTime? closeDate;
public TimeSpan? closeTime;
public decimal open = 0;
public decimal high = 0;
public decimal low = 0;
public decimal close = 0;
public int? volume = 0;
public decimal totalPrice = 0;
public decimal bollingerUp = 0; //Bollinger upper line
public decimal bollingerDown = 0; //Bollinger below line
public int CompareTo(candle other)
{
if (totalPrice == other.totalPrice)
{
return other.totalPrice.CompareTo(totalPrice); //Return the later item
}
return totalPrice.CompareTo(other.totalPrice); //Return the earlier item
}
}
class param : IComparable<param> //Data element represent a trade event signal
{
public int par1;
public int bollPar;
public int par2;
public int par3;
public int par4;
public int par5;
public int par6;
public decimal par7;
public decimal par8;
public decimal par9;
public decimal par10;
int IComparable<param>.CompareTo(param other)
{
throw new NotImplementedException();
}
}
class programCLass
{
void myProgram()
{
Console.WriteLine("Hello");
Console.WindowWidth = 180;
string[] sources = new string[]
{
#"C:\test\source\sourceW1.csv",
#"C:\test\source\sourceW2.csv",
};
List<candle>[] sourceCandleList = new List<candle>[sources.Count()];
List<param> paramList = new List<param>(10000000);
var csvAnalyzer = new StringBuilder();
{
List<tick>[] updatelist = new List<tick>[sources.Count()];
Console.WriteLine("START LOAD");
for (var i = 0; i < sources.Count(); i++)
{
var file = sources[i];
updatelist[i] = new List<tick>();
// ---------- Read CSV file ----------
var reader = new StreamReader(File.OpenRead(file));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
tick update = new tick();
update.disp_name = values[0].ToString();
update.trd_date = Convert.ToDateTime(values[1]);
update.trdtim_1 = TimeSpan.Parse(values[2]);
update.trdprc_1 = Convert.ToDecimal(values[3]);
update.trdvol_1 = Convert.ToInt32(values[4]);
updatelist[i].Add(update);
}
Console.WriteLine(i);
}
Console.WriteLine("END LOAD"); // All files are in the memory
// Aggreagate
Console.WriteLine("AGGREGATE START");
int tickAggr = 500;
for (var w = 0; w < sources.Count(); w++)
{
sourceCandleList[w] = new List<candle>();
List<tick> FuturesList = new List<tick>();
foreach (var update in updatelist[w])
{
tick t = new tick();
t.disp_name = update.disp_name.ToString();
t.trd_date = update.trd_date;
t.trdtim_1 = update.trdtim_1;
t.trdprc_1 = Convert.ToDecimal(update.trdprc_1);
t.trdvol_1 = update.trdvol_1;
// Add new tick to the list
FuturesList.Add(t);
if (FuturesList.Count == Math.Truncate(FuturesList.Count / (decimal)tickAggr) * tickAggr)
{
candle c = new candle();
c.openDate = FuturesList[FuturesList.Count - tickAggr].trd_date;
c.openTime = FuturesList[FuturesList.Count - tickAggr].trdtim_1;
c.closeDate = FuturesList.Last().trd_date;
c.closeTime = FuturesList.Last().trdtim_1;
c.open = FuturesList[FuturesList.Count - tickAggr].trdprc_1;
c.high = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Max().trdprc_1;
c.low = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Min().trdprc_1;
c.close = FuturesList.Last().trdprc_1;
c.volume = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Sum(tick => tick.trdvol_1);
c.totalPrice = (c.open + c.high + c.low + c.close) / 4;
sourceCandleList[w].Add(c);
if (sourceCandleList[w].Count == 1)
{
c.id = 0;
}
else
{
c.id = sourceCandleList[w][sourceCandleList[w].Count - 2].id + 1;
}
}
}
FuturesList.Clear();
}
Console.WriteLine("AGGREGATE END");
for (var i = 0; i < sources.Count(); i++)
{
updatelist[i].Clear();
}
}
Console.WriteLine("BUILD PARAMLIST");
for (int par1 = 8; par1 <= 20; par1 += 4) // parameter deployed
{
for (int bollPar = 10; bollPar <= 25; bollPar += 5) // parameter deployed
{
for (int par2 = 6; par2 <= 18; par2 += 4) // parameter deployed
{
for (int par3 = 14; par3 <= 20; par3 += 3) // parameter deployed
{
for (int par4 = 10; par4 <= 20; par4 += 5) // parameter deployed
{
for (int par5 = 4; par5 <= 10; par5 += 2) // parameter deployed
{
for (int par6 = 5; par6 <= 30; par6 += 5)
{
for (decimal par7 = 1.0005M; par7 <= 1.002M; par7 += 0.0005M)
{
for (decimal par8 = 1.002M; par8 <= 1.0048M; par8 += 0.0007M)
{
for (decimal par9 = 0.2M; par9 <= 0.5M; par9 += 0.1M)
{
for (decimal par10 = 0.5M; par10 <= 2; par10 += 0.5M)
{
param p = new param();
p.par1 = par1;
p.bollPar = bollPar;
p.par2 = par2;
p.par3 = par3;
p.par4 = par4;
p.par5 = par5;
p.par6 = par6;
p.par7 = par7;
p.par8 = par8;
p.par9 = par9;
p.par10 = par10;
paramList.Add(p);
}
}
}
}
}
}
}
}
}
}
}
Console.WriteLine("END BUILD PARAMLIST, scenarios to test:{0}", paramList.Count);
var sourceCount = sources.Count();
sources = null;
Console.WriteLine("Start building pools");
int maxThreads = 64;
ConcurrentBag<int> pool = new ConcurrentBag<int>();
List<candle>[,] CandleList = new List<candle>[maxThreads, sourceCount];
for (int i = 0; i <= maxThreads - 1; i++)
{
pool.Add(i);
for (int w = 0; w <= sourceCount - 1; w++)
{
CandleList[i, w] = sourceCandleList[w].ConvertAll(p => p);
}
}
Console.WriteLine("End building pools");
int pItemsProcessed = 0;
Parallel.ForEach(paramList,
new ParallelOptions { MaxDegreeOfParallelism = maxThreads },
p =>
{
int slot = 1000;
while (!pool.TryTake(out slot));
var bollPar = p.bollPar;
decimal bollingerMiddle = 0;
double bBandDeltaX = 0;
for (var w = 0; w < sourceCount; w++)
{
lock (CandleList[slot, w])
{
for (var ctr = 0; ctr < CandleList[slot, w].Count; ctr++)
{
CandleList[slot, w][ctr].bollingerUp = 0; //Bollinger upper line
CandleList[slot, w][ctr].bollingerDown = 0; //Bollinger below line
//Bollinger Bands Calculation
if (ctr + 1 >= bollPar)
{
bollingerMiddle = 0;
bBandDeltaX = 0;
for (int i = 0; i <= bollPar - 1; i++)
{
bollingerMiddle = bollingerMiddle + CandleList[slot, w][ctr - i].totalPrice;
}
bollingerMiddle = bollingerMiddle / bollPar; //average
for (int i = 0; i <= bollPar - 1; i++)
{
bBandDeltaX = bBandDeltaX + (double)Math.Pow(System.Convert.ToDouble(CandleList[slot, w][ctr - i].totalPrice) - System.Convert.ToDouble(bollingerMiddle), 2);
}
bBandDeltaX = bBandDeltaX / bollPar;
decimal bBandDelta = (decimal)Math.Sqrt(System.Convert.ToDouble(bBandDeltaX));
CandleList[slot, w][ctr].bollingerUp = bollingerMiddle + 2 * bBandDelta;
CandleList[slot, w][ctr].bollingerDown = bollingerMiddle - 2 * bBandDelta;
if (CandleList[slot, w][ctr].bollingerUp == CandleList[slot, w][ctr].bollingerDown)
{
Console.WriteLine("?! Items processed=" + pItemsProcessed + " bollPar=" + bollPar + " ctr=" + ctr + " bollingerMiddle=" + bollingerMiddle + " bBandDeltaX=" + bBandDeltaX + " bBandDelta=" + bBandDelta + " bollingerUp=" + CandleList[slot, w][ctr].bollingerUp + " bollingerDown=" + CandleList[slot, w][ctr].bollingerDown);
}
}
// REMOVED Further calculations happen here
}
// REMOVED Some evaluations happen here
}
}
// REMOVED Some more evaluations happen here
Interlocked.Increment(ref pItemsProcessed);
pool.Add(slot);
});
}
static void Main(string[] args)
{
var P = new programCLass();
P.myProgram();
}
}
}

FileStream read ending prematurely

I have a function that strips a wav file from a video, then using FileStream I read from the wavefile. The problem is, the read function returns -1 (no more bytes to be read) prematurely. Its a 20 minute wav file, but only about 17.5 minutes are written.
In this function, I am mixing several wave files into a one large one. The problem is the filestream reader for the large wave file is ending too early. I can't figure out why.
Here is my code:
public void combineWaveFileData(object status)
{
//ProgressWindow progressWindow = status as ProgressWindow;
ExportProgressWindow exportProgressWindow = status as ExportProgressWindow;
string videoAudioFile = outfileName + ".temp";
int descriptionStartSample = 0;
int highestNumber = 0;
int extraSamplesFromExtendedDescription = 0;
const double VOLUME_VIDEO_FACTOR = 0.8; //controls video volume levels; won't be const as volume control will be added later
const double VOLUME_DESCRIPTION_FACTOR = 1.5; //controls description volume levels
double currentSample = 0; //keeps track of the current sample in the video audio track
byte[] videoAudioBuffer = new byte[4];//new byte[bitsPerSample / 8];
int sample = 0; //holds raw audio data sample
int videoReadStatus = 1;
int descriptionEndSample = 0;
byte[] buffer = new byte[4];
FileStream tempStream;
videoAudioStream = new FileStream(videoAudioFile, FileMode.Open, FileAccess.ReadWrite);
videoAudioStream.Seek(DATA_START_POS - 4, 0);
videoAudioStream.Read(buffer, 0, buffer.Length);
totalRawSoundDataBits = BitConverter.ToInt32(buffer, 0);
//totalRawSoundDataBits = videoAudioStream.Length;
videoAudioStream.Seek(24, 0);
videoAudioStream.Read(buffer, 0, 4);
int videoSampleRate = BitConverter.ToInt32(buffer, 0);
sampleRateHz = videoSampleRate;
outFileStream = new FileStream(outfileName, FileMode.Create, FileAccess.ReadWrite);
videoAudioStream.Seek(0, 0);
writeAudioFileHeader(outFileStream, videoAudioStream);
// videoAudioStream.Seek(0, 0); //reset video audio position to 0 (beginning)
convertStatus = false;
if (compatibilityIssue)
{
exportProgressWindow.Close();
return;
}
//calculate total length of extended description files
foreach (Description description in descriptionList)
{
if (description.IsExtendedDescription)
{
tempStream = new FileStream(description.getFilename(), FileMode.Open);
totalRawSoundDataBits += tempStream.Length - DATA_START_POS;
try
{
tempStream.Close();
tempStream.Dispose();
tempStream = null;
}
catch { }
}
WaveReader read = new WaveReader(File.OpenRead(description.getFilename()));
IntPtr oldFormat = read.ReadFormat();
WaveFormat waveformat = AudioCompressionManager.GetWaveFormat(oldFormat);
int descriptionSampleRateHz = waveformat.nSamplesPerSec;
read.Close();
string resampledFilename = description.getFilename();
if (descriptionSampleRateHz != sampleRateHz)
{
exportProgressWindow.SetText(".");
resampledFilename = convertSampleRate(description.getFilename(), sampleRateHz);
description.setFilename(resampledFilename);
}
}
for (int i = 0; i < descriptionList.Count; i++)
{
for (int j = 0; j < descriptionList.Count; j++)
{
Description tempDescription;
if (((Description)descriptionList[i]).getStart() < ((Description)descriptionList[j]).getStart())
{
tempDescription = (Description)descriptionList[j];
descriptionList[j] = descriptionList[i];
descriptionList[i] = tempDescription;
}
}
}
int k = 0;
while (videoReadStatus > 0)
{
try
{
Description description;
description = (Description)descriptionList[k];
descriptionStartSample = (int)Math.Truncate(sampleRateHz * description.getStart());
descriptionEndSample = (int)Math.Truncate(sampleRateHz * description.getEnd());
if (videoAudioStream.Position / 4 > descriptionStartSample )
{
double currentTime = videoAudioStream.Position / 4 / sampleRateHz;
Console.WriteLine(currentTime+ " " + description.getStart() + " " + description.getEnd());
if (k < descriptionList.Count - 1)
{
k++;
}
double percentage = Convert.ToDouble(k) / Convert.ToDouble(descriptionList.Count) * 100.0;
try
{
exportProgressWindow.Increment(percentage);
}
catch (Exception ex)
{
return;
}
buffer = new byte[4];
tempStream = new FileStream(description.getFilename(), FileMode.Open);
try
{
tempStream.Seek(44, 0); //to search for position 34; write: use writeSample()
int tempReadStatus = 1;
while (tempReadStatus > 0 && videoReadStatus > 0)//(currentSample < descriptionEndSample)
{
//If description isn't an extended description then mix the description with the video audio
if (!description.IsExtendedDescription)
{
videoReadStatus = videoAudioStream.Read(videoAudioBuffer, 0, 2);
tempReadStatus = tempStream.Read(buffer, 0, 2);
if (videoReadStatus == 0)
{
Console.WriteLine(currentTime);
int debug = 0;
}
if (tempReadStatus <= 0 || videoReadStatus <=0)
{
int deleteme = 0;
}
sample += (int)(((BitConverter.ToInt16(buffer, 0))* VOLUME_DESCRIPTION_FACTOR + (BitConverter.ToInt16(videoAudioBuffer, 0) * VOLUME_VIDEO_FACTOR)) / 2);
writeSample(sample);
sample = 0;
}
else
// If description is extended then only write the description samples
{
int tempStatus = 1;
while (tempReadStatus > 0)
{
tempReadStatus = tempStream.Read(buffer, 0, 2);
sample = (int)((BitConverter.ToInt16(buffer, 0)));// -((sample * (int)(BitConverter.ToInt16(buffer, 0))) / 65535); //Z = A+B-AB/65535 http://www.vttoth.com/CMS/index.php/technical-notes/68 //* VOLUME_DESCRIPTION_FACTOR);
writeSample(sample);
sample = 0;
}
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Debug 1: " + ex.Message);//MessageBox.Show(ex.Message);
}
finally
{
tempStream.Close();
tempStream.Dispose();
tempStream = null;
}
}
else
{
try
{
videoReadStatus = videoAudioStream.Read(videoAudioBuffer, 0, 2);
sample += (int)((BitConverter.ToInt16(videoAudioBuffer, 0)) * VOLUME_VIDEO_FACTOR) ;
if (videoReadStatus == 0)
{
int debug = 0;
}
writeSample(sample);
sample = 0;
convertStatus = true;
}
catch (Exception ex)
{
int test = 0;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.GetBaseException().ToString());
}
}
exportProgressWindow.SetText("\n\nLiveDescribe has successfully exported the file.");
try
{
closeStreams();
Control.CheckForIllegalCrossThreadCalls = false;
}
catch (Exception ex)
{
}
}

Categories