how to run multiple background process in a button - c#

I am having a problem. I am new in c#. In this code when I click the button2, it will run bgutures.RunWorkerAsync(); only. But I need to modify it such like if I click on button2, all items the checkedListBox1.allitems contains are download, one by one in bgworker. Can anyone please help in this.
My code is :
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
string DayAtoZ = " ";
string DayDead = " ";
string Dayutures = " ";
string Daysify = " ";
string Dayfx = " ";
if (checkedListBox1.SelectedItem == "")
{
}
else if (checkedListBox1.SelectedItem == Dayutures)
{
}
else if (checkedListBox1.SelectedItem == DayAtoZ)
{
}
else if (checkedListBox1.SelectedItem == Daysify)
{
}
else if (checkedListBox1.SelectedItem == DayDead)
{
}
else if (checkedListBox1.SelectedItem == Dayfx)
{
}
{
bgutures.RunWorkerAsync();
}
{
bgDead.RunWorkerAsync();
}
{
bgsify.RunWorkerAsync();
}
{
bgAtoZ.RunWorkerAsync();
}
{
}
}

Instead of one BackgoundWorker use as many as your need.
if (checkedListBox1.SelectedItem == "")
{
var worker = new BackgroundWorker();
.. do setup
worker.RunWorkerAsync();
}
else if (checkedListBox1.SelectedItem == Dayutures)
{
var worker = new BackgroundWorker();
.. do setup
worker.RunWorkerAsync();
}

Related

Convert Button Click to Page Load

I have an ASP button click method that I want to change from a user clicking the button
<asp:Button id="createInvoice" runat="server" OnClick="InvoiceBtn_Click" Text="Create Invoice button" />
to executing on Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
AsyncMode = true;
if (!dictionary.ContainsKey("accessToken"))
{
if (Request.QueryString.Count > 0)
{
var response = new AuthorizeResponse(Request.QueryString.ToString());
if (response.State != null)
{
if (oauthClient.CSRFToken == response.State)
{
if (response.RealmId != null)
{
realmId = response.RealmId;
if (!dictionary.ContainsKey("realmId"))
{
dictionary.Add("realmId", realmId);
}
}
if (response.Code != null)
{
authCode = response.Code;
Session["authcodes"] = authCode;
output("Authorization code obtained.");
PageAsyncTask t = new PageAsyncTask(performCodeExchange);
Page.RegisterAsyncTask(t);
Page.ExecuteRegisteredAsyncTasks();
}
}
else
{
output("Invalid State");
dictionary.Clear();
}
}
}
}
else
{
oauth.Visible = true;
connected.Visible = true;
}
}
#region button click events
public async void InvoiceBtn_Click()
{
if (dictionary.ContainsKey("realmId") && dictionary.ContainsKey("accessToken"))
{
Action<ServiceContext> apiCallFucntion = new Action<ServiceContext>(CreateInvoiceCall);
await QBOApiCall(apiCallFucntion);
}
else
{
lblQBOCall.Visible = true;
lblQBOCall.Text = "Access token not found.";
}
}
I changed the final else statement and final line in the method and it works. I'm sure it needs refactoring but it works.
else
{
oauth.Visible = true;
connected.Visible = true;
InvoiceBtn_Click(createInvoice, EventArgs.Empty);
}
InvoiceBtn_Click(createInvoice, EventArgs.Empty);

how to set timer_ticker to sleep until the process is completed in the background

