TLSharp exception during reading messages from chat - c#

I use the following code for reading new messages from Telegram chat:
public async Task GatherChatHistory(string channelName, string ch_id, string mid, int offset = 0, int minId = 0, int maxId = -1, int limit = 100)
{
Log.Info(Tag, "In GatherChatHistory Start");
TelegramClient client = CreateClient();
await InitializeAndAuthenticateClient(client);
int maximal = Convert.ToInt32(mid);
Log.Info(Tag, "In GatherChatHistory Before GetUserDialogAsync");
try
{
var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
var chat = dialogs.chats.lists
.OfType<TLChat>()
.FirstOrDefault(c => c.title == channelName);
Log.Info(Tag, "In GatherChatHistory After GetUserDialogAsync " + (chat != null));
if (chat != null)
{
Log.Info(Tag, "Chat != null, " + channelName);
try
{
var tlAbsMessages =
await client.GetHistoryAsync(
new TLInputPeerChat { chat_id = chat.id }, offset,
minId, maxId, limit);
Log.Info(Tag, "After GetHistoryAsync");
var tlChannelMessages = (TLMessages)tlAbsMessages;
Log.Info(Tag, "GatherChatHistory Messages count = " + (tlChannelMessages.messages.lists.Count - 1));
for (var index = 0; index < tlChannelMessages.messages.lists.Count - 1; index++)
{
var tlAbsMessage = tlChannelMessages.messages.lists[index];
Log.Info(Tag, "Message Type = " + tlAbsMessage.GetType());
if (tlAbsMessage.GetType().ToString().Equals("TeleSharp.TL.TLMessageService"))
continue;
var message = (TLMessage)tlAbsMessage;
if (message.id == maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " maximal was reached");
break;
}
if (message.id <= maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " message.id = " + message.id + " maxid = " + maximal);
continue;
}
if (message.media == null)
{
Log.Info(Tag, "Message ID = " + message.id);
Log.Info(Tag, "Chat ID = " + chat.id);
Log.Info(Tag, "Content = " + message.message);
await AddNewMessageToDatabase(channelName, ch_id, message.message, null, message.from_id.GetValueOrDefault(), message.id);
}
else
{
switch (message.media.GetType().ToString())
{
case "TeleSharp.TL.TLMessageMediaPhoto":
var tLMessageMediaPhoto = (TLMessageMediaPhoto)message.media;
var photo = (TLPhoto)tLMessageMediaPhoto.photo;
var photoSize = photo.sizes.lists.OfType<TLPhotoSize>().Last();
TLFileLocation tf = (TLFileLocation)photoSize.location;
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
using (var ms = new MemoryStream(resFile.bytes))
{
byte[] byteArr = ms.ToArray();
string base64image = Convert.ToBase64String(byteArr);
Log.Info(Tag, "Caption = " + tLMessageMediaPhoto.caption);
Log.Info(Tag, "Base64 Image = " + base64image);
await AddNewMessageToDatabase(channelName, ch_id, tLMessageMediaPhoto.caption, base64image, message.from_id.GetValueOrDefault(), message.id);
}
break;
case "TeleSharp.TL.TLMessageMediaDocument":
var tLMessageMediaDocument = (TLMessageMediaDocument)message.media;
break;
case "TeleSharp.TL.TLMessageMediaWebPage":
var tLMessageMediaWebPage = (TLMessageMediaWebPage)message.media;
string url = string.Empty;
if (tLMessageMediaWebPage.webpage.GetType().ToString() != "TeleSharp.TL.TLWebPageEmpty")
{
var webPage = (TLWebPage)tLMessageMediaWebPage.webpage;
url = webPage.url;
}
break;
}
}
}
}
catch (Exception e)
{
Logger.Error("Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History StackTrace = " + e.ToString());
}
}
else
Log.Info(Tag, "Chat == null");
}
catch (Exception e)
{
Log.Error(Tag, "ReadUserAsync Error : " + e.Message);
}
}
I check chat for new messages one time per minute. I don't have any problems with text messages, all of them I read without any problem. Also I can read one photo, but only one per time. If in chat there are more than one photo or photo and text messages after reading photo TLSharp throws exception:
[MessagingService:TelegramBridge] Telegram Chat History exception: msg_seqno
too low (the server has already received a message with a lower msg_id but
with either a higher or an equal and odd seqno)
[MessagingService:TelegramBridge] Telegram Chat History StackTrace =
System.InvalidOperationException: msg_seqno too low (the server has already
received a message with a lower msg_id but with either a higher or an equal
and odd seqno)
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.HandleBadMsgNotification (System.UInt64
messageId, System.Int32 sequence, System.IO.BinaryReader messageReader)
[0x0009f] in <24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.processMessage (System.UInt64 messageId,
System.Int32 sequence, System.IO.BinaryReader messageReader,
TeleSharp.TL.TLMethod request) [0x00182] in
<24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at TLSharp.Core.Network.MtProtoSender+
<Receive>d__9.MoveNext () [0x000bb] in <24dee86ac15149c89ccf3cac229b439d>:0
Can anybody help me with this problem?
UPD
I localize the place of the error:
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
but I still don't know what to do...
UPD
This is main function:
async Task<int> WriteMessagesFromChannels()
{
Log.Info(Tag, "In WriteMessagesFromChannels");
var url = "http://" + MainActivity.Host + ":" + MainActivity.Port + MainActivity.Url + "/groups?page=1&pageSize=10000";
Log.Info(Tag, "URL = " + url);
var json = FetchServerData(url);
if (json == null)
{
Log.Info(Tag, "In WriteMessagesFromChannels: JSON = NULL");
return -1;
}
var obj = JObject.Parse(json);
var groups = JsonConvert.DeserializeObject<TelegramChannel[]>(obj["data"]["items"].ToString());
Log.Info(Tag, "In WriteMessagesFromChannels: size = " + groups.Length);
if (groups != null)
{
foreach (var gr in groups)
{
Log.Info(Tag, "Group name = " + gr.name + ", monitor = " + gr.monitor);
if (gr.ischannel == true || gr.monitor == false)
continue;
string maxid = ReadMaxId(gr.id);
if (maxid == "")
continue;
Log.Info(Tag, "In WriteMessagesFromChannels: MAXID = " + maxid);
await ReadMessagesFromChat(gr.name, gr.id, maxid);
Thread.Sleep(3000);
}
Log.Info(Tag, "In WriteMesasagesFromChannels: CYCLE IS FINISHED");
}
else
{
Log.Info(Tag, "In WriteMessagesFromChannels: GROUPS = NULL");
}
return 1;
}
async Task<int> ReadMessagesFromChat(string name, string ch_id, string maxid)
{
Log.Info(Tag, "In ReadMessagesFromChat");
//await bridge.GetPhotoFromChannel(name);
await bridge.GatherChatHistory(name, ch_id, maxid);
return 1;
}

