Convert console.writeline to RichTextBox.AppendText() c# - c#

I have some code that reads the ssid and rssi from multiple access points. However it is a console app and I need to convert it to a winform app.
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
foreach (Wlan.WlanAvailableNetwork network in networks)
{
Console.WriteLine("Found network with SSID {0} and Siqnal Quality {1}.", GetStringForSSID(network.dot11Ssid), network.wlanSignalQuality);
}
I wish to convert the line that prints the list in the console to a line (or lines) that will print to a rich text box. Everything I have tried has resulted in just printing one entry from the list.
Thanks
EDIT
Thanks for the responses, here's what I went with..
richTextBox1.AppendText("Found network with SSID---" + GetStringForSSID(network.dot11Ssid) + "and Siqnal Quality---" + rssi + "\n")

You have to make sure the Multiline property to true on the RichTextBox (this is the default so it should be). Use the RichTextBox.AppendText() method and make sure you add a newline character to the end of your string.

I assume here that you are building up a list of networks, for multiple string appends, I would advise using a StringBuilder MSDN Link.
Something like this should work:
StringBuilder builder = new StringBuilder();
foreach(Wlan.WlanAvailableNetwork Network network in networks)
{
string ssidString = GetStringForSSID(network.dot11Ssid);
builder.AppendFormat("Found network with SSID {0} and Signal Quality {1}.", ssidString , network.wlanSignalQuality).AppendLine();
}
textBox.Text = builder.ToString();

TextBox.Lines= networks.Select(n => string.Format("Found network with SSID {0} and Signal Quality {1}.", n.dot11Ssid, n.wlanSignalQuality)).ToArray();

Related

How can I get an incoming email's message in C#?

The code I am using at the moment is
try
{
//using MailKit.Net.Pop3;
string pathLog = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
string fileNameLog = Path.Combine(pathLog, "pop3.txt");
using (var client = new Pop3Client(new ProtocolLogger(fileNameLog)))
//using (var client = new Pop3Client(new ProtocolLogger("pop3.log")))
{
strProgress = strProgress + "c";
client.Connect("outlook.office365.com", 995, SecureSocketOptions.SslOnConnect); //POP3 port is 995
strProgress = strProgress + "d";
client.Authenticate("xxx", "yyy");
strProgress = strProgress + "e";
for (int i = 0; i < client.Count; i++)
{
strProgress = strProgress + "f";
var message = client.GetMessage(i);
strProgress = strProgress + "g";
//Write the message to a file
message.WriteTo(string.Format("{0}.msg", i)); //<<<<<<<<<error here
numCountEmailsDownloaded = numCountEmailsDownloaded + 1;
}
client.Disconnect(true);
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message + "\n\nStopped after " + strProgress, ToastLength.Long).Show();
}
I get an error message which says 'Access to the path "/0.msg" is denied. Stopped after abcdefg (I use strProgress to mark where the error is).
I've tried getting the email body as a string but the error message says 'Do not use string to serialize ...use WriteTo instead', except that it doesn't tell me what to do with it even if it worked.
The idea of receiving emails and then wanting to know what they say must be a common one, but many other questions and answers on the web seem to think it isn't worth actually spelling out.
How can I extract the email body text from the above? Thank you.
You are trying to write the message to a file in the current working directory. This will most likely be the application's path.
Applications are generally installed under the Program Files folder. Regular users do not have permission to write to that folder.
You will need to use a different path to store your files. For example, somewhere under the LocalApplicationData folder which you're using for your log files.
Where should I store my data?
I've tried getting the email body as a string
If that's what you really want, maybe replace the line with this:
string messageBody = message.GetTextBody(MimeKit.Text.TextFormat.Plain);
as per the docs for the MimeMessage type. See more options for the TextFormat here:
http://www.mimekit.net/docs/html/T_MimeKit_Text_TextFormat.htm
This may also work:
string messageBody = message.TextBody;
In both cases this is looking for the Text option within a MIME message. It's somewhat common these days to find messages where the text format doesn't exist, and the message only includes an HTML content body. In that situation you need to know how to check both the text and fallback to HTML (or vice versa).
Otherwise, answers and comments suggesting file permissions sound right on the mark.