I have a problem with timerTick() because it executes every 0.5 seconds, for me it's ok because he checks every 0.5 seconds for connectetCard(), now if so he should assign it The 5 seconds that I in _bw.DoWork assigned to run, how can I set timerTick() to fire again, but only when the process in backgroundWorker is completed.
This is my code:
public FormMenu()
{
InitializeComponent();
SelectDevice();
establishContext();
timerBatch.Start();
_bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
}
private void timerBatch_Tick(object sender, EventArgs e)
{
if (connectCard())
{
cardUID = getcardUID();
if (cardUID != "Error")
{
using (DBEntities db = new DBEntities())
{
try
{
personData = db.Persons.Where(x => x.BATCH_ID == cardUID).FirstOrDefault();
if (maDaten == null)
{
labelInfo.Text = "Batch invalid.";
return;
}
else
{
person = db.Person.Where(x => x.LPE_ID == personData.MA_ID).FirstOrDefault();
_bw.DoWork += _bw_DoWork;
_bw.ProgressChanged += bw_ProgressChanged;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;
_bw.RunWorkerAsync();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
};
}
}
}
private void _bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 5; i >= 0; i -= 1)
{
if (_bw.CancellationPending) {
e.Cancel = true; return;
}
if (i == 0)
{
e.Cancel = true; return;
}
_bw.ReportProgress(i);
Thread.Sleep(1000);
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
labelInfo.Text = "Hello " + person.FirstName + " " + person.LastName + " " + e.ProgressPercentage.ToString();
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
labelInfo.Text = labelInfo.Text.Trim();
}
Try something like this:
public FormMenu()
{
InitializeComponent();
SelectDevice();
establishContext();
timerBatch.Start();
_bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
}
//CHANGE:
bool backgroundworkerRunning = false;
private void timerBatch_Tick(object sender, EventArgs e)
{
//CHANGE:
if (backgroundworkerRunning)
return;
if (connectCard())
{
cardUID = getcardUID();
if (cardUID != "Error")
{
using (DBEntities db = new DBEntities())
{
try
{
personData = db.Persons.Where(x => x.BATCH_ID == cardUID).FirstOrDefault();
if (maDaten == null)
{
labelInfo.Text = "Batch invalid.";
return;
}
else
{
person = db.Person.Where(x => x.LPE_ID == personData.MA_ID).FirstOrDefault();
_bw.DoWork += _bw_DoWork;
_bw.ProgressChanged += bw_ProgressChanged;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;
//CHANGE:
backgroundworkerRunning = true;
_bw.RunWorkerAsync();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
};
}
}
}
private void _bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 5; i >= 0; i -= 1)
{
if (_bw.CancellationPending) {
e.Cancel = true; return;
}
if (i == 0)
{
e.Cancel = true; return;
}
_bw.ReportProgress(i);
Thread.Sleep(1000);
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
labelInfo.Text = "Hello " + person.FirstName + " " + person.LastName + " " + e.ProgressPercentage.ToString();
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//CHANGE:
backgroundworkerRunning = false;
labelInfo.Text = labelInfo.Text.Trim();
}

Adding a new line when checking a checkbox

When I click on a checkbox I want the next checkbox information to be displayed on a new line, I know how to do this with "\r\n" however when unchecking the box and rechecking the box, it adds a new line above the text moving the original text down by 1 line. https://imgur.com/a/IHDDG85
I've tried "\r\n" and Environment.NewLine
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
if (chkHamburger.Checked == true)
{
txtHamburger.Enabled = true;
txtHamburger.Text = "";
txtHamburger.Focus();
txtOrder.Text += ("Hamburger");
}
else
{
txtHamburger.Enabled = false;
txtHamburger.Text = "0";
}
if (chkHamburger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Hamburger", "");
}
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
if (chkCheeseBurger.Checked == true)
{
txtCheeseBurger.Enabled = true;
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
txtOrder.Text += ("Cheese Burger");
}
else
{
txtCheeseBurger.Enabled = false;
txtCheeseBurger.Text = "0";
}
if (chkCheeseBurger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Cheese Burger", "");
}
}
I want the text of a checkbox to be displayed on a new line but when rechecking the box a whitespace should not appear above it.
I suggest you to use a List<string> where you add or remove your orders. Then it is easy to rebuild the txtOrder data with a single line of code using string.Join
List<string> orders = new List<string>();
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
txtHamburger.Enabled = chkHamburger.Checked;
if (chkHamburger.Checked)
{
txtHamburger.Text = "";
txtHamburger.Focus();
orders.Add("Hamburger");
}
else
{
txtHamburger.Text = "0";
orders.Remove("Hamburger");
}
UpdateOrders();
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
txtCheeseBurger.Enabled = chkCheeseBurger.Checked;
if (chkCheeseBurger.Checked)
{
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
orders.Add("Cheese Burger");
}
else
{
txtCheeseBurger.Text = "0";
orders.Remove("Cheese Burger");
}
UpdateOrders();
}
private void UpdateOrders()
{
txtOrders.Text = string.Join(Environment.NewLine, orders);
}
The best way to do this is to have a routine that builds the contents of the text independent of what just happened -- this you could use join or a loop to create the text contents.
Make this a function and call it when the check boxes change. The function loops over all your items and adds them to the output with the formatting and totals etc.

