WIFI upload speed C# vs Android Java - c#

I am working on a WIFI boot loader for an embedded device. It is working fine, but now I want to increase the speed. I have a C# client and an Android client with the device acting as server. The embedded device is rather slow so the clients must sleep between data records while the device writes to program memory. Here is the strange part: Required sleep for the Windows C# client is 300ms while it is 800ms for Android. Any less of a wait causes the server to send an error. This results in an 8 minute operation in C# and 21 minutes in Android. Why is this?
Here is the loop in C#:
for (int line = 0; line < lines.Count; line++) {
if (lines[line].StartsWith(";")) break;
byte[] sbytes = Encoding.ASCII.GetBytes(lines[line]);
gStream.Write(sbytes, 0, sbytes.Length);
textBoxTerminal.AppendText(lines[line]);
textBoxTerminal.AppendText("\n");
Application.DoEvents();
wait(300);
if (gStream.DataAvailable) break;
}
Here it is in Android Java:
while((data = br.readLine()) != null) {
if (data.startsWith(";")) break;
dataOutputStream.writeBytes(data + "\r");
lines++;
mData = lines + " Lines of " + tlines + " sent";
mHandler.post(mShowData);
dataOutputStream.flush();
Thread.sleep(800);
if (inputStream.available() > 0) break;
}

Related

XAMPP becomes super slow after some time

Does anyone ever encounter the MYSQL in XAMPP being super slow after sometime?
I have a unity application that asking a string to be downloaded with this php script.
<?php
include 'Config.php'; // Just a normal mysqli connection setup
//the post from Unity.
$var_uniqueID = $_POST['uniqueID_Post'];
$conn = OpenCon(); // open connection
//create a query
$sql = "SELECT
var_name,
var_value
FROM variable_current_values
WHERE uniqueID = '".$var_uniqueID."' ";
$result = mysqli_query($conn, $sql);
if( mysqli_num_rows($result) > 0)
{
//show data for each row
while($row = mysqli_fetch_assoc($result))
{
echo "".$row['var_name'] .
"|".$row['var_value'] . "";
}
}
CloseCon($conn); // close the connection
?>
This PHP script is being called with c# script of UnityWebRequest
//www variable
private UnityWebRequest unityWebRequest;
void Update ()
{
if (unityWebRequest == null)
{
//fetch The data Widget
StartCoroutine(RealDataFetchWhere(this.name));
}
}
private IEnumerator RealDataFetchWhere(string _uniqueIDPost)
{
//gives the unique key
WWWForm fetchingForm = new WWWForm();
fetchingForm.AddField("uniqueID_Post", _uniqueIDPost);
//load and wait until the data is downloaded
unityWebRequest = UnityWebRequest.Post(**thePHPLink**, fetchingForm);
yield return unityWebRequest.SendWebRequest();
string data = unityWebRequest.downloadHandler.text;
print("the Data is : " + data);
}
At first everything seems to be fine. Data is downloaded perfectly(almost in realtime speed).
However after like more than 10 minutes, the XAMPP mySQL starting to slow down considerably. I try to modified the data manually in XAMPP and it takes about 5 - 8 seconds until the "row is affected"
If i leave them longer without closing my unity program, XAMPP start to freeze and disconnected.
Does anyone know the solutions to counter this problem ?

writing to/updating a TextBox in "real time" on a networked form C#

I have a windows form in visual studio 10 that connects to a python server program and receives a string of data repeatedly from the server. it then writes this string to a textbox. currently for testing purposes the server sends this string 10 times and then turns off. what i want the client to do is after it receives each string it writes it to the text box immediately but currently it waits until the server has finished and then writes the last string. the client code for this is as follows:
while (TestConnection(client))
{
char tt = ' ';
try{
tt = Convert.ToChar(clientStreamReader.Read());
if (count < 17)
{
message = tt.ToString();
m += message;
count += 1;
}
else if (count >= 17)
{
textBox2.Text = m + "\r\n";
m = "";
count = 0;
}
}catch(OverflowException){
m += "";
}
}
how can I change this to write each string as they are received?
(TestConnection is a custom bool that indicates weather the connection is good)
EDIT:
(loop is inside button click event)
You could write an background Worker process, which always checks in a loop if there is a new string wich can be written to your textbox.
Check out this link: example on CodeProject

