C# Multi threading not starting worker/job? - c#

For some reason my threads are ignoring my job, it looks like anyone have any sort of idea why it is doing this? Help is very welcome and extremely appreciated, thank you. What this program is, is a ProxyChecker, because i've bought a bunch and will continue to do so of proxies with different user/passes etc, however some have expired
static List<String> user = new List<String>();
static List<String> pass = new List<String>();
static List<String> ips = new List<String>();
static Random rnd = new Random();
static void Main(string[] args)
{
int threads = 4;
loadips();
Console.WriteLine("Enter the amount of threads to run (4 default):");
threads = Int32.Parse(Console.ReadLine());
Console.WriteLine("Starting on " + threads + " threads...");
for (int i = 0; i < threads; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CheckProxy), i);
}
//Console.ReadLine();
}
public class MyIP
{
public string IP { get; set; }
public bool AcceptsConnection { get; set; }
}
private static void CheckProxy(object state)
{
var u = user[0];
var p = pass[0];
var l = new List<MyIP>();
Parallel.ForEach(l.ToArray(), (item) =>
{
string ip = getip();
try
{
using (var client = new ProxyClient(ip, u, p))
{
Console.WriteLine(ip, user, pass);
client.Connect();
item.AcceptsConnection = client.IsConnected;
}
}
catch
{
l.Remove(item);
}
});
foreach (var item in l)
{
if (item.AcceptsConnection == true)
{
WriteToFile(user[0], pass[0]);
}
Console.WriteLine(item.IP + " is " + (item.AcceptsConnection) + " accepts connections" + " doesn not accept connections");
}
}
private static void loadips()
{
using (TextReader tr = new StreamReader("ips.txt"))
{
string line = null;
while ((line = tr.ReadLine()) != null)
{
ips.Add(line);
}
}
}

You didn't understand my code example... You should add the IP's to the list l, instead of a getip() method... So lose the getip() method
private static void CheckProxy(object state)
{
var u = user[0];
var p = pass[0];
var l = new List<MyIP>();
l.Add(new MyIP { IP = "192.168.1.1" });
l.Add(new MyIP { IP = "192.168.1.2" });
l.Add(new MyIP { IP = "192.168.1.3" });
Parallel.ForEach(l.ToArray(), (ip_item) =>
{
try
{
using (var client = new ProxyClient(ip_item, u, p))
{
Console.WriteLine(ip_item, user, pass);
client.Connect();
item.AcceptsConnection = client.IsConnected;
}
}
catch
{
lock(l)
l.Remove(item);
}
});
foreach (var item in l)
{
if (item.AcceptsConnection == true)
{
WriteToFile(user[0], pass[0]);
}
Console.WriteLine(item.IP + " is " + (item.AcceptsConnection) + " accepts connections" + " doesn not accept connections");
}
}

Related

How can i handle and how should i handle exception The remote server returned an error: (500) Internal Server Error?

