SmtpClient timeout when sending to Exchange server - c#

I have a problem with mailing to a exchange server.
The mails got delivered, but the SmtpClient always waits for 8 seconds and then receives a timeout exception.
I think it has something to do with the exchange mail queue, but i don't find a fix for it.
Best regards,
Michael
public void SendMessage(MailMessage message, string guid)
{
if(!ValidSettings())
{
return;
}
if(!string.IsNullOrEmpty(_bccEmail))
{
message.Bcc.Add(_bccEmail);
}
message.From = new MailAddress(_emailFrom, _weergaveNaam);
bool error = true;
int tried = 0;
while(error && tried < _maxRetry)
{
if(_smtpClient == null)
{
_smtpClient = new SmtpClient(_serverUrl, _serverPort) {Credentials = new NetworkCredential(_serverUser, _serverPassword), EnableSsl = _useSsl};
}
using(UnitOfWork uow = new UnitOfWork())
{
tried++;
EmailLog log = new EmailLog(uow) {Guid = guid, From = message.From.Address};
StringBuilder sb = new StringBuilder();
foreach(MailAddress mailAddress in message.To)
{
if(sb.Length > 0)
{
sb.Append(",");
}
sb.Append(mailAddress.Address);
}
log.To = sb.ToString();
sb.Clear();
foreach (MailAddress mailAddress in message.Bcc)
{
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(mailAddress.Address);
}
log.Bcc = sb.ToString();
sb.Clear();
foreach (MailAddress mailAddress in message.CC)
{
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(mailAddress.Address);
}
log.Cc = sb.ToString();
sb.Clear();
log.Subject = message.Subject;
try
{
_smtpClient.Timeout = 8000;
_smtpClient.Send(message);
log.EmailStatus = EmailStatusEnum.Succes;
error = false;
}
catch(SmtpException ex)
{
log.EmailStatus = EmailStatusEnum.Error;
log.ServerMessage = ex.Message;
log.ServerCode = ex.StatusCode.ToString();
error = true;
}
catch(Exception ex)
{
log.EmailStatus = EmailStatusEnum.Error;
log.ServerMessage = ex.Message;
error = true;
}
finally
{
log.Save();
uow.CommitChanges();
}
}
}
message.Dispose();
}
Echange log :
http://pastebin.com/UUiNyVx8

Related

C# - polling a device by TCP/IP

