I have an array which sometimes holds values like "ABC, XYZ, TTT" and sometime only "ABC"
So while iterating through the arrays when it holds multiple it checks only for the first item and not the other item.
string[] strStateArray = new string[] { "" };
strStateArray = strOne.Split(',');
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].ToString()) // not checking for multiple items
{
}
}
updated code
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].Trim().ToString())
{
if (dt.Rows.Count > 0)
{
dt.TableName = "RecodSet";
string xml = ConvertDatatableToXML(dt);
mycon.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('File uploaded successfully.!!');", true);
// System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('File uploaded successfully.!!');", true);
}
else
{
string noData = "No data to upload.";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", noData, false);
}
}
else
{
string file_name = fluUploadBtn.FileName;
if ((System.IO.File.Exists(file_name)))
{
System.IO.File.Delete(file_name);
}
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('User is not authorised to upload data for state mentioned in excel report ');", true);
}
}
Could you just go debug the value then?
let me rewrite some code for you
String logMsg ="";
String targetKeyword = dt.Rows[0]["CIRCLE"].ToString();
for (int i = 0; i < strStateArray.Length; i++)
{
String tmp_Val_Pure = strStateArray[i] ==null? null : strStateArray[i].ToString(); //debug here see the value1
String tmp_Val = strStateArray[i] ==null? "" : strStateArray[i].ToString().Trim(); //debug here see the value2
bool isThisOk = (targetKeyword == tmp_Val ); //debug here see the val of isThisOk
if ( isThisOk )
{
logMsg += "Success Record : "+ i.ToString() + " val : " + tmp_Val ;
if (dt.Rows.Count > 0)
{ // alert case OK
} else { // alert no val dt }
}
else
{
logMsg += "Err Record : "+ i.ToString() + " val : " + tmp_Val ;
}
} //end loop
//Go check logMsg
I would like to ask, How I can use the While statement for downloading URL?
Here's what I want to happen.
I want to check if the url from CheckBoxListItems is already exist from my ListView
There's a case that I'm adding another urls to my listbox and I don't want to download again.
if url is already exists in my listview it will skip and proceed to the next url(which is not yet downloaded).
Here's my current codes:
int count = 0;
int total = LB.CheckedItems.Count;
string counter = string.Empty;
using (cts = new CancellationTokenSource())
{
try
{
if (cts.IsCancellationRequested) { throw new TaskCanceledException(); }
txtOutput.Text = string.Empty;
Cursor = Cursors.WaitCursor;
Parsing = true;
Text = "Getting links information. Please wait...";
foreach (string url in LB.CheckedItems)
{
var info = await Task.Run(() => Parser.GetJsonData(url, cts.Token));
count++;
counter = "( " + count + " of " + total + " )";
lblTotalLinks.Text = counter;
Text = "Parsing in progress. Please wait... " + counter;
AddToListView(info); //ADD DOWNLOADED STRINGS TO LISTVIEW
}
Text = "Parsing done. " + counter;
}
catch (OperationCanceledException ex)
{ Text = ex.Message; }
catch (Exception ex)
{ MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
Parsing = false;
Cursor = Cursors.Default;
cts = null;
//ADD TO LISTVIEW()
private void AddToListView(MediaInfo info)
{
int count = LV.Items.Count + 1;
var results = new List<ListViewItem> { new ListViewItem(new[]
{
count.ToString(),
info.Series,
"Episode " + info.Episode,
info.Title,
info.Runtime,
info.Resolution,
info.Category,
info.URL, //here's what I want to check if already exists
info.M3u8_url,
info.FileSize,
info.Fragments
})};
ListViewItem[] array = results.ToArray();
LV.BeginUpdate();
LV.ListViewItemSorter = null;
LV.Items.AddRange(array);
LV.Focus();
LV.EndUpdate();
Countlists();
LV.Items[LV.Items.Count - 1].EnsureVisible();
}
this is the example of what I want:
string urlExists = string.Empty;
foreach (ListViewItem item in LV.Items)
{
urlExists = item.SubItems[7].Text;
foreach (string url in LB.CheckedItems)
{
while (url != urlExists)
{
}
}
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.
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);
}
These codes allow me to access the registry and grab out the lastvisitedMRU values which are in a non-readable format. What I did here was to convert them into a readable format. I placed them in an array and output them into console.
The output goes like this:
C : \ P r o g r a m F i l e s \ i P o d \ f i l e . t x t
How do I remove the spacings in between?
Thanks in advance.
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
String[] names = rk.GetValueNames();
Console.WriteLine("Subkeys of " + rk.Name);
Console.WriteLine("-----------------------------------------------");
foreach (String s in names)
{
try
{
if (s == "MRUList")
{
continue;
}
else
{
try
{
Byte[] byteValue = (Byte[])rk.GetValue(s);
string str = BitConverter.ToString(byteValue).Replace("00", "");
str = BitConverter.ToString(byteValue).Replace("-", "");
//str binry AND VAR CONVERTED TEXT
Console.WriteLine(s + " Contains the value of : " + str);
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= str.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(str.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
String val = Convert.ToString(sb).Replace(" ", "");
Console.WriteLine(s + " Contains the value of : " + val);
}
catch (Exception Errors)
{
Console.WriteLine("An error has occurred: " + Errors.Message);
}
}
//rk.Close();
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
Console.WriteLine("-----------------------------------------------");
//rk.Close();
}
The binary there is unicode encoded. I fixed your code and verified it is working on my XP. However, it doesn't work on Windows 7 or Vista because LastVisitedMRU no longer exists.
static void Main(string[] args)
{
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception ex)
{
Console.WriteLine("An error has occurred: " + ex.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
foreach (String s in rk.GetValueNames())
{
if (s == "MRUList")
{
continue;
}
Byte[] byteValue = (Byte[])rk.GetValue(s);
UnicodeEncoding unicode = new UnicodeEncoding();
string val = unicode.GetString(byteValue);
Console.Out.WriteLine(val);
}
Console.ReadLine();
}