C# threading + timer + windows. Why Task live only 30 minutes? - c#

Today I encountered a problem. When I use cmd application , create thread with Task.Factory than my Task live only 30 minutes. I tried create with nssm - background service in windows. But this service work only 30 minutes. I solved this problem, when use main thread and synchronic programming. But I don't have idea for what my task live only === 30 minutes. I think GC, but ....
For example code:
Task.Factory.StartNew(() =>
{
string Milliseconds = builder.Configuration["DefaultParams:CheckingTime"];
try
{
var hetmanClient = Hetman.Instance;
int MS = Int32.Parse(Milliseconds);
Timer aTimer = new Timer((object? o) =>
{
CheckNewFileInFolder(app.Environment);
}, null, 0, MS);
}
catch
{
PrintToFile.PrintToFileAndConsole("Wrong number in params: DefaultParams:CheckingTime");
}
})
void CheckNewFileInFolder(IWebHostEnvironment appEnvironment)
{
PrintToFile.PrintToFileAndConsole($"Checking new record in folder");
string path = appEnvironment.WebRootPath + #"\ReceivedXMLs";
string[] NewFiles = Directory.GetFiles(path);
foreach(var i in NewFiles)
{
string NextPath = appEnvironment.WebRootPath + #"\AddedToDBXMLs" + i.Replace(path, "");
string text = File.ReadAllText(i);
try
{
string queryString = $"JUST SQL";
PrintToFile.PrintToFileAndConsole(queryString);
OdbcCommand command = new OdbcCommand(queryString, instance.conn);
int result = command.ExecuteNonQuery();
PrintToFile.PrintToFileAndConsole("Result code from database: " + result);
File.Move(i, NextPath);
}
catch(Exception ex)
{
PrintToFile.PrintToFileAndConsole("ERROR: " + ex.Message);
}
}
}
public class PrintToFile
{
private static PrintToFile instance = null;
private PrintToFile() {}
public static PrintToFile Instance
{
get
{
if (instance == null)
{
instance = new PrintToFile();
}
return instance;
}
}
private static readonly object _lock = new object();
public static string path = string.Empty;
public void Create(IWebHostEnvironment appEnvironment)
{
path = appEnvironment.WebRootPath + #"\Logging\Log.txt";
}
public static void PrintToFileAndConsole(string text)
{
lock (_lock)
{
Console.WriteLine(DateTime.Now + " : " + text);
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None))
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine(DateTime.Now + " : " + text);
}
}
}
}
Answer Why my task lived only 30 minutes

Related

Multithreaded Selenium Bot does not work correctly

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

WebRequests in C# are very CPU Intensive. Need something better

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.

C# ClientWebSocket not receiving all packets?

