C# check if download upload bytes greater then - c#

I have dialer program in C#. I wanted to change image if download / upload is in progress. How can I add such check in following code?
private void UpdateNetworkInterface()
{
this.Invoke((MethodInvoker)delegate
{
NetworkInterface nic = nicArr[cmbInterface.SelectedIndex];
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
long lngBytesSent = 0;
long lngBtyesReceived = 0;
int bytesSentSpeed = (int)(interfaceStats.BytesSent - lngBytesSent) /1024;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - lngBtyesReceived) /1024;
// Update the labels
lblInterfaceType.Text = nic.NetworkInterfaceType.ToString();
lblUpload.Text = bytesSentSpeed.ToString() + " KB";
lblDownload.Text = bytesReceivedSpeed.ToString() + " KB";
//this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n DOWNLOAD/UPLOAD in progress", ""));
});
}

Those property gives you the total bytes transferred, what you need is the derivative of that number (The rate of change).
The easiest way is just do the simple math problem
So you will need to recordings then compare those two points to get the speed.
private long _lastBytesRecevied;
private long _lastBytesSent;
private DateTime _lastReceivedMesurement;
private DateTime _lastSentMesurement;
//This needs to be done once at the start of the class to "seed" the first value.
private Init()
{
_lastReceivedMesurement = DateTime.UtcNow;
_lastBytesRecevied = interfaceStats.BytesReceived;
_lastSentMesurement = DateTime.UtcNow;
_lastBytesSent = interfaceStats.BytesSent;
}
private double getKBDownloadSpeed()
{
double result = (interfaceStats.BytesReceived - _lastBytesRecevied) / (DateTime.UtcNow - _lastReceivedMesurement).TotalSeconds;
_lastReceivedMesurement = DateTime.UtcNow;
_lastBytesRecevied = interfaceStats.BytesReceived;
return result / 1024d;
}
private double getKBUploadSpeed()
{
double result = (interfaceStats.BytesSent - _lastBytesSent) / (DateTime.UtcNow - _lastSentMesurement).TotalSeconds;
_lastSentMesurement = DateTime.UtcNow;
_lastBytesSent = interfaceStats.BytesSent;
return result / 1024d;
}
Now your two functions returns the average download speed between the last time the function was called and the current call.
If you get value in download speed, change the image as download icon.
If you get value in Upload speed, change the image as upload icon.
Sincerely,
Thiyagu Rajendran
**Please mark the replies as answers if they helps.

You can use System.Net.WebClient to do it.
it has an event DownloadProgressChanged and it has parameters and it has fields that contain downloaded bytes and total bytes of the file.
It is fired by WebClient.DownloadFileAsync().
MSDN Link : https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx
Example :
private void DownloadChanged(object sender, DownloadProgressChangedEventArgs e)
{
labelProgress.Text = string.Format("{0} Percents Completed",
e.BytesReceived / e.TotalBytesToReceive * 100);
}
private void StartDownload(object sender, EventArgs e) // Button Event
{
var webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadChanged);
webClient.DownloadFileAsync(/* URL */);
}
Getting upload bytes is same as Download one. Happy Programming! :)

Related

WebClient.DownloadFileAsync - How do I keep track of the total amount of bytes downloaded when downloading multiple files?

So I'm trying to download two images and just for demonstration I've checked their sizes and summed it up to a variable called totalBytes.
I want to keep track of how much has been downloaded out of those total bytes so I can calculate the percentage by taking downloaded / totalBytes * 100
But I have no idea how to keep track of the mount of bytes that has been downloaded.
public static int totalBytes = 1378954;
static void Main(string[] args)
{
var images = new List<string>
{
"http://4.bp.blogspot.com/-HTvSYzA-pO4/UgQb4Zh_u0I/AAAAAAAAEuI/XwhtogT_1tA/s1600/3+cute2.jpg",
"http://getwallpapers.com/wallpaper/full/7/7/0/74728.jpg"
};
foreach (var image in images)
{
int i = 0;
using (var wc = new WebClient())
{
wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
wc.DownloadFileAsync(new Uri(image), $"image{i}.png");
i++;
Console.ReadKey();
}
}
}
private static void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine($"Downloaded: {e.BytesReceived} out of {totalBytes}");
}
Assuming that you do not intend to actually start downloading files in parallel (as you dispose the WebClient before starting another download), the problem can be solved with two field
One to store the current total
Another to store the previous ReceivedByte value
private static long _totalBytesReceivedAllFiles = 0;
private static long _previousBytesReceivedForCurrentFile = 0;
private static object _lock = new Object();
private static void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// There are no guarantees in the documentation that such events are serialized and can't execute in parallel even for a single file,
// thus we will use lock to at least partially serialize it and ensure atomic field access.
// !!!It is not intended to handle actual parallel downloads!!!
lock (_lock)
{
_totalBytesReceivedAllFiles = _totalBytesReceivedAllFiles - _previousBytesReceivedForCurrentFile + e.BytesReceived;
_previousBytesReceivedForCurrentFile = e.BytesReceived;
Console.WriteLine($"Downloaded: {_totalBytesReceivedAllFiles} out of {totalBytes}");
if (e.ProgressPercentage == 100)
{
Console.WriteLine("Current file downloaded");
_previousBytesReceivedForCurrentFile = 0;
}
}
}
If on the other hand you want to start downloads truly in parallel, then you will have to
Not to dispose (in the loop!) the client, for obvious reasons.
Use a per-file Wc_DownloadProgressChanged with closure to have an actual per-file _previousBytesReceivedForCurrentFile

