C# Called method is ignored with no error - c#

I am developing a C# Windows Form program in which there are a number of called Methods (what in VB I called Subs). Excuse me if I'm using the wrong terms, new to C#. One of these methods is being ignored, CreateFolder(). When I set break points to debug and step through, the program gets to the called method and goes right through it like it like it was a blank line, no errors warning just goes through. The program is a bit large so I'm including what I hope is helpful. Sorry if too much. The method (sub) not being executed is CreateFolder(). Again, the debugger will stop on this line[CreateFolder()] in the ProcessEmail() routine but just goes on without going to the called code. Thoughts?
public partial class FrmProcessNew : Form
{
...bunch of global vaiables
private void FrmProcessNew_Load(object sender, EventArgs e)
{
chkBoxTesting.Checked = Convert.ToBoolean(ConfigurationManager.AppSettings["testing"]); //check if test to ignore bad credit cards
}
private void btnStart_Click(object sender, EventArgs e)
{
ProcessEmail(); //check for, process and then move new Outlook emails
}
public void ScrollBox(string box) //try to get scroll box right
{
if (box == "Text")
{
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();
}
if (box == "List")
{ listBox1.TopIndex = listBox1.Items.Count - 1; }
}
public static int GetLineNumber(COMException ex) //Get the line number if an error occurs - from stack overflow
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
private void ProcessEmail() // Process the new email
{
while (inboxFolder.Items.Count == 0) //check for any email in Inbox
{
textBox1.Text = textBox1.Text + ("Inbox is empty - Listening for New emails!\r\n");
ScrollBox("Text");
textBox1.Update();
Delay(); //wait 5 seconds
}
CreateFolder(); //Create new destination folder to move processed emails to - NOT FORWARDING TO THIS SUB!!
try
{
foreach (Microsoft.Office.Interop.Outlook.MailItem mailItem in inboxFolder.Items)
{
....processing stuff
}
catch (System.Runtime.InteropServices.COMException ex)
{
....capture error
}
finally
{
....reset stuff
}
}
public void CreateFolder() //Create Outlook Folders to store processed emails = NEVER GETS TO THIS CODE!!!
{
DateTime fldDate = DateTime.Now;
if (fldDate.DayOfWeek != DayOfWeek.Friday) //must process with a Friday date, set date to next Friday
{
fldDate = NextFriday(fldDate);
}
String myYear = fldDate.ToString("yyyy");
string myMonth = fldDate.ToString("MM");
string myDay = fldDate.ToString("dd"); //day of the month
string fileDate = (myYear.ToString()) + "-" + (myMonth.ToString()) + "-" + myDay; // build the Date for Destination "file";
try
{olDestinationFolder = ns.Folders[mailBoxName].Folders[("done")].Folders[(fileDate)]; }
catch
{ olDestinationFolder = ns.Folders[mailBoxName].Folders[("done")].Folders.Add(fileDate); }
try
{ olBadCreditFolder = ns.Folders[mailBoxName].Folders[("done")].Folders[(fileDate)].Folders[("BadCredit")]; }
catch
{ olBadCreditFolder = ns.Folders[mailBoxName].Folders[("done")].Folders[(fileDate)].Folders.Add("BadCredit"); }
try
{ olNonOrderEmails = ns.Folders[mailBoxName].Folders[("done")].Folders[(fileDate)].Folders[("Non-OrderEmails")]; }
catch
{ olNonOrderEmails = ns.Folders[mailBoxName].Folders[("done")].Folders[(fileDate)].Folders.Add("Non-OrderEmails"); }
}
private void Delay() //If no emails then want 5 seconds and try again
{
textBox1.Text = textBox1.Text + ("Inbox is empty - Listening for New emails!\r\n");
ScrollBox("Text");
textBox1.Update();
// await Task.Delay(5000); //Wait 5 seconds for new email
var t = Task.Run(async delegate
{
await Task.Delay(TimeSpan.FromSeconds(5.5));
ScrollBox("Text");
return 42;
});
}
static DateTime NextFriday(DateTime fldDate) //Find the next FRIDAY date.
{
do
{
fldDate = fldDate.AddDays(1);
}
while (fldDate.DayOfWeek != DayOfWeek.Friday);
return fldDate;
}
}
}