I tried to poll the device using the Modbus protocol for TCP/IP, and it works well, but there are problems.
If I run this code on a weak computer, the response time will increase and very much...
The difference in polling speed is about 6 seconds.
For example - I send a request on my computer 01 03 04 50 00 01 85 2B and received a response in 0.057 seconds, and on a weaker computer this request is received in 0.560 seconds. The answer is the same 01 03 02 02 C1 78 B4. The device is the same and connected in the same way.
public override void Run()
{
IsRunning = true;
OnJobStarted?.Invoke(this);
OnLogMessage?.Invoke(this, "JOB START");
try
{
while (Job.ThreadState == ThreadState.Running && !isJobTerminated)
{
var ts = DateTime.Now;
if (!Ping())
{
}
var es = DateTime.Now;
var ms = (es - ts).TotalMilliseconds;
while (!isJobTerminated && (DateTime.Now - ts).TotalMilliseconds <= this.PingInterval * 1000)
Thread.Sleep(10);
}
}
catch (Exception ex)
{
OnLogMessage?.Invoke(this, " RUN: " + ex.Message);
}
OnLogMessage?.Invoke(this, "JOB END");
OnJobEnded?.Invoke(this);
IsRunning = false;
}
.
public override bool Ping()
{
var result = false;
try
{
PingStat.LastPingDateTime = DateTime.Now;
PingStat.PingInterval = this.PingInterval;
result = true;
PingStat.TotalPingCount++;
if (!result)
PingStat.ErrorCount++;
if (result)
{
foreach (var md in Children.Where(m => !m.IsSuspended && m.IsEnabled))
{
var pingResult = ReadConfiguration(md).ErrorCode == 0;
Thread.Sleep(10);
if (pingResult)
ReadState(md);
if (pingResult && md.IsMaskChanged)
{
var maskResult = WriteSingleRegister(md, 0x05FC, md.Mask);
md.IsMaskChanged = !(maskResult.ErrorCode == 0);
}
md.PingStat.IsLastPingOk = pingResult;
md.OnPing?.Invoke(md, pingResult);
}
}
}
catch (Exception ex)
{
OnLogMessage?.Invoke(this, ex.Message + Environment.NewLine + ex.StackTrace);
result = false;
}
finally
{
PingStat.IsLastPingOk = result;
OnPing?.Invoke(this, result);
}
return result;
}
.
public override RcResult ExecuteModBus(RcModBusDevice device, byte[] request, out byte[] answer)
{
answer = null;
var result = new RcResult();
var dt = DateTime.Now;
Random rnd = new Random();
try
{
OnLogMessage?.Invoke(this, "ExecuteModBus Lock?");
lock (communication)
{
OnLogMessage?.Invoke(this, "ExecuteModBus Lock!");
using (var tcpClient = new TcpClient())
{
tcpClient.Connect(IP, Port);
tcpClient.SendTimeout = SendTimeout;
tcpClient.ReceiveTimeout = Math.Max(100, ReceiveTimeout);
using (var stream = tcpClient.GetStream())
{
dt = DateTime.Now;
OnLogMessage?.Invoke(this, "REQUEST->:" + Utils.BytesToHex(request));
stream.Write(request, 0, request.Length);
var tmp = new byte[0xA0];
int dataLength = 0;
try
{
for (dataLength = 0; dataLength < tmp.Length; dataLength++)
{
tmp[dataLength] = (byte)(stream.ReadByte());
tcpClient.ReceiveTimeout = 100 - Properties.Settings.Default.coefIP;
Thread.Sleep(0);
}
}
catch (Exception ex)
{
}
if (dataLength < 2)
result.ErrorCode = 1;
else
{
var crc = Utils.GetCRC(tmp, 0, dataLength - 2);
if (crc[0] != tmp[dataLength - 2] || crc[1] != tmp[dataLength - 1])
{
result.ErrorCode = 1;
result.ErrorText = "Bad CRC";
}
}
answer = new byte[dataLength];
Array.Copy(tmp, 0, answer, 0, dataLength);
}
OnLogMessage?.Invoke(this, "ANSWER<-:" + Utils.BytesToHex(answer));
if (device != null)
SaveToLog(DbID, device.DbID, dt, Utils.BytesToHex(request), DateTime.Now, Utils.BytesToHex(answer));
}
}
OnLogMessage?.Invoke(this, "ExecuteModBus UnLock");
}
catch (Exception ex)
{
SaveToLog(DbID, device.DbID, dt, Utils.BytesToHex(request), DateTime.Now, "ERROR", ex.Message);
OnLogMessage?.Invoke(this, ex.Message + Environment.NewLine + ex.StackTrace);
result = new RcResult() { ErrorCode = 1, ErrorText = ex.Message };
}
return result;
}

Slowness in LAZY<T> Enumeration

ic = new ImapClient("imap.yandex.com", Email, email.Password, AuthMethods.Login, 993, true);
var mailMessage = ic.SearchMessages(SearchCondition.From("somemail#gmail.com"), false, true).ToList();
if (mailMessage.Count > 0)
{
foreach (Lazy<AE.Net.Mail.MailMessage> Lmail in mailMessage)
{
AE.Net.Mail.MailMessage mail = Lmail.Value;
//SendSmtpMail(mail.Subject, ReplyData, Email, Password, mail.From,mail.MessageID);
if (mail != null)
{
if (mail.To.FirstOrDefault(x => x.Equals(email.EmailName)) != null)
{
if (mail.Body.IndexOf("Attachment Name:", StringComparison.OrdinalIgnoreCase) > -1)
{
Code= Between(mail.Body, "to:", "\r");
}
else
{
_msg.Add("CODE NOT FOUND..." + Environment.NewLine);
}
}
}
}
}
I'm using AE Mail plugin from nuget. Problem is, the following line:
AE.Net.Mail.MailMessage mail = Lmail.Value;
took almost 1 second for lazy enumeration. This is so bothering when parsing lots of mails. Any suggestions?