Xamarin Forms entry text doesn't return a number

I'm very new to programming. I'm trying to store entry text in float variables, then calculate basic percentage and show it below inside a label. In place of a variable inside a label it prints NaN. If I use integers instead it says that I'm trying to divide by zero which tells me that the text read from entry returns nothing.
What could be the reason for that?
public partial class GoalTrackerPage : ContentPage
{
float goal = 0.0000f;
float done = 0.0000f;
float progress = 0.0000f;
public GoalTrackerPage ()
{
InitializeComponent ();
g1EntryGoal = new Entry();
g1EntryDone = new Entry();
g1PrBar = new ProgressBar();
}
private void add1_Clicked(object sender, EventArgs e)
{
GoalStatusLabelView();
}
private void GoalStatusLabelView ()
{
progress = done / goal * 100.0000f;
g1StatusLabel.Text = "The Goal is at " + progress;
}
private void g1EntryGoal_Completed(object sender, EventArgs e)
{
goal = float.Parse(g1EntryGoal.Text ?? "0");
}
private void g1EntryDone_Completed(object sender, EventArgs e)
{
done = float.Parse(g1EntryDone.Text ?? "0");
}
{
progress = done / goal * 100.0000f;
g1StatusLabel.Text = "The Goal is at " + progress;
}
The result is basically just zero, and since it is carrying a double value, it will return NaN at g1StatusLabel.Text.
Perhaps this could shed a little more info on dealing NaN result.
Double.NaN Field
I figured it out! Since I've been assigning text property inside the event "Text Completed" I should've used different syntax.
The proper syntax for this case would be:
var g1DoneText = ((Entry)sender).Text;
instead of standard:
var g1DoneText = G1EntryDone.Text;

How to add a seekbar in VLC dot net forms in c# windows forms application

I need to add a custom seekbar / trackbar as you may say in c# windows forms. But the issue is there is almost no documentation on vlc dot net forms library. I need to know how to add a custom seekbar in windows forms application.
remember, i am not using vlc activeX plugin*. **Rather i am using nuget package of dot net library of vlc and everything is working fine. I have added toggle play and pause button, stop button, able to get current time, able to get total time and everything else. But i have no idea how to add a seekbar so that when i seek, the video moves to that position. Please help me with full code.
I successfully finish, thank you it was a good practice for me. I've added the media in formdeneme() method
You have to make public the object which is in VlcControl.cs class.(private VlcMediaPlayer myVlcMediaPlayer;){Very important}
public int a = 0 ;`
public int c = 0;
public delegate void UpdateControlsDelegate(); //Execute when video loads
public formdeneme()
{
InitializeComponent();
myVlcControl.Play("file:///C:/Users/1315k/Downloads/machine.mp4");
// You can add your media like above.
//Event handler for 'current media time' label
this.vlcControl1.PositionChanged += new System.EventHandler<Vlc.DotNet.Core.VlcMediaPlayerPositionChangedEventArgs>(this.vlcControl1_PositionChanged);
//Event handler for setting trackBar1.Maximum on media load
vlcControl1.Playing += new System.EventHandler<VlcMediaPlayerPlayingEventArgs>(SetProgresMax);
}
// This is the main function which you looking.
private void trackBar1_Scroll(object sender, EventArgs e)
{
myVlcControl.myVlcMediaPlayer.Time = trackBar1.Value * 1000;
int b = (int)myVlcControl.myVlcMediaPlayer.Time / 1000;
int d = b / 60;
b = b - d * 60;
label1.Text = d+":"+b + "/"+ c + ":" + a;
// The Time value is milisecond, you have divide 1000 for be second.
}
private void formdeneme_Load(object sender, EventArgs e)
{
a = (int)myVlcControl.myVlcMediaPlayer.Length / 1000;
trackBar1.Maximum = a;
c = a / 60;
a = a - c * 60;
label1.Text = 0 + "/" + c+":"+a;
}
You can add a button that can change media and trackbar.Maximum value.
UPDATED
Thanks to askepott
He added some codes below, I didn't try but Looks good to me.
In order to have a label that displays the current media time, add this delegate function, it's called function (currentTrackTime) below and declaration at the top of this post. Also, don't forget to add the vlcControl1_PositionChanged event handler at the top.
//Update current video time label (delegate)
public void InvokeUpdateControls()
{
if (this.InvokeRequired)
{
this.Invoke(new UpdateControlsDelegate(currentTrackTime));
}
else
{
currentTrackTime();
}
}
//Update current video time label
private void currentTrackTime()
{
int b = (int)vlcControl1.VlcMediaPlayer.Time / 1000;
int d = b / 60;
b = b - d * 60;
label1.Text = d+":"+b + "/"+ c + ":" + a; //min : sec /
}
//Add this to currentTrackTime() if you want your trackbar to automatically update it's value based on current media position
trackBar1.Value = b;
//Invoke update controls on video position change
private void vlcControl1_PositionChanged(object sender, Vlc.DotNet.Core.VlcMediaPlayerPositionChangedEventArgs e)
{
InvokeUpdateControls();
}
//Furthermore, in case you have trouble getting and setting the vlcControl1.Length when loading the video, use this:
//Fire event when the video starts
private void SetProgresMax(object sender, VlcMediaPlayerPlayingEventArgs e)
{
Invoke(new Action(() =>
{
trackBar1.Value = trackBar1.Minimum;
var vlc = (VlcControl)sender;
trackBar1.Maximum = (int)vlc.Length / 1000;
a = (int)vlc.Length / 1000; // Length (s)
c = a / 60; // Length (m)
a = a % 60; // Length (s)
label1.Text = 0 + "/" + c+":"+a;
}));

'double' does not contain a definition for 'Text' and no extension method

Me and my teacher cannot figure this out. It's a windows forms app with all the appropriate fields linked, this is my only issue.
Error 1 'double' does not contain a definition for 'Text' and no extension method
here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculate_Click(object sender, EventArgs e)
{
double total = 0; //total amount
double tip = 0; //tip percentage
double meal = 0; //meal amount
tip = Convert.ToDouble(tip.Text) / 100;
meal = Convert.ToDouble(meal.Text);
total = (meal * tip);
total.Text = "$ " + Convert.ToString(total);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
It looks like you named your class-level Textboxes the exact same as your method-scoped variables. Or at least, that's my best assumption without knowing what your textboxes are actually called.
Your problem is you are trying to find a property Text on a double, which certainly does not exist. If you actually did name your textboxes the same (which is legal in C#), you'll want to reference them by using this.total and this.tip when trying to set the Text property.
It's worth noting that I'm concerned for your education if your teacher is unable to debug this.
I think you are trying to display the result into a Textbox; but Here in the code you declared total as double. please use the textbox name here (total.Text) in place of the variable total; And also use .ToString() instead of .Text inside your Convert.ToDouble(
Few more tips for you:
use double.TryParse for converting string to double
use total.ToString("$#00.00"); to get the the number prefixed with a $ symbol and rounded to 2 digits after the decimal
Let me assume the UI elements are :
//txtTip be the Textbox for tip percentage
//txtMeal be the Textbox for meal amount
//txtTotal be the Textbox for Total Amount
Then your code will be like the following:
double total = 0; //total amount
double tip = 0; //tip percentage
double meal = 0; //meal amount
if(! double.TryParse(txtTip.Text,out tip))
{
// show conversion failed error
}
if(! double.TryParse(txtMeal.Text,out meal))
{
// show conversion failed error
}
tip = tip / 100;
total = (meal * tip);
txtTotal.Text =total.ToString("$#00.00") ;
I think this is a mistake of use local variable and global variable.
class Test
{
// global variable.
int va = 1;
int vb = 2;
public void local()
{
bool va = false; // local variable
Console.WriteLine(va); // va is bool here.use local value.
Console.WriteLine(vb); // vb is int, use global value.
}
}
in your code, you declared local variables.
public partial class Form1 : Form
{
private void calculate_Click(object sender, EventArgs e)
{
// declare local variables...
// overwrite global varables.
double total = 0; //total amount
double tip = 0; //tip percentage
double meal = 0; //meal amount
// maybe, you want to invoke textbox.Text.
// but, tip(TextBox) object is overwrote by double.
// double has not the Text property, throw exception.
tip = Convert.ToDouble(tip.Text) / 100;
meal = Convert.ToDouble(meal.Text);
total = (meal * tip);
total.Text = "$ " + Convert.ToString(total);
}
}
how to fix it? just declare different variable name, like this:
private void calculate_Click(object sender, EventArgs e)
{
// make the local variable name is different with global.
double d_total = 0; //total amount
double d_tip = 0; //tip percentage
double d_meal = 0; //meal amount
d_tip = Convert.ToDouble(tip.Text) / 100; // tip is TextBox here
d_meal = Convert.ToDouble(meal.Text);
d_total = (d_meal * d_tip);
total.Text = "$ " + Convert.ToString(d_total);
}
or use this like this:
private void calculate_Click(object sender, EventArgs e)
{
double total = 0; //total amount
double tip = 0; //tip percentage
double meal = 0; //meal amount
tip = Convert.ToDouble(this.tip.Text) / 100;
meal = Convert.ToDouble(this.meal.Text);
total = (meal * tip);
this.total.Text = "$ " + Convert.ToString(total);
}

Adding percentage text to progressbar C#

I have a method that shows when a process bar is in execution and when is successfully completed.
I worked fine, but I would like to add a percentage showing a 100% if is complete and less if it got stuck some where.
I have made several research online but I could not adapt anything to the solution that I am looking for.
This is my code:
private void progressBar()
{
int i;
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
for (i = 0; i <= 100; i++)
{
progressBar1.Value = i;
}
}
I use the method call on my execution button by calling it with the follow:
progressBar();
Thanks
I have adjust the prograssBar method with the following lines.
The solution works.
Thanks
int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
progressBar1.Refresh();
progressBar1.CreateGraphics().DrawString(percent.ToString() + "%",
new Font("Arial", (float)8.25, FontStyle.Regular),
Brushes.Black,
new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
In order to implement the progress in your operation, the operation's length must be calculated first. if it's not possible, you can't show a progress bar for that operation. (maybe only a loading gif)
but if so, There is an interface (IProgress) which can help you implement the progress reports.
First thing you should know, You must do the main task on another thread, and report the progress to the UI Thread. a simple example of this work would be something like this.
Progress.cs
public class Progress<T> : IProgress<T>
{
private readonly Action<T> _progressAction;
public Progress(Action<T> action)
{
_progressAction = action;
}
public void Report(T value)
{
_progressAction?.Invoke(value);
}
}
Your code would be like this, in which the task starts after you click a button named ButtonBase
Progress<int> MyProgressObject { get; set; }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
MyProgressObject = new Progress<int>(ProgressAction);
ThreadPool.QueueUserWorkItem(TimeConsumingTask);
}
public void TimeConsumingTask(object state)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
MyProgressBar.Dispatcher.Invoke(() => ProgressAction(i));
}
}
public void ProgressAction(int progress)
{
MyProgressBar.Value = progress;
}
I know It might look difficult but this is the proper way of doing time consuming tasks and prevent UI block
If you use it as a part of backgroundworker it works perfectly
I added a Label in the middle of the progressbar
And i added last row in my bgw_ProgressChanged method
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
p_bar.Value = e.ProgressPercentage;
fnameLbl.Text = e.UserState.ToString();
percentLbl.Text = "%" + (e.ProgressPercentage).ToString();
}
ProgressPercentagevalue comes from the method below
foreach (var item in filebox1)
{
System.IO.File.Move(item, Path.Combine(destdir, Path.GetFileName(item)));
++counter;
int tmp = (int)((counter* 100) / totfiles);
bgw.ReportProgress(tmp, "File transfered : " + Path.GetFileName(item));
Thread.Sleep(100);
}
Totfiles is the number of files that I get from server.
Thread.Sleep(100) let's you see for a short time what is displayed with fnameLbl.Text
int total = ;
int val = ;
double createDivider = total / 100;
int percent = val / createDivider;
this value (percent) is the right percent '%' of total

Categories