The exception is happen most of the times but there are times it's working fine.
The exception is always the same
The remote server returned an error: (500) Internal Server Error.
Also the stacktrace is the same:
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadData(Uri address)
at System.Net.WebClient.DownloadData(String address)
at SatelliteImages.ExtractImages.ExtractDateAndTime(String baseAddress) in D:\C-Sharp\SatelliteImages\SatelliteImages\SatelliteImages\ExtractImages.cs:line 120
Line 120 is:
var temp = wc.DownloadData("/en");
The method:
public void ExtractDateAndTime(string baseAddress)
{
try
{
var wc = new WebClient();
wc.BaseAddress = baseAddress;
HtmlDocument doc = new HtmlDocument();
var temp = wc.DownloadData("/en");
doc.Load(new MemoryStream(temp));
var secTokenScript = doc.DocumentNode.Descendants()
.Where(e =>
String.Compare(e.Name, "script", true) == 0 &&
String.Compare(e.ParentNode.Name, "div", true) == 0 &&
e.InnerText.Length > 0 &&
e.InnerText.Trim().StartsWith("var region")
).FirstOrDefault().InnerText;
var securityToken = secTokenScript;
securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
foreach (var date in scriptDates)
{
DatesAndTimes.Add(date.DateString);
}
}
catch(WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
}
}
}
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
this.Init();
}
}
When I use a breakpoint on the line:
string error = reader.ReadToEnd();
I see html content and in the content I see the text:
error occurred while processing your request. Return to the homepage of Sat24.com
What I want to do is somehow when the exception happen to start over again and try the download try the method ExtractDateAndTime.
I think using a timer some how and count back showing the user something like 30 seconds and try again. Will 30 seconds try will be consider as spam/flooding in the server site ?
This is the full class code but the exception is on this method ExtractDateAndTime.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Xml;
using HtmlAgilityPack;
using System.ComponentModel;
namespace SatelliteImages
{
class ExtractImages
{
static WebClient client;
static string htmltoextract;
public static List<string> countriescodes = new List<string>();
public static List<string> countriesnames = new List<string>();
public static List<string> DatesAndTimes = new List<string>();
public static List<string> imagesUrls = new List<string>();
static string firstUrlPart = "http://www.sat24.com/image2.ashx?region=";
static string secondUrlPart = "&time=";
static string thirdUrlPart = "&ir=";
public class ProgressEventArgs : EventArgs
{
public int Percentage { get; set; }
public string StateText { get; set; }
}
public event EventHandler<ProgressEventArgs> ProgressChanged;
public void Init()
{
object obj = null;
int index = 0;
ExtractCountires();
foreach (string cc in countriescodes)
{
// raise event here
ProgressChanged?.Invoke(obj,new ProgressEventArgs{ Percentage = 100 * index / countriescodes.Count, StateText = cc });
ExtractDateAndTime("http://www.sat24.com/image2.ashx?region=" + cc);
index +=1;
}
ImagesLinks();
}
public void ExtractCountires()
{
try
{
htmltoextract = "http://sat24.com/en/?ir=true";//"http://sat24.com/en/";// + regions;
client = new WebClient();
client.DownloadFile(htmltoextract, #"c:\temp\sat24.html");
client.Dispose();
string tag1 = "<li><a href=\"/en/";
string tag2 = "</a></li>";
string s = System.IO.File.ReadAllText(#"c:\temp\sat24.html");
s = s.Substring(s.IndexOf(tag1));
s = s.Substring(0, s.LastIndexOf(tag2) + tag2.ToCharArray().Length);
s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
string[] parts = s.Split(new string[] { tag1, tag2 }, StringSplitOptions.RemoveEmptyEntries);
string tag3 = "<li><ahref=\"/en/";
for (int i = 0; i < parts.Length; i++)
{
if (i == 17)
{
//break;
}
string l = "";
if (parts[i].Contains(tag3))
l = parts[i].Replace(tag3, "");
string z1 = l.Substring(0, l.IndexOf('"'));
if (z1.Contains("</ul></li><liclass="))
{
z1 = z1.Replace("</ul></li><liclass=", "af");
}
countriescodes.Add(z1);
countriescodes.GroupBy(n => n).Any(c => c.Count() > 1);
string z2 = parts[i].Substring(parts[i].LastIndexOf('>') + 1);
if (z2.Contains("&"))
{
z2 = z2.Replace("&", " & ");
}
countriesnames.Add(z2);
countriesnames.GroupBy(n => n).Any(c => c.Count() > 1);
}
}
catch (Exception e)
{
if (countriescodes.Count == 0)
{
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
Init();
}
}
}
public void ExtractDateAndTime(string baseAddress)
{
try
{
var wc = new WebClient();
wc.BaseAddress = baseAddress;
HtmlDocument doc = new HtmlDocument();
var temp = wc.DownloadData("/en");
doc.Load(new MemoryStream(temp));
var secTokenScript = doc.DocumentNode.Descendants()
.Where(e =>
String.Compare(e.Name, "script", true) == 0 &&
String.Compare(e.ParentNode.Name, "div", true) == 0 &&
e.InnerText.Length > 0 &&
e.InnerText.Trim().StartsWith("var region")
).FirstOrDefault().InnerText;
var securityToken = secTokenScript;
securityToken = securityToken.Substring(0, securityToken.IndexOf("arrayImageTimes.push"));
securityToken = secTokenScript.Substring(securityToken.Length).Replace("arrayImageTimes.push('", "").Replace("')", "");
var dates = securityToken.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var scriptDates = dates.Select(x => new ScriptDate { DateString = x });
foreach (var date in scriptDates)
{
DatesAndTimes.Add(date.DateString);
}
}
catch(WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
}
}
}
countriescodes = new List<string>();
countriesnames = new List<string>();
DatesAndTimes = new List<string>();
imagesUrls = new List<string>();
this.Init();
}
}
public class ScriptDate
{
public string DateString { get; set; }
public int Year
{
get
{
return Convert.ToInt32(this.DateString.Substring(0, 4));
}
}
public int Month
{
get
{
return Convert.ToInt32(this.DateString.Substring(4, 2));
}
}
public int Day
{
get
{
return Convert.ToInt32(this.DateString.Substring(6, 2));
}
}
public int Hours
{
get
{
return Convert.ToInt32(this.DateString.Substring(8, 2));
}
}
public int Minutes
{
get
{
return Convert.ToInt32(this.DateString.Substring(10, 2));
}
}
}
public void ImagesLinks()
{
int cnt = 0;
foreach (string countryCode in countriescodes)
{
cnt++;
for (; cnt < DatesAndTimes.Count(); cnt++)
{
string imageUrl = firstUrlPart + countryCode + secondUrlPart + DatesAndTimes[cnt] + thirdUrlPart + "true";
imagesUrls.Add(imageUrl);
if (cnt % 10 == 0) break;
}
}
}
}
}
What i want is in case of the exception happen to start over clean over again the whole class operation.
In Form1 i start the class operation first time once:
In top:
ExtractImages ei = new ExtractImages();
Then in constructor:
ei.Init();
The problem is this exception that sometimes happen.
You could go with something like Polly or the Transient Fault Handling Application Block to apply a retry strategy to your code.
Both packages provide multiple out-of-the-box components for various scenarios and you can always develop you own. Some of the included retry policies:
Incremental
Fixed interval
Exponential back-off
Retry
Retry for ever
Retry and wait
Wait and retry for ever
...