Related

How can you prevent UI in C# WPF from hanging?

I have a C# script that connects to remote server and display all members of a local group. The script is running but it hangs upon searching/connecting to the server.
I have the following required fields in the WPF:
ServerList (combobox)
UserAccess (textbox multiline)
DataGridResult (DataGrid for output)
Here's my async/await script, but still hangs:
private async void ButtonRun_Click(object sender, EventArgs e)
{
if (UserAccess.SelectedItem == null)
{
MessageBox.Show("What Access are we going to display?");
return;
}
string[] separate = new string[] { "\r\n" };
string[] strServers = ServerList.Text.Split(separate, StringSplitOptions.RemoveEmptyEntries);
if (strServers == null || ServerList.Text == "")
{
MessageBox.Show("There are no Servers Defined!");
return;
}
int strServersCount = ServerList.LineCount;
DataTable temptable = new DataTable();
temptable.Columns.Add("Server");
temptable.Columns.Add("Comments");
ButtonRun.IsEnabled = false;
await Task.Run(() =>
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
for (var i = 0; i <= strServersCount - 1; i++)
{
try
{
DirectoryEntry directoryServers = new DirectoryEntry("WinNT://" + strServers[i] + ",computer");
DirectoryEntry directoryGroup = directoryServers.Children.Find(UserAccess.Text + ",group");
object members = directoryGroup.Invoke("members", null);
foreach (object GroupMember in (IEnumerable)members)
{
DirectoryEntry directoryMember = new DirectoryEntry(GroupMember);
Console.WriteLine(directoryMember.Name + " | " + directoryMember.Path);
temptable.Rows.Add(strServers[i], directoryMember.Name + " | " + directoryMember.Path);
}
}
catch (Exception ex)
{
temptable.Rows.Add(strServers[i], "Error: " + ex.InnerException + " | " + ex.Message);
}
DataGridResult.ItemsSource = temptable.DefaultView;
ButtonRun.IsEnabled = true;
}
}));
});
}
An attempt to fix this, untested:
string userAccessText = UserAccess.Text;
await Task.Run(() =>
{
//this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
// {
for (var i = 0; i <= strServersCount - 1; i++)
{
try
{
DirectoryEntry directoryServers = new DirectoryEntry("WinNT://" + strServers[i] + ",computer");
DirectoryEntry directoryGroup = directoryServers.Children.Find(userAccessText + ",group");
object members = directoryGroup.Invoke("members", null);
foreach (object GroupMember in (IEnumerable)members)
{
DirectoryEntry directoryMember = new DirectoryEntry(GroupMember);
Console.WriteLine(directoryMember.Name + " | " + directoryMember.Path);
temptable.Rows.Add(strServers[i], directoryMember.Name + " | " + directoryMember.Path);
}
}
catch (Exception ex)
{
temptable.Rows.Add(strServers[i], "Error: " + ex.InnerException + " | " + ex.Message);
}
// DataGridResult.ItemsSource = temptable.DefaultView;
// ButtonRun.IsEnabled = true;
}
// })); // End of Invoke
});
DataGridResult.ItemsSource = temptable.DefaultView;
ButtonRun.IsEnabled = true;
The basic idea is to put all the non-GUI stuff inside the Task, and then consume the data in the async OnClick method after awaiting that Task.

Failed to marshal the objective-c object