Reading Multiple Outlook Email for multiple IDs in C#

Referring to the answer mentioned in the post:
Reading Outlook Mail with C#
This code works well for a single account, but the issue with the current code is that it reads the email of the default id which was set as the first one in the outlook app.
For example, if "abcxyz#outlook.com" is set as the first account and "decxyz#outlook.com" is set as the second one, then it reads the inbox of only the first id, i.e., "abcxyz#outlook.com". I tried doing some modifications in the code but it did not work. Below is my code:
public static void OutLookMailStart(string EmailID, string password)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(EmailID, password, false, true);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
foreach (Object mail in inboxFolder.Items)
{
if ((mail as MailItem) != null && (mail as MailItem).UnRead == true)
{
// Email Subject
string Subject = (mail as MailItem).Subject.ToString();
if (Subject.Contains(FileDomain))
{
// Email Body
var ReplyText = ExtractReply(((mail as MailItem).Body.ToString()), FromTrimName);
}
// (mail as MailItem).UnRead = false;
(mail as MailItem).Save();
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ns.Logoff();
inboxFolder = null;
subFolder = null;
mailItem = null;
app = null;
}}
Any sort of help will be appreciated.
public static void OutLookMailStart(string EmailID, string password)
{
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(EmailID, password, true, true);
inboxFolder = ns.Folders[EmailID].Folders[2];
foreach (Microsoft.Office.Interop.Outlook.MailItem mailItemm in inboxFolder.Items)
{
if (mailItemm.UnRead) // I only process the mail if unread
{
// Email Subject
Console.WriteLine("Subject : {0}", mailItemm.Subject);
string Subject = mailItemm.Subject;
if (!string.IsNullOrEmpty(Subject) && !string.IsNullOrWhiteSpace(Subject))
{
if (Subject.Contains(FileDomain))
{
var SenderName = mailItemm.Sender.Name;
//Email Body
Console.WriteLine("Accounts: {0}", mailItemm.Body);
// Read All Attachements
var attachments = (mailItemm as MailItem).Attachments;
if (attachments != null && attachments.Count > 0)
{
for (int i = 1; i <= attachments.Count; i++)
{
attachments[i].SaveAsFile(tempFolderPath + (mailItemm as MailItem).Attachments[i].FileName);
}
}
}
}
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ns.Logoff();
inboxFolder = null;
subFolder = null;
mailItem = null;
app = null;
}
}
Using ExchangeService service
public static void Cloud_OutLookMailStart(string EmailID, string password, string StoreFilePath)
{
try
{
LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->");
DistributionReplyEntity ObjDistributionReplyEntity = new DistributionReplyEntity();
ObjDistributionReplyEntity.OutLookEmailID = EmailID;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials(EmailID, password);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
//service.Url = new Uri("https://IP/EWS/Exchange.asmx");
service.AutodiscoverUrl(EmailID, RedirectionUrlValidationCallback);
Microsoft.Exchange.WebServices.Data.Folder inbox = Microsoft.Exchange.WebServices.Data.Folder.Bind(service, WellKnownFolderName.Inbox);
var items = service.FindItems(
//Find Mails from Inbox of the given Mailbox
new FolderId(WellKnownFolderName.Inbox, new Mailbox(EmailID)),
//Filter criterion
// new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] {
// new SearchFilter.ContainsSubstring(ItemSchema.Subject, ConfigurationManager.AppSettings["ValidEmailIdentifier"].ToString()),
new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
// }),
//View Size as 15
new ItemView(50));
Console.WriteLine("Email {0}, unread Total Count{1}", EmailID, items.Count());
foreach (Item item in items)
{
EmailMessage email = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId.ToString()));
if (!string.IsNullOrEmpty(email.Subject) && !string.IsNullOrWhiteSpace(email.Subject))
{
var subject = email.Subject.ToString();
String[] arr = subject.Split(' ');
String firstWord = arr[0];
if (firstWord != "Undeliverable:")
{
//PROCESS EMAIL MESSAGE
Console.WriteLine("Subject :{0}", email.Subject);
// TO
if (email.ToRecipients.Count > 0)
{
var propertySet = new PropertySet(ItemSchema.UniqueBody);
EmailMessage email2 = EmailMessage.Bind(service, email.Id, propertySet);
EmailMessage str = (EmailMessage)email2;
string str1 = str.UniqueBody.Text.ToString();
var EmailBody = ExtractReply(str1, "");
// string ReceiverEmail = email.ReceivedBy != null?email.ReceivedBy.Address:"" ;
// Email Body
// var subjectEmail = ExtractReply(email.Body.ToString(), email.ReceivedBy.Address);
Console.WriteLine("Body {0}", EmailBody.ToString()); // Body
ObjDistributionReplyEntity.EmailBody = EmailBody;
string maltipleTo = string.Empty;
foreach (var toemailid in email.ToRecipients)
{
if (string.IsNullOrEmpty(maltipleTo))
{
maltipleTo = toemailid.Address.ToString();
}
else
{
maltipleTo += ";" + toemailid.Address.ToString();
}
}
Console.WriteLine("TO {0}", maltipleTo.ToString()); // TO
ObjDistributionReplyEntity.ReplyTO = maltipleTo.ToString();
}
// CC
if (email.CcRecipients.Count > 0)
{
string maltipleCC = string.Empty;
foreach (var ccemailid in email.CcRecipients)
{
if (string.IsNullOrEmpty(maltipleCC))
{
maltipleCC = ccemailid.Address.ToString();
}
else
{
maltipleCC += ";" + ccemailid.Address.ToString();
}
}
Console.WriteLine("CC {0}", maltipleCC.ToString());
ObjDistributionReplyEntity.ReplyCC = maltipleCC.ToString();
}
// Form
if (email.Sender.Address != "")
{
ObjDistributionReplyEntity.ReplyForm = email.Sender.Address;
}
Console.WriteLine("Subject {0}", email.Subject.ToString()); // Subject
ObjDistributionReplyEntity.Subject = email.Subject.ToString();
ObjDistributionReplyEntity.TransactionsID = 0;
ObjDistributionReplyEntity.IsProjectRelated = 0;
string Subject = email.Subject;
ObjDistributionReplyEntity.ReceivedTime = email.DateTimeReceived;
var getSharePointFileUrl = GetAttachmentsFromEmail(service, item.Id, StoreFilePath, ObjDistributionReplyEntity.TransactionsID);
email.IsRead = true;
email.Update(ConflictResolutionMode.AlwaysOverwrite);
}
}
}
LogHelper.LogMessage("<----- Cloud_OutLookMailStart Start ----->");
}
catch (Exception ex)
{
LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception");
LogHelper.LogError("Exception Message :" + ex.Message);
if (ex.InnerException != null)
{
LogHelper.LogError("Exception InnerException :" + ex.InnerException);
}
LogHelper.LogError("Exception StackTrace :" + ex.StackTrace);
LogHelper.LogError("OutLookMailStart -> Cloud_OutLookMailStart Exception");
}
}
public static string GetAttachmentsFromEmail(ExchangeService service, ItemId itemId, string StoreFilePath, Int64 TransactionsID)
{
try
{
LogHelper.LogMessage("<----- GetAttachmentsFromEmail Start ----->");
// Bind to an existing message item and retrieve the attachments collection.
// This method results in an GetItem call to EWS.
EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));
List<ResponseMessage> ObjResponseMessage = new List<ResponseMessage>();
// Iterate through the attachments collection and load each attachment.
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
// Load the attachment into a file.
// This call results in a GetAttachment call to EWS.
fileAttachment.Load(StoreFilePath + fileAttachment.Name);
string FileName = fileAttachment.Name;
LogHelper.LogMessage("OutLookMailStart In attachments File Name :" + FileName );
Console.WriteLine("File attachment name: " + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
ItemAttachment itemAttachment = attachment as ItemAttachment;
// Load attachment into memory and write out the subject.
// This does not save the file like it does with a file attachment.
// This call results in a GetAttachment call to EWS.
itemAttachment.Load();
Console.WriteLine("Item attachment name: " + itemAttachment.Name);
}
}
}
catch (Exception ex)
{
LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception");
LogHelper.LogError("Exception Message :" + ex.Message);
if (ex.InnerException != null)
{
LogHelper.LogError("Exception InnerException :" + ex.InnerException);
}
LogHelper.LogError("Exception StackTrace :" + ex.StackTrace);
LogHelper.LogError("OutLookMailStart -> GetAttachmentsFromEmail Exception"); ;
}
LogHelper.LogMessage("<----- GetAttachmentsFromEmail End ----->");
}

