I need help converting this WebClient to HttpClient code if it's possible, I will be really happy if it is.
I've been looking for something/someone that will convert it to me and I sadly didn't find anything.
Thanks!
private void bunifuFlatButton9_Click(object sender, EventArgs e)
{
{
using (WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.Complete);
webClient.DownloadDataAsync(new Uri("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
}
}
}
private void Complete(object sender, DownloadDataCompletedEventArgs e)
{
MatchCollection matchCollection = Regex.Matches(new UTF8Encoding().GetString(e.Result), "(https:\\/\\/pastebin.com\\/\\w+)");
int num = checked(matchCollection.Count - 1);
int i = 0;
while (i <= num)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.Complete2);
webClient.DownloadStringAsync(new Uri(matchCollection[i].Value));
}
checked { ++i; }
}
}
You should do something like this:
HttpClient client = new HttpClient();
List<string> urls = new List<string>();
urls.Add("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text);
urls.Add("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text);
//and so on...
foreach(var url in urls)
{
client.GetAsync(url)
.ContinueWith(async (T) => {
string result = await T.Result.ReadAsStringAsync();
OnComplete(result);
});
}
Then:
public void OnComplete(string result)
{
//todo: convert your result to utf-8 and so on...
}
You can do some exception handling inside ContinueWith block to prevent errors.
Related
good evening all,
i been working on a little downloader for my program only downloads the python installer small little things will be adding more over time,
however i have a issue when i run it in debug it works downloads fine
when i do it in the debug folder and run the exe without visual studio it load the update box but creates a file with 0 bytes and says when trying to load,
this is not compatible with your os
code i have.
private string GetFileName(string url)
{
string[] parts = url.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = url;
return fileName;
}
private String getFileName(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string fileName = "";
try
{
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
fileName = res.Headers["Content-Disposition"] != null ?
res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) :
Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
Path.GetFileName(res.ResponseUri.ToString()) : GetFileName(url);
}
res.Close();
}
catch { }
return fileName;
}
public async Task downloadupdate()
{
if(os == "x86")
{
filename = getFileName("https://www.python.org/ftp/python/3.11.0/python-3.11.0-amd64.exe");
string url = "https://www.python.org/ftp/python/3.11.0/python-3.11.0-amd64.exe";
lblfilename.Text = "File Name: " + getFileName(url);
using (WebClient wc = new WebClient())
{
wc.DownloadFileCompleted += wc_completed;
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
XtraMessageBox.Show(filename);
filename = "python.exe";
wc.DownloadFileAsync(new Uri(url), "C://Temp" + "//" + filename);
}
}
else
{
filename = getFileName("https://www.python.org/ftp/python/3.11.0/python-3.11.0.exe");
string url = "https://www.python.org/ftp/python/3.11.0/python-3.11.0.exe";
lblfilename.Text = "File Name: " + getFileName(url);
using (WebClient wc = new WebClient())
{
wc.DownloadFileCompleted += wc_completed;
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync(new Uri(url), "C://Temp" + "//" + filename);
}
}
}
private void wc_completed(object sender, AsyncCompletedEventArgs e)
{
_MessageResult.Instance.Append("Download Completed!");
//unzipupdate(Tiaga_Res.unzipupdate = "fixes19.zip");
//DirectoryCopy(Tiaga_Res.startpath + "\\fixes19\\", Tiaga_Res._bo3_root, true);
//XtraMessageBox.Show("Applied Fix Aug And Reflex Sight Fix");
// richTextBox1.Text = _MessageResult.Instance.Merge();
Process.Start("C://Temp" + "//" + filename);
this.Close();
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBarControl1.Properties.Step = 1;
progressBarControl1.Properties.PercentView = true;
//progressBarControl1.Properties.Maximum = e.ProgressPercentage;
progressBarControl1.PerformStep();
UpdateProgressBar(e.ProgressPercentage);
txtpercent.Text = e.ProgressPercentage + "%";
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
lbldownloaded.Text = "Downloaded: " + bytesIn + "/" + totalBytes;
}
private void UpdateProgressBar(int value)
{
progressBarControl1.EditValue = value;
}
screen shot of in debug.
any help would be much appreciated i cant see it would be a libz issue i used that since day one to compile dlls into my project never had this issue before
This question already has an answer here:
What would be a good way to Cancel long running IO/Network operation using Tasks?
(1 answer)
Closed 2 years ago.
I'm playing with TcpClient and when i use some Async operations they ignore the CancellationToken. After some reading, i know that it is intentionally and also knows that exists some ways to cancel awaits on Asyncs operations.
I just read next StackOverflow questions and articles that clarifies some points:
How to cancel a Task in await?
https://devblogs.microsoft.com/pfxteam/how-do-i-cancel-non-cancelable-async-operations/
Following previous articles, I could cancel NetworkStream.ReadAsync but that mechanisms doesn't work when i use them on NetworkStream.WriteAsync.
I have this code as minimal example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CancellationTokenSource ctSource;
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
string http_resp = "";
var request_uri = new Uri("http://icanhazip.com");
//BIG FILE as postdata to test the WriteAsync (use one that you have on your disk)
string contents = File.ReadAllText(#"C:\Portables\4test.txt");
string post_data = contents;
ctSource = new CancellationTokenSource();
CancellationToken ct = ctSource.Token;
Task<string> task = HttpRequestAsync(post_data, request_uri, ct);
try
{
http_resp = await task;
}
catch
{
http_resp = "General error";
}
textBox1.Text = http_resp;
button1.Enabled = true;
}
private static async Task<string> HttpRequestAsync(string post_data, Uri request_uri, CancellationToken ct)
{
string result = string.Empty;
string http_method = "POST";
string post_content_type = "application/x-www-form-urlencoded";
var hostname = request_uri.Host;
var port = request_uri.Port;
var scheme = request_uri.Scheme;
using (TcpClient tcpClient = new TcpClient())
{
tcpClient.SendTimeout = 15;
tcpClient.ReceiveTimeout = 15;
try
{
await tcpClient.ConnectAsync(hostname, port);
}
catch (Exception d1)
{
if (ct.IsCancellationRequested)
{
result = "Cancelation requested on ConnectAsync";
}
else
{
result = d1.Message + "\r\n" + d1.GetType().FullName + d1.StackTrace; ;
}
return result;
}
//Build HTTP headers
string reqString = "";
string header_host = "Host: " + hostname + "\r\n";
string header_close = "Connection: Close\r\n";
string basic_headers = "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0\r\n";
basic_headers += "Referer: https://www.google.com\r\n";
string header_post = "";
if (http_method == "POST")
{
string header_content_type = "";
header_content_type = "Content-type: " + post_content_type + "\r\n";
int content_length = 0;
content_length = post_data.Length;
string header_content_length = "Content-length: " + content_length + "\r\n";
header_post = header_content_type + header_content_length;
}
reqString = http_method + " " + request_uri.PathAndQuery + " " + "HTTP/1.1" + "\r\n" + header_host + basic_headers + header_close + header_post + "\r\n";
if (http_method == "POST")
{
reqString += post_data;
}
var header_bytes = Encoding.ASCII.GetBytes(reqString.ToString());
//Starting the I/O Network operations
using (NetworkStream tcp_stream = tcpClient.GetStream())
{
try
{
//HERE is where i have problems cancelling this await while WriteAsync is working.
await tcp_stream.WriteAsync(header_bytes, 0, header_bytes.Length, ct).WithCancellation(ct);
//await tcp_stream.WriteAsync(header_bytes, 0, header_bytes.Length, ct);
}
catch (Exception d2)
{
if (ct.IsCancellationRequested)
{
result = "Cancelation requested on WriteAsync";
}
else
{
result = d2.Message + "\r\n" + d2.GetType().FullName + d2.StackTrace;
}
return result;
}
using (var memory = new MemoryStream())
{
try
{
await tcp_stream.CopyToAsync(memory, 81920, ct);
}
catch (Exception d3)
{
if (ct.IsCancellationRequested)
{
result = "Request cancelled by user (on read)";
}
else
{
result = d3.Message + "\r\n" + d3.GetType().FullName + d3.StackTrace;
}
return result;
}
memory.Position = 0;
byte[] data = memory.ToArray();
result = Encoding.UTF8.GetString(data);
}
}
}
return result;
}
private void button2_Click(object sender, EventArgs e)
{
ctSource.Cancel();
}
}
It works good when i use it on ReadAsync:
await tcp_stream.ReadAsync(response, 0, response.Length, ct).WithCancellation(ct);
It doesn't work when i use it on WriteAsync:
await tcp_stream.WriteAsync(header_bytes, 0, header_bytes.Length, ct).WithCancellation(ct);
No error is returned, simply the await isn't cancelled. To be more clear i added a minimal example as a Visual Studio 2015 project that you can download here: https://github.com/Zeokat/minimal_ex/archive/master.zip
It also includes a file 4test.rar that you can decompress into a file of 39MB 4test.txt. I use this text file as post_data contents for test because is big enougth to call the Cancel action while the WriteAsync is running.
Can someone give me a hand on this? I spend some days trying to fix this but couldn't achieve a proper solution.
Thanks in advance.
Dont use .WithCancellation(ct) use only await tcp_stream.WriteAsync(header_bytes, 0, header_bytes.Length, ct).
cts = new CancellationTokenSource();
pass ct = cts.Token
in cancel_event() :
if(cts != null) cts.Cancel();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have tried this, but it is giving me an error of "cannot convert from double to string", I wanted to change a variable ProgressBarMegabyte to the equation below.
ProgressBarMegabyte = (Int32.Parse(ProgressBarMegabyte) + Double.Parse(Convert.ToString(ProgressedMegabytes)));
My Whole Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace SoftwareStoreClientDownloader
{
public partial class OfflineInstaller : Form
{
public OfflineInstaller()
{
InitializeComponent();
FormClosing += OfflineInstaller_FormClosing;
}
private void OfflineInstaller_FormClosing(object sender, FormClosingEventArgs e)
{
File.WriteAllText("C:\\Closed.txt", "true");
}
private void OfflineInstaller_Load(object sender, EventArgs e)
{
if (!Directory.Exists("C:\\Program Files\\SoftwareStoreOffline"))
{
Directory.CreateDirectory("C:\\Program Files\\SoftwareStoreOffline");
}
}
private void BrowseButton_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.DefaultExt = "iso";
s.AddExtension = false;
s.CheckPathExists = true;
s.ShowDialog();
try
{
BrowseFileTextBox.Text = s.FileName;
}
catch (Exception dew)
{
}
}
private async void button1_Click(object sender, EventArgs e)
{
var i = 2;
button1.Enabled = false;
button1.Text = "Initializing";
await Initialize();
button1.Text = "Downloading";
TotalProgressBar.Maximum = Int32.Parse(Parts);
if (Int32.Parse(Parts) > 99)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part001.exe",
MainDirectory + "\\" + "Setup-Files.part001.exe");
}
else
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part01.exe",
MainDirectory + "\\" + "Setup-Files.part01.exe");
}
var TotalProgressBytes = ((Int32.Parse(TotalBytes) / 1024d / 1024d) * Int32.Parse(Parts));
var TotalMegabytes = TotalProgressBytes;
var ProgressedMegabytes = (Int32.Parse(TotalBytes) / 1024d / 1024d);
var ProgressBarMegabyte = string.Empty;
ProgressBarMegabyte = ProgressedMegabytes.ToString();
while (i < Int32.Parse(Parts) + 1)
{
if (Int32.Parse(Parts) < 100)
{
if (i < 10)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part0" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part0" + i + ".rar");
}
else
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
}
else if (Int32.Parse(Parts) > 99)
{
if (i < 10 && i < 100)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part00" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part00" + i + ".rar");
}
else if(i > 10 && i < 100)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part0" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part0" + i + ".rar");
}
else if (i > 99)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
}
else if (Int32.Parse(Parts) < 10)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
DownloadProgressLabel.Text = "Status: (" + i + "/" + Parts + ")";
if (i < TotalProgressBar.Maximum)
{
TotalProgressBar.Value = i;
}
if (first == false)
{
TotalProgressLabel.Text = "(" + ProgressBarMegabyte + " MB / " + TotalMegabytes + " MB)";
first = true;
}
else
{
TotalProgressLabel.Text = "(" + ProgressBarMegabyte + " MB / " + TotalMegabytes + " MB)";
}
int Equation = Convert.ToInt32(Int32.Parse(ProgressBarMegabyte) +
Double.Parse(Convert.ToString(ProgressedMegabytes)));
ProgressBarMegabyte = Equation.ToString();
i++;
}
if (Int32.Parse(Parts) > 99)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part001.exe").WaitForExit();
});
}
else if (Int32.Parse(Parts) < 100)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part01.exe");
});
}
else if(Int32.Parse(Parts) < 10)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part1.exe");
});
}
}
private bool first = false;
private string MainDirectory = "C:\\Program Files\\SoftwareStoreOffline";
private string TotalBytes = string.Empty;
private async Task Download(string link, string Filename)
{
using (var client = new WebClient())
{
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadFileAsync(new Uri(link), Filename);
while (client.IsBusy)
{
await Task.Delay(10);
}
}
}
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
}
else if (e.Error != null)
{
}
else
{
}
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
TotalBytes = e.TotalBytesToReceive.ToString();
DownloadProgressBar.Value = e.ProgressPercentage;
}
private string Parts = string.Empty;
private string Database = string.Empty;
private string Version = string.Empty;
private async Task Initialize()
{
try
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineDatabaseNumber.txt",
MainDirectory + "\\OfflineDatabaseNumber.txt");
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineParts.txt",
MainDirectory + "\\OfflineParts.txt");
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineVersion.txt",
MainDirectory + "\\OfflineVersion.txt");
Parts = File.ReadLines(MainDirectory + "\\OfflineParts.txt").First();
Database = File.ReadLines(MainDirectory + "\\OfflineDatabaseNumber.txt").First();
Version = File.ReadLines(MainDirectory + "\\OfflineVersion.txt").First();
}
catch (Exception dew)
{
Console.WriteLine(dew);
throw;
}
}
}
}
I'm trying to use that equation, because I wanted to solve the progress bar, which I eventually figured out. I used the int
Instead of using the Convert.ToString()
you can simply do: ProgressedMegabytes.ToString()
You problem is with different types:
ProgressBarMegabyte is a string
ProgressedMegabytes is double as you said.
Then your assignent is:
sting = int + double
Hence you error. To fix it - simply convert the result to string:
double ProgressedMegabytes = 1.5;
string ProgressBarMegabyte = "83345603 .....................";
ProgressBarMegabyte = (Int32.Parse(ProgressBarMegabyte.TrimEnd('.')) + ProgressedMegabytes).ToString();
Console.WriteLine(ProgressBarMegabyte); // 83345604.5
And be careful with the value of ProgressBarMegabyte - you are working with an assumption that it is a number!
This is not an answer to your question - I just wanted to post a refactored version of your code that might help you to move forward.
private async void button1_Click(object sender, EventArgs e)
{
var i = 2;
await Initialize();
var name = Parts > 99 ? "part001" : "part01";
await Download($"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline{Database}/master/SoftwareStore{Version}Setup-Files.{name}.exe", $"{MainDirectory}\\Setup-Files.{name}.exe");
var format = new string('0', Parts.ToString().Length)
while (i < Parts + 1)
{
await Download($"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline{Database}/master/SoftwareStore{Version}Setup-Files.part{i.ToString(format)}.rar", $"{MainDirectory}\\Setup-Files.{i.ToString(format)}.rar");
i++;
}
await Task.Factory.StartNew(() =>
{
Process.Start($#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part{1.ToString(format)}.exe").WaitForExit();
});
}
private string MainDirectory = "C:\\Program Files\\SoftwareStoreOffline";
private async Task Download(string link, string Filename)
{
using (var client = new WebClient())
{
await client.DownloadFileTaskAsync(link, Filename);
}
}
private int Parts;
private string Database = string.Empty;
private string Version = string.Empty;
private async Task Initialize()
{
try
{
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineDatabaseNumber.txt", MainDirectory + "\\OfflineDatabaseNumber.txt");
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineParts.txt", MainDirectory + "\\OfflineParts.txt");
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineVersion.txt", MainDirectory + "\\OfflineVersion.txt");
Parts = int.Parse(File.ReadLines(MainDirectory + "\\OfflineParts.txt").First());
Database = File.ReadLines(MainDirectory + "\\OfflineDatabaseNumber.txt").First();
Version = File.ReadLines(MainDirectory + "\\OfflineVersion.txt").First();
}
catch (Exception dew)
{
Console.WriteLine(dew);
throw;
}
}
I solved the problem myself using cheap methods:
int Equation = Convert.ToInt32(Int32.Parse(ProgressBarMegabyte)
+ Double.Parse(Convert.ToString(ProgressedMegabytes)));
ProgressBarMegabyte = Equation.ToString();
I am using csvhelper with windows service which runs non stop. I want to create a new csv log file and put the header values only once until the file size grown to 1000 kb and then create another new file so the file size grow too big. At the moment csv file is created once when windows service starts but it repeats header values every time it writes into it.
Do we have some config properties in csv helper to flag size file?
Please have a look at the code and suggest if it can be done efficiently in .net 4.0.
Windows Service code
public partial class Service1 : ServiceBase
{
private Thread executeThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread.Sleep(30000);
executeThread = new Thread(new ThreadStart(Execute));
executeThread.Start();
}
catch (Exception e)
{
Library.LogData("Error : " + DateTime.UtcNow + " " + e.Message);
OnStop();
}
}
protected override void OnStop()
{
try
{
Library.LogData("Stopped: " + DateTime.UtcNow);
executeThread.Abort();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
public void Execute()
{
try
{
Library.LogData("Started");
while (true)
{
Library.LogData("Logging Execute" + DateTime.UtcNow);
Thread.Sleep(5000);
}
}
catch (Exception e)
{
Library.LogData("Error : " + DateTime.UtcNow + " " + e.Message);
OnStop();
}
Library.LogData("Out of Execute" + DateTime.UtcNow);
}
}
Logging code called by windows service
public static class Library
{
public static void LogData(string Message)
{
StreamWriter sw = null;
GetData getData = new GetData();
var dataClasslist = new List<DataClass>
{
new DataClass {}
};
try
{
dataClasslist = getData.ReadData();
using (sw = new StreamWriter("E:\\DataLogs\\LogFile.csv", true))
using (var csv = new CsvWriter(sw))
{
csv.Configuration.RegisterClassMap<DataClassMap>();
csv.WriteHeader<DataClass>();
csv.Configuration.TrimHeaders = true;
csv.Configuration.HasHeaderRecord = false;
csv.WriteRecords(dataClasslist);
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + ": " + e.Message.ToString());
err.Flush();
err.Close();
}
}
}
Main windows service
public partial class Service1 : ServiceBase
{
private Thread executeThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Thread.Sleep(10000);
executeThread = new Thread(new ThreadStart(Execute));
executeThread.Start();
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + " OnStart: " + e.Message.ToString());
err.Flush();
err.Close();
OnStop();
}
}
protected override void OnStop()
{
try
{
executeThread.Abort();
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + "OnStop exception: " + e.Message.ToString());
err.Flush();
err.Close();
}
}
public void Execute()
{
try
{
StreamWriter sw = null;
string FileNameAndPath = null;
FileNameAndPath = "E:\\DataLogs\\LogFile" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
using (sw = new StreamWriter(FileNameAndPath, true))
{
sw.WriteLine("TimeStamp " + "," + "col1" + "," + "col2" + "," + "col3"
+ "," + "col4" + "," + "col5" + "," + "col6" + ","
+ "col8" + "," + "col9" + "," + "col7" + "," + "col10");
sw.Flush();
sw.Close();
}
while (true)
{
Library.LogData(FileNameAndPath);
Thread.Sleep(5000);
}
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + " Execute: " + e.Message.ToString());
err.Flush();
err.Close();
OnStop();
}
}
public void TestInConsole(string[] args)
{
Console.WriteLine("Starting.....");
this.OnStart(args);
}
So OnExecute will be called as soon as file hits 100kb and new file will be created with headers written in it only once.
public static class Library
{
public static void LogData(string FileNameAndPath)
{
StreamWriter sw = null;
GetData getData = new GetData();
var dataClasslist = new List<DataClass>
{
new DataClass {}
};
try
{
//System.Diagnostics.Debugger.Break();
dataClasslist = getData.ReadData();
//Create a file seperately
using (sw = new StreamWriter(FileNameAndPath, true))
using (var csv = new CsvWriter(sw))
{
csv.Configuration.RegisterClassMap<DataClassMap>();
//csv.WriteHeader<DataClass>();
csv.Configuration.TrimHeaders = true;
csv.Configuration.HasHeaderRecord = false;
csv.WriteRecords(dataClasslist);
sw.Flush();
sw.Close();
}
var FileSize = new FileInfo(FileNameAndPath);
//for each 1000 kb
if (FileSize.Length >= 1e+6)
{
//go back to the start to create a new file and column headers
Service1 serive1 = new Service1();
serive1.Execute();
}
}
catch (Exception e)
{
var err = new StreamWriter("E:\\DataLogs\\Errors", true);
err.WriteLine(DateTime.Now.ToString() + " LogData: " + e.Message.ToString());
err.Flush();
err.Close();
}
}
}
Im open for suggests, please let me know if you can thing of a better way to to do this.
I'm using a Nokia 5228 to send a SMS via the COM port, and I get wrong symbols when I send UTF-8 chars. English chars are working good.
How can I solve that problem?
public static string SMSMessage = "Привет";
public static string CellNumber = "number...";
private void Form1_Load(object sender, EventArgs e)
{
sp = new SerialPort();
sp.PortName = "COM12";
sp.Encoding = UTF8Encoding.UTF8;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (!sp.IsOpen)
{
sp.Open();
this.sp.WriteLine(#"AT" + (char)(13));
Thread.Sleep(200);
this.sp.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(200);
this.sp.WriteLine(#"AT+CMGS=""" + CellNumber + #"""" + (char)(13));
Thread.Sleep(200);
this.sp.WriteLine(SMSMessage + (char)(26));
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Exception : {0}", ex.Message), "Port Error");
}
}
The problem was, that I had to use UCS2.
this.sp.WriteLine(StringToUCS2("Привет, привіт !##%") + char.ConvertFromUtf32(26));
public static string StringToUCS2(string str)
{
UnicodeEncoding ue = new UnicodeEncoding();
byte[] ucs2 = ue.GetBytes(str);
int i = 0;
while (i < ucs2.Length)
{
byte b = ucs2[i + 1];
ucs2[i + 1] = ucs2[i];
ucs2[i] = b;
i += 2;
}
return BitConverter.ToString(ucs2).Replace("-", "");
}