How to build my own VB.NET mail server on Windows 10 - vb.net

I would like to build my own (simple) mail server on a Windows machine (in VB.NET) in order to receive mails from one sender. My emailadress will be something like "myname#myserver.com".
What do I have to build ? ... an SMTP-server with the SMTPServer class ? ... as f.e. below code.
How can I test that locally on my machine, without having to buy domain myserver.com. I know how to send an email via VB.NET, but what should I use as outgoing smtp-server ?
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace FakeSMTP
{
public class SMTPServer
{
TcpClient client;
NetworkStream stream;
System.IO.StreamReader reader;
System.IO.StreamWriter writer;
public SMTPServer(TcpClient client)
{
this.client = client;
this.client.ReceiveTimeout = 5000;
stream = client.GetStream();
reader = new System.IO.StreamReader(stream);
writer = new System.IO.StreamWriter(stream);
writer.NewLine = "\r\n";
writer.AutoFlush = true;
}
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Loopback,25);
listener.Start();
while (true)
{
SMTPServer handler = new SMTPServer(listener.AcceptTcpClient());
Thread thread = new System.Threading.Thread(new ThreadStart(handler.Run));
thread.Start();
}
}
public void Run()
{
writer.WriteLine("220 localhost -- Fake proxy server");
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
Console.Error.WriteLine("Read line {0}", line);
switch (line)
{
case "DATA":
writer.WriteLine("354 Start input, end data with <CRLF>.<CRLF>");
StringBuilder data = new StringBuilder();
String subject = "";
line = reader.ReadLine();
if (line != null && line != ".")
{
const string SUBJECT = "Subject: ";
if (line.StartsWith(SUBJECT))
subject = line.Substring(SUBJECT.Length);
else data.AppendLine(line);
for (line = reader.ReadLine();
line != null && line != ".";
line = reader.ReadLine())
{
data.AppendLine(line);
}
}
String message = data.ToString();
Console.Error.WriteLine("Received ­ email with subject: {0} and message: {1}",
subject, message);
writer.WriteLine("250 OK");
client.Close();
return;
default:
writer.WriteLine("250 OK");
break;
}
}
}
}
}

Related

"Validation failed for one or more entities. ERROR