Lumisoft.net IMAP server can't add attachments to messages

I'm trying to set up an IMAP server which is pulling data from a SQL database.
I've got the messages working no problems, but I can't work out how to attach attachments to them.
The attachments object on the Mail_Message object also only has a getter and a method called GetAttachments() which doesn't seem to connect to anywhere.
My current code is:
//this is my own object I'm using to pull data from the database
var cmMsg = _ml.GetMessage(mId, session.AuthenticatedUserIdentity.Name, -1);
var msgBody = new MIME_b_Text(MIME_MediaTypes.Text.html);
var msg = new Mail_Message();
msg.Body = msgBody;
msg.To = new Mail_t_AddressList();
msg.From = new Mail_t_MailboxList {new Mail_t_Mailbox(cmMsg.From, cmMsg.FromEmail)};
msg.Cc = new Mail_t_AddressList();
msg.Bcc = new Mail_t_AddressList();
foreach (var recipient in cmMsg.Recipients)
{
if (recipient.isTo)
{
msg.To.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if(recipient.isCC)
{
msg.Cc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if (recipient.isBCC)
{
msg.Bcc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
}
//I tried adding a setter to the attachment object, but just get errors with this code
var a = new List<MIME_Entity>();
foreach (var attachment in cmMsg.Attachments)
{
var aCT = new MIME_b_Multipart(new MIME_h_ContentType("application/octet-stream"));
a.Add(new MIME_Entity
{
Body = aCT,
ContentDisposition = new MIME_h_ContentDisposition("attachment"),
});
}
msg.Attachments = a.ToArray();
msg.Subject = cmMsg.Subject;
msg.Date = cmMsg.TimeDate;
msg.MessageID = cmMsg.InternetMessageId;
if (e.FetchDataType == IMAP_Fetch_DataType.MessageStructure)
{
}
else if(e.FetchDataType == IMAP_Fetch_DataType.MessageHeader)
{
}
else
{
msgBody.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, cmMsg.HtmlBody);
_da.MarkAsRead(archiveID, session.AuthenticatedUserIdentity.Name);
}
e.AddData(info, msg);
I'm not sure if I'm missing something or just got this set up wrong. I noticed there was a MySQL API in the example projects, but that didn't have anything to do with attachments in it either.
Ok so turns out I was going about it the complete wrong way. Below is the code required
Effectively, it requires setting the message to be multipart mixes instead of just text. You can then add the attachments as a body part.
var cmMsg = _ml.GetMessage(mId, session.AuthenticatedUserIdentity.Name, -1);
MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
var msg = new Mail_Message();
msg.To = new Mail_t_AddressList();
msg.From = new Mail_t_MailboxList {new Mail_t_Mailbox(cmMsg.From, cmMsg.FromEmail)};
msg.Cc = new Mail_t_AddressList();
msg.Bcc = new Mail_t_AddressList();
msg.Body = multipartMixed;
foreach (var recipient in cmMsg.Recipients)
{
if (recipient.isTo)
{
msg.To.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if(recipient.isCC)
{
msg.Cc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
else if (recipient.isBCC)
{
msg.Bcc.Add(new Mail_t_Mailbox(recipient.FullName, recipient.SMTPAddress));
}
}
msg.Subject = cmMsg.Subject;
msg.Date = cmMsg.TimeDate;
msg.MessageID = cmMsg.InternetMessageId;
msg.MimeVersion = "1.0";
msg.Header.Add(new MIME_h_Unstructured("X-MS-Has-Attach", "yes"));
if (e.FetchDataType == IMAP_Fetch_DataType.MessageStructure)
{
}
else if(e.FetchDataType == IMAP_Fetch_DataType.MessageHeader)
{
}
else
{
MIME_Entity entity_text_plain = new MIME_Entity();
MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
entity_text_plain.Body = text_plain;
text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, cmMsg.HtmlBody);
multipartMixed.BodyParts.Add(entity_text_plain);
foreach (var attachment in cmMsg.Attachments)
{
using (var fs = new FileStream(#"C:\test.txt", FileMode.Open))
{
multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(fs, "test.txt"));
}
}
}
e.AddData(info, msg);

Parallel.Foreach do not finish stream

For load testing purposes I need to simulate multiple users trying to login to a system at the same time. I have code written by another developer that can send a login request to the system. With an ok login it will also return other information in xml.
I've tried using Parallel.ForEach, but dont have any real experience with parallel programming:
Parallel.ForEach(clientList, client =>
{
RunTest(client);
});
public void RunTest(object data)
{
if (!(data is IGprsClient))
{
return;
}
_noRunningTests += 1;
IGprsClient gprsClient = data as IGprsClient;
DateTime startTime = DateTime.Now;
Log(gprsClient.Id, "Test started.");
bool result = gprsClient.StartTest(20000);
DateTime endTime = DateTime.Now;
TimeSpan diff = endTime - startTime;
if (result == false)
{
Log(gprsClient.Id, "Test failed.");
}
Log(gprsClient.Id, "Test took {0}ms. ", (int)diff.TotalMilliseconds);
_noRunningTests -= 1;
}
override public bool StartTest(int timeout)
{
_testStarted = true;
try
{
LogDebug("Trying to connect.");
_client = new TcpClient(ipAddress, port);
LogDebug("Connected.");
bool result = false;
//Todo: insert testcase into client
switch (TestCaseName)
{
case "LoginTEST":
var testCase = new LoginTEST(this);
result = testCase.Execute(user, pwd, phoneNum);
break;
default:
Log("Unknown test case: " + TestCaseName);
break;
}
_client.Close();
return result;
}
catch (Exception ex)
{
if (_client != null)
_client.Close();
Log(ex.Message);
return false;
}
}
Which in turn will send the request and read the response.
public bool Execute(string user, string pwd, string phoneNum)
{
SendDataListRequest(userId);
string requiredDataResponse = Client.ReadMsg();
return true;
}
Run test will send a request and reads the message like so:
public string ReadMsg()
{
int msgLength = -1;
var stream = _client.GetStream();
while (_testStarted)
{
int b = stream.ReadByte();
if (b == -1)
{
return "";
}
else if (b == 0x02 || msgLength == -1)
{
while (b != 0x02 && _testStarted)
{
b = stream.ReadByte(); // Finds the start token
if (b == -1)
{
return "";
}
}
msgLength = 0; // Starts collecting data
}
else if (b == 0x03)
{
byte[] encryptedMsg = Convert.FromBase64String(
Encoding.UTF8.GetString(byteBuffer, 0, msgLength));
byte[] decryptedMsg = SttCipher.DecryptMessage(encryptedMsg);
MemoryStream ms = new MemoryStream(decryptedMsg);
GZipStream gZipStream = new GZipStream(ms, CompressionMode.Decompress, true);
var bufLen = ReadAllBytesFromStream(gZipStream, decompressedBuffer);
gZipStream.Close();
string completeMsg = Encoding.UTF8.GetString(decompressedBuffer, 0, bufLen);
if (completeMsg.Length < 500)
LogDebug("Received XML-data:\n{0}", completeMsg);
else
LogDebug("Received XML-data: {0} bytes\n{1}...", completeMsg.Length, completeMsg.Substring(0, 500));
return completeMsg;
}
else
{
if (byteBuffer.Length <= msgLength)
{
throw new Exception("XML message too long!");
}
byteBuffer[msgLength] = (byte)b;
msgLength++;
}
}
return "";
}
Running one client is fine and will wait for the response. The issue is with several clients, the responses gets cut off. Leaving me with unclosed xml in the response.But I cant't figure out why. Does anyone have a reasonable explanation and/or a solution or a better way of doing it?

Categories