C# Multiple downloads with webclient - download

I have a download list into a txt file. (http://launcher.dryadmu.com/Update/ArchiveList.txt)
And it check if crc32 has changed, and only then download the file to the client, the problem is that it takes too long when the list grows.
The download class:
class FileDownloader
{
private static int curFile;
private static long lastBytes;
private static long currentBytes;
private static Stopwatch stopWatch = new Stopwatch();
public static void DownloadFile()
{
if (Globals.OldFiles.Count <= 0)
{
Common.ChangeStatus("CHECKCOMPLETE");
Common.UpdateCompleteProgress(100);
Common.StartGame();
return;
}
if (curFile >= Globals.OldFiles.Count)
{
Common.ChangeStatus("DOWNLOADCOMPLETE");
Common.StartGame();
return;
}
if (Globals.OldFiles[curFile].Contains("/"))
{
Directory.CreateDirectory(Path.GetDirectoryName(Globals.OldFiles[curFile]));
}
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
stopWatch.Start();
webClient.DownloadFileAsync(new Uri(Globals.ServerURL + Globals.OldFiles[curFile]), Globals.OldFiles[curFile]);
}
private static void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
currentBytes = lastBytes + e.BytesReceived;
Common.ChangeStatus("DOWNLOADFILE", Globals.OldFiles[curFile], curFile.ToString(), Globals.OldFiles.Count.ToString());
Common.UpdateCompleteProgress(Computer.Compute(Globals.completeSize + currentBytes));
Common.UpdateCurrentProgress(e.ProgressPercentage, Computer.ComputeDownloadSpeed(e.BytesReceived, stopWatch));
}
private static void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
lastBytes = currentBytes;
Common.UpdateCurrentProgress(100, 0);
curFile++;
stopWatch.Reset();
DownloadFile();
}
}
I couldn't figured out how to add DownloadFileTaskAsync. Any help would be appreciated. Thx

Related

Freemarker Debugger framework usage example

I have started working on a Freemarker Debugger using breakpoints etc. The supplied framework is based on java RMI. So far I get it to suspend at one breakpoint but then ... nothing.
Is there a very basic example setup for the serverpart and the client part other then the debug/imp classes supplied with the sources. That would be of great help.
this is my server class:
class DebuggerServer {
private final int port;
private final String templateName1;
private final Environment templateEnv;
private boolean stop = false;
public DebuggerServer(String templateName) throws IOException {
System.setProperty("freemarker.debug.password", "hello");
port = SecurityUtilities.getSystemProperty("freemarker.debug.port", Debugger.DEFAULT_PORT).intValue();
System.setProperty("freemarker.debug.password", "hello");
Configuration cfg = new Configuration();
// Some other recommended settings:
cfg.setIncompatibleImprovements(new Version(2, 3, 20));
cfg.setDefaultEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Template template = cfg.getTemplate(templateName);
templateName1 = template.getName();
System.out.println("Debugging " + templateName1);
Map<String, Object> root = new HashMap();
Writer consoleWriter = new OutputStreamWriter(System.out);
templateEnv = new Environment(template, null, consoleWriter);
DebuggerService.registerTemplate(template);
}
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
startInternal();
}
}, "FreeMarker Debugger Server Acceptor").start();
}
private void startInternal() {
boolean handled = false;
while (!stop) {
List breakPoints = DebuggerService.getBreakpoints(templateName1);
for (int i = 0; i < breakPoints.size(); i++) {
try {
Breakpoint bp = (Breakpoint) breakPoints.get(i);
handled = DebuggerService.suspendEnvironment(templateEnv, templateName1, bp.getLine());
} catch (RemoteException e) {
System.err.println(e.getMessage());
}
}
}
}
public void stop() {
this.stop = true;
}
}
This is the client class:
class DebuggerClientHandler {
private final Debugger client;
private boolean stop = false;
public DebuggerClientHandler(String templateName) throws IOException {
// System.setProperty("freemarker.debug.password", "hello");
// System.setProperty("java.rmi.server.hostname", "192.168.2.160");
client = DebuggerClient.getDebugger(InetAddress.getByName("localhost"), Debugger.DEFAULT_PORT, "hello");
client.addDebuggerListener(environmentSuspendedEvent -> {
System.out.println("Break " + environmentSuspendedEvent.getName() + " at line " + environmentSuspendedEvent.getLine());
// environmentSuspendedEvent.getEnvironment().resume();
});
}
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
startInternal();
}
}, "FreeMarker Debugger Server").start();
}
private void startInternal() {
while (!stop) {
}
}
public void stop() {
this.stop = true;
}
public void addBreakPoint(String s, int i) throws RemoteException {
Breakpoint bp = new Breakpoint(s, i);
List breakpoints = client.getBreakpoints();
client.addBreakpoint(bp);
}
}
Liferay IDE (https://github.com/liferay/liferay-ide) has FreeMarker template debug support (https://issues.liferay.com/browse/IDE-976), so somehow they managed to use it. I have never seen it in action though. Other than that, I'm not aware of anything that uses the debug API.

Webclient returning download progress as 0

I have written a helper class to download file from a server using the webclient class. The code was working fine until a while ago. All of a sudden the code is not working, the download progress is always 0 and toal bytes to receive is always -1. The download works fine but the issue is only with the actual progress change. The download progress remains zero from start to the end of download process, even the total bytes to receive remain as -1.
Please find the sample code mentioned below.
public class FileDownloader
{
private string _zipFilePath;
private string _destinationPath;
private int _productId;
public Action<int,int> progressListener;
private WebClient _client;
public void Download(string cloudPath, string localPath,int id)
{
_productId = id;
_zipFilePath = localPath +id+ ".zip";
_destinationPath = localPath + id;
if (!Directory.Exists(localPath))
{
Directory.CreateDirectory(localPath);
}
_client = new WebClient();
if (cloudPath != "")
{
Uri uri = new Uri(cloudPath);
_client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback);
_client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
_client.DownloadFileAsync(uri, _zipFilePath);
}else
{
progressListener?.Invoke(_productId, -1);
}
}
public void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
if(e.ProgressPercentage != 100)
progressListener?.Invoke(_productId, e.ProgressPercentage);
}
public void CancelDownload()
{
_client.CancelAsync();
}
public void DownloadFileCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == false && e.Error == null)
{
//UnzipContent(_destinationPath,_zipFilePath);
UnzipHandler unzipHandler = new UnzipHandler(_destinationPath, _zipFilePath,new UnzipCompletionCallback(UnzippedCourse));
Thread thread = new Thread(new ThreadStart(unzipHandler.UnzipContent));
thread.Start();
}
else
{
DeleteZip(_zipFilePath);
progressListener?.Invoke(_productId, -1);
}
}
private void DeleteZip(string zipPath)
{
if (File.Exists(zipPath))
{
File.Delete(zipPath);
}
}
public void UnzippedCourse(bool status)
{
DeleteZip(_zipFilePath);
if(status)
progressListener?.Invoke(_productId, 100);
else
progressListener?.Invoke(_productId, -1);
}
public delegate void UnzipCompletionCallback(bool result);
}