I am having a tough time with the following error:
Failed to marshal the Objective-C object 0x17109780 (type:
SMBSC_iOS_EddystoneManagerDelegate). Could not find an existing
managed instance for this object, nor was it possible to create a new
managed instance (because the type
'SMBSC.iOS.EddystoneManagerDelegate' does not have a constructor that
takes one IntPtr argument).
I have added the constructor it is looking for, but the application still crashes with this error.
I am working with the Kontakt Xamarin component.
I am creating a new scan with the following line:
manager = new KTKEddystoneManager(new EddystoneManagerDelegate() { ScanID = ID });
Here is the delegate that is causing the error:
public class EddystoneManagerDelegate : KTKEddystoneManagerDelegate
{
public static int closestRssi { get; set; }
public static string closestInstance { get; set; }
public int ScanID { get; set; }
public EddystoneManagerDelegate()
{
}
public EddystoneManagerDelegate(IntPtr handle) : base(handle)
{
}
public override void DidFailToStartDiscovery(KTKEddystoneManager manager, NSError error)
{
Console.WriteLine("Eddystone discovery failed with error: " + error.Description);
}
public override void DidUpdateEddystone(KTKEddystoneManager manager, KTKEddystone eddystone, KTKEddystoneFrameType frameType)
{
string bkpnt = "";
}
public override void DidDiscoverEddystones(KTKEddystoneManager manager, NSSet<KTKEddystone> eddystones, KTKEddystoneRegion region)
{
try
{
Console.WriteLine("");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
int i = 0;
foreach (SavedPoint p in App.discoveredBeaconList)
{
i += 1;
Console.WriteLine("Existing Beacon List: " + p.BeaconInstanceID + " - " + p.BeaconTruckDesc + " - " + p.RSSI);
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon Before Logic: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
}
else
{
Console.WriteLine("Selected Beacon Before Logic: no beacon selected");
}
App.singleOutputValue = "";
Console.WriteLine("Discovered " + eddystones.Count + " eddystones");
App.beaconTimer = DateTime.Now;
App.trackingBeaconTimer = DateTime.Now;
MessagingCenter.Send<App>(App.instance, "Output");
if (eddystones.Count == 1)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("First Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " First Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 2)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Second Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Second Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 3)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Third Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Third Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 4)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Fourth Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Fourth Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
App.closestBeaconForTracking = null;
foreach (var stone in eddystones)
{
KTKEddystone eddystone = (KTKEddystone)stone;
Console.WriteLine(eddystone.RSSI + ", " + eddystone.EddystoneUID.InstanceID);
App.outputValue += " " + eddystone.RSSI + ", " + ScanID + "; " + eddystone.EddystoneUID.InstanceID + Environment.NewLine;
App.instanceID = eddystone.EddystoneUID.InstanceID;
App.NameSpaceID = eddystone.EddystoneUID.NamespaceID;
App.rssi = eddystone.RSSI.Int32Value;
App.BeaconCount = (int)eddystones.Count;
App.lastBeaconTime = DateTime.Now.ToString();
if (App.isViewingBeacons)
{
MessagingCenter.Send<App>(App.instance, "StoneForBeaconList");
}
MapApp.Beacon beacon = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
if (beacon != null)
{
beacon.RSSI = eddystone.RSSI.Int32Value;
SavedPoint point = new SavedPoint() { BeaconID = beacon.BeaconID, BeaconInstanceID = beacon.instanceID, BeaconName = beacon.Name, BeaconNameSpaceID = beacon.namespaceID, RSSI = beacon.RSSI, BeaconTruckDesc = beacon.truckDesc };
point.LastSeenTime = DateTime.Now;
if (App.discoveredBeaconList == null)
{
App.discoveredBeaconList = new List<SavedPoint>();
}
if (!App.discoveredBeaconList.Exists(x => x.BeaconInstanceID == point.BeaconInstanceID) && beacon.RSSI != 0)
{
App.discoveredBeaconList.Add(point);
}
else
{
foreach (SavedPoint p in App.discoveredBeaconList)
{
if (p.BeaconInstanceID == point.BeaconInstanceID && beacon.RSSI != 0)
{
p.LastSeenTime = DateTime.Now;
p.RSSI = point.RSSI;
}
}
}
}
if (eddystone.RSSI.Int32Value != 0)
{
if (string.IsNullOrWhiteSpace(App.closestBeaconOutput))
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if (closestInstance == eddystone.EddystoneUID.InstanceID)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if ((int)eddystone.RSSI > closestRssi)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
//if(App.closestBeaconForTracking == null)
//{
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if(App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
//}
//if (App.closestBeaconForTracking != null)
//{
// if (App.closestBeaconForTracking.instanceID.ToLower() == eddystone.EddystoneUID.InstanceID && App.closestBeaconForTracking.namespaceID.ToLower() == eddystone.EddystoneUID.NamespaceID)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// if (eddystone.RSSI.Int32Value > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if (App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// }
//}
}
SavedPoint flipPoint = new SavedPoint();
//if(App.discoveredBeaconList.Count > 1)
//{
// try
// {
// if (App.discoveredBeaconList[0].BeaconInstanceID != App.closestBeaconForTracking.instanceID)
// {
// App.discoveredBeaconList.Insert(1, App.discoveredBeaconList[1]);
// App.discoveredBeaconList[0].BeaconInstanceID = App.closestBeaconForTracking.instanceID;
// App.discoveredBeaconList[0].BeaconNameSpaceID = App.closestBeaconForTracking.namespaceID;
// App.discoveredBeaconList[0].BeaconID = App.closestBeaconForTracking.BeaconID;
// App.discoveredBeaconList[0].RSSI = App.closestBeaconForTracking.RSSI;
// }
// }
// catch (Exception ex)
// {
// throw new Exception("Error in App.discoveredBeaconList.Count > 1");
// }
//}
//if(App.discoveredBeaconList.Count > 1)
//{
// if(App.discoveredBeaconList[0].RSSI > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking.instanceID = App.discoveredBeaconList[0].BeaconInstanceID;
// App.closestBeaconForTracking.namespaceID = App.discoveredBeaconList[0].BeaconNameSpaceID;
// App.closestBeaconForTracking.RSSI = App.discoveredBeaconList[0].RSSI;
// App.closestBeaconForTracking.truckDesc = App.discoveredBeaconList[0].BeaconTruckDesc;
// }
//}
App.singleOutputValue += eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI.Int32Value + "; ";
}
if (App.discoveredBeaconList.Count > 0)
{
SavedPoint topBeacon = App.discoveredBeaconList.OrderByDescending(c => c.RSSI).First();
MapApp.Beacon convertedBeacon = new MapApp.Beacon();
convertedBeacon.RSSI = topBeacon.RSSI;
convertedBeacon.Name = topBeacon.BeaconName;
convertedBeacon.namespaceID = topBeacon.BeaconNameSpaceID;
convertedBeacon.instanceID = topBeacon.BeaconInstanceID;
convertedBeacon.BeaconID = topBeacon.BeaconID;
convertedBeacon.truckDesc = topBeacon.BeaconTruckDesc;
App.closestBeaconForTracking = convertedBeacon;
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
MapApp.Beacon beacon = App.Database.GetBeaconByID(App.closestBeaconForTracking.instanceID, App.closestBeaconForTracking.namespaceID);
if(!string.IsNullOrWhiteSpace(beacon.truckDesc))
{
App.catchTruckDesc = beacon.truckDesc;
//Insights.Identify(App.catchTruckDesc);
}
}
else
{
Console.WriteLine("Selected Beacon: no beacon selected");
}
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("");
//if (App.closestBeaconForTracking != null && !string.IsNullOrWhiteSpace(App.closestBeaconForTracking.instanceID))
//{
// App.singleOutputValue = "Beacon found at: " + DateTime.Now + Environment.NewLine + App.closestBeaconForTracking.instanceID + " " + App.closestBeaconForTracking.RSSI;
//}
MessagingCenter.Send<App>(App.instance, "singleOutput");
MessagingCenter.Send<App>(App.instance, "UpdateStartText");
MessagingCenter.Send<App>(App.instance, "Output");
}
catch (Exception ex)
{
if (string.IsNullOrWhiteSpace(App.catchFieldDesc))
{
App.catchFieldDesc = "Null";
}
if (string.IsNullOrWhiteSpace(App.catchTruckDesc))
{
App.catchTruckDesc = "Null";
}
Insights.Report(ex, new Dictionary<string, string>() { { "DidDiscoverEddystone", ex.StackTrace }, { "Field Description", App.catchFieldDesc }, { "Truck Description", App.catchTruckDesc } }, Insights.Severity.Critical);
}
}
I have done some searching on the internet, but I have not found anything that would be relevant to my scenario. I'm sure there is an error with my code, but I do not fully understand this error.
I have read that this error can be caused by the Garbage Collector collecting the object.
What exactly does this error mean and what can I look at to attempt a fix?
Thanks!