C# - Communicate with WinUSB device with LIBUSB

I am trying to communicate with a Nokia Lumia phone(RM-917), over USB using LIBUSING and C#. LIBUSB is able to see the device's information(pid,vid,etc). However, I am not able to successfully write to ANY endpoint, even sending the exact command as the Windows Device Recovery Tool.
According to WinUSB, the write endpoint is EP07, however, this endpoint just times out. I have tried every other endpoint, and all of these fail.
`
public void initDevice()
{
if(this.lumiaDevice == null)
{
throw new Exception("LumiaPhoneManager does not have a selected device");
}
UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0421, 0x0661);
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(1);
}
if (this.writer == null)
{
writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep07);
}
}
public void readPCode()
{
currentID++;
var _x = new jsonPkt();
ErrorCode ec = ErrorCode.None;
int bytesWritten;
_x.id = this.currentID + 1;
_x.method = "ReadProductCode";
string value = #"{""jsonrpc"":""<JSONRPC>"",""id"":<ID>,""method"":""<METHOD>"",""params"":null}";
value = value.Replace("<JSONRPC>", "2.0");
value = value.Replace("<ID>", currentID.ToString());
value = value.Replace("<METHOD>", _x.method.ToString());
ec = writer.Write(Encoding.Default.GetBytes(value), 8000, out bytesWritten);
currentID++;
if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 100 milliseconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 100, out bytesRead);
// if (bytesRead == 0) throw new Exception("No more bytes!");
// Write that output to the console.
this.rtb.Text += Encoding.Default.GetString(readBuffer, 0, bytesRead).ToString() + "\n";
}
}
Found the solution
Debugged the OEM software and found the program was using a different path to the USB device. After that I was getting access denied errors, which was solved by moving the project to a different drive. For reasons unknown, when the program runs on c drive, the CreateFile function fails with access denied
Its possible that to activate write, you need to send some class specific control request first. You mentioned that windows device recovery tool is able to write.
You can install USB packet sniffer software in your windows PC and then use the device manager to write some data to the device. Packet sniffer tool will be able to capture all the packets sent to the device.
This way you can see the exact device requests which are required to enable write operation.
Analyzer software - http://www.usblyzer.com/
Please try this way to resolve your problem.
PS- I am assuming you do not have a hardware USB packet analyzer like Lecroy advisor or Beagle. Software packet sniffer should be fine since the host is a PC.

-ERR Exceeded the login limit for a 15 minute period. Reduce the frequency of requests to the POP3 server

using following code i have reading msg from my hotmail account . But sometimes the following error coming . -ERR Exceeded the login limit for a 15 minute period. Reduce the frequency of requests to the POP3 server . can anyone tell me whats the reason for this ? Is that server problem or anything else ? other than pop3 anyother protocol can we use for hotmail?
public string hotmail(string username, string password)
{
string result = "";
string str = string.Empty;
string strTemp = string.Empty;
try
{
TcpClient tcpclient = new TcpClient();
tcpclient.Connect("pop3.live.com", 995);
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
sslstream.AuthenticateAsClient("pop3.live.com");
System.IO.StreamWriter sw = new StreamWriter(sslstream);
System.IO.StreamReader reader = new StreamReader(sslstream);
strTemp = reader.ReadLine();
sw.WriteLine("USER" + " " + username);
sw.Flush();
strTemp = reader.ReadLine();
sw.WriteLine("PASS" + " " + password);
sw.Flush();
strTemp = reader.ReadLine();
string[] numbers = Regex.Split(strTemp, #"\D+");
int a = 0;
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
numbers[a] = i.ToString();
a++;
}
}
sw.WriteLine("RETR" + " " + numbers[0]);
sw.Flush();
strTemp = reader.ReadLine();
while ((strTemp = reader.ReadLine()) != null)
{
if (strTemp == ".")
{
break;
}
if (strTemp.IndexOf("-ERR") != -1)
{
break;
}
str += strTemp;
}
sw.WriteLine("Quit ");
sw.Flush();
result = str;
return result;
}
Catch ( Exception ex)
{}
return result;
}
thanks in advance ..
Any other protocol you can use? Yes, hotmail/outlook.com now supports IMAP.
But the issue with the code here seems to be that you're creating a new TcpClient every time you run this. If you're running it many times in in a row, Outlook.com/Hotmail will eventually complain. It's as if you've got tons of clients from a single source connecting to their server, which is, when it's not testing code, often a sign of email abuse.
TcpClient tcpclient = new TcpClient(); // Hello, new.
tcpclient.Connect("pop3.live.com", 995);
If you've got a lot to do on the server, keep a single connection active longer, and close it up when you're done.
Every time you run the code in your question, you're creating (and not tcpclient.Close()-ing) a connection to pop3.live.com. I usually only get this error when I've had a lot of connections that don't close properly due to errors when I'm messing with my code.
MSDN actually has a decent example for TcpClient, but you might be more interested in another example from SO here. Check out how it uses using, and nests a loop inside.
using (TcpClient client = new TcpClient())
{
client.Connect("pop3.live.com", 995);
while(variableThatRepresentsRunning)
{
// talk to POP server
}
}
By the way, the best advice I can give here is to tell you not to reinvent the wheel (unless you're just having fun playing with the POP server. Throwing commands via TCP can be lots of fun, especially with IMAP).
OpenPop.NET is a great library to handle POP requests in C#, includes a good MIME parser, and, if you're still working on this, should speed you along quite a bit. Its examples page is excellent.
Go to the mail inbox , you may get mail regarding this and accept it. Otherwise Try to give the request after some time. Because google having some restriction to read mail using pop settings.

Hostname scanning in C#

Iv'e recently started a new job as an ICT Technician and im creating an Console application which will consists of stuff that will help our daily tools!
My first tool is a Network Scanner, Our system currently runs on Vanilla and Asset tags but the only way we can find the hostname / ip address is by going into the Windows Console tools and nslookup which to me can be improved
I want to create an application in which I enter a 6 digit number and the application will search the whole DNS for a possible match!
Our hostsnames are like so
ICTLN-D006609-edw.srv.internal the d 006609 would be the asset tag for that computer.
I wish to enter that into the Console Application and it search through every hostname and the ones that contain the entered asset tag within the string will be returned along with an ip and full computer name ready for VNC / Remote Desktop.
Firstly how would I go about building this, shall i start the project of as a console app or a WPF. can you provide an example of how I can scan the hostnames via C#, or if there's an opensource C# version can you provide a link.
Any information would be a great help as it will take out alot of issues in the workpalce as we have to ask the customer to go into there My Computer adn properties etc and then read the Computer name back to use which I find pointless.
Regards.
Updates:
*1 C# Version I made: http://pastebin.com/wBWxyyuh
I would actually go about this with PowerShell, since automating tasks is kinda its thing. In fact, here's a PowerShell script to list out all computers visible on the network. This is easily translatable into C# if you really want it there instead.
function Find-Computer( [string]$assetTag ) {
$searcher = New-Object System.DirectoryServices.DirectorySearcher;
$searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry;
$searcher.SearchScope = 'Subtree';
$searcher.PageSize = 1000;
$searcher.Filter = '(objectCategory=computer)';
$results = $searcher.FindAll();
$computers = #();
foreach($result in $results) {
$computers += $result.GetDirectoryEntry();
}
$results.Dispose(); #Explicitly needed to free resources.
$computers |? { $_.Name -match $assetTag }
}
Here's a way you can accomplish this, although it's not the best. You might consider hitting Active Directory to find the legitimate machines on your network. The code below shows how you might resolve a machine name, and shows how to ping it:
static void Main()
{
for (int index = 0; index < 999999; index++)
{
string computerName = string.Format("ICTLN-D{0:000000}-edw.srv.internal", index);
string fqdn = computerName;
try
{
fqdn = Dns.GetHostEntry(computerName).HostName;
}
catch (SocketException exception)
{
Console.WriteLine(">>Computer not found: " + computerName + " - " + exception.Message);
}
using (Ping ping = new Ping())
{
PingReply reply = ping.Send(fqdn);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine(">>Computer is alive: " + computerName);
}
else
{
Console.WriteLine(">>Computer did not respond to ping: " + computerName);
}
}
}
}
Hope that helps...

Categories