Can't send udp packet with pcapdotnet

My code has shown below:
i already setup winpcap too. There arent any problem with programs which used by pcapdotnet
i think problem should be in layers but i dont know very well.
Console.Write("\r IP:Port = ");
string[] answer = Console.ReadLine().Split(':');
//answer[0] = ip , answer[1] = port
Console.WriteLine(answer[0] + "-"+answer[1]);
Attack_Void(answer[0], Convert.ToInt32(answer[1]));
Console.ReadKey();
}
private static void Attack_Void (string ip,int port)
{
try
{
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
PacketDevice selectedDevice = allDevices[0];
Console.WriteLine(selectedDevice.Description);
PacketCommunicator communicator = selectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);
while (true)
{
Thread tret = new Thread(() => Attack_Thread(communicator, ip, port));
tret.Start();
tret.Join();
tret.Abort();
}
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private static void Attack_Thread(PacketCommunicator comm,string ip,int port)
{
string rnd_ip = random_ip();
comm.SendPacket(UdpPacket(rnd_ip,ip,port,false,100));
//comm.SendPacket(Udp_Pack_2());
PacketCounter++;
Console.WriteLine("Veriler {0} ip adresine, {1} ip adresinden gönderildi. NO: {2} ",ip,rnd_ip,Convert.ToString(PacketCounter));
}
private static string random_ip()
{
string srcip = rnd.Next(0, 255) + "." + rnd.Next(0, 255) + "." + rnd.Next(0, 255) + "." + rnd.Next(0, 255);
return srcip;
}
private static Packet UdpPacket(string src_ip, string rem_ip, int rem_port, bool default_port, int src_port)
{
int port;
if (default_port == true)
{
port = src_port;
} else { port = rnd.Next(0, 65535); }
EthernetLayer ethernetLayer = new EthernetLayer {
Source = new MacAddress("48:E2:44:5E:A8:07"),
Destination = new MacAddress("48:E2:44:5E:A8:07") };
IpV4Layer ipv4Layer = new IpV4Layer
{
// Source = new IpV4Address(src_ip),
Source = new IpV4Address("127.0.0.1"),
CurrentDestination = new IpV4Address(rem_ip),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null, // Will be filled automatically.
Identification = 123,
Options = IpV4Options.None,
Protocol = null,
Ttl = 100,
TypeOfService = 0,
};
UdpLayer udpLayer =
new UdpLayer
{
SourcePort = (ushort)port,
DestinationPort = (ushort)rem_port, //port
Checksum = null,
CalculateChecksumValue = true,
};
PayloadLayer payloadLayer =
new PayloadLayer
{
Data = new Datagram(new byte[] { 0x28 }),
};
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipv4Layer, udpLayer, payloadLayer);
return builder.Build(DateTime.Now);
}
These are my code i actually made a udp server to take packet from this program but i cant send packet.
Also it doesnt give any errors.
And i dont know if my network modem enabled spoofing
Try this but remember it works only with IPv4.
using PcapDotNet.Core;
using PcapDotNet.Core.Extensions;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace UDP
{
public static class NetworkDevice
{
private static string GetLocalMachineIpAddress()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
throw new Exception("Network is not available. Please check connection to the internet.");
}
using (Socket socket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address.ToString();
}
}
public static PacketDevice GetIpv4PacketDevice()
{
string localMachineIpAddress = GetLocalMachineIpAddress();
IEnumerable<LivePacketDevice> ipV4adapters = LivePacketDevice.AllLocalMachine.Where(w =>
(w.Addresses.Select(s => s.Address.Family))
.Contains(SocketAddressFamily.Internet));
foreach (var adapter in ipV4adapters)
{
var adapterAddresses = adapter.Addresses
.Where(w => w.Address.Family == SocketAddressFamily.Internet)
.Select(s => ((IpV4SocketAddress)s.Address).Address.ToString());
if (adapterAddresses.Contains(localMachineIpAddress))
return adapter;
}
throw new ArgumentException("System didn't find any adapter.");
}
}
public static class DefaultGateway
{
private static IPAddress GetDefaultGateway()
{
return NetworkInterface
.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up)
.SelectMany(n => n.GetIPProperties()?.GatewayAddresses)
.Select(g => g?.Address)
.FirstOrDefault(a => a != null);
}
private static string GetMacAddressFromResultOfARPcommand(string[] commandResult, string separator)
{
string macAddress = commandResult[3].Substring(Math.Max(0, commandResult[3].Length - 2))
+ separator + commandResult[4] + separator + commandResult[5] + separator + commandResult[6]
+ separator + commandResult[7] + separator
+ commandResult[8].Substring(0, 2);
return macAddress;
}
public static string GetMacAddress(char separator = ':')
{
IPAddress defaultGateway = GetDefaultGateway();
if (defaultGateway == null)
{
throw new Exception("System didn't find the default gateway.");
}
string defaultGatewayIpAddress = defaultGateway.ToString();
return GetMacAddress(defaultGatewayIpAddress, separator);
}
public static string GetMacAddress(string ipAddress, char separator)
{
Process process = new Process();
process.StartInfo.FileName = "arp";
process.StartInfo.Arguments = "-a " + ipAddress;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
string strOutput = process.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length <= 8)
{
throw new Exception("System didn't find the default gateway mac address.");
}
return GetMacAddressFromResultOfARPcommand(substrings, separator.ToString());
}
}
public class UdpProcessor
{
private string _destinationMacAddress;
private string _destinationIPAddress;
private ushort _destinationPort;
private string _sourceMacAddress;
private string _sourceIPAddress;
private ushort _sourcePort;
private static LivePacketDevice _device = null;
public UdpProcessor(string destinationIp)
{
_sourcePort = 55555;
_destinationPort = 44444;
_device = NetworkDevice.GetIpv4PacketDevice() as LivePacketDevice;
_destinationIPAddress = destinationIp;
_sourceIPAddress = _device.Addresses[1].Address.ToString().Split(' ')[1]; //todo
_sourceMacAddress = (_device as LivePacketDevice).GetMacAddress().ToString();
_destinationMacAddress = DefaultGateway.GetMacAddress();
}
private EthernetLayer CreateEthernetLayer()
{
return new EthernetLayer
{
Source = new MacAddress(_sourceMacAddress),
Destination = new MacAddress(_destinationMacAddress),
EtherType = EthernetType.None,
};
}
private IpV4Layer CreateIpV4Layer()
{
return new IpV4Layer
{
Source = new IpV4Address(_sourceIPAddress),
CurrentDestination = new IpV4Address(_destinationIPAddress),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null,
Identification = 123,
Options = IpV4Options.None,
Protocol = null,
Ttl = 100,
TypeOfService = 0,
};
}
private UdpLayer CreateUdpLayer()
{
return new UdpLayer
{
SourcePort = _sourcePort,
DestinationPort = _destinationPort,
Checksum = null,
CalculateChecksumValue = true,
};
}
public void SendUDP()
{
EthernetLayer ethernetLayer = CreateEthernetLayer();
IpV4Layer ipV4Layer = CreateIpV4Layer();
UdpLayer udpLayer = CreateUdpLayer();
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer);
using (PacketCommunicator communicator = _device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.SendPacket(builder.Build(DateTime.Now));
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("\r IP:Port = ");
string ipAddress = Console.ReadLine();
new UdpProcessor(ipAddress).SendUDP();
Console.ReadKey();
}
}
}
Result in wireshark:

Is my PLINQ code threadsafe?

I have the following code:
static void Main(string[] args)
{
DateTime currentDay = DateTime.Now;
List<Task> taskList = new List<Task>();
List<string> markets = new List<string>() { "amex", "nasdaq", "nyse", "global" };
Parallel.ForEach(markets, market =>
{
Downloads.startInitialMarketSymbolsDownload(market);
}
);
Console.WriteLine("All downloads finished!");
}
public static void startInitialMarketSymbolsDownload(string market)
{
try
{
object valueTypeLock = new object();
List<string> symbolList = new List<string>() { "GOOG", "YHOO", "AAP" }
var historicalGroups = symbolList.AsParallel().Select((x, i) => new { x, i })
.GroupBy(x => x.i / 100)
.Select(g => g.Select(x => x.x).ToArray());
historicalGroups.AsParallel().ForAll(g => {
lock (valueTypeLock) {
getHistoricalStockData(g, market);
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public static void getHistoricalStockData(string[] symbols, string market)
{
// download data for list of symbols and then upload to db tables
Uri uri;
string url, line;
decimal open = 0, high = 0, low = 0, close = 0, adjClose = 0;
DateTime date;
Int64 volume = 0;
string[] lineArray;
List<string> symbolError = new List<string>();
Dictionary<string, string> badNameError = new Dictionary<string, string>();
System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
Parallel.ForEach(symbols, symbol =>
{
url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=1&c=1900&d=" + (DateTime.Now.Month - 1) + "&e=" + DateTime.Now.Day + "&f=" + DateTime.Now.Year + "&g=d&ignore=.csv";
uri = new Uri(url);
using (ooplesfinanceEntities entity = new ooplesfinanceEntities())
using (WebClient client = new WebClient())
using (Stream stream = client.OpenRead(uri))
using (StreamReader reader = new StreamReader(stream))
{
entity.Database.Connection.Open();
while (reader.EndOfStream == false)
{
line = reader.ReadLine();
lineArray = line.Split(',');
// if it isn't the very first line
if (lineArray[0] != "Date")
{
switch (market)
{
case "amex":
DailyAmexData amexData = new DailyAmexData();
var amexQuery = from r in entity.DailyAmexDatas.AsParallel().AsEnumerable()
where r.Date == date
select new StockData { Close = r.AdjustedClose };
List<StockData> amexResult = amexQuery.AsParallel().ToList();
if (amexResult.AsParallel().Count() > 0) // **never hits this breakpoint line**
{
// add the row to the table if it isn't there
// now checks for stock splits and updates if necessary
if (amexResult.AsParallel().FirstOrDefault().Close != adjClose)
{
// this means there is a stock split so it needs to have the other adjusted close prices updated
amexResult.AsParallel().FirstOrDefault().Close = adjClose;
}
else
{
continue;
}
}
else
{
// set the data then add it
amexData.Symbol = symbol;
entity.DailyAmexDatas.Add(amexData);
}
break;
default:
break;
}
}
}
// now save everything
entity.SaveChanges();
Console.WriteLine(symbol + " added to the " + market + " database!");
}
}
);
}
Everything starts fine and I get no exceptions but I'm getting no results and the code gets stuck one the line that I marked and the memory keeps shooting up. I figured the problem was with the above code because maybe I was doing something wrong. I just don't know where to start as this is my first time dealing with plinq/parallel processing and the tutorials don't show anything this complex.

SWIProlog C# System.AccessViolationException

please help me because I'm desperate because I don't understand why my method doesn't work.
I have this:
public static List<int> caminhoMaisCurto(int iduser1, int iduser2)
{
List<int> ret = new List<int>();
using (PlQuery q = new PlQuery("mais_curto(" + iduser1 + "," + iduser2 + ",C)."))
{
PlTermV v = q.Solutions.First();
IReadOnlyCollection<PlTerm> lista = v[2].ToList();
foreach(var row in lista)
{
int num = Convert.ToInt32(row.ToString());
ret.Add(num);
}
}
return ret;
}
It belongs to a webservice that communicates with a .pl file with prolog.
It initiates like this:
public static void init()
{
Environment.SetEnvironmentVariable("SWI_HOME_DIR", #"C:\Users\João\Desktop\SWI-PrologPortable\App\SWI-Prolog");
Environment.SetEnvironmentVariable("Path", #"C:\Users\João\Desktop\SWI-PrologPortable\App\SWI-Prolog");
Environment.SetEnvironmentVariable("Path", #"C:\Users\João\Desktop\SWI-PrologPortable\App\SWI-Prolog\\bin");
if (!PlEngine.IsInitialized)
{
String[] param = { "-q", "-s", "C:\\Users\\João\\final\\lapr5-dei-link\\DAL_BLL\\AIWebService\\AIWebService\\AI.pl" }; // suppressing informational and banner messages
PlEngine.Initialize(param);
}
}
and it gives the System.AccessviolationException in this line:
using (PlQuery q = new PlQuery("mais_curto(" + iduser1 + "," + iduser2 + ",C)."))
I dont' understand why... Can someone help?

How to deal with multiple EventHandlers to AsyncQuery

I am working on Windows Phone 8 project. In my project there are 10 Events with 10 EventHandlers ReverseGeocodeQuery_QueryCompleted (1 to 10). When first EventHandler is completed it turn on second event.
What should I implement to manage those Events without so much code.
code
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(0);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_1;
myReverseGeocodeQuery.QueryAsync();
private void ReverseGeocodeQuery_QueryCompleted_1(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Pierwszy");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
}
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(1);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_2;
myReverseGeocodeQuery.QueryAsync();
}
}
private void ReverseGeocodeQuery_QueryCompleted_2(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Drugi");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(2);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_3;
myReverseGeocodeQuery.QueryAsync();
}
}
}
Example Solution 1
public class DataContainer
{
public string Description { get; set; }
public GeoCoordinate Coordinate { get; set; }
//public List<GeoCoordinate> mySimulationCoordinates { get; set; }
public String EnterSimulation() {
StringBuilder strRet = new StringBuilder();
List<GeoCoordinate> mySimulationCoordinates = new List<GeoCoordinate>();
mySimulationCoordinates.Add(new GeoCoordinate(51.760752, 19.458216));
mySimulationCoordinates.Add(new GeoCoordinate(51.760757, 19.458356));
mySimulationCoordinates.Add(new GeoCoordinate(51.760738, 19.458442));
mySimulationCoordinates.Add(new GeoCoordinate(51.7607, 19.458501));
mySimulationCoordinates.Add(new GeoCoordinate(51.760662, 19.458533));
var descriptions = new[] { "Pierwszy", "Drugi", "Trzeci", "Czwarty", "Piąty" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
int k = zipped.Count();
foreach (var item in zipped)
{
var currentItem = item;
using (var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = item.Coordinate;
geocodeQuery.QueryCompleted += (sender, args) =>
{
if (args.Error == null)
{
if (args.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
//label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("House Number" + address.HouseNumber);
str.AppendLine("Street " + address.Street);
strRet.AppendLine("->");
strRet.Append(str);
waitHandle.Set();
}
}
};
geocodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
return strRet.ToString();
}
It stuck on 1st item. Is inside and wait ... wait ... can't pass to next element.
Umm... Let's see, shouldn't that be easier?
Warning: untested
public class DataContainer
{
public string Description {get;set;}
public GeoCoordinate Coordinate {get;set;}
}
var descriptions = new[] {"Pierwszy" , "Drugi" , "Trzeci" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
foreach(var item in zipped)
{
var currentItem = item;
using(var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = currentItem.Coordinates;
geocodeQuery.QueryCompleted += (sender, args) => {
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
waitHandle.Set();
}
}
};
geoCodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
That should guarantee you that one event is handled after another in order.

Categories

Resources