Creating manual threads, also tried using parallel.foreach and async await - but getting duplicate [duplicate]

This question already has answers here:
Creating manual threads - but getting duplicate threads
(2 answers)
Closed 9 years ago.
ISSUE: Getting duplicate items, i.e more threads are getting created than the array size...
Hi Folks, I am creating thread in the loop for each element of array. The real use is that the of sending a batch of messages using amazon ses. the messages are stored in the messageamazonRequestBatch and the loop runs through the batch and sends the messages.
HERE IS THE CODE:
Thread thrdSendEmail;
try
{
string amazonMessageID = string.Empty;
List<Thread> lstThread = new List<Thread>();
foreach (int n in arrMessageid)
{
thrdSendEmail = new Thread(() =>
{
try
{
amazonMessageID = SendSimpleEmail_Part2(messageAmazonRequestBatch.ElementAt(n).req);
messageAmazonRequestBatch.ElementAt(n).msg.AmazonMessageID = amazonMessageID;
logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n , true);
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n + ",\t" + messageAmazonRequestBatch.ElementAt(n).msg.QueueMessageId + ",\t" + amazonMessageID, true);
}
catch (Exception ex) { logManager_RunSummary.LogMessage(ex.Message, true); }
});
thrdSendEmail.Name = n.ToString();
lstThread.Add(thrdSendEmail);
thrdSendEmail.Start();
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n, true);
}
foreach (Thread t in lstThread)
{
t.Join();
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + t.Name, true);
}
}
catch (Exception ex)
{
logManager_RunSummary.LogMessage(ex.Message, true);
}
I have also tried parallel.foreach and asynch and await options... they also give the duplicates. I know that the lock will solve the problem but in my case the lock degrades the performance by a factor of 10.. that is my performance drops 10 times... coz putting the sendemail login in lock is blocking untill i get a return amazonmessageid from amazon...
Any help on this will be greatly appreciated. I am not a novice programmer but new to threading...my contact email is shabbirbohra#gmail.com
ALSO TRIED MANY VERSION OF PARALLEL.foreach
private int SendEmailTask_Ver9_23Jan()//tried to create manual threads in parallel foreach and called SendSimpleEmail_Part3 but still duplicates
{
activeThreadCount++; threadCount++;
IList<Airmail.Core.Message> messageBatch = null;
lock (dbLocker)
{
if (activeThreadCount > maxNoofTaskCount)//targetThreadCount
{
return 0;
}
if (abort)
{
sendComplete = true;
return 0;
}
try
{
messageBatch = messageRepository.ash_GetNextBatch_AirmailVer2(maxBatchSize, this.senderTrackingHost);//messageBatch = messageRepository.ash_GetNextBatch(maxBatchSize);
}
catch (Exception ex)
{
logManager_RunSummary.LogException(ex);
messageBatch = new List<Airmail.Core.Message>();
}
Console.WriteLine(this.currentStatus);
}
while (messageBatch != null && messageBatch.Count != 0)
{
IDictionary<Airmail.Core.Message, MessageHistory> toUpdate = new Dictionary<Airmail.Core.Message, MessageHistory>();
batchSize = messageBatch.Count;
sendComplete = false;
//foreach (Airmail.Core.Message message in messageBatch)
logManager_CollectionLog.LogMessage("\tBatch\t-\t" + messageBatch.Count + "\t-\t" + System.Threading.Thread.CurrentThread.ManagedThreadId, true);//ASH-TEST 11Jan14
int intCounter = 0;//ash-teset 11han14
System.Collections.Concurrent.ConcurrentBag<Airmail.Core.Message> messageBatchConcurrent = new System.Collections.Concurrent.ConcurrentBag<Airmail.Core.Message>(messageBatch);
//All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads.
//foreach (Airmail.Core.Message message in messageBatchConcurrent)
Parallel.ForEach(messageBatchConcurrent, message =>
{
//messageBatchConcurrent.Where(x => x == message).Take(1);//ash12Jan14
lock (statLocker)
{
//messageBatchConcurrent.TryTake(out message);
totalProcessed++;
intCounter += 1;//ASH-TEST 10Jan14
message.ash_BatchLoopCounter = intCounter.ToString();
//message.ash_BatchSizeCount = messageBatchConcurrent.Count.ToString();
}
if (message.ExpiryDate < DateTime.UtcNow)
{
toUpdate.Add(message, message.UpdateStatus(MessageStatus.Expired, "", null, null, true));
//message.continue(); //continue;//continue will just skip the current iteration.
return; //using return instead of continue as --> (the body is just a function called for each item)
}
lock (statLocker)
{
StatisticKey key = new StatisticKey(Convert.ToInt32(message.ash_campaignHistoryID), Convert.ToInt32(message.ash_campaignTemplateID), message.Status);//ASH25,OCT13//Airmail 2.0 changes
if (!statistics.ContainsKey(key)) statistics.Add(key, 0);
statistics[key]--;
}
try
{
string amazonMessageID = string.Empty;
if (message.Attachments == null || message.Attachments == "")//ASH25,OCT13//Airmail 2.0 changes
{
//test//if (intCounter > 1000) { Debugger.Break(); }
SendEmailResponse response = null;
if (message.ash_isSent == "YES") { return; }
//if (message.ash_isSent == null) { response = SendSimpleEmail(ref message, message.QueueMessageId, message.ash_BatchLoopCounter + "-" + message.ash_BatchSizeCount, message.ash_isSent); }//ASH-TEST 11Jan14
/// Start - this is parallel.invoke testing on 23Jan14
try
{
//Parallel.Invoke(
// delegate() // Param #2 - in-line delegate
// {
//mReq.msg.AmazonMessageID = SendSimpleEmail_Part2((SendEmailRequest)mReq.req);
//logManager_MessageLog.LogMessage(",\t" + mReq.msg.QueueMessageId, true);
// }
//);
//intthreadCount++;
//logManager_MessageLog.LogMessage(",\t creating new thread", true);
Thread thrdSendEmail = new Thread(() =>
{
if (message.ash_isSent == null) { response = SendSimpleEmail_Part3(message, message.QueueMessageId, message.ash_BatchLoopCounter + "-" + message.ash_BatchSizeCount, message.ash_isSent); }
});
lock (statLocker)
{
thrdSendEmail.Start();
}
thrdSendEmail.Join();
//logManager_MessageLog.LogMessage(",\t finishing new thread", true);
}
// No exception is expected in this example, but if one is still thrown from a task,
// it will be wrapped in AggregateException and propagated to the main thread.
catch (AggregateException e)
{
Console.WriteLine("An action has thrown an exception. THIS WAS UNEXPECTED.\n{0}", e.InnerException.ToString());
}
/// End - this is parallel.invoke testing on 23Jan14
//SendRawEmailResponse response = SendRawEmail(message);
//cSH12Jan14-test//sqlLogSentMessage += "EXEC ash_Log_SentMessageids " + "#MessageID = " + message.QueueMessageId + ", " + "#Identifier = '" + message.Identifier.ToString() + "', " + "#AmazonMessageID = '" + message.AmazonMessageID + "', " + "#Status = " + ((int)message.Status).ToString() + ", " + "#ToEmailAddress = '" + message.To.Address + "', " + "#CreatedDate = '" + DateTime.UtcNow.ToString() + "'\n";
//logManager_MessageLog.LogMessage( ",\t" + message.ash_BatchLoopCounter + "-" + message.ash_BatchSizeCount + ",\t" + response.SendEmailResult.MessageId + ",\t" + message.QueueMessageId, true);//ASH-TEST 11Jan14
lock (statLocker)
{
if (response != null) amazonMessageID = response.SendEmailResult.MessageId;
if (message.ash_isSent == "DUPLICATE") { return; }
}
//logManager_CollectionLog.LogMessage("\tSendSimpleEmail\t-\t" + message.ash_BatchSizeCount + "-" + message.ash_BatchLoopCounter + "\t-\t" + message.QueueMessageId, true);//ASH-TEST 10Jan14
}
else
{
SendRawEmailResponse response = SendRawEmail(message);
lock (statLocker)
{
if (response != null) amazonMessageID = response.SendRawEmailResult.MessageId;
intCounter += 1;//ASH-TEST 10Jan14
logManager_MessageLog.LogMessage("\tSendRawEmail-1" + intCounter + "\t-\t" + amazonMessageID + "\t-\t" + message.QueueMessageId, true);//ASH-TEST 10Jan14
}
}
lock (statLocker)
{
message.AmazonMessageID = amazonMessageID;
toUpdate.Add(message, message.UpdateStatus(amazonMessageID == string.Empty ? MessageStatus.Tested : MessageStatus.Sent,
"", null, null, true));
messageCount++;
}
}
catch (Exception ex)
{
if (ex.Message.ToLower().Contains("blacklist")
|| ex.Message.ToLower().Contains("rejected")
|| ex.Message.ToLower().Contains("not verified")
|| ex.Message.ToLower().Contains("illegal")
//|| message.OldStatus == MessageStatus.Failed)
|| message.Status == MessageStatus.Failed)
{
toUpdate.Add(message, message.UpdateStatus(MessageStatus.Undeliverable, ex.Message, null, null, true));
}
else
{
toUpdate.Add(message, message.UpdateStatus(MessageStatus.Failed, ex.Message, null, null, true));
}
Console.WriteLine(ex.Message.ToLower());//ASH22Nov
}
lock (statLocker)
{
StatisticKey key = new StatisticKey(Convert.ToInt32(message.ash_campaignHistoryID), Convert.ToInt32(message.ash_campaignTemplateID), message.Status);//ASH25,OCT13//Airmail 2.0 changes
if (!statistics.ContainsKey(key)) statistics.Add(key, 0);
statistics[key]++;
}
});
lock (dbLocker)
{
//cSH12Jan14-test//messageRepository.ash_Log_SentMessageids(sqlLogSentMessage);//ASH12Jan14
try
{
Task UpdateMessages_Task = Task.Factory.StartNew(() => messageRepository.ash_UpdateMessages(toUpdate), TaskCreationOptions.AttachedToParent);
UpdateMessages_Task.Wait();//ASH18Sep2013 - This task added for updating message asynchronously
}
catch (Exception ex)
{
logManager_RunSummary.LogException(ex);
}
if (activeThreadCount > maxNoofTaskCount)//targetThreadCount
{
return 0;
}
if (abort)
{
sendComplete = true;
return 1;
}
try
{
if (messageBatch == null && messageBatch.Count == 0)
{
messageBatch = messageRepository.ash_GetNextBatch_AirmailVer2(maxBatchSize, this.senderTrackingHost);//messageBatch = messageRepository.ash_GetNextBatch(maxBatchSize);
}
else { messageBatch = null; }
}
catch (Exception ex)
{
logManager_RunSummary.LogException(ex);
messageBatch = new List<Airmail.Core.Message>();
}
Console.WriteLine(this.currentStatus);
}
}
return 1;
}
It's an "Access to modified closure" problem. Look into that for more details. There's a lot of examples of what it is.
Simple fix is to store your n variable in a temp variable everywhere you use it in your delegate.
foreach (int n in arrMessageid)
{
int tempN = n;
Thread thrdSendEmail = new Thread(() =>
{
try
{
amazonMessageID = SendSimpleEmail_Part2(messageAmazonRequestBatch.ElementAt(tempN ).req);
messageAmazonRequestBatch.ElementAt(tempN ).msg.AmazonMessageID = amazonMessageID;
logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + tempN , true);
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + tempN + ",\t" + messageAmazonRequestBatch.ElementAt(tempN ).msg.QueueMessageId + ",\t" + amazonMessageID, true);
}
catch (Exception ex) { logManager_RunSummary.LogMessage(ex.Message, true); }
});
thrdSendEmail.Name = n.ToString();
lstThread.Add(thrdSendEmail);
thrdSendEmail.Start();
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n, true);
}