Related

how to wait c# webbrowser to complete document load in TPL

Hi I have this two blocks of code
when I navigate the browser to a url and try to wait for it I get a deadlock I think=) any help suggestions are much appreciated!
I'm just adding some more text here so I am able to post the question :/ sorry
foreach (var davaType in davaTypes)
{
Parallel.ForEach(years, year =>
{
ts.Add(Task.Run(() =>
{
var th = new Thread(async () =>
{
await doWorkAsync(year, davaType, tarafType);
Application.Run();
});
th.IsBackground = true;
th.SetApartmentState(ApartmentState.STA);
th.Start();
}));
});
}
and
public static async Task doWorkAsync(int year, string davaType, string tarafType)
{
using (var browser = new MyBrowser())
{
Console.WriteLine("Im Created Here");
browser.Navigate("some url");
while (!browser.MyLoaded)
{
Console.WriteLine("waiting");
await Task.Delay(10);
}
Console.WriteLine("complete");
browser.Document?.GetElementById("DropDownList1")?.SetAttribute("value", davaType);
browser.Document.GetElementById("DropDownList3")?.SetAttribute("value", tarafType);
browser.Document.GetElementById("DropDownList4")?.SetAttribute("value", year.ToString());
browser.Document.GetElementById("Button1").MyClick();
await browser.WaitPageLoad(10);
Console.WriteLine("Im DoneHere");
}
}
You can use TaskCompletionSource to create a task and await for it after the page is loaded.
See: UWP WebView await navigate.
I have experienced this problem before and the solution I have applied is as follows;
private void waitTillLoad()
{
WebBrowserReadyState loadStatus = default(WebBrowserReadyState);
int waittime = 100000;
int counter = 0;
while (true)
{
loadStatus = webBrowser1.ReadyState;
Application.DoEvents();
if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) || (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
{
break; // TODO: might not be correct. Was : Exit While
}
counter += 1;
}
counter = 0;
while (true)
{
loadStatus = webBrowser1.ReadyState;
Application.DoEvents();
if (loadStatus == WebBrowserReadyState.Complete)
{
break; // TODO: might not be correct. Was : Exit While
}
counter += 1;
}
}
You need to create only one separate thread for WinForms. Other threads will be created by individual browsers themselves. What you do need is handling their DocumentCompleted event. The first time the document completes you enter and submit data, the second time it completes you get the result. When all browsers finish, you exit the winforms thread and you're done.
Note: To launch bots from winforms thread, I made use of Idle event handler, just because it was the first solution that came to my mind. You may find better way.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
namespace ConsoleBrowsers
{
class Program
{
static void Main(string[] args)
{
string url = "https://your.url.com";
string[] years = { "2001", "2002", "2003"};
string[] davas = { "1", "2", "3" };
string taraf = "1";
int completed = 0, succeeded = 0;
var bots = new List<Bot>();
var started = false;
var startBots = (EventHandler)delegate (object sender, EventArgs b)
{
if (started)
return;
started = true;
foreach (var dava in davas)
foreach (var year in years)
bots.Add(new Bot { Year = year, Dava = dava, Taraf = taraf, Url = url }.Run((bot, result) =>
{
Console.WriteLine($"{result}: {bot.Year}, {bot.Dava}");
succeeded += result ? 1 : 0;
if (++completed == years.Length * davas.Length)
Application.ExitThread();
}));
};
var forms = new Thread((ThreadStart) delegate {
Application.EnableVisualStyles();
Application.Idle += startBots;
Application.Run();
});
forms.SetApartmentState(ApartmentState.STA);
forms.Start();
forms.Join();
Console.WriteLine($"All bots finished, succeeded: {succeeded}, failed:{bots.Count - succeeded}.");
}
}
class Bot
{
public string Url, Dava, Taraf, Year;
public delegate void CompletionCallback(Bot sender, bool result);
WebBrowser browser;
CompletionCallback callback;
bool submitted;
public Bot Run(CompletionCallback callback)
{
this.callback = callback;
browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
browser.DocumentCompleted += Browser_DocumentCompleted;
browser.Navigate(Url);
return this;
}
void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (browser.ReadyState == WebBrowserReadyState.Complete)
{
if (submitted)
{
callback(this, true);
return;
}
var ok = SetValue("DropDownList1", Dava);
ok &= SetValue("DropDownList3", Taraf);
ok &= SetValue("DropDownList4", Year);
if (ok)
ok &= Click("Button1");
if (!(submitted = ok))
callback(this, false);
}
}
bool SetValue(string id, string value, string name = "value")
{
var e = browser?.Document?.GetElementById(id);
e?.SetAttribute(name, value);
return e != null;
}
bool Click(string id)
{
var element = browser?.Document?.GetElementById(id);
element?.InvokeMember("click");
return element != null;
}
}
}