I've built a windows service that subscribes to around 10,000 stock tickers in real-time using ClientWebSocket. If I subscribe to 1,000 tickers I receive all the data points as I should (receiving few hundred messages a second), as soon as I get up to 2,000 tickers I don't seem to be receiving the data I should be, 10,000 (receiving thousands of messages a second) its even worse. I've run comparison reports and it looks like I'm losing up to 60% of the packets. I've talked to polygon (the provider of the real-time data) about this issue and they claim their Socket is a firehose and everything that should go out, goes out, and that none of their other clients are complaining. So the only logical thing here would to be to assume its my code, or some limitation. Maybe it's the Task portion of the Receive method? Maybe window's has a max task limitation and I'm exceeding it.
I've also tested this on a high powered dedicated server with 10gb connection so it doesnt seem to be a connection or hardware limitation.
I've also by passed my BlockingCollection cache and the problem still persisted.
Hopefully one of you has some insight, thank you!
Here's my code:
public static ConcurrentDictionary<string, TradeObj> TradeFeed = new ConcurrentDictionary<string, TradeObj>();
public static ConcurrentDictionary<string, QuoteObj> QuoteFeed = new ConcurrentDictionary<string, QuoteObj>();
public static ConcurrentDictionary<string, AggObj> AggFeed = new ConcurrentDictionary<string, AggObj>();
public static BlockingCollection<byte[]> packets = new BlockingCollection<byte[]>();
private static void Start(string[] args)
{
try
{
Polygon.StartSub();
int HowManyConsumers = 2;
for (int i = 0; i < HowManyConsumers; i++)
{
Task.Factory.StartNew(Polygon.ConsumePackets);
}
} catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
public static async Task StartSub()
{
do
{
using (var socket = new ClientWebSocket())
try
{
// socket.Options.KeepAliveInterval = TimeSpan.Zero;
var Connection = "wss://socket.polygon.io/stocks";
await socket.ConnectAsync(new Uri(Connection), CancellationToken.None);
Console.WriteLine("Websocket opened to Polygon.");
await Send(socket, "{\"action\":\"auth\",\"params\":\""+ConfigurationManager.AppSettings["PolygonAPIToken"]+"\"}");
List<List<string>> batches = new List<List<string>>();
for (int i = 0; i < FeedCache.Tickers.Count(); i += 500)
{
var tempList = new List<string>();
tempList.AddRange(FeedCache.Tickers.Skip(i).Take(500));
batches.Add(tempList);
}
int bNum = 0;
string[] quoteStrings = new string[batches.Count()];
foreach (var tList in batches)
{
var tQuery = "";
tQuery = tQuery + "T." + string.Join(",T.", tList.ToArray());
tQuery = tQuery + ",A." + string.Join(",A.", tList.ToArray());
tQuery = tQuery + ",Q." + string.Join(",Q.", tList.ToArray());
quoteStrings[bNum] = tQuery;
bNum++;
}
for (int i = 0; i < quoteStrings.Count(); i++)
{
string SubscribeString = "{\"action\":\"subscribe\",\"params\":\"" + quoteStrings[i] + "\"}";
await Send(socket, SubscribeString);
}
await Receive(socket);
}
catch (Exception ex)
{
Console.WriteLine($"ERROR - {ex.Message}");
Console.WriteLine(ex.ToString());
}
} while (true);
}
static async Task Send(ClientWebSocket socket, string data)
{
var segment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(data));
await socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
}
static async Task Receive(ClientWebSocket socket)
{
do {
WebSocketReceiveResult result;
var buffer = new ArraySegment<byte>(new byte[2000]);
using (var ms = new MemoryStream())
{
do
{
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
} while (!result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Close)
{
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closed in server by the client", CancellationToken.None);
Console.WriteLine("Socket disconnecting, trying to reconnect.");
await StartSub();
}
else
{
packets.Add(ms.ToArray());
}
}
} while (true);
}
public static async void ConsumePackets()
{
foreach (var buffer in packets.GetConsumingEnumerable())
{
using (var ms = new MemoryStream(buffer))
{
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var data = await reader.ReadToEndAsync();
try
{
var j = JArray.Parse(data);
if (j != null)
{
string id = (string)j[0]["ev"];
switch (id)
{
case "T":
AddOrUpdateTrade((string)j[0]["sym"], j);
break;
case "Q":
AddOrUpdateQuote((string)j[0]["sym"], j);
break;
case "A":
AddOrUpdateAgg((string)j[0]["sym"], j);
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
public static void AddOrUpdateTrade(string ticker, JArray data)
{
TradeFeed.AddOrUpdate(ticker, new TradeObj {
LastPrice = (double)data[0]["p"],
TradeCount = 1
}, (key, existingVal) =>
{
return new TradeObj {
LastPrice = (double)data[0]["p"],
TradeCount = existingVal.TradeCount + 1,
PriceDirection = (double)data[0]["p"] < existingVal.LastPrice ? "D" : "U"
};
});
}
public static void AddOrUpdateAgg(string ticker, JArray data)
{
AggFeed.AddOrUpdate(ticker, new AggObj
{
TickVolume = (long)data[0]["v"],
VolumeShare = (long)data[0]["av"],
OpenPrice = (double)data[0]["op"],
TickAverage = (double)data[0]["a"],
VWAP = (double)data[0]["vw"],
TickClosePrice = (double)data[0]["c"],
TickHighPrice = (double)data[0]["h"],
TickLowPrice = (double)data[0]["l"],
TickOpenPrice = (double)data[0]["o"]
}, (key, existingVal) =>
{
return new AggObj
{
TickVolume = (long)data[0]["v"],
VolumeShare = (long)data[0]["av"],
OpenPrice = (double)data[0]["op"],
TickAverage = (double)data[0]["a"],
VWAP = (double)data[0]["vw"],
TickClosePrice = (double)data[0]["c"],
TickHighPrice = (double)data[0]["h"],
TickLowPrice = (double)data[0]["l"],
TickOpenPrice = (double)data[0]["o"]
};
});
}
public static void AddOrUpdateQuote(string ticker, JArray data)
{
QuoteFeed.AddOrUpdate(ticker, new QuoteObj
{
BidPrice = (double)data[0]["bp"],
BidSize = (double)data[0]["bs"],
AskPrice = (double)data[0]["ap"],
AskSize = (double)data[0]["as"]
}, (key, existingVal) =>
{
return new QuoteObj
{
BidPrice = (double)data[0]["bp"],
BidSize = (double)data[0]["bs"],
AskPrice = (double)data[0]["ap"],
AskSize = (double)data[0]["as"]
};
});
}

C# SuperWebSocket Max connection number 100 was reached

I write program using SuperWebsocket i Library , but my connections more than 100 connections result message is : Max connection number 100 was reached ! how can i increase number of connections ?
I didn't test it, but the WebSocketServer class has a Config property.
It is of type IServerConfig, which has a property MaxConnectionNumber.
(The default value is 100).
The WebSocketServer class has a method Setup, which takes an IServerConfig as parameter.
The following code shows how to change MaxConnectionNumber.
class Program
{
protected static WebSocketServer wsServer { get; private set; }
static void Main(string[] args)
{
wsServer = new WebSocketServer();
var config = new ServerConfig();
config.Port = 8088;
config.Ip = "Any";
config.Mode = SocketMode.Tcp;
config.MaxConnectionNumber = 1000;
config.Name = "ChatServer";
config.ReceiveBufferSize = 16384;
config.SendBufferSize = 1024;
var rootConfig = new RootConfig() { };
var ret = wsServer.Setup(rootConfig, config, null, null, new ConsoleLogFactory(), null, null);
if (!ret)
{
throw new Exception("Server is not setup correctly");
}
else
{
wsServer.NewSessionConnected += wsServer_NewSessionConnected;
wsServer.NewMessageReceived += wsServer_NewMessageReceived;
wsServer.NewDataReceived += wsServer_NewDataReceived;
wsServer.SessionClosed += wsServer_SessionClosed;
wsServer.Start();
int maxConn = wsServer.Config.MaxConnectionNumber;
Console.WriteLine("Server is running on port " + config.Port + ". Max Connection is " + maxConn.ToString() + ". Press Enter to exit...");
Console.ReadKey();
wsServer.Stop();
}
}
static void wsServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine("NewSessionConnected");
}
static void wsServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
Console.WriteLine("sessionClosed");
}
static void wsServer_NewDataReceived(WebSocketSession session, byte[] value)
{
Console.WriteLine("NewDataReceived");
}
static void wsServer_NewMessageReceived(WebSocketSession session, string value)
{
Console.WriteLine("NewMessageReceived: " + value);
}
}

Switch-case statement not working as expected

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?

Categories