I wrote a bot in C#, I used Selenium.
Problem: When I start more threads at same time, the bot does the work in the first window. All of the e-mail addresses are being added to the "E-mail" textbox in the same window instead of one e-mail address per window.
But it should look like:
Start function: DivisionStart()
private void DivisionStart() {
foreach(var account in BotConfig.AccountList) {
while (CurrentBotThreads >= BotConfig.MaxLoginsAtSameTime) {
Thread.Sleep(1000);
}
StartedBotThreads++;
CurrentBotThreads++;
int startIndex = (StartedBotThreads * BotConfig.AdsPerAccount + 1) - BotConfig.AdsPerAccount - 1;
int stopIndex = BotConfig.AdsPerAccount * CurrentBotThreads;
if (stopIndex > BotConfig.ProductList.Count) {
stopIndex = BotConfig.ProductList.Count;
}
Debug.Print("Thread: " + StartedBotThreads);
var adList = GetAdListBy(startIndex, stopIndex);
foreach(var ad in adList) {
Debug.Print("Für thread: " + StartedBotThreads + " | Anzeige: " + ad.AdTitle);
}
Debug.Print("Parallel");
var ebayBotThread = new Thread(() => {
var botOptions = new IBotOptionsModel() {
CaptchaSolverApiKey = CaptchaSolverApiKey,
ReCaptchaSiteKey = "6LcZlE0UAAAAAFQKM6e6WA2XynMyr6WFd5z1l1Nr",
StartPageUrl = "https://www.ebay-kleinanzeigen.de/m-einloggen.html?targetUrl=/",
EbayLoginEmail = account.AccountEmail,
EbayLoginPassword = account.AccountPassword,
Ads = adList,
};
var ebayBot = new EbayBot(this, botOptions);
ebayBot.Start(StartedBotThreads);
Thread.Sleep(5000);
});
ebayBotThread.Start();
}
}
The class with function which will be executed in each thread:
using OpenQA.Selenium;
using Selenium.WebDriver.UndetectedChromeDriver;
using System.Diagnostics;
using TwoCaptcha.Captcha;
using System.Drawing;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
namespace EbayBot
{
class EbayBot
{
public Selenium.Extensions.SlDriver Driver;
private WebDriverHelper DriverHelper;
private Bot Sender;
private bool CaptchaSolved = false;
public IBotOptionsModel Options;
public EbayBot(Bot sender, IBotOptionsModel options)
{
Sender = sender;
Options = options;
}
public void Start(int threadIndex)
{
var chromeOptions = new ChromeOptions();
/*if (Sender.BotConfig.EnableProxy)
{
chromeOptions.AddHttpProxy(
Options.Proxy.IpAddress,
Options.Proxy.Port,
Options.Proxy.Username,
Options.Proxy.Password
);
}*/
Driver = UndetectedChromeDriver.Instance(null, chromeOptions);
DriverHelper = new WebDriverHelper(Driver);
string status = "";
Debug.Print("Bot-Thread: " + threadIndex);
Driver.Url = Options.StartPageUrl + Options.EbayLoginEmail;
PressAcceptCookiesButton();
Login();
if (!CaptchaSolved) return;
Driver.Wait(3);
if (LoginError() || !IsLoggedIn())
{
status = "Login für '" + Options.EbayLoginEmail + "' fehlgeschlagen!";
Debug.Print(status);
Sender.ProcessStatus = new IStatusModel(status, Color.Red);
return;
}
else
{
status = "Login für '" + Options.EbayLoginEmail + "' war erfolgreich!";
Debug.Print(status);
Sender.ProcessStatus = new IStatusModel(status, Color.Green);
}
Driver.Wait(5);
BeginFillFormular();
}
private bool CookiesAccepted()
{
try
{
var btnAcceptCookies = Driver.FindElement(By.Id(Config.PageElements["id_banner"]));
return btnAcceptCookies == null;
}
catch (Exception)
{
return true;
}
}
private void PressAcceptCookiesButton()
{
DriverHelper.WaitForElement(Config.PageElements["id_banner"], "", 10);
if (CookiesAccepted()) return;
var btnAcceptCookies = Driver.FindElement(By.Id(Config.PageElements["id_banner"]));
btnAcceptCookies.Click();
}
private bool IsLoggedIn()
{
Debug.Print("Check if logged in already");
try
{
var userEmail = Driver.FindElement(By.Id("user-email")).Text;
return userEmail.ToLower().Contains(Options.EbayLoginEmail);
}
catch (Exception)
{
return false;
}
}
private bool LoginError()
{
try
{
var loginErrorH1 = Driver.FindElements(By.TagName("h1"));
return loginErrorH1[0].Text.Contains("ungültig");
}
catch (Exception)
{
return false;
}
}
private void Login()
{
if (IsLoggedIn()) return;
string status = "Anmelden bei " + Options.EbayLoginEmail + "...";
Debug.Print(status);
Sender.ProcessStatus = Sender.ProcessStatus = new IStatusModel(status, Color.DimGray);
Driver.Wait(5);
var fieldEmail = Driver.FindElement(By.Id(Config.PageElements["id_login_email"]));
var fieldPassword = Driver.FindElement(By.Id(Config.PageElements["id_login_password"]));
var btnLoginSubmit = Driver.FindElement(By.Id(Config.PageElements["id_login_button"]));
fieldEmail.SendKeys(Options.EbayLoginEmail);
Driver.Wait(4);
fieldPassword.SendKeys(Options.EbayLoginPassword);
SolveCaptcha();
if (!CaptchaSolved)
{
return;
}
Debug.Print("Clicking login button");
btnLoginSubmit.Click();
}
public void BeginFillFormular()
{
Debug.Print("Formular setup, Inserate: " + Options.Ads.Count);
foreach (var adData in Options.Ads)
{
Debug.Print("Setting up formular for " + adData.AdTitle);
var adFormular = new AdFormular(Driver, adData, Options);
adFormular._EbayBot = this;
adFormular.CreateAd(Sender);
// 10 seconds
Debug.Print("Nächstes Insert für " + adData.AdTitle);
}
}
public string GetSolvedCaptchaAnswer(string captchaUrl = "")
{
string code = string.Empty;
var solver = new TwoCaptcha.TwoCaptcha(Options.CaptchaSolverApiKey);
var captcha = new ReCaptcha();
captcha.SetSiteKey(Options.ReCaptchaSiteKey);
captcha.SetUrl(captchaUrl == "" ? Options.StartPageUrl : captchaUrl);
try
{
solver.Solve(captcha).Wait();
code = captcha.Code;
}
catch (AggregateException e)
{
Sender.ProcessStatus = new IStatusModel("Captcha Api-Fehler: " + e.InnerExceptions.First().Message, Color.Red);
Driver.Wait(10);
}
return code;
}
public void SolveCaptcha(string captchaUrl = "")
{
Debug.Print("Solving captcha...");
var solvedCaptchaAnswer = GetSolvedCaptchaAnswer(captchaUrl);
if (solvedCaptchaAnswer == string.Empty)
{
Debug.Print("Captcha konnte nicht gelöst werden");
Sender.ProcessStatus = new IStatusModel("Captcha konnte nicht gelöst werden", Color.Red);
CaptchaSolved = false;
Driver.Wait(10);
return;
}
CaptchaSolved = true;
Debug.Print("Captcha answer: " + solvedCaptchaAnswer);
Driver.ExecuteScript("document.getElementById('g-recaptcha-response').innerHTML = '" + solvedCaptchaAnswer + "'");
Debug.Print("Captcha solved!");
Driver.Wait(2);
}
}
}
If I remove the Thread.Sleep(5000); in the DivisionStart function it will work, but I need it I actually want to wait for a found proxy but I simulated it with Thread.Sleep
How can I solve my problem?
Thanks for any answer!
I fixed it.
I used UndetectedChromeDriver wich does not use different ports.
I use another Undetected driver now.
Thank you all
Related
I have a program that needs to scan for other devices running my program on the network. The solution I came up with was to call each ipAddress to see if my program is running.
The code below is completely blocking the cpu:-
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FileWire
{
class SearchNearby
{
private bool pc_search_cancelled = false;
private SynchronizedCollection<Thread> PCSearchThreadList;
private ConcurrentDictionary<String, String> NearbyPCList;
public void NewPcFound(string s, string s1)
{
Console.WriteLine(string.Format("PC Found at: {0} PC Name: {1}", s, s1));
}
public SearchNearby()
{
startPCScan();
while (true)
{
bool isAnyAlive = false;
foreach(Thread t in PCSearchThreadList)
{
isAnyAlive |= t.IsAlive;
}
if (!isAnyAlive)
{
Console.WriteLine("Search Complete");
foreach (var a in NearbyPCList)
{
Console.WriteLine(a.Key + " ;; " + a.Value);
}
startPCScan();
}
Thread.Sleep(100);
}
}
private void startPCScan()
{
PCSearchThreadList = new SynchronizedCollection<Thread>();
NearbyPCList = new ConcurrentDictionary<String, String>();
pc_search_cancelled = false;
String add = "";
System.Net.IPAddress[] ad = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList;
foreach (System.Net.IPAddress ip in ad)
{
add += ip.ToString() + "\n";
}
bool connected;
if (add.Trim(' ').Length == 0)
{
connected = false;
}
else
{
connected = true;
}
if (connected)
{
try
{
String[] addresses = add.Split('\n');
foreach (String address in addresses)
{
int myIP = int.Parse(address.Substring(address.LastIndexOf(".") + 1));
for (int def = 0; def <= 10; def++)
{
int finalDef = def;
for (int j = 0; j < 10; j++)
{
string finalJ = j.ToString();
Thread thread = new Thread(new ThreadStart(() =>
{
if (!pc_search_cancelled)
{
for (int i = (finalDef * 25); i < (finalDef * 25) + 25 && i <= 255; i++)
{
if (!pc_search_cancelled)
{
if (i != myIP)
{
String callToAddress = "http://" + address.Substring(0, address.LastIndexOf(".")) + "." + i + ":" + (1234 + int.Parse(finalJ)).ToString();
String name = canGetNameAndAvatar(callToAddress);
if (name != null)
{
NearbyPCList[callToAddress] = name;
NewPcFound(callToAddress, name);
}
}
}
}
}
}));
PCSearchThreadList.Add(thread);
thread.Start();
}
}
}
} catch (Exception e) {
}
}
}
private String canGetNameAndAvatar(String connection)
{
String link = connection + "/getAvatarAndName";
link = link.Replace(" ", "%20");
try
{
var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(500);
var a = new Task<HttpResponseMessage>[1];
a[0] = client.GetAsync(link);
Task.WaitAll(a);
var b = a[0].Result.Content.ReadAsStringAsync();
Task.WaitAll(b);
Console.WriteLine(b.Result);
string result = b.Result;
result = result.Substring(result.IndexOf("<body>") + 6, result.IndexOf("</body>") - (result.IndexOf("<body>") + 6));
AvtarAndName json = JsonConvert.DeserializeObject<AvtarAndName>(result);
if (json != null)
{
return json.name;
}
}
catch
{
return null;
}
return null;
}
}
}
This is the exact C# version of the java code I was using in Java:-
import com.sun.istack.internal.Nullable;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class PCScan {
private static boolean pc_search_cancelled = false;
private static List<Thread> PCSearchThreadList;
private static HashMapWithListener<String, String> NearbyPCList;
public static void main(String[] args) {
start();
while (true) {
int numCompleted = 0;
for (Thread t : PCSearchThreadList) {
if (!t.isAlive()) {
numCompleted++;
}
}
if (numCompleted == PCSearchThreadList.size()) {
start();
}
}
}
private static void start() {
try {
startPCScan();
} catch (SocketException e) {
e.printStackTrace();
}
NearbyPCList.setPutListener(new HashMapWithListener.putListener() {
#Override
public void onPut(Object key, Object value) {
System.out.println(key.toString() + ";;" + value.toString());
}
});
}
private static void startPCScan() throws SocketException {
pc_search_cancelled = false;
PCSearchThreadList = new CopyOnWriteArrayList<>();
NearbyPCList = new HashMapWithListener<>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
boolean connected;
String add = "";
while (enumeration.hasMoreElements()) {
NetworkInterface interfacea = enumeration.nextElement();
if (!interfacea.isLoopback()) {
Enumeration<InetAddress> enumeration1 = interfacea.getInetAddresses();
while (enumeration1.hasMoreElements()) {
String address = enumeration1.nextElement().getHostAddress();
if (address.split("\\.").length == 4) {
add += address + "\n";
}
}
}
}
System.out.println(add);
connected = true;
if (connected) {
try {
String[] addresses = add.split("\n");
addresses = new HashSet<String>(Arrays.asList(addresses)).toArray(new String[0]);
for (String address : addresses) {
int myIP = Integer.parseInt(address.substring(address.lastIndexOf(".") + 1));
for (int def = 0; def <= 10; def++) {
int finalDef = def;
for (int j = 0; j < 10; j++) {
int finalJ = j;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
if (!pc_search_cancelled) {
for (int i = (finalDef * 25); i < (finalDef * 25) + 25 && i <= 255; i++) {
if (!pc_search_cancelled) {
if (i != myIP) {
String callToAddress = "http://" + address.substring(0, address.lastIndexOf(".")) + "." + i + ":" + String.valueOf(Integer.parseInt("1234") + finalJ);
String name = canGetNameAndAvatar(callToAddress);
if (name != null) {
NearbyPCList.put(callToAddress, name);
}
}
}
}
}
}
});
PCSearchThreadList.add(thread);
thread.start();
}
}
// }
// }).start();
}
} catch (Exception e) {
}
}
}
private static String canGetNameAndAvatar(String connection) {
String link = connection + "/getAvatarAndName";
link = link.replaceAll(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParams = client.getParams();
httpParams.setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 500);
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
String result = sb.toString();
result = result.substring(result.indexOf("<body>") + 6, result.indexOf("</body>"));
JSONObject json = new JSONObject(result);
if (json != null) {
return json.getString("name");
}
}
catch (Exception ignored){
return null;
}
return null;
}
static class HashMapWithListener<K, V> extends HashMap<K, V> {
private putListener PutListener;
public void setPutListener(putListener PutListener) {
this.PutListener = PutListener;
}
#Nullable
#Override
public V put(K key, V value) {
PutListener.onPut(key, value);
return super.put(key, value);
}
interface putListener {
public void onPut(Object key, Object value);
}
}
}
The java code runs absolutely fine and only uses about 20 percent cpu while c# code absolutely locks the PC. I tried Webclient, webrequest, httpClient. All have literally the same performance.
I need the code to be in c# as I can't include whole JRE in my program since it is too large. The rest of my program and GUI is in WPF format.
Also, I need the code to take a maximum of 50seconds while scanning ports 1234-1243. This code also works absolutely fine even on a midrange android phone. So, I don't know what the problem is.
I would suggest something like this (I've simplified it for the sake of an example):
private static HttpClient _client = new HttpClient() { Timeout = TimeSpan.FromMilliseconds(500) };
private async Task<Something> GetSomething(string url)
{
using (HttpResponseMessage response = await _client.GetAsync(url))
{
string json = await response.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Something>(json);
}
}
private async Task<Something[]> GetSomethings(string[] urls)
{
IEnumerable<Task<Something>> requestTasks = urls.Select(u => GetSomething(u));
Something[] results = await Task.WhenAll<Something>(requestTasks);
return results;
}
You should also make the method calling GetSomethings async, and await it, and do the same all the way up the call chain.
async/await uses a thread pool to execute, and the thread is actually suspended while the IO part of the request occurs, meaning that no CPU time is used during this period. When then IO part is done, it resumes the code at the await.
Related information:
Asynchronous programming documentation
How and when to use 'async' and 'await'
You are using threads and multithreading completely wrong.
Because I cannot really understand what you are trying to do because everything is cramped into one function, I cannot provide you with a more detailed solution.
But let me suggest the following: I understand, you want to execute some operation in the background connecting to some other computer, try something like this
var taskList = new List<Task>();
foreach (var pc in computers)
{
var currentPcTask = Task.Run(() => DoYourWorkForSomePcHere(pc));
taskList.Add(currentPcTask);
}
Task.WaitAll(taskList.ToArray());
This will be very CPU efficient.
Below is the function where I am trying to execute a function in the background and then carry on without waiting for a result from it.
When debugging the task itself is executed but the actual function within it does not. The rest of the code then carries on like normal.
What could be the issue as there is no error produced after that to indicate otherwise?
This is on a page load.
public ActionResult ExceptionReport(int? id)
{
var ExceptionList = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == id);
if (ExceptionList.Count() == 0)
{
globalInvoice.Status = "Exception Verification";
db.Entry(globalInvoice).State = EntityState.Modified;
db.SaveChanges();
Task.Run(() => ExceptionFinalTests(globalInvoice)); //Function To run in the background
TempData["warning"] = "Verifying all exceptions fixed. A notification will be sent when the verifications are complete.";
return RedirectToAction("Index", "GlobalInvoices");
}
return View(ExceptionList);
}
private void ExceptionFinalTests(GlobalInvoice globalInvoice)
{
RunTests(globalInvoice, true);
decimal TotalPaymentAmount = db.Invoices.Where(m => m.GlobalInvoiceID == globalInvoice.Id).Sum(m => m.Invoice_Amount) ?? 0;
}
GlobalInvoicesController globalInvoicesController = new GlobalInvoicesController();
var ApproverList = globalInvoicesController.GetUserEmailsInRole(globalInvoice, "Reviewer");
globalInvoicesController.Dispose();
var exceptionExistCompulsoryTest = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == globalInvoice.Id);
if (exceptionExistCompulsoryTest.Count() > 0)
{
try
{
string baseUrl = ConfigurationManager.AppSettings["site"];
EmailExtension emailExtension = new EmailExtension();
foreach (var approver in ApproverList)
{
string approvalLink = baseUrl + "/Invoices/ExceptionReport/" + globalInvoice.Id;
StringBuilder mailbody = new StringBuilder();
mailbody.AppendFormat("Hi<br/>");
mailbody.AppendFormat("There are " + exceptionExistCompulsoryTest.Count() + " exceptions for invoice #" + globalInvoice.Id + "that need attention before proceeding. - <a href='" + approvalLink + "'>Click Here</a> <br/><br/>");
mailbody.AppendFormat("Exception Count: {0}<br/>", exceptionExistCompulsoryTest.Count());
mailbody.AppendFormat("Invoice Amount: {0}<br/>", TotalPaymentAmount.ToString("C"));
mailbody.AppendFormat("Reviewed By: {0} <br/>", "");
mailbody.AppendFormat("Approved By: {0} <br/>", "");
EmailVM emailVM = new EmailVM()
{
Subject = "Invoice - #" + globalInvoice.Id,
EmailAddress = approver,
Message = mailbody.ToString()
};
emailExtension.SendEmail(emailVM);
}
}
catch (Exception ex)
{
LogWriter.WriteLog(ex.Message);
LogWriter.WriteLog(ex.StackTrace);
}
}
}
private void RunTests(GlobalInvoice globalInvoice, bool retestFlag = false)
{
List<Invoice> invoices;
var vendorTests = globalInvoice.Vendor.VendorTests;
string[] testsToRun = vendorTests.Split(',');
if (retestFlag == true)
{
if (globalInvoice.Vendor.VendorHasHierarchy == true)
{
testsToRun = new string[] { "Account Number", "Hierarchy" };
}
else
{
testsToRun = new string[] { "Account Number" };
}
}
using (var context = new MyContext())
{
invoices = context.Invoices.Where(m => m.GlobalInvoiceID == globalInvoiceToTestID).ToList();
}
foreach (var test in testsToRun)
{
if (test == "Account Number")
{
LogWriter.WriteLog("Starting Account Number Check : Invoice Batch ID - " + globalInvoice.Id);
AccountNumberCheck(invoices, globalInvoice.VendorID);
LogWriter.WriteLog("Account Number Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
if (test == "Hierarchy")
{
LogWriter.WriteLog("Starting Hierarchy Check : Invoice Batch ID - " + globalInvoice.Id);
BillingHierarchyCheck(invoices);
LogWriter.WriteLog("Hierarchy Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
}
}
I am having trouble with system.outofmemoryexception on my C# win application. I don't know the cause of the error. The computer memory is not freeing.
I am using visual studio 2017 and devexpress 2017 with Firebird 3 as my database.
here is a sample of my database procedures
CREATE PROCEDURE APP_INSERT(
WORKXP_PK INTEGER,
EMP_PK INTEGER,
APP_FRONT BLOB,
APP_BACK BLOB,
USER_PK SMALLINT,
APP_UPDATETIME TIMESTAMP)
AS
BEGIN
INSERT INTO APPOINTMENT (
WORKXP_PK,
EMP_PK,
APP_FRONT,
APP_BACK,
USER_PK,
APP_UPDATETIME)
VALUES (
:WORKXP_PK,
:EMP_PK,
:APP_FRONT,
:APP_BACK,
:USER_PK,
CURRENT_TIMESTAMP);
END;
CREATE PROCEDURE APP_UPDATE(
APP_FRONT BLOB,
APP_BACK BLOB,
USER_PK SMALLINT,
APP_UPDATETIME TIMESTAMP,
WORKXP_PK INTEGER)
AS
BEGIN
UPDATE APPOINTMENT
SET
APP_FRONT = :APP_FRONT,
APP_BACK = :APP_BACK,
USER_PK = :USER_PK,
APP_UPDATETIME = CURRENT_TIMESTAMP
WHERE
(WORKXP_PK = :WORKXP_PK);
END;
And here is a sample of my c# class
using DevExpress.XtraEditors;
using FirebirdSql.Data.FirebirdClient;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
namespace DepEdZDSMS.Class
{
class ClsAppointmntPic : IDisposable
{
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
FirebirdService.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public MemoryStream APP_FRONT { get; set; }
public MemoryStream APP_BACK { get; set; }
public void UpdateAppImage()
{
byte[] x = null; //front image
byte[] y = null; //back image
try
{
var adder = new FbConnection(ClsConnectionImages.FirebirdSQL);
var fbcmd = new FbCommand("APP_UPDATE", adder)
{
CommandType = CommandType.StoredProcedure
};
if (APP_FRONT != null) x = APP_FRONT.ToArray();
fbcmd.Parameters.Add("#APP_FRONT", FbDbType.Binary).Value = x;
if (APP_BACK != null) y = APP_BACK.ToArray();
fbcmd.Parameters.Add("#APP_BACK", FbDbType.Binary).Value = y;
fbcmd.Parameters.Add("#USER_PK", FbDbType.SmallInt).Value = ClsEmployee.USER_PK;
fbcmd.Parameters.Add("#APP_UPDATETIME", FbDbType.VarChar).Value = EventTimestamp;
fbcmd.Parameters.Add("#WORKXP_PK", FbDbType.VarChar).Value = ClsEmployee.UpdateHandler2;
fbcmd.Connection.Open();
fbcmd.ExecuteNonQuery();
fbcmd.Connection.Close();
}
catch (Exception errorcode)
{
XtraMessageBox.Show(String.Format("Error in connection: {0}. Saving failed.", errorcode.Message), #"Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public void SaveAppImage() //122
{
byte[] x = null; //front image
byte[] y = null; //back image
try
{
var adder = new FbConnection(ClsConnectionImages.FirebirdSQL);
var fbcmd = new FbCommand("APP_INSERT", adder)
{
CommandType = CommandType.StoredProcedure
};
fbcmd.Parameters.Add("#WORKXP_PK", FbDbType.VarChar).Value = ClsEmployee.UpdateHandler2;
fbcmd.Parameters.Add("#EMP_PK", FbDbType.VarChar).Value = ClsEmployee.UpdateHandler;
if (APP_FRONT != null) x = APP_FRONT.ToArray();
fbcmd.Parameters.Add("#APP_FRONT", FbDbType.Binary).Value = x;
if (APP_BACK != null) y = APP_BACK.ToArray();
fbcmd.Parameters.Add("#APP_BACK", FbDbType.Binary).Value = y;
fbcmd.Parameters.Add("#USER_PK", FbDbType.SmallInt).Value = ClsEmployee.USER_PK;
fbcmd.Parameters.Add("#APP_UPDATETIME", FbDbType.VarChar).Value = EventTimestamp;
fbcmd.Connection.Open();
fbcmd.ExecuteNonQuery();
fbcmd.Connection.Close();
}
catch (Exception errorcode)
{
XtraMessageBox.Show(String.Format("Error in connection: {0}. Saving failed.", errorcode.Message), #"Server Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public ClsAppointmntPic(int refID)
{
try
{
var app = new ClsAppointmntPic();
var x = new DataSet();
var y = new FbDataAdapter();
var f = new FbCommand("IMAGE_APPOINTMENT", FirebirdService);
f.Parameters.Add("#X", FbDbType.Integer).Value = refID;
f.CommandType = CommandType.StoredProcedure;
y.SelectCommand = f;
y.Fill(x, "APPOINTMENT");
if (x.Tables[0].Rows.Count > 0)
{
var fx = x.Tables[0].Rows[0];
if (!fx["APP_FRONT"].Equals(DBNull.Value))
{
var i = (byte[])fx["APP_FRONT"];
var fx2 = new MemoryStream(i);
APP_FRONT = fx2;
}
if (!fx["APP_BACK"].Equals(DBNull.Value))
{
var j = (byte[])fx["APP_BACK"];
var fx2 = new MemoryStream(j);
APP_BACK = fx2;
}
}
app.FirebirdService.Close();
}
catch (Exception e)
{
XtraMessageBox.Show(#"Error: " + e.Message, #"DepEdZDSUIS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public ClsAppointmntPic()
{
// TODO: Complete member initialization
}
private void Openconnection()
{
if (FirebirdService.State == ConnectionState.Open)
{
FirebirdService.Close();
}
FirebirdService.Open();
}
private void Closeconnection()
{
FirebirdService.Close();
}
private static readonly string Firebird = ClsConnectionImages.FirebirdSQL;
/// <summary>
///
/// </summary>
private readonly FbConnection FirebirdService = new FbConnection(Firebird);
}
}
and also I used public static string and int frequently and some arrays
public static int sdsapprove_ref = 0;
public static string sdsapprove_word = "";
public static string[] reasonReg = new string[] { "Deceased", "Promoted to", "Retired", "Resigned",
"Transferred to"};
in my main view form I use this code in displaying data
private void GetWorkXPList()
{
picAppFront.Image = Properties.Resources.no_image;
picAppBack.Image = Properties.Resources.no_image;
ClsEmployee.UpdateHandler2 = "0";
gridControl2.DataSource = ClsEmployee.WorkXP_SrvcRcrdListing();
gridView2.OptionsSelection.InvertSelection = false;
gridView2.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView2.OptionsSelection.EnableAppearanceFocusedRow = true;
}
public void GetAppointmentImage()
{
int getID = Convert.ToInt32(ClsEmployee.UpdateHandler2);
var f = new ClsAppointmntPic(getID);
if (f.APP_FRONT != null)
{
var i = new Bitmap(f.APP_FRONT);
picAppFront.Image = i;
}
else
{
picAppFront.Image = Properties.Resources.no_image;
}
if (f.APP_BACK != null)
{
var j = new Bitmap(f.APP_BACK);
picAppBack.Image = j;
}
else
{
picAppBack.Image = Properties.Resources.no_image;
}
}
and in my save/update form, i use this codes when saving and editing
private void UpdateWorXP()
{
var adder = new ClsEmployee()
{
WORKXP_DATEFROM = dateFrom.Text,
WORKXP_DATETO = dateTo.Text,
WORKXP_PRESENT = ifPresent,
WORKXP_POSITION = txtPosition.Text,
WORKXP_ABBR = txtAbb.Text,
WORKXP_ITMENUM = txtItemNo.Text,
WORKXP_AGENCY = txtAgency.Text,
WORKXP_STATION = txtStation.Text,
WORKXP_BRANCH = txtBranch.Text,
WORKXP_SLRYGRD = txtSG.Text,
WORKXP_INCRMNT = cboxIncrmnt.Text,
WORKXP_SALARYANN = txtAnnual.Text,
WORKXP_SALARYMON = txtMonthly.Text,
WORKXP_STATUS = cboxStatus.Text,
WORKXP_GOVORPRIV = cboxGov.Text,
WORKXP_CAUSE = cboxCause.Text,
WORKXP_AMOUNT = Convert.ToDecimal(txtAmount.Text),
};
adder.EditWorkXP();
adder.UpdateLog();
//UpdateEmpLatestApp();
XtraMessageBox.Show("Successfully Updated.", "Update ",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
ClsEmployee.UpdateHandler2 = "0";
switch (ClsArray.Reference)
{
case 1:
obj1.loaddata();
break;
case 2:
obj2.loaddata();
break;
case 3:
obj3.loaddata2();
break;
}
this.Close();
}
private void AddNewWorkXP()
{
var adder = new ClsEmployee()
{
WORKXP_DATEFROM = dateFrom.Text,
WORKXP_DATETO = dateTo.Text,
WORKXP_PRESENT = ifPresent,
WORKXP_POSITION = txtPosition.Text,
WORKXP_ABBR = txtAbb.Text,
WORKXP_ITMENUM = txtItemNo.Text,
WORKXP_AGENCY = txtAgency.Text,
WORKXP_STATION = txtStation.Text,
WORKXP_BRANCH = txtBranch.Text,
WORKXP_SLRYGRD = txtSG.Text,
WORKXP_INCRMNT = cboxIncrmnt.Text,
WORKXP_SALARYANN = txtAnnual.Text,
WORKXP_SALARYMON = txtMonthly.Text,
WORKXP_STATUS = cboxStatus.Text,
WORKXP_GOVORPRIV = cboxGov.Text,
WORKXP_CAUSE = cboxCause.Text,
WORKXP_AMOUNT = Convert.ToDecimal(txtAmount.Text),
};
adder.SaveWorkXP();
adder.UpdateLog();
//UpdateEmpLatestApp();
XtraMessageBox.Show("Successfully Saved.", "Save ",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
ClsEmployee.UpdateHandler2 = "0";
switch (ClsArray.Reference)
{
case 1:
obj1.loaddata();
break;
case 2:
obj2.loaddata();
break;
case 3:
obj3.loaddata2();
break;
}
this.Close();
}
Been looking at this for the past few days now and I'm no closer to a solution. The code below is based on the CortanaVoiceCommand sample at https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/CortanaVoiceCommand and the code works perfectly on desktop but the background task is crashing on mobile each time.
In OnTaskCanceled the BackgroundTaskCancellationReason always reports as SystemPolicy but I'm no closer to finding a solution.
Appreciate any help anyone can suggest.
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.VoiceCommands;
namespace TramTimesVoice
{
public sealed class VoiceCommandService : IBackgroundTask
{
private BackgroundTaskDeferral backgroundTaskDeferral;
private IEnumerable services;
private Service service;
private Stop stop;
private VoiceCommandServiceConnection voiceCommandServiceConnection;
public async void Run(IBackgroundTaskInstance taskInstance)
{
backgroundTaskDeferral = taskInstance.GetDeferral();
taskInstance.Canceled += OnTaskCanceled;
AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService")
{
try
{
voiceCommandServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
voiceCommandServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;
VoiceCommand voiceCommand = await voiceCommandServiceConnection.GetVoiceCommandAsync();
if (voiceCommand.CommandName == "getServices")
{
await SendCompletionMessageForServices(voiceCommand.Properties["stop"][0]);
}
else
{
LaunchAppInForeground();
}
}
catch (Exception ex)
{
throw new Exception("Handling Voice Command Failed: " + ex.ToString());
}
}
}
private async void LaunchAppInForeground()
{
VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
userMessage.SpokenMessage = "Launching Tram Times";
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage);
response.AppLaunchArgument = "";
await voiceCommandServiceConnection.RequestAppLaunchAsync(response);
}
private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
if (backgroundTaskDeferral != null)
{
backgroundTaskDeferral.Complete();
}
}
private void OnVoiceCommandCompleted(VoiceCommandServiceConnection sender, VoiceCommandCompletedEventArgs args)
{
if (backgroundTaskDeferral != null)
{
backgroundTaskDeferral.Complete();
}
}
private async Task SendCompletionMessageForServices(String input)
{
await ShowProgressScreen("Working On It");
IEnumerable stops = new Stops().Get();
foreach (Stop item in stops)
{
if (input == item.Voice)
{
stop = new Stop()
{
Code = item.Code,
Name = item.Name,
Latitude = item.Latitude,
Longitude = item.Longitude,
ApiCodes = item.ApiCodes,
City = item.City,
Lines = item.Lines,
Voice = item.Voice
};
break;
}
}
if (stop.City == "Blackpool")
{
services = await new Blackpool().Get(stop.ApiCodes);
}
else if (stop.City == "Edinburgh")
{
services = await new Edinburgh().Get(stop.ApiCodes);
}
else if (stop.City == "London")
{
services = await new London().Get(stop.ApiCodes);
}
else if (stop.City == "Manchester")
{
services = await new Manchester().Get(stop.ApiCodes);
}
else if (stop.City == "Midland")
{
services = await new Midland().Get(stop.ApiCodes);
}
else if (stop.City == "Nottingham")
{
services = await new Nottingham().Get(stop.ApiCodes);
}
else if (stop.City == "Sheffield")
{
services = await new Sheffield().Get(stop.ApiCodes);
}
ObservableCollection<Service> data = new ObservableCollection<Service>();
foreach (Service item in services)
{
if (item.DestinationScheduled != null)
{
service = new Service()
{
Destination = item.Destination,
DestinationRealtime = item.DestinationRealtime,
DestinationRealtimeFull = item.DestinationRealtimeFull,
DestinationScheduled = item.DestinationScheduled,
DestinationScheduledFull = item.DestinationScheduledFull
};
data.Add(service);
}
else
{
service = new Service()
{
Destination = item.Destination,
DestinationRealtime = item.DestinationRealtime,
DestinationRealtimeFull = item.DestinationRealtimeFull,
DestinationScheduled = item.DestinationRealtime,
DestinationScheduledFull = item.DestinationRealtimeFull
};
data.Add(service);
}
}
data = new ObservableCollection<Service>(data.OrderBy(service => service.DestinationScheduledFull).ThenBy(service => service.Destination));
VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
userMessage.DisplayMessage = "I Found These Services";
userMessage.SpokenMessage = "I found these services from " + stop.Voice + ". ";
Collection<VoiceCommandContentTile> tiles = new Collection<VoiceCommandContentTile>();
VoiceCommandContentTile tile = new VoiceCommandContentTile();
tile.AppLaunchArgument = stop.Name;
tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
tile.Title = stop.Name;
if (data.Count > 0)
{
if (data[0].DestinationRealtime != null)
{
tile.TextLine1 = data[0].DestinationRealtime + " " + data[0].Destination;
userMessage.SpokenMessage += data[0].DestinationRealtime + " to " + data[0].Destination + ". ";
}
else
{
tile.TextLine1 = data[0].DestinationScheduled + " " + data[0].Destination;
userMessage.SpokenMessage += data[0].DestinationScheduled + " to " + data[0].Destination + ". ";
}
}
if (data.Count > 1)
{
if (data[1].DestinationRealtime != null)
{
tile.TextLine2 = data[1].DestinationRealtime + " " + data[1].Destination;
userMessage.SpokenMessage += data[1].DestinationRealtime + " to " + data[1].Destination + ". ";
}
else
{
tile.TextLine2 = data[1].DestinationScheduled + " " + data[1].Destination;
userMessage.SpokenMessage += data[1].DestinationScheduled + " to " + data[1].Destination + ". ";
}
}
if (data.Count > 2)
{
if (data[2].DestinationRealtime != null)
{
tile.TextLine3 = data[2].DestinationRealtime + " " + data[2].Destination;
userMessage.SpokenMessage += data[2].DestinationRealtime + " to " + data[2].Destination + ". ";
}
else
{
tile.TextLine3 = data[2].DestinationScheduled + " " + data[2].Destination;
userMessage.SpokenMessage += data[2].DestinationScheduled + " to " + data[2].Destination + ". ";
}
}
tiles.Add(tile);
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, tiles);
response.AppLaunchArgument = "";
await voiceCommandServiceConnection.ReportSuccessAsync(response);
}
private async Task ShowProgressScreen(String message)
{
var userProgressMessage = new VoiceCommandUserMessage();
userProgressMessage.DisplayMessage = message;
userProgressMessage.SpokenMessage = message;
VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userProgressMessage);
await voiceCommandServiceConnection.ReportProgressAsync(response);
}
}
}
While sending email via System.Net.Mail to multiple recipients (one single email with multiple recipients), if one recipients address fail, will the rest reach the email?
There might be duplicates of the same question, but I'm asking something different in contrast.
For prompting such question, I was taken into consideration of Email clients available like Outlook where such does not happen even if one single address failed. Perhaps, System.Net.Mail is a lightweight client and does not allow such functionality? Or is it the way I'm writing my code incorrectly.
I was asked as if why this happens, hope I can get an explanation so that I can pass it by.
I was running such a scenario from my code below:
public void sendBusinessEmail(communication.email.business.config.BusinessEmailList[] aEmailList)
{
System.Net.Mail.MailMessage objMsg = null;
string[] aEmail = null;
System.Net.Mail.SmtpClient objSmtpClient = null;
int iRetries = 0;
if (aEmailList == null)
{
return;
}
try
{
if (Properties.Settings.Default.IS_SMTP_TLS)
{
objSmtpClient = getSMTP_TLS_Client();
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
}
else
{
objSmtpClient = getSMTP_Default_Client();
}
foreach (communication.email.business.config.BusinessEmailList obj in aEmailList)
{
try
{
objMsg = new System.Net.Mail.MailMessage();
objMsg.From = new System.Net.Mail.MailAddress("jkstock#keells.com", "JKSB Business Services");
aEmail = obj.Emails;
if (Properties.Settings.Default.TO_TEST_EMAIL)
{
objMsg.To.Add(Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString());
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.Body += aEmail[i] + Environment.NewLine;
}
}
else
{
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.To.Add(new System.Net.Mail.MailAddress(aEmail[i]));
}
objMsg.Body = obj.EmailBody;
}
objMsg.Subject = checkAllReadySent(obj.EmailSubject);
objMsg.Attachments.Add(new System.Net.Mail.Attachment(obj.AttachmentPath, (System.IO.Path.GetExtension(obj.AttachmentPath) == ".pdf" ? System.Net.Mime.MediaTypeNames.Application.Pdf : System.Net.Mime.MediaTypeNames.Application.Octet)));
//sending emails
//send for 5 times if error persists, unless otherwise success
for (int i = 0; i < 5; i++)
{
try
{
objSmtpClient.Send(objMsg);
obj.updateLog("OK", (i+1));
break;
}
catch (Exception e)
{
if (i == 4)
{
obj.updateLog(e.Message, (i+1));
}
}
}
objMsg = null;
}
catch (System.Net.Mail.SmtpFailedRecipientsException e0)
{
obj.updateLog("Invalid Recipient(s)",0);
}
catch (Exception e1)
{
obj.updateLog("Error",0);
}
}
objSmtpClient = null;
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
objMsg = null;
objSmtpClient = null;
}
}
References for the above code:
public abstract class BusinessEmailList
{
private string _accountid = string.Empty;
private string _attachmentPath = string.Empty;
private string _emailsubject = string.Empty;
private string _agentid = string.Empty;
private string _response = string.Empty;
private string _ccTo = string.Empty;
private string _bccTo = string.Empty;
protected string _additionalBody = string.Empty;
private string[] _aEmail = null;
public string AccountID
{
get { return _accountid; }
set { _accountid = value; }
}
public string AgentID
{
get { return _agentid; }
set { _agentid = value; }
}
public string Response
{
get { return _response; }
set { _response = value; }
}
public string AttachmentPath
{
get { return _attachmentPath; }
set
{
if (System.IO.File.Exists(value))
{
_attachmentPath = value;
}
else { throw (new Exception("Attachment Not Found")); }
}
}
public string EmailSubject
{
get { return _emailsubject; }
set { _emailsubject = value; }
}
public string[] Emails
{
get { return getEmail(); }
}
public string EmailBody
{
get { return getMsgBody(); }
set { _additionalBody = value; }
}
public string ccTo
{
get { return _ccTo; }
set { _ccTo = value; }
}
public string bccTo
{
get { return _bccTo; }
set { _bccTo = value; }
}
public virtual string[] getEmail()
{
return null;
}
public virtual string getMsgBody()
{
if (System.IO.Path.GetExtension(this.AttachmentPath) == ".pdf")
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"To view the attached PDF files you need Adobe Acrobat Reader installed in your computer. Download Adobe Reader from http://get.adobe.com/reader/ " +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
else
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
}
public void updateLog(string status, int retries)
{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "JKSBSCHEMA.EMAILLOG_ADD_PROC";
string[] aEmail = this.Emails;
OracleParameter p = null;
foreach (string s in aEmail)
{
cmd.Parameters.Clear();
p = new OracleParameter("pemail", OracleType.VarChar);
p.Value = s;
cmd.Parameters.Add(p);
p = new OracleParameter("psubject", OracleType.VarChar);
p.Value = this.EmailSubject;
cmd.Parameters.Add(p);
p = new OracleParameter("pattachement", OracleType.VarChar);
p.Value = this.AttachmentPath;
cmd.Parameters.Add(p);
p = new OracleParameter("presponse", OracleType.VarChar);
p.Value = status;
cmd.Parameters.Add(p);
p = new OracleParameter("pseqno", OracleType.Number);
p.Direction = ParameterDirection.InputOutput;
p.Value = "0";
cmd.Parameters.Add(p);
p = new OracleParameter("pretries", OracleType.Number);
p.Value = retries;
cmd.Parameters.Add(p);
oracleConn.Open();
cmd.ExecuteNonQuery();
oracleConn.Close();
}
}
}
catch (Exception er)
{
this.Response = er.Message;
}
}
}
public class BusinessClientEmailList : BusinessEmailList
{
public override string[] getEmail()
{
string[] aEmail;
//if (Properties.Settings.Default.TO_TEST_EMAIL == false)
//{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
string sql = "SELECT EMAIL " +
"FROM " +
"(" +
"SELECT A.EMAIL AS EMAIL " +
"FROM JKSBSCHEMA.AGENTEMAIL A " +
"WHERE A.AGENTID = '" + this.AgentID + "' " +
"AND A.AGENTID != 'JKSB' "+
"AND A.ISACTIVE = 1 " +
"UNION " +
"SELECT B.EMAILID AS EMAIL " +
"FROM JKSBSCHEMA.CLIENTACCOUNTEMAIL B " +
"WHERE B.CLIENTACCOUNTID = '" + this.AccountID + "' " +
"AND B.IS_CONFIRMATION = 1 " +
") " +
"GROUP BY EMAIL";
int i = 0;
DataTable tbl = new DataTable();
OracleCommand cmd = new OracleCommand(sql, oracleConn);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(tbl);
aEmail = new string[tbl.Rows.Count];
foreach (DataRow rw in tbl.Rows)
{
aEmail[i] = rw[0].ToString();
i++;
}
}
}
catch (Exception)
{
aEmail = null;
}
//}
//else
//{
// aEmail = new string[1];
// aEmail[0] = Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString();
//}
return aEmail;
}
public override string getMsgBody()
{
return base.getMsgBody();
}
}