Picking specific numbers out of text file and assign to variable

Someone here at works needs some calculations done from some numbers within a text file. I know how to do the calculation but I haven't worked with text file before. So I spent the night reading and wrote a little something for the first number I needed but it doesn't work.
So here is an example of the file.
So that first number that comes after FSD: 0.264 I need to read that number and save to a variable. The number will always be different per file. Then I need the first 3.4572 number read to a variable. and the last number of that column as well which you don't see here but for the example it can be the last one shown in the image of 3.3852 read and saved to a variable.
Maybe I'm making this much harder than it needs to be but this is what I was playing around with
public partial class FrmTravelTime : Form
{
string file = "";
public FrmTravelTime()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
var sLines = File.ReadAllLines(file)
.Where(s => !s.StartsWith("FSD:"))
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => new
{
SValue = Regex.Match(s, "(?<=S)[\\d.]*").Value,
})
.ToArray();
string Value = "";
for (int i = 0; i < sLines.Length; i++)
{
if (sLines[i].SValue == "")
{
Value = (sLines[i].SValue);
}
}
}
}
EDIT FOR #Ramankingdom
So if you see here all lines have an ending column of 0.00 until we get to
3.0164 7793 1 0 0.159 0.02
So what I'd like to do, is edit what we did to skip everything that has a column with 0.00 in that last column and make the first non 0.00 the info.firstvalue so in this case 3.0164
Now I tried this on my own and used
var data = lines.Where(line => (!line.Contains(Data_Start_Point_Identifier) && !line.Contains(FSD__Line_Identifier) && !line.EndsWith("0.00"))).ToList();
But that breaks info.startvalue and data = dataWithAvgVolts[dataWithAvgVolts.Count - 1].Split(splitter);
So I'd figured I'd check with you.
So I tried this but I keep getting invalid data error on info.startvalue
FileInfo info = new FileInfo();
var lines = File.ReadAllLines(row.Cells["colfilelocation"].Value.ToString());
var fsdLine = lines.FirstOrDefault(line =>
line.Contains(FSD__Line_Identifier));
info.FSD = fsdLine.Substring(fsdLine.IndexOf(FSD_Identifier) + FSD_Identifier.Length, 7);
var dataWithAvgVolts = lines.SkipWhile(line => !line.Contains(Data_Start_Point_Identifier)).ToList();
int index =1;
while(index < dataWithAvgVolts.Count())
{
var data = dataWithAvgVolts[index].Split(splitter);
if(data.Count() >1)
{
if(!Convert.ToDouble(data[data.Count()-1]) == 0)
{
//set start info
break;
}
}
index++;
}
the reverse loop you can run to set the end value
Here is the code
class Program
{
const string FSD_Identifier = "FSD:";
const string FSD__Line_Identifier = "Drilling Data";
const string Data_Start_Point_Identifier = "AVG_VOLTS";
static readonly char[] splitter = {' ','\t'};
static void Main(string[] args)
{
var result = GetFileInfo("c:\\sample.txt");
}
private static MyFileInfo GetFileInfo(string path)
{
MyFileInfo info = new MyFileInfo();
try
{
var lines = File.ReadAllLines(path);
var fsdLine = lines.FirstOrDefault(line => line.Contains(FSD__Line_Identifier));
info.FSD = fsdLine.Substring(fsdLine.IndexOf(FSD_Identifier) + FSD_Identifier.Length, 10); // take lenght you can specify or your own logic
var dataWithAvgVolts = lines.SkipWhile(line => !line.Contains(Data_Start_Point_Identifier)).ToList<string>();
if (dataWithAvgVolts.Count() > 1)
{
var data = dataWithAvgVolts[1].Split(splitter);
info.startvalue = Convert.ToDouble(data[0]);
data = dataWithAvgVolts[dataWithAvgVolts.Count-1].Split(splitter);
info.endvalue = Convert.ToDouble(data[0]);
}
}
catch (Exception ex)
{
//logging here
}
return info;
}
}
public class MyFileInfo
{
public string FSD;
public double startvalue;
public double endvalue;
}