Disable Right Click in Popup Window

how should I disable the right click in Popup Window. I dont want the user to save or print the document in the Popup Window. Here is my interface Interface
Here is my aspx.cs code under TreeView1_SelectedNodeChanged
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
if (Session["loggedUserID"] == null && Session["loggedRoleID"] == null)
{
Response.Redirect("~/Login.aspx");
}
else
{
if (TreeView1.SelectedNode.Parent == null)
{
ltEmbed.Visible = false;
}
else
{
ltEmbed.Visible = true;
string Text = TreeView1.SelectedNode.Text.ToString();
int loggedUserID = Convert.ToInt32(Session["loggedUserID"]);
List<BOL.UserInfo> userslist = new UserInfos().List();
BOL.UserInfo loggeduser = userslist.Where(x => x.UserID == loggedUserID).FirstOrDefault();
BOL.DMS getdetail = new DMSS().GET_FILE(loggeduser.SUBSIDIARY_CD, Text);
string FILE_NAME = getdetail.F_NAME;
string FILE_PATH = getdetail.MAIN;
string url = String.Format(ResolveUrl(FILE_PATH));
string script = "window.open('" + url + "', '_blank','popup_window','width=700,height=600,left=100,top=100,resizable=false,oncontextmenu= return false');";
ClientScript.RegisterStartupScript(this.GetType(), "popUp", script, true);
}
}
}
Thank you.

Better approach in C# to search data on a third party web site

Here's my requirement. There is a public website which takes alphanumeric string as input and Retrieves data into a table element (via button click). The table element has couple of labels which gets populated with corresponding data. I need a tool/solution which can check if a particular string exists in the website's database. If so retrieve all the Ids of all the occurrences of that string. Looking at the "view source" of the website (No JavaScript used there), I noted the input element name and the button element name and with the help of existing samples I was able to get a working solution. Below is the code which works but I want to check if there is any better and faster approach. I know the below code has some issues like "infinite loop" issue and others. But I am basically looking at alternate solution which can work quickly for a million records.
namespace SearchWebSite
{
public partial class Form1 : Form
{
bool searched = false;
long i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = null;
if (searched == false)
{
b = (WebBrowser)sender;
b.Document.GetElementById("txtId").InnerText = "M" + i.ToString();
b.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
if (b.ReadyState == WebBrowserReadyState.Complete)
{
if (b.Document.GetElementById("lblName") != null)
{
string IdNo = "M" + i.ToString();
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
{
using (StreamWriter w = File.AppendText("log.txt"))
{
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
}
}
}
If the page after seach button clicked contains txtId and btnSearch controls than you can use this code snippet, this is not faster but the correct form I think.
public partial class Form1 : Form
{
bool searched = false;
long i = 1;
private string IdNo { get { return "M" + i.ToString(); } }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
if (b.ReadyState == WebBrowserReadyState. Complete)
{
if (searched == false)
{
DoSearch(b); return;
}
if (b.Document.GetElementById("lblName") != null)
{
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
using (StreamWriter w = File.AppendText("log.txt"))
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
}
i++;
DoSearch(b);
}
}
private void DoSearch(WebBrowser wb)
{
wb.Document.GetElementById("txtId").InnerText = IdNo;
wb.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
}

Categories

Resources