Creating manual threads, also tried using parallel.foreach and async await - but getting duplicate [duplicate]

This question already has an answer here:
Creating manual threads, also tried using parallel.foreach and async await - but getting duplicate [duplicate]
(1 answer)
Closed 8 years ago.
ISSUE: Getting duplicate items, i.e more threads are getting created than the array size...
Hi Folks, I am creating thread in the loop for each element of array. The real use is that the of sending a batch of messages using amazon ses. the messages are stored in the messageamazonRequestBatch and the loop runs through the batch and sends the messages.
HERE IS THE CODE:
Thread thrdSendEmail;
try
{
string amazonMessageID = string.Empty;
List<Thread> lstThread = new List<Thread>();
foreach (int n in arrMessageid)
{
thrdSendEmail = new Thread(() =>
{
try
{
amazonMessageID = SendSimpleEmail_Part2(messageAmazonRequestBatch.ElementAt(n).req);
messageAmazonRequestBatch.ElementAt(n).msg.AmazonMessageID = amazonMessageID;
logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n , true);
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n + ",\t" + messageAmazonRequestBatch.ElementAt(n).msg.QueueMessageId + ",\t" + amazonMessageID, true);
}
catch (Exception ex) { logManager_RunSummary.LogMessage(ex.Message, true); }
});
thrdSendEmail.Name = n.ToString();
lstThread.Add(thrdSendEmail);
thrdSendEmail.Start();
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n, true);
}
foreach (Thread t in lstThread)
{
t.Join();
//logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + t.Name, true);
}
}
catch (Exception ex)
{
logManager_RunSummary.LogMessage(ex.Message, true);
}
I have also tried parallel.foreach and asynch and await options... they also give the duplicates. I know that the lock will solve the problem but in my case the lock degrades the performance by a factor of 10.. that is my performance drops 10 times... coz putting the sendemail login in lock is blocking untill i get a return amazonmessageid from amazon...
Any help on this will be greatly appreciated. I am not a novice programmer but new to threading.
ALSO TRIED MANY VERSION OF PARALLEL.foreach
private int SendEmailTask_Ver9_23Jan()//tried to create manual threads in parallel foreach and called SendSimpleEmail_Part3 but still duplicates
{
activeThreadCount++; threadCount++;
IList<Airmail.Core.Message> messageBatch = null;
lock (dbLocker)
{
if (activeThreadCount > maxNoofTaskCount)//targetThreadCount
{
return 0;
}
if (abort)
{
sendComplete = true;
return 0;
}
try
{
messageBatch = messageRepository.ash_GetNextBatch_AirmailVer2(maxBatchSize, this.senderTrackingHost);//messageBatch = messageRepository.ash_GetNextBatch(maxBatchSize);
}
catch (Exception ex)
{
logManager_RunSummary.LogException(ex);
messageBatch = new List<Airmail.Core.Message>();
}
Console.WriteLine(this.currentStatus);
}
while (messageBatch != null && messageBatch.Count != 0)
{
IDictionary<Airmail.Core.Message, MessageHistory> toUpdate = new Dictionary<Airmail.Core.Message, MessageHistory>();
batchSize = messageBatch.Count;
sendComplete = false;
//foreach (Airmail.Core.Message message in messageBatch)
logManager_CollectionLog.LogMessage("\tBatch\t-\t" + messageBatch.Count + "\t-\t" + System.Threading.Thread.CurrentThread.ManagedThreadId, true);//ASH-TEST 11Jan14
int intCounter = 0;//ash-teset 11han14
System.Collections.Concurrent.ConcurrentBag<Airmail.Core.Message> messageBatchConcurrent = new System.Collections.Concurrent.ConcurrentBag<Airmail.Core.Message>(messageBatch);
//All public and protected members of ConcurrentBag<T> are thread-safe and may be used concurrently from multiple threads.
//foreach (Airmail.Core.Message message in messageBatchConcurrent)
Parallel.ForEach(messageBatchConcurrent, message =>
{
//messageBatchConcurrent.Where(x => x == message).Take(1);//ash12Jan14
lock (statLocker)
{
//messageBatchConcurrent.TryTake(out message);
totalProcessed++;
intCounter += 1;//ASH-TEST 10Jan14
message.ash_BatchLoopCounter = intCounter.ToString();
//message.ash_BatchSizeCount = messageBatchConcurrent.Count.ToString();
}
if (message.ExpiryDate < DateTime.UtcNow)
{
toUpdate.Add(message, message.UpdateStatus(MessageStatus.Expired, "", null, null, true));
//message.continue(); //continue;//continue will just skip the current iteration.
return; //using return instead of continue as --> (the body is just a function called for each item)
}
lock (statLocker)
{
StatisticKey key = new StatisticKey(Convert.ToInt32(message.ash_campaignHistoryID), Convert.ToInt32(message.ash_campaignTemplateID), message.Status);//ASH25,OCT13//Airmail 2.0 changes
if (!statistics.ContainsKey(key)) statistics.Add(key, 0);
statistics[key]--;
}
try
{
string amazonMessageID = string.Empty;
if (message.Attachments == null || message.Attachments == "")//ASH25,OCT13//Airmail 2.0 changes
{
//test//if (intCounter > 1000) { Debugger.Break(); }
SendEmailResponse response = null;
if (message.ash_isSent == "YES") { return; }
//if (message.ash_isSent == null) { response = SendSimpleEmail(ref message, message.QueueMessageId, message.ash_BatchLoopCounter + "-" + message.ash_BatchSizeCount, message.ash_isSent); }//ASH-TEST 11Jan14
/// Start - this is parallel.invoke testing on 23Jan14
try
{
//Parallel.Invoke(
// delegate() // Param #2 - in-line delegate
// {
//mReq.msg.AmazonMessageID = SendSimpleEmail_Part2((SendEmailRequest)mReq.req);
//logManager_MessageLog.LogMessage(",\t" + mReq.msg.QueueMessageId, true);
// }
//);
//intthreadCount++;
//logManager_MessageLog.LogMessage(",\t creating new thread", true);
Thread thrdSendEmail = new Thread(() =>
{
if (message.ash_isSent == null) { response = SendSimpleEmail_Part3(message, message.QueueMessageId, message.ash_BatchLoopCounter + "-" + message.ash_BatchSizeCount, message.ash_isSent); }
});
lock (statLocker)
{
thrdSendEmail.Start();
}
thrdSendEmail.Join();
//logManager_MessageLog.LogMessage(",\t finishing new thread", true);
}
// No exception is expected in this example, but if one is still thrown from a task,
// it will be wrapped in AggregateException and propagated to the main thread.
catch (AggregateException e)
{
Console.WriteLine("An action has thrown an exception. THIS WAS UNEXPECTED.\n{0}", e.InnerException.ToString());
}
/// End - this is parallel.invoke testing on 23Jan14
//SendRawEmailResponse response = SendRawEmail(message);
//cSH12Jan14-test//sqlLogSentMessage += "EXEC ash_Log_SentMessageids " + "#MessageID = " + message.QueueMessageId + ", " + "#Identifier = '" + message.Identifier.ToString() + "', " + "#AmazonMessageID = '" + message.AmazonMessageID + "', " + "#Status = " + ((int)message.Status).ToString() + ", " + "#ToEmailAddress = '" + message.To.Address + "', " + "#CreatedDate = '" + DateTime.UtcNow.ToString() + "'\n";
//logManager_MessageLog.LogMessage( ",\t" + message.ash_BatchLoopCounter + "-" + message.ash_BatchSizeCount + ",\t" + response.SendEmailResult.MessageId + ",\t" + message.QueueMessageId, true);//ASH-TEST 11Jan14
lock (statLocker)
{
if (response != null) amazonMessageID = response.SendEmailResult.MessageId;
if (message.ash_isSent == "DUPLICATE") { return; }
}
//logManager_CollectionLog.LogMessage("\tSendSimpleEmail\t-\t" + message.ash_BatchSizeCount + "-" + message.ash_BatchLoopCounter + "\t-\t" + message.QueueMessageId, true);//ASH-TEST 10Jan14
}
else
{
SendRawEmailResponse response = SendRawEmail(message);
lock (statLocker)
{
if (response != null) amazonMessageID = response.SendRawEmailResult.MessageId;
intCounter += 1;//ASH-TEST 10Jan14
logManager_MessageLog.LogMessage("\tSendRawEmail-1" + intCounter + "\t-\t" + amazonMessageID + "\t-\t" + message.QueueMessageId, true);//ASH-TEST 10Jan14
}
}
lock (statLocker)
{
message.AmazonMessageID = amazonMessageID;
toUpdate.Add(message, message.UpdateStatus(amazonMessageID == string.Empty ? MessageStatus.Tested : MessageStatus.Sent,
"", null, null, true));
messageCount++;
}
}
catch (Exception ex)
{
if (ex.Message.ToLower().Contains("blacklist")
|| ex.Message.ToLower().Contains("rejected")
|| ex.Message.ToLower().Contains("not verified")
|| ex.Message.ToLower().Contains("illegal")
//|| message.OldStatus == MessageStatus.Failed)
|| message.Status == MessageStatus.Failed)
{
toUpdate.Add(message, message.UpdateStatus(MessageStatus.Undeliverable, ex.Message, null, null, true));
}
else
{
toUpdate.Add(message, message.UpdateStatus(MessageStatus.Failed, ex.Message, null, null, true));
}
Console.WriteLine(ex.Message.ToLower());//ASH22Nov
}
lock (statLocker)
{
StatisticKey key = new StatisticKey(Convert.ToInt32(message.ash_campaignHistoryID), Convert.ToInt32(message.ash_campaignTemplateID), message.Status);//ASH25,OCT13//Airmail 2.0 changes
if (!statistics.ContainsKey(key)) statistics.Add(key, 0);
statistics[key]++;
}
});
lock (dbLocker)
{
//cSH12Jan14-test//messageRepository.ash_Log_SentMessageids(sqlLogSentMessage);//ASH12Jan14
try
{
Task UpdateMessages_Task = Task.Factory.StartNew(() => messageRepository.ash_UpdateMessages(toUpdate), TaskCreationOptions.AttachedToParent);
UpdateMessages_Task.Wait();//ASH18Sep2013 - This task added for updating message asynchronously
}
catch (Exception ex)
{
logManager_RunSummary.LogException(ex);
}
if (activeThreadCount > maxNoofTaskCount)//targetThreadCount
{
return 0;
}
if (abort)
{
sendComplete = true;
return 1;
}
try
{
if (messageBatch == null && messageBatch.Count == 0)
{
messageBatch = messageRepository.ash_GetNextBatch_AirmailVer2(maxBatchSize, this.senderTrackingHost);//messageBatch = messageRepository.ash_GetNextBatch(maxBatchSize);
}
else { messageBatch = null; }
}
catch (Exception ex)
{
logManager_RunSummary.LogException(ex);
messageBatch = new List<Airmail.Core.Message>();
}
Console.WriteLine(this.currentStatus);
}
}
return 1;
}
You are probably having issue that happens when you combine loop constructs and lambda expressions. Read more about it here. Cleanest way to fix it is to create an object, that represents the thread set it's parameters and start it. Or you can just create local copies of all variables you are using as suggested in the previous link.