Realtime data exchange between Android Wearable and Handheld

I am working on a simple app which will run on both wearable(Samsung Gear Live) and handheld(Moto G). I want to display the data from the wearable's heart rate sensor, accelerometer and gyroscope on the handheld. Which is the best way to achieve this.
Now I am using DataApi, but since I am updating data each second, it is allocating too much memory, and then killed by OS.
Here is my service which runs on the wearable
public class SensorDataListener extends Service implements SensorEventListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = SensorDataListener.class.getSimpleName();
private static final int TIMEOUT_HEART_RATE = 1000000;
private static final int TIMEOUT_ACCELEROMETER = 1000000;
private static final int TIMEOUT_GYROSCOPE = 1000000;
private static final String PATH_SENSOR_DATA = "/sensor_data";
private static final String KEY_HEART_RATE = "heart_rate";
private static final String KEY_ACC_X = "acc_x";
private static final String KEY_ACC_Y = "acc_y";
private static final String KEY_ACC_Z = "acc_z";
private static final String KEY_GYRO_X = "gyro_x";
private static final String KEY_GYRO_Y = "gyro_y";
private static final String KEY_GYRO_Z = "gyro_z";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mGyroscope;
private Sensor mHeartRate;
private int mCurHeartRateVal;
private float[] mCurAccelerometerVal = new float[3];
private float[] mCurGyroscopeVal = new float[3];
private GoogleApiClient mGoogleApiClient;
ScheduledExecutorService mUpdateScheduler;
ScheduledExecutorService scheduler;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(com.google.android.gms.wearable.Wearable.API)
.build();
mGoogleApiClient.connect();
mSensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
startDataUpdated();
}
private void startDataUpdated() {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
updateData();
}
}, 5, 3, TimeUnit.SECONDS);
}
private void updateData() {
PutDataMapRequest dataMap = PutDataMapRequest.create(PATH_SENSOR_DATA);
dataMap.getDataMap().putInt(KEY_HEART_RATE, mCurHeartRateVal);
dataMap.getDataMap().putFloat(KEY_ACC_X, mCurAccelerometerVal[0]);
dataMap.getDataMap().putFloat(KEY_ACC_Y, mCurAccelerometerVal[1]);
dataMap.getDataMap().putFloat(KEY_ACC_Z, mCurAccelerometerVal[2]);
dataMap.getDataMap().putFloat(KEY_GYRO_X, mCurGyroscopeVal[0]);
dataMap.getDataMap().putFloat(KEY_GYRO_Y, mCurGyroscopeVal[1]);
dataMap.getDataMap().putFloat(KEY_GYRO_Z, mCurGyroscopeVal[2]);
PutDataRequest request = dataMap.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, request);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager.registerListener(this, mHeartRate, TIMEOUT_HEART_RATE);
mSensorManager.registerListener(this, mAccelerometer, TIMEOUT_ACCELEROMETER);
mSensorManager.registerListener(this, mGyroscope, TIMEOUT_GYROSCOPE);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
mGoogleApiClient.disconnect();
scheduler.shutdown();
mSensorManager.unregisterListener(this);
//mUpdateScheduler.shutdownNow();
super.onDestroy();
}
#Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()) {
case Sensor.TYPE_HEART_RATE:
if(event.values[0] <= 0) // HR sensor is being initialized
return;
mCurHeartRateVal = Float.valueOf(event.values[0]).intValue();
break;
case Sensor.TYPE_ACCELEROMETER:
mCurAccelerometerVal[0] = event.values[0];
mCurAccelerometerVal[1] = event.values[1];
mCurAccelerometerVal[2] = event.values[2];
break;
case Sensor.TYPE_GYROSCOPE: {
mCurGyroscopeVal[0] = event.values[0];
mCurGyroscopeVal[1] = event.values[1];
mCurGyroscopeVal[2] = event.values[2];
break;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
#Override
public void onConnected(Bundle bundle) { Log.d(TAG, "onConnected"); }
#Override
public void onConnectionSuspended(int i) { Log.d(TAG, "onConnectionSuspended"); }
#Override
public void onConnectionFailed(ConnectionResult connectionResult) { Log.d(TAG, "onConnectionFailed"); }
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Try using the Message API instead of the Data API. Simply create a message containing your data and send it over to your other device : http://developer.android.com/reference/com/google/android/gms/wearable/MessageApi.html
Have you try with Teleport (data sync & messaging lib) by Mario Viviani

How to display a client ip address in a ListView when client connected and shutdown or wakeup client using c#

![Server][1]
Code Server :
public partial class Form1 : Form
{
private TcpClient tcpclient;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
IPAddress[] localip = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localip)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBox1.Text = address.ToString();
textBox2.Text = "8888";
}
}
}
private void button1_Click(object sender, EventArgs e)
{
TcpListener listenner = new TcpListener(IPAddress.Any, int.Parse(textBox2.Text));
listenner.Start();
tcpclient = listenner.AcceptTcpClient();
}
![client][2]
Code Client
namespace CLIENT
{
public partial class Form1 : Form
{
private TcpClient tcpclient;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
labelmessage.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
tcpclient = new TcpClient();
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
try
{
tcpclient.Connect(ipe);
if (tcpclient.Connected)
{
labelmessage.Visible = true;
labelmessage.Text = "Conected...";
}
}
catch
{
}
}
}
}
Use the TCPClient instance returned by the AcceptTCPClient() method.
TCPClient _client = _listener.AcceptTCPClient();
// Add to listview here for connection
Console.WriteLine(String.Format("{0} connected", _client.Client.RemoteEndPoint.ToString()));
// Same for others
UPDATE
TCPClient _client = _listener.AcceptTCPClient();
ListViewItem _item = new ListViewItem(_client.Client.RemoteEndPoint.ToString());
listview1.Items.Add(_item);
More on working with ListView Controls
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx

Need slideshow of images when my application is launched in windows phone 7

How to get the slideshow of images with time interval of 2 seconds. I had referred the below code from stackoverflow but while running iam nt getting any images displayed.. Please tel where iam went wrong...
Xaml:
<image Name=myImg Source={Binding bi}/>
Code:
private DispatcherTimer tmr = new DispatcherTimer();
private List<string> images = new List<string>();
private int imageIndex = 0;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(tmr_Tick);
LoadImages();
ShowNextImage();
}
private void LoadImages()
{
// list the files (includede in the XAP file) here
images.Add("/images/filename1.jpg");
images.Add("/images/filename2.jpg");
images.Add("/images/filename3.jpg");
images.Add("/images/filename4.jpg");
}
private void ShowNextImage()
{
Imagesource bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
myImg.Source = bi;
imageIndex = (imageIndex + 1) % images.Count;
}
void tmr_Tick(object sender, EventArgs e)
{
ShowNextImage();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (!tmr.IsEnabled)
{
tmr.Start();
}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
tmr.Stop();
base.OnNavigatedFrom(e);
}
Thanks in Advance
Change Name=myImg to x:Name="myImg" and remove the Source attribute entirely. Otherwise it looks like it should work.

Resources