Serial Port Request-Response communication using c#

I want to do serial port communication with a machine which uses RS232-USB ports.
I am using serial port class. I am very new to the concept. In my first Machine interfacing I only had to do the serialport.readLine( to get the readings from the machine and there was no need to send ACK /NAK). but for the new machine interface the document says following things:
The following is an example of the RA500 communication:
Computer :<05h 31h 0dh>
RA500 :1st line of information
Computer :<06h 0dh>
RA500 :2nd line of information
Computer :<06h 0dh>
RA500 :”EOF”<0dh>
What i understood from this is i have to write to comport before reading from it. this is what i am doing in my code:
ACK = "06 0d"; NAK = "15 0d"; str = "05 31 0d";
while (count <= 5)
{
rx = ComPortDataReceived(str);
if (!string.IsNullOrEmpty(rx))
{
str = ACK;
returnReading += rx;
}
else if (string.IsNullOrEmpty(rx)) str = NAK;
count++;
}
private string ComPortDataReceived(string str)
{
string Rx = string.Empty;
string exceptionMessage = string.Empty;
try
{
byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
comPort.Write(bytes, 0, bytes.Length);
Rx = comPort.ReadExisting();
PEHRsLibrary.writeTextFile(DateTime.Now + " RxString :" + Rx);
return Rx;
}
catch(Exception e){}
when i use this code i am receiving empty strings as responce. but if i use comPort.ReadExisting() only without using comPort.Write i am receving a string with all the readings but the probblem is it only gives one line of information and dosnt give 2nd or 3rd line readings.
when i try using comPort.ReadLine() after Write() I am getting Timeout exception.
i dont know what i am doing wrong in this case. I am writing ACk after receving 1st line but not receving 2nd line. Next thing i am gonna try is read() as byte and then convert it to string instead of using ReadExisting(). Any other way i can do this?

-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...

How to find a list of wireless networks (SSID's) in Java, C#, and/or C?

Is there a toolkit/package that is available that I could use to find a list of wireless networks (SSID's) that are available in either Java, C#, or C for Windows XP+? Any sample code would be appreciated.
For C#, take a look at the Managed Wifi API, which is a wrapper for the Native Wifi API provided with Windows XP SP2 and later.
I have not tested this code, but looking at the Managed Wifi API sample code, this should list the available SSIDs.
WlanClient client = new WlanClient();
foreach ( WlanClient.WlanInterface wlanIface in client.Interfaces )
{
// Lists all available networks
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList( 0 );
foreach ( Wlan.WlanAvailableNetwork network in networks )
{
Console.WriteLine( "Found network with SSID {0}.", GetStringForSSID(network.dot11Ssid));
}
}
static string GetStringForSSID(Wlan.Dot11Ssid ssid)
{
return Encoding.ASCII.GetString( ssid.SSID, 0, (int) ssid.SSIDLength );
}
ArrayList<String>ssids=new ArrayList<String>();
ArrayList<String>signals=new ArrayList<String>();
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "netsh wlan show all");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line.contains("SSID")||line.contains("Signal")){
if(!line.contains("BSSID"))
if(line.contains("SSID")&&!line.contains("name")&&!line.contains("SSIDs"))
{
line=line.substring(8);
ssids.add(line);
}
if(line.contains("Signal"))
{
line=line.substring(30);
signals.add(line);
}
if(signals.size()==7)
{
break;
}
}
}
for (int i=1;i<ssids.size();i++)
{
System.out.println("SSID name == "+ssids.get(i)+" and its signal == "+signals.get(i) );
}
Well, you didn't specify the OS so, for Linux I will suggest Wireless Tools for Linux by Jean Tourrilhes (http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html). The iwlist() command displays a lot of information about the available networks. The source code is in C. Another way is to write your own code in C using libpcap for capturing the beacon frames and extracting SSID from them (in monitor mode only). I haven't tested my sniffing code yet so I won't paste it here but it is pretty simple job.

Categories