Site Monitoring Utility can't connect to website even though site is up and working

I have created a Site Monitoring Utility, that sends an HTTP and PING request to a site, checks the database to make sure it's up and ready to take requests, and checks a service that the website needs.
The problem is, the utility will randomly lose connection to the server for hours at a time, with no reason why.
I have run WireShark multiple times on the server to see if there is something network related, but I keep coming up with nothing. WireShark says no packets or anything is getting dropped.
Has anybody else ever run into anything like that?
I can't post the code for the service, as it contains sensitive information in it. I don't think it's my code, but I'm having a hard time figuring out what it could be!
Here is my Code:
private void HttpRequest()
{
foreach(string urlToTest in urls)
{
bool Success = false;
HttpWebResponse URLRes = null;
HttpWebRequest URLReq = null;
bool Timed = false;
StringBuilder Message = null;
HttpStatusCode code = HttpStatusCode.Unused;
string codeDescript = string.Empty;
for (int i = 0; i < HTTPThreshold; i++)
{
try
{
WriteToOwnEventLog("Sending HTTP Request to " + urlToTest, "Http Request", true);
URLReq = (HttpWebRequest) WebRequest.Create(urlToTest);
URLReq.Timeout = 300000;
URLReq.Proxy = null;
URLReq.ServicePoint.ConnectionLeaseTimeout = 300000;
URLReq.ServicePoint.MaxIdleTime = 300000;
URLReq.AllowAutoRedirect = true;
URLReq.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
using(URLRes = (HttpWebResponse) URLReq.GetResponse())
{
if (URLReq.HaveResponse)
{
if (URLRes.StatusCode == HttpStatusCode.OK || URLRes.StatusCode == HttpStatusCode.Continue)
{
Success = true;
Timed = false;
break;
}
}
}
}
catch (Exception ex)
{
if (URLRes != null && URLRes.StatusCode != null)
code = URLRes.StatusCode;
if (URLRes != null && URLRes.StatusDescription != null)
codeDescript = URLRes.StatusDescription;
if (ex.Message == "The operation has timed out")
{
Timed = true;
}
else
{
LogError(ex);
if (i + 1 == HTTPThreshold)
{
Message = new StringBuilder("Message: " + ex.Message + "<br/>");
if (ex.InnerException != null)
Message.Append("Inner Exception: " + ex.InnerException + "<br/>");
if (ex.Source != null)
Message.Append("Source: " + ex.Source + "<br/>");
if (ex.StackTrace != null)
Message.Append("Stack Trace" + ex.StackTrace + "<br/>");
}
}
}
finally
{
if (URLReq != null)
{
URLReq.Abort();
URLReq = null;
}
if (URLRes != null)
{
URLRes.Close();
URLRes = null;
}
GC.Collect();
}
}
if (Success)
{
WriteToOwnEventLog("HTTP Request returned Successful", "Http Request", true);
}
else
{
if (!Timed && code != HttpStatusCode.Unused && !string.IsNullOrEmpty(codeDescript) && Message == null)
EmailError("Site '" + urlToTest + "' HttpRequest returned with a status of " + code.ToString() + ". \n Description: \n " + codeDescript);
else if (!Timed && code != HttpStatusCode.Unused && !string.IsNullOrEmpty(codeDescript) && Message != null)
EmailError("Site '" + urlToTest + "' errored with an exception. HttpRequest returned with a status of " + code.ToString() + ". \n Description: \n " + codeDescript + Message.ToString());
else if (!Timed && code == HttpStatusCode.Unused && string.IsNullOrEmpty(codeDescript) && Message == null)
EmailError("Site '" + urlToTest + "' HttpRequest returned with Error. No information to display");
else if (!Timed && code == HttpStatusCode.Unused && string.IsNullOrEmpty(codeDescript) && Message != null)
EmailError("Site '" + urlToTest + "' HTTPRequest errored with an exception.<br/>" + Message.ToString());
else if (Timed)
EmailError("Site '" + urlToTest + "' HTTPRequest Timed Out");
WriteToOwnEventLog("HTTP Request failed, Email Sent", "Http Request", true);
}
}
WriteToOwnEventLog("<--------------------------------------------------------------------------------------------->", "Http Request", false);
}
private void PingUrl()
{
foreach(string urlToTest in urls)
{
bool Success = false;
PingReply reply = null;
StringBuilder Message = null;
IPStatus status = IPStatus.Unknown;
for (int i = 0; i < PingThreshold; i++)
{
Ping ping = null;
try
{
ping = new Ping();
WriteToOwnEventLog("Ping sent to " + urlToTest, "Ping", true);
string urlToTest1 = urlToTest.Substring(urlToTest.IndexOf(":") + 3);
if (urlToTest1.Contains('/'))
{
urlToTest1 = urlToTest1.Substring(0, urlToTest1.IndexOf('/'));
}
reply = ping.Send(urlToTest1);
status = reply.Status;
if (reply.Status == IPStatus.Success)
{
Success = true;
break;
}
}
catch (Exception ex)
{
LogError(ex);
if (i + 1 == PingThreshold)
{
Message = new StringBuilder("Message: " + ex.Message + "<br/>");
if (ex.InnerException != null)
Message.Append("Inner Exception: " + ex.InnerException + "<br/>");
if (ex.Source != null)
Message.Append("Source: " + ex.Source + "<br/>");
if (ex.StackTrace != null)
Message.Append("Stack Trace" + ex.StackTrace + "<br/>");
}
}
finally
{
if (ping != null)
{
ping.Dispose();
ping = null;
}
if (reply != null)
{
reply = null;
}
GC.Collect();
}
}
if (Success)
{
WriteToOwnEventLog("Ping Received Successfully", "Ping", true);
}
else
{
if (status != IPStatus.Unknown && Message != null)
EmailError("Ping Failed. Returned with a status of " + reply.Status.ToString() + " for site '" + urlToTest + "'. Exception:" + Message);
else if (status != IPStatus.Unknown && Message == null)
EmailError("Ping Failed. Returned with a status of " + reply.Status.ToString() + " for site '" + urlToTest + "'.");
else if (status == IPStatus.Unknown && Message != null)
EmailError("Ping failed with an exception. <br/>" + Message.ToString());
else if (status == null && Message == null)
EmailError("Ping failed. No information available");
WriteToOwnEventLog("Ping Failed. Email sent", "Ping", true);
}
}
WriteToOwnEventLog("<--------------------------------------------------------------------------------------------->", "Ping", false);
}
private void CheckDatabase()
{
foreach(string database in databases)
{
bool Success = false;
StringBuilder Message = null;
string dbName = "";
string dbServer = "";
for (int i = 0; i < DatabaseThreshold; i++)
{
SqlConnection conn = null;
try
{
using(conn = new SqlConnection(database))
{
dbName = conn.Database;
dbServer = conn.DataSource;
WriteToOwnEventLog("Opening Connection to SQL Database " + dbName + " On " + dbServer, "Database", true);
conn.Open();
Success = true;
conn.Close();
break;
}
}
catch (Exception ex)
{
LogError(ex);
if (i + 1 == DatabaseThreshold)
{
Message = new StringBuilder("Message: " + ex.Message + "<br/>");
if (ex.InnerException != null)
Message.Append("Inner Exception: " + ex.InnerException + "<br/>");
if (ex.Source != null)
Message.Append("Source: " + ex.Source + "<br/>");
if (ex.StackTrace != null)
Message.Append("Stack Trace" + ex.StackTrace + "<br/>");
}
}
finally
{
if (conn != null)
{
conn.Close();
conn.Dispose();
}
GC.Collect();
}
}
if (Success)
{
WriteToOwnEventLog("SQL Database Connection Successful To " + dbName + " on " + dbServer, "Database", true);
}
else
{
if (Message != null)
{
EmailError("Cannot connect to SQL Database " + dbName + " on " + dbServer + "<br/>" + Message.ToString());
WriteToOwnEventLog("SQL Database Connection Failed for database " + dbName + " on " + dbServer + ", Email Sent<br>" + Message.ToString(), "Database", true);
}
else
{
EmailError("Cannot connect to SQL Database " + dbName + " on " + dbServer + ", No information available");
WriteToOwnEventLog("SQL Database Connection Failed for database " + dbName + " on " + dbServer + ", Email Sent, No information available", "Database", true);
}
}
}
WriteToOwnEventLog("<--------------------------------------------------------------------------------------------->", "Database", false);
}

Categories

Resources