Is that logic to reset the Lists and call Init() over again if there was an exception with the download/s?

And how can i report to the user that there was a problem and that it's trying over again ? And should i just do it like i'm doing it now reseting everything and calling Init() again or should i use some timer and wait some seconds before trying again ?
In the class i did:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Xml;
using HtmlAgilityPack;
using System.ComponentModel;
namespace TestingDownloads
{
class ExtractImages
{
static WebClient client;
static string htmltoextract;
public static List<string> countriescodes = new List<string>();
public static List<string> countriesnames = new List<string>();
public static List<string> DatesAndTimes = new List<string>();
public static List<string> imagesUrls = new List<string>();
static string firstUrlPart = "http://www.sat24.com/image2.ashx?region=";
static string secondUrlPart = "&time=";
static string thirdUrlPart = "&ir=";
public class ProgressEventArgs : EventArgs
{
public int Percentage { get; set; }
public string StateText { get; set; }
}
public event EventHandler<ProgressEventArgs> ProgressChanged;
public void Init()
{
object obj = null;
int index = 0;
ExtractCountires();
foreach (string cc in countriescodes)
{
// raise event here
ProgressChanged?.Invoke(obj,new ProgressEventArgs{ Percentage = 100 * index / countriescodes.Count, StateText = cc });
ExtractDateAndTime("http://www.sat24.com/image2.ashx?region=" + cc);
index +=1;
}
ImagesLinks();
}
public void ExtractCountires()
{
try
{
htmltoextract = "http://sat24.com/en/?ir=true";//"http://sat24.com/en/";// + regions;
client = new WebClient();
client.DownloadFile(htmltoextract, #"c:\temp\sat24.html");
client.Dispose();
string tag1 = "<li><a href=\"/en/";
string tag2 = "</a></li>";
string s = System.IO.File.ReadAllText(#"c:\temp\sat24.html");
s = s.Substring(s.IndexOf(tag1));
s = s.Substring(0, s.LastIndexOf(tag2) + tag2.ToCharArray().Length);
s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
string[] parts = s.Split(new string[] { tag1, tag2 }, StringSplitOptions.RemoveEmptyEntries);
string tag3 = "<li><ahref=\"/en/";
for (int i = 0; i < parts.Length; i++)
{
if (i == 17)
{
//break;
}
string l = "";
if (parts[i].Contains(tag3))
l = parts[i].Replace(tag3, "");
string z1 = l.Substring(0, l.IndexOf('"'));
if (z1.Contains("</ul></li><liclass="))
{
z1 = z1.Replace("</ul></li><liclass=", "af");
}
countriescodes.Add(z1);
countriescodes.GroupBy(n => n).Any(c => c.Count() > 1);
string z2 = parts[i].Substring(parts[i].LastIndexOf('>') + 1);
if (z2.Contains("&"))
{
z2 = z2.Replace("&", " & ");
}
countriesnames.Add(z2);
countriesnames.GroupBy(n => n).Any(c => c.Count() > 1);
}
}
catch (Exception e)
{
if (countriescodes.Count == 0)
{
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
Init();
}
}
}
public void ExtractDateAndTime(string baseAddress)
{
try
{
var wc = new WebClient();
wc.BaseAddress = baseAddress;
HtmlDocument doc = new HtmlDocument();
var temp = wc.DownloadData("/en");
doc.Load(new MemoryStream(temp));
var secTokenScript = doc.DocumentNode.Descendants()
.Where(e =>
String.Compare(e.Name, "script", true) == 0 &&
String.Compare(e.ParentNode.Name, "div", true) == 0 &&
e.InnerText.Length > 0 &&
e.InnerText.Trim().StartsWith("var region")
).FirstOrDefault().InnerText;
var securityToken = secTokenScript;
securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
foreach (var date in scriptDates)
{
DatesAndTimes.Add(date.DateString);
}
}
catch
{
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
this.Init();
}
}
public class ScriptDate
{
public string DateString { get; set; }
public int Year
{
get
{
return Convert.ToInt32(this.DateString.Substring(0, 4));
}
}
public int Month
{
get
{
return Convert.ToInt32(this.DateString.Substring(4, 2));
}
}
public int Day
{
get
{
return Convert.ToInt32(this.DateString.Substring(6, 2));
}
}
public int Hours
{
get
{
return Convert.ToInt32(this.DateString.Substring(8, 2));
}
}
public int Minutes
{
get
{
return Convert.ToInt32(this.DateString.Substring(10, 2));
}
}
}
public void ImagesLinks()
{
int cnt = 0;
foreach (string countryCode in countriescodes)
{
cnt++;
for (; cnt < DatesAndTimes.Count(); cnt++)
{
string imageUrl = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
imagesUrls.Add(imageUrl);
if (cnt % 10 == 0) break;
}
}
}
}
}
In both cases where i'm using try and catch if it's getting to the catch i'm trying over again the whole operation by reseting the Lists and calling Init() again.
Then in form1
ExtractImages ei = new ExtractImages();
public Form1()
{
InitializeComponent();
ProgressBar1.Minimum = 0;
ProgressBar1.Maximum = 100;
backgroundWorker1.RunWorkerAsync();
}
events of backgroundworker
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
return; // this will fall to the finally and close everything
}
else
{
ei.ProgressChanged += (senders, eee) => backgroundWorker1.ReportProgress(eee.Percentage, eee.StateText);
ei.Init();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressBar1.Value = e.ProgressPercentage;
label7.Text = e.UserState.ToString();
label8.Text = e.ProgressPercentage + "%";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null)
{
ProgressBar1.Value = 100;
}
else
{
}
}
Another thing not sure if it's a problem. When there is no a problem with the class i see in form1 in label7 all the codes running from the first to the last.
But the progressBar1.Value and label8 both are getting only to 97% so i need in the completed event to add the progressBar1.Value = 100; is that fine or there is a problem with the reporting calculation in the class ?
For the 1st question:
Better catch the exception at client side and display the error msg, 'cause you probably need to control your program behavior accrodingly when sth went wrong.
Consider this: if the DOM struct of the page changed, according to you code, your program probably throw expections, with each exception catching, client.DownloadFile is excuted for one time, if this happens, u will need to know what go wrong, and if u donot change ur code behavior, such hi-freq client.DownloadFile excution will cause the firewall of the website block ur ip for a while.
Add a timer at client side is a good idea i think.
For the 2nd one:
did u define how to handle RunWorkerCompleted event?

