I have written a small program that basically works on a SWITCH statement. It reads each case within the switch statement and calls and executes the appropriate functions. But, I am facing a problem that, all the functions are getting executed when the first case of the switch statement is getting called. It should not be the case because only that function which is called by a particular switch-case statement should be executed. Can some one suggest me what is wrong with my code? Posting my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using System.ComponentModel;
using System.ServiceModel.Security;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using Excel1.MWMClient.MWMServiceProxy;
namespace Excel1
{
class WebServiceFunctions
{
private string siteID = "INDIA";
static TemplateClient templateClient;
static TaskClient taskClient;
public WebServiceFunctions()
{
templateClient = new Excel1.MWMClient.MWMServiceProxy.TemplateClient();
templateClient.ClientCredentials.UserName.UserName = "admin";
templateClient.ClientCredentials.UserName.Password = "admin";
templateClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
taskClient = new Excel1.MWMClient.MWMServiceProxy.TaskClient();
taskClient.ClientCredentials.UserName.UserName = "admin";
taskClient.ClientCredentials.UserName.Password = "admin";
taskClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
}
public void GetAllTemplateNames(String strSite, String strRetVal)
{
//GetAllTemplateNames
Console.WriteLine("Invoking GetAllTemplate method");
Console.WriteLine("List of all templates with details");
Console.WriteLine("-----------------------------------");
List<Excel1.MWMClient.MWMServiceProxy.TemplateData> tData = templateClient.GetAllTemplate(strSite).ToList();
foreach (Excel1.MWMClient.MWMServiceProxy.TemplateData data in tData)
{
Console.WriteLine("TemplateName:" + data.name);
Console.WriteLine("TemplateDescription:" + data.description);
Console.WriteLine("SiteName:" + data.site_name);
Console.WriteLine("-----------------------------------");
}
Console.WriteLine("-----------------------------------");
}
public List<TemplateData> ReturnAllTemplateNames()
{
// Console.WriteLine("Invoking GetAllTemplate method");
// Console.WriteLine("List of all templates with details");
// Console.WriteLine("-----------------------------------");
List<Excel1.MWMClient.MWMServiceProxy.TemplateData> tData = templateClient.GetAllTemplate(siteID).ToList();
foreach (Excel1.MWMClient.MWMServiceProxy.TemplateData data in tData)
{
Console.WriteLine("TemplateName:" + data.name);
Console.WriteLine("TemplateDescription:" + data.description);
Console.WriteLine("SiteName:" + data.site_name);
Console.WriteLine("-----------------------------------");
}
Console.WriteLine("-----------------------------------");
return tData;
}
public void GetTaskInstanceFromTemplate(Excel1.MWMClient.MWMServiceProxy.TemplateData data)
{
Console.WriteLine("Invoking GetTaskInstanceFromTemplate method");
Console.WriteLine("-----------------------------------");
Excel1.MWMClient.MWMServiceProxy.TaskInstance tInstance = taskClient.GetTaskInstanceFromTemplate(siteID, data);
if (tInstance != null)
{
Console.WriteLine("TaskName: " + tInstance.name);
Console.WriteLine("TaskDescription :" + tInstance.description);
}
Console.WriteLine("-----------------------------------");
}
public TaskInstance ReturnTaskInstanceFromTemplate(Excel1.MWMClient.MWMServiceProxy.TemplateData data)
{
Console.WriteLine("Invoking GetTaskInstanceFromTemplate method");
Console.WriteLine("-----------------------------------");
Excel1.MWMClient.MWMServiceProxy.TaskInstance tInstance = taskClient.GetTaskInstanceFromTemplate(siteID, data);
if (tInstance != null)
{
Console.WriteLine("TaskName: " + tInstance.name);
Console.WriteLine("TaskDescription :" + tInstance.description);
}
Console.WriteLine("----------------------" + tInstance.name + "-------------");
return tInstance;
}
public int CreateTask(Excel1.MWMClient.MWMServiceProxy.TaskInstance instance)
{
Console.WriteLine("Invoking CreateTask method");
Console.WriteLine("-----------------------------------");
int retVal = taskClient.CreateTask(instance);
Console.WriteLine("Task create successfully:ID=" + retVal.ToString());
Console.WriteLine("-----------------------------------");
return retVal;
}
public void GetTaskStatus(int taskId)
{
Console.WriteLine("Invoking GetTaskStatus method");
Console.WriteLine("------------------****-----------------");
Excel1.MWMClient.MWMServiceProxy.TaskStatus taskStatus = new Excel1.MWMClient.MWMServiceProxy.TaskStatus();
taskStatus = taskClient.GetTaskStatus(taskId);
Console.WriteLine("Task status : " + taskStatus.taskStatus.ToString());
Console.WriteLine("-----------------------------------");
}
public void PerformTaskOperation(int taskId, string operation, String reason)
{
Console.WriteLine("PerformTaskOperation method");
Console.WriteLine("-----------------------------------");
int operationStatusCode = 0;
operationStatusCode = taskClient.PerformTaskOperation(taskId, operation, reason);
String updateSuccess = operationStatusCode == 1 ? "update success" : "update failed";
Console.WriteLine("Returned Operation Status Code = " + operationStatusCode + "|| Updation status message:" + updateSuccess);
}
//public void GetTaskHistory(int taskId, int detailLevel)
//{
// Console.WriteLine("Invoking GetTaskHistory method");
// Console.WriteLine("------------------*****-----------------");
// Excel1.MWMClient.MWMServiceProxy.TaskHistory taskHistory = new Excel1.MWMClient.MWMServiceProxy.TaskHistory();
// taskHistory = taskClient.GetTaskHistory(taskId, detailLevel);
// if (taskHistory.listOfAllowedActions != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskAllowedAction allowedAction in taskHistory.listOfAllowedActions)
// {
// Console.WriteLine("Task History - allowedAction : " + allowedAction.actionName);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.listOfCustomAttributes != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskCustomAttributes customAttribute in taskHistory.listOfCustomAttributes)
// {
// Console.WriteLine("Custom Attribute : " + customAttribute.key + " | Value:" + customAttribute.value);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskinstanceEscalations != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskEscaltion taskEscaltion in taskHistory.taskinstanceEscalations)
// {
// Console.WriteLine("Task Escaltion : " + taskEscaltion.escalationLevel + " | escalationType : " + taskEscaltion.escalationType);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskInstanceUsers != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskUser taskUser in taskHistory.taskInstanceUsers)
// {
// Console.WriteLine("Task User : " + taskUser.firstName + " , " + taskUser.lastName);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskInstanceGroups != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskGroup group in taskHistory.taskInstanceGroups)
// {
// Console.WriteLine("Group : " + group.groupName + "| escalationLevel : " + group.escalationLevel);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskInstanceSkills != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskSkill skill in taskHistory.taskInstanceSkills)
// {
// Console.WriteLine("Skill : " + skill.skillName + "| description : " + skill.description);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskStatusList != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskStatus taskStatus in taskHistory.taskStatusList)
// {
// Console.WriteLine("TaskStatus : " + taskStatus.taskStatus);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.userTaskInstanceList != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.UserTaskInstance userTaskInstance in taskHistory.userTaskInstanceList)
// {
// Console.WriteLine("UserTaskInstance status: " + userTaskInstance.status);
// Console.WriteLine("-----------------------------------");
// }
// //taskHistory.listOfAllowedActions
//}
public void CreateTaskFromTemplate(Excel1.MWMClient.MWMServiceProxy.TemplateData data)
{
//taskClient.ClientCredentials.UserName.UserName = "USR";
//taskClient.ClientCredentials.UserName.Password = "PWD";
//taskClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
Console.WriteLine("Invoking CreateTaskFromTemplate method");
Console.WriteLine("------------------***-----------------");
int taskId = taskClient.CreateTaskFromTemplate(siteID, data);
Console.WriteLine("Created task from template with TaskId: " + taskId);
Console.WriteLine("-----------------------------------");
}
};
class Program
{
static WebServiceFunctions wsf = new WebServiceFunctions();
public static void Main(string[] args)
{
//
//Initializing the excel sheet
//
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"D:/WebServiceTemplate.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
//
//Getting row count, column count and the number of sheets
//
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
int numSheets = xlWorkbook.Sheets.Count;
//
// Iterate through the sheets. They are indexed starting at 1.
//
for (int row = 2; row <= rowCount; row++)
{
//
// Do something with the data in the array with a custom method.
//
String strRetVal = xlRange.Cells[row, 3].Value;
String strFunctionName = xlRange.Cells[row, 4].Value;
String strParam1 = xlRange.Cells[row, 6].Value;
String strParam2 = xlRange.Cells[row, 7].Value;
String strParam3 = xlRange.Cells[row, 8].Value;
String strParam4 = xlRange.Cells[row, 9].Value;
TemplateData tData = new TemplateData();
TaskInstance tInstance = new TaskInstance();
int tID = 0;
ProcessInput(strRetVal, strFunctionName, strParam1, strParam2, strParam3, strParam4, tData, tInstance, tID);
//creating a task from templates in one flow
//1)Get all templates.
List<Excel1.MWMClient.MWMServiceProxy.TemplateData> templateDataList = new List<TemplateData>();
//bool createTaskFromTemplate_Flag = false;
templateDataList = wsf.ReturnAllTemplateNames();
//if (createTaskFromTemplate_Flag)
//{
// foreach (TemplateData templateDataInst in templateDataList)
// {
// //We are not using the method CreateTaskFromTemplate for this application
// //WebServiceFunctions.CreateTaskFromTemplate(templateDataInst);
// }
//}
bool createTaskForAll = false;
if (createTaskForAll)
{
foreach (TemplateData templateDataInst in templateDataList)
{
//2)Get task instance
TaskInstance taskInstance = new TaskInstance();
taskInstance = wsf.ReturnTaskInstanceFromTemplate(templateDataInst);
taskInstance.scheduleActivity = new ScheduleActivity();
taskInstance.scheduleActivity.nextRun = new DateTime();
taskInstance.scheduleActivity.isRecurring = 0;
//over riding taskType in task
taskInstance.taskType = "pull";
//3)Create task.
wsf.CreateTask(taskInstance);
}
}
else
{
int numberOfTemplatesReturned = templateDataList.Count();
Random random = new Random();
int randomTemplateInList = random.Next(0, numberOfTemplatesReturned);
Console.WriteLine("Random number from template list:" + randomTemplateInList);
TemplateData templateDataInstance = new TemplateData();
templateDataInstance = templateDataList.ElementAt(randomTemplateInList);
//2)Get task instance
TaskInstance taskInstance = new TaskInstance();
taskInstance = wsf.ReturnTaskInstanceFromTemplate(templateDataInstance);
// 3)Create task.
tID = wsf.CreateTask(taskInstance);
wsf.GetTaskStatus(tID);
//int detailLevel = 2;
// Console.WriteLine("Task History for a newly created task would contain minimal details.");
// Console.WriteLine("Run method with taskId of a task which has gone through various phases to see detailed history.");
// wsf.GetTaskHistory(tID, detailLevel);
}
// Console.WriteLine("Updating status via update task status");
//wsf.PerformTaskOperation(tID, "DELETE", "trying pauseeee");
// Console.WriteLine("Press Enter To Exit Client Application.");
Console.ReadLine();
}
}
public static void ProcessInput(String strRetVal, String strFunctionName, /*String strParamCount,*/ String strParam1, String strParam2, String strParam3, String strParam4, TemplateData tData, TaskInstance tInstance, int tID)
{
switch (strFunctionName)
{
case "ITemplate.GetAllTemplate":
{
//ITemplate.GetAllTemplate code
MessageBox.Show("ITemplate.GetAllTemplate");
wsf.GetAllTemplateNames(strParam1, strRetVal);
break;
}
case "ITask.GetTaskInstanceFromTemplate":
{
//ITask.GetTaskInstanceFromTemplate code
MessageBox.Show("ITask.GetTaskInstanceFromTemplate");
wsf.GetTaskInstanceFromTemplate(tData);
break;
}
case "CreateTask":
{
//CreateTask code
MessageBox.Show("CreateTask");
wsf.CreateTask(tInstance);
break;
}
case "UpdateDatabase":
{
//UpdateDatabase code
MessageBox.Show("UpdateDatabase");
break;
}
case "GetTaskStatus":
{
//GetTaskStatus code
MessageBox.Show("GetTaskStatus");
wsf.GetTaskStatus(tID);
break;
}
case "VerifyValue":
{
//VerifyValue code
MessageBox.Show("VerifyValue");
}
break;
}
}
};
}
The call to ProcessInput() is in a loop. Have you run this in debug? That switch should work. Are you sure a SINGLE call to ProcessInput runs all the case conditions?
Related
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
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.
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);
}
}
}
I read this article , I want to get sent bytes and receive bytes for all process, but sent bytes and receive bytes of all process always return 0;
Here is my code:
namespace Network
{
public class NetworkTraffic
{
private List<PerformanceCounter> listBytesSentPerformanceCounter;
private List<PerformanceCounter> listBytesReceivedPerformanceCounter;
//private PerformanceCounter bytesSentPerformanceCounter;
//private PerformanceCounter bytesReceivedPerformanceCounter;
public NetworkTraffic()
{
listBytesSentPerformanceCounter = new List<PerformanceCounter>();
listBytesReceivedPerformanceCounter = new List<PerformanceCounter>();
List<string> listInstanceName = GetInstanceName();
foreach (string str in listInstanceName)
{
PerformanceCounter bytesSentPerformanceCounter = new PerformanceCounter();
PerformanceCounter bytesReceivedPerformanceCounter = new PerformanceCounter();
bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
bytesSentPerformanceCounter.CounterName = "Bytes Sent";
bytesSentPerformanceCounter.InstanceName = str;
bytesSentPerformanceCounter.ReadOnly = false;
listBytesSentPerformanceCounter.Add(bytesSentPerformanceCounter);
bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
bytesReceivedPerformanceCounter.InstanceName = str;
bytesReceivedPerformanceCounter.ReadOnly = false;
listBytesReceivedPerformanceCounter.Add(bytesReceivedPerformanceCounter);
}
}
//public float GetBytesSent()
//{
// float bytesSent = bytesSentPerformanceCounter.RawValue;
// return bytesSent;
//}
//public float GetBytesReceived()
//{
// float bytesReceived = bytesReceivedPerformanceCounter.RawValue;
// return bytesReceived;
//}
private static List<string> GetInstanceName()
{
// Used Reflector to find the correct formatting:
string assemblyName = GetAssemblyName();
if ((assemblyName == null) || (assemblyName.Length == 0))
{
assemblyName = AppDomain.CurrentDomain.FriendlyName;
}
StringBuilder builder = new StringBuilder(assemblyName);
for (int i = 0; i < builder.Length; i++)
{
switch (builder[i])
{
case '/':
case '\\':
case '#':
builder[i] = '_';
break;
case '(':
builder[i] = '[';
break;
case ')':
builder[i] = ']';
break;
}
}
List<string> listInstanceName = new List<string>();
Process[] listProcess = Process.GetProcesses();
string InstanceName;
foreach (Process pro in listProcess)
{
InstanceName = string.Format(CultureInfo.CurrentCulture,
"{0}[{1}]",
builder.ToString(),
pro.Id);
listInstanceName.Add(InstanceName);
}
return listInstanceName;
}
private static string GetAssemblyName()
{
string str = null;
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
AssemblyName name = entryAssembly.GetName();
if (name != null)
{
str = name.Name;
}
}
return str;
}
public static void Main()
{
NetworkTraffic networkTraffic = new NetworkTraffic();
try
{
while (true)
{
WebRequest webRequest = WebRequest.Create("http://www.google.com");
webRequest.Method = "GET";
using (WebResponse response = webRequest.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
}
//Console.WriteLine("Bytes sent: {0}", networkTraffic.GetBytesSent());
//Console.WriteLine("Bytes received: {0}", networkTraffic.GetBytesReceived());
foreach (PerformanceCounter send in networkTraffic.listBytesSentPerformanceCounter)
{
Console.WriteLine("Instance name: " + send.InstanceName + " Sent: " + send.RawValue);
}
Thread.Sleep(1000);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
Anyone can help me resolve this.
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();
}
}