I am creating web API to save the uploaded file in my local storage. When I testing my code it gives an error as ExceptionMessage": "Validation failed for one or more entities. See EntityValidationErrors' property for more details."
Can anyone help to fix this issue. Thanks in advance.
Controller(FileUploadController)
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Web.Http;
using VantageCore.BL;
namespace VantageCoreApi.Controllers.Api
{
public class FileUploadController : ApiController
{
[HttpPost]
[Route("api/FileUpload")]
public async Task<IHttpActionResult> UploadFile(string FileName, int Id)
{
try
{
List<string> ids = new List<string>();
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var referenceId = FileName.Split('_')[0];
foreach (var file in provider.Contents)
{
Guid guid;
ids.Add(Guid.TryParse(await new FileUploadMgt().ReceiveFile(file, FileName, Id), out guid) ? FileName : "Error");
}
return Ok(ids);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
public string SaveFile(byte[] File, string path)
{
string Result = "";
try
{
//LOCAL SERVER PATH
var fs = new BinaryWriter(new FileStream(#"F:\Testfolder" + path, FileMode.Append, FileAccess.Write));
fs.Write(File);
fs.Close();
Result = path;
}
catch (Exception ee)
{
Result = ee.ToString();
}
return Result;
}
}
}
BL (FileUplodMgt.cs)
using System;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net.Http;
using VantageCore.Entity.Model;
using File = VantageCore.Entity.Model.File;
namespace VantageCore.BL
{
public class FileUploadMgt
{
public async Task<string> ReceiveFile(HttpContent receivedFile, string receivedFileName, int Id)
{
if (receivedFile != null)
{
var fileId = Guid.NewGuid();
using (var c = new DBEntities())
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string folder = appSettings["TestPath"];
var fileName = fileId.ToString() + Path.GetExtension(receivedFileName).ToLower();
var file = Path.Combine(folder, fileName);
bool exists = Directory.Exists(folder);
if (!exists) Directory.CreateDirectory(folder);
using (var fs = new BinaryWriter(new FileStream(file, FileMode.Create, FileAccess.Write)))
{
fs.Write(await receivedFile.ReadAsByteArrayAsync());
}
string extention = Path.GetExtension(file);
receivedFileName = Path.GetFileNameWithoutExtension(receivedFileName).Length <= 32
? Path.GetFileNameWithoutExtension(receivedFileName)
: Path.GetFileNameWithoutExtension(receivedFileName).Substring(0, 31) + "~";
var newFile = new File
{
Uid = fileId,
FileExtention = extention,
FileName = receivedFileName,
FileSize = (int)(receivedFile.Headers.ContentLength / 1024),
CreatedDate = DateTime.UtcNow
};
c.Files.Add(newFile);
c.SaveChanges();
}
return fileId.ToString();
}
else
{
return "Error,Invalid file Or file size exceeded";
}
}
}
}
You could try as below to observe the error message when you debug and share it;
try
{
c.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
}
}

How to convert MailAttachment to MimeKit Attachment

We have to rework how we're sending emails since we are using Amazon SES. In the past, we were using smtp but can't do that in this case. The class that needs updated has taken in a MailMessage object and used smtp to send it. So I'm trying to rework the method to be able to continue to accept the MailMessage object and convert it to a MimeKit MimeMessage. For the most part it's working fine except when it comes to attachments. In the code I have, the attachment gets added and sent, however, when trying to open it appears it's corrupted or something. In my test case I attached a csv file. I could not open it in excel after receiving the email.
public class EmailAbstraction
{
public virtual void Send(MailMessage mailMessage)
{
sendMessage(mailMessage);
}
private static void sendMessage(MailMessage mailMessage)
{
using (var client = new AmazonSimpleEmailServiceClient(AwsConstants.SESAWSKey, AwsConstants.SESAWSSecret, AwsConstants.RegionEndpoint))
{
foreach (var to in mailMessage.To)
{
using (var messageStream = new MemoryStream())
{
var newMessage = new MimeMessage();
var builder = new BodyBuilder
{
HtmlBody = mailMessage.Body
};
newMessage.From.Add(mailMessage.From == null
? new MailboxAddress(EmailConstants.DefaultFromEmailDisplayName, EmailConstants.DefaultFromEmailAddress)
: new MailboxAddress(mailMessage.From.Address));
newMessage.To.Add(new MailboxAddress(to.DisplayName, to.Address));
newMessage.Subject = mailMessage.Subject;
foreach (var attachment in mailMessage.Attachments)
{
builder.Attachments.Add(attachment.Name, attachment.ContentStream);
}
newMessage.Body = builder.ToMessageBody();
newMessage.WriteTo(messageStream);
var request = new SendRawEmailRequest
{
RawMessage = new RawMessage { Data = messageStream }
};
client.SendRawEmail(request);
}
}
}
}
}
And in my test app, I have this.
internal class Program
{
private static void Main(string[] args)
{
var s = GetFileStream();
var m = new MailMessage();
var sender = new MailAddress("info#ourwebsite.com", "info");
m.From = sender;
m.Sender = sender;
m.Body = "test email";
m.Subject = "test subject";
m.To.Add(myemail);
m.Attachments.Add(new Attachment(s, "test-file.csv"));
new EmailAbstraction().Send(m);
}
private static MemoryStream GetFileStream()
{
var stream = new MemoryStream();
var fileStream = File.Open(#"C:\Users\dev\Desktop\test-file.csv", FileMode.Open);
fileStream.CopyTo(stream);
fileStream.Close();
return stream;
}
}
This is just copied from the MimeKit source code:
static MimePart GetMimePart (System.Net.Mail.AttachmentBase item)
{
var mimeType = item.ContentType.ToString ();
var contentType = ContentType.Parse (mimeType);
var attachment = item as System.Net.Mail.Attachment;
MimePart part;
if (contentType.MediaType.Equals ("text", StringComparison.OrdinalIgnoreCase))
part = new TextPart (contentType);
else
part = new MimePart (contentType);
if (attachment != null) {
var disposition = attachment.ContentDisposition.ToString ();
part.ContentDisposition = ContentDisposition.Parse (disposition);
}
switch (item.TransferEncoding) {
case System.Net.Mime.TransferEncoding.QuotedPrintable:
part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
break;
case System.Net.Mime.TransferEncoding.Base64:
part.ContentTransferEncoding = ContentEncoding.Base64;
break;
case System.Net.Mime.TransferEncoding.SevenBit:
part.ContentTransferEncoding = ContentEncoding.SevenBit;
break;
//case System.Net.Mime.TransferEncoding.EightBit:
// part.ContentTransferEncoding = ContentEncoding.EightBit;
// break;
}
if (item.ContentId != null)
part.ContentId = item.ContentId;
var stream = new MemoryStream ();
item.ContentStream.CopyTo (stream);
stream.Position = 0;
part.Content = new MimeContent (stream);
return part;
}

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

how can we make world of warcraft 2.4.3 packet in c# without using wow path

hello i have a wow server Arcemu on local Ip and I want check accounts
if they exist on wow server with c# by sending packets for example i
want to send a udp pack with c# it includes username , password , ...
and server return succed (999 status ) how can I do that?
here is my code :
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
public class clnt {
public static void Main() {
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("serverip", port);
Console.WriteLine("Connected");
String username= "username";
String password= "password";
bool HasPassword;
int[] Selected;
bool AutoUpdate ;
bool Minimize;
bool Hide ;
HasPassword = false;
Selected = new int[] { 0 };
AutoUpdate = true;
Minimize = true;
Hide = false;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] user=asen.GetBytes(username);
byte[] pass= asen.GetBytes(password);
Console.WriteLine("Transmitting.....");
stm.Write(user,0,user.Length);
stm.Write(pass, 0, pass.Length);
byte[] bb=new byte[1400];
int k=stm.Read(bb,0,1400);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.GetStream();
NetworkStream clientStream = tcpclnt.GetStream();
StreamReader clientStreamReader = new StreamReader(clientStream);
Console.WriteLine(clientStreamReader.Read().ToString());
Console.ReadKey();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadKey();
}
}
}

Why am I getting, "Unable to connect to the remote server"?

This err msg is the next one I get after resolving “NotSupportedException” as noted here
I don't even reach the break point in the server code (set on the first line of the method that should be getting called).
This is the relevant server code:
[Route("api/PlatypusItems/PostArgsAndXMLFileAsStr")]
public async void PostArgsAndXMLFileAsStr([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
string beginningInvoiceNum = string.Empty; // <= Breakpoint on this line
string endingInvoiceNum = string.Empty;
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
. . .
And the client (handheld, Compact Framework) code:
private void menuItem4_Click(object sender, EventArgs e)
{
GetAndSendXMLFiles("LocateNLaunch"); // There is a "LocateNLaunch.xml" file
}
private void GetAndSendXMLFiles(string fileType)
{
string serNum = User.getSerialNo();
string siteNum = User.getSiteNo();
if (serNum.Length == 0)
{
serNum = "8675309";
}
if (siteNum.Length == 0)
{
siteNum = "03";
}
string uri = string.Format("http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum={0}&siteNum={1}", serNum, siteNum);
List<String> XMLFiles = HHSUtils.GetXMLFiles(fileType, #"\");
MessageBox.Show(XMLFiles.Count.ToString());
foreach (string fullXMLFilePath in XMLFiles)
{
MessageBox.Show(fullXMLFilePath);
RESTfulMethods.SendXMLFile(fullXMLFilePath, uri, 500);
}
}
public static string SendXMLFile(string xmlFilepath, string uri, int timeout) // timeout should be 500
{
MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));
MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
if (timeout < 0)
{
request.ReadWriteTimeout = timeout;
request.Timeout = timeout;
}
request.ContentLength = postBytes.Length;
request.KeepAlive = false;
request.ContentType = "application/xml";
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("SendXMLFile exception " + ex.Message);
request.Abort();
return string.Empty;
}
}
}
Running this code, I see from the client the following "debug strings":
0) "1" (from MessageBox.Show(XMLFiles.Count.ToString());)
1) "\Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(fullXMLFilePath);)
2) "In SendXMLFile() - xmlFilePath == \Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));)
3) "In SendXMLFile() - uri == http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum=8675309&siteNum=03" (from MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));)
- and then this one from somewhere:
4) "SendXMLFile exception Unable to connect to the remote server"...
So what could be causing this inability to connect?
UPDATE
The same thing ("Unable to Connect to the Remote Server") happens with this code (different operation, but also from the WindowsCE/Compact Framework/handheld app that tries to connect to the Web API server app):
private void menuItem3_Click(object sender, EventArgs e)
{
string serNum = User.getSerialNo();
if (serNum.Length == 0)
{
serNum = "8675309";
}
string clientVer =
HHSUtils.GetFileVersion(#"\Application\sscs\vsd_setup.dll");
if (clientVer.Contains("Win32Exception"))
{
clientVer = "0.0.0.0";
}
MessageBox.Show(string.Format("After call to GetFileVersion(), serial num == {0};
clientVer == {1}", serNum, clientVer));
string uri =
string.Format("http://localhost:28642/api/FileTransfer/GetHHSetupUpdate?
serialNum={0}&clientVersion={1}", serNum, clientVer);
RESTfulMethods.DownloadNewerVersionOfHHSetup(uri);
}
public static void DownloadNewerVersionOfHHSetup(string uri)
{
string dateElements = DateTime.Now.ToString("yyyyMMddHHmmssfff",
CultureInfo.InvariantCulture);
var outputFileName = string.Format("HHSetup_{0}.exe", dateElements);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}",
outputFileName));
}
}
}
catch (WebException webex)
{
MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
}
}
// I see the "After call to GetFileVersion()" message in menuItem3_Click() handler, but then "DownloadNewerVersionOfHHSetup: Unable to Connect to the Remote Server" in DownloadNewerVersionOfHHSetup()
And yes, the server app is running.
UPDATE 2
Here is the code that I tested prior to "dumbing it down" (retrofitting it, making it as similar as possible to this working test code, yet that may not be saying much) for Compact Framework:
Client code:
DownloadTheFile(textBoxFinalURI.Text); // with textBoxFinalURI.Text being
"http://localhost:28642/api/FileTransfer/GetUpdatedHHSetup?
serialNum=8675309&clientVersion=1.3.3.3" and the file on the server being
version 1.4.0.15
private void DownloadTheFile(string uri)
{
var outputFileName = "Whatever.exe";
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}",
outputFileName));
}
}
}
catch (WebException webex)
{
MessageBox.Show(webex.Message);
}
}
Server code:
public HttpResponseMessage GetHHSetupUpdate(string serialNum, string clientVersion)
{
HttpResponseMessage result;
string filePath = GetAvailableUpdateForCustomer(serialNum);
FileVersionInfo currentVersion = FileVersionInfo.GetVersionInfo(filePath);
if (!ServerFileIsNewer(clientVersion, currentVersion))
{
result = new HttpResponseMessage(HttpStatusCode.NoContent);
}
else
{
result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(filePath, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
}
return result;
}
private string GetAvailableUpdateForCustomer(string serialNum)
{
if (serialNum == "8675309")
{
return HostingEnvironment.MapPath(#"~\App_Data\HHSetup.exe");
}
else
{
return HostingEnvironment.MapPath(#"~\App_Data\HDP.exe");
}
}
// clientFileVersion is expected to be something like "1.4.0.15"
private bool ServerFileIsNewer(string clientFileVersion, FileVersionInfo serverFile)
{
Version client = new Version(clientFileVersion);
Version server = new Version(string.Format("{0}.{1}.{2}.{3}",
serverFile.FileMajorPart, serverFile.FileMinorPart,
serverFile.FileBuildPart, serverFile.FilePrivatePart));
return server > client;
}
... This code works fine (server code is the same; the client code has been "retrofied")
I can't use the code as-is because of the limitations of Compact Framework / Windows CE. As the title of this post makes clear, I'm not even able to connect to the server from there yet. Is it possible? If so, what needs to change in my client code (not the client code in Update 2, which works in newer versions of .NET, but the client code shown prior to there)?
It's a similar story with the other method that is also returning "Unable to connect to the remote server" - it works fine in "modern" code running in a test app, but once it's retrofitted (better word than refactored when "dumbing down" to Compact Frameworkerize the code).
UPDATE 3
I tried to get more info from the err msg with the code below (old line commented out), but this "rewards" me instead with a NullReferenceException:
catch (WebException webex)
{
//MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string resp = webex.Response.ToString();
string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
}
UPDATE 4
As I continued to get NREs, I commented out each subsequent line, one-by-one, until I now have this that runs:
//string innerEx = webex.InnerException.ToString();
//string resp = webex.Response.ToString();
//string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
//string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
//string.Format("Message: {0}; Response: {1}; Stack Trace: {2}; Status: {3}", msg, resp, stackTrace, status));
//string.Format("Message: {0}; Stack Trace: {1}; Status: {2}", msg, stackTrace, status));
string.Format("Message: {0}; Status: {1}", msg, status));
...but all I get from it is Status of "ConnectFailure" (I already knew that).
UPDATE 5
This runs without an NRE:
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string status = webex.Status.ToString();
MessageBox.Show(string.Format("Message: {0}; Status: {1}; inner Ex: {2}", msg, status, innerEx));
And this is what I see:
So why would the server actively refuse the connection?
BTW, ASAP I'm going to bountify this question, or will bountify the answerer after the fact*, with a bounty that would make even Long John Silver and Perro-Negro's eyes glimmer and gleam (cared they for geekCoin, that is).
For facts leading to the arrest and eviction of this bug.
PSYCHE! I changed my mind/there's been a mutiny on the bounty => the bountification will happen here instead.
UPDATE 6
This also (using the "raw" IP Address of the server machine) gives me an NRE:
string uri = string.Format("http://192.168.125.50:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={0}&clientVersion={1}", serNum, clientVer);
...as does using the "friendly name" ("Platypus") of the machine in place of the IP Address.
The large problem I see here is the fact that you have localhost as your address. That's absolutely wrong. localhost means, effectively, "on the same machine as I am running" so unless you've somehow managed to get a async .NET 4.0 web service to run on your Windows CE device and your server code is running there, then this is most certainly not what you want.
If you're running on an emulator, it's still wrong. The emulator is, for all intents and purposes, a separate machine.
You must use the address of the server/PC where that web service is running. It must be a routable address, meaning if you're connected over USB then it's probably ppp_peer and not an IP address (well it resolves to a private address, but the name is easier to remember).