Wav files in Windows Media Player queued items not playing correctly at times with C#

I am doing an application which shows tokens on screen like A0001 Counter 1. Each of the tokens "A","0","0","0","0" "Counter" "1" has wav files stored in a folder ENGLISH in my project as A.wav, 0.wav,0.wav etc. Now I'm using wmplib.dll and running vs 2012 on Win 7 64 bit. I tried using single threading like
new System.Threading.Thread(() => {
//my code here
}).Start();
Thread.Sleep(700); //I know this is not a good way to use threads.
This code works on Win 7 64 bit perfectly. Now when I try to use it on XP 32 bit the audio sometimes overlaps and sometimes doesn't play. So I used an alternative way using backgroundworker thread. The code is as below.
Issue with this is that the queued items ie. the URL of the files like C:\project path\ENGLISH\A.wav, C:\project path\ENGLISH\0.wav etc. are queued to the queue and then added to Windows Media player playlist. But they are not playing in order and going off sync at times.
public void playAudiofile(String counter_prefix, String counter_name, String token_number)
{
String[] token_langs = Config.getTokenLanguages(token_number);
/*BUZZER*/
audio_annoucements.Enqueue(audio_file_dir + "buzzer.wav");
foreach (String tlang in token_langs)
{
String lang = tlang.Trim().ToUpper();
try
{
if (lang != "NONE")
{
/*TOKEN*/
audio_annoucements.Enqueue(audio_file_dir + "Token.wav");
/*TOKEN NO*/
token_number = token_number.ToUpper();
char[] tokens = token_number.ToCharArray();
foreach (char token in tokens)
{
if (Char.IsLetter(token))
{
audio_annoucements.Enqueue(audio_file_dir + token + ".wav");
}
else
{
audio_annoucements.Enqueue(audio_file_dir + token + ".wav");
}
}
/*COUNTER*/
counter_prefix = counter_prefix.ToUpper();
audio_annoucements.Enqueue(audio_file_dir + "COUNTER.wav");
/*COUNTER NAME*/
counter_name = counter_name.ToUpper();
char[] counters = counter_name.ToCharArray();
foreach (char counter in counters)
{
if (Char.IsLetter(counter))
{
audio_annoucements.Enqueue(audio_file_dir + counter + ".wav");
}
else
{
audio_annoucements.Enqueue(audio_file_dir+ counter + ".wav");
}
}
}
}
catch (Exception) { }
if (!backgroundWorker1.IsBusy)
{
timer1.Stop();// i turn off the timer so that backgroundworker can run properly without issues. I turn it on later.
backgroundWorker1.RunWorkerAsync();
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
String tmpPlaylist = "tmpPlaylist";
WMPLib.IWMPPlaylist pls;
WMPLib.IWMPPlaylistArray plItems;
WMPLib.WindowsMediaPlayer mediaPlayer = new WMPLib.WindowsMediaPlayer();
plItems = mediaPlayer.playlistCollection.getByName(tmpPlaylist);
if (plItems.count == 0)
{
pls = mediaPlayer.playlistCollection.newPlaylist(tmpPlaylist);
}
else
{
pls = plItems.Item(0);
pls.clear();
}
while (audio_annoucements.Count > 0)
{
WMPLib.IWMPMedia m1 = mediaPlayer.newMedia(audio_annoucements.Dequeue().ToString());
pls.appendItem(m1);
}
mediaPlayer.currentPlaylist = pls;
mediaPlayer.controls.play();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
timer1.Start();// theres a 1 second timer in the form that checks db entries
}
if you want to execute every 700 millisecond try:
System.Timers.Timer t = new System.Timers.Timer(700);
t.Start()
t.Elapsed += (object s1, System.Timers.ElapsedEventArgs e1) => {
new System.Threading.Thread(() => {
//my code here
}).Start();
};

How to pause the "for" loop until getting response

I am using a for loop for making Calls for a list of numbers.
I want to take the first number from the list and make a call and to wait for the response and then proceed to the next number in the list.
I have used AutoResetEvent to do this.But it is not working.
for (int k = 0; k < list_Items.Count; k++) {
Number_To_Call = "9" + list_Items[k].ToString();
phoneCall.Start();
waitingToPickUp.Set(); //AutoReset Event
Thread.Sleep();
waitingToPickUp.WaitOne();
string detector = VoiceDetected;
if (detector == "Machine") {
//code
} else if (detector == "Human") {
//code
} else {
//code
}
}
Code for getting response form the call
void phoneCall_CallStateChanged(object sender, VoIPEventArgs<CallState> e)
{
if (e.Item.IsInCall())
{
phoneCallAudioReceiver.AttachToCall(phoneCall);
phoneCallAudioSender.AttachToCall(phoneCall);
manchineDetector.Start();
waitingToPickUp.Set();
string str = VoiceDetected;
}
else if (e.Item.IsCallEnded())
{
phoneCallAudioReceiver.Detach();
phoneCallAudioSender.Detach();
manchineDetector.Stop();
phoneCall = null;
//Number_To_Call = string.Empty;
InvokeOnGUIThread(() =>
{
Number_To_Call = string.Empty;
});
}
}
Code for Detecting Machine or Human
void manchineDetector_DetectionCompleted(object sender, VoIPEventArgs<AnswerMachineDetectionResult> e)
{
try
{
string VoiceDetected = e.Item.ToString();
}
catch (Exception ex)
{
}
}
Set and immediately WaitOne makes no sense - wait will not need to wait for anything and immediately continue.
Most likely should be reset-call-wait:
waitingToPickUp.Reset();
phoneCall.Start();
waitingToPickUp.WaitOne();

Categories