SWIProlog C# System.AccessViolationException - c#

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?

Related

WMI Query Library C#

I am having hard time understanding why there's not a single WMI query library
in here or google pointed out. Simply interface to query WMI for information. All I can find is "write a new query like this..."-style of topics all over web which makes no sense to me while there's few hundred queries I am working with.
So, here's my current effort building one:
using System;
using System.Management;
namespace hardware
{
public class Info
{
public static Tuple<string[], int, int> Query(string Select, string From, string Where = null, string Answer = null, string Root = "root\\CIMV2")
{
int Count = 0;
string[] Values = Select.Split(',');
if (Where != null && Answer != null)
{
ManagementObjectSearcher s = new ManagementObjectSearcher(Root, "SELECT " + Select + " FROM " + From + " WHERE " + Where + " = '" + Answer + "'");
string[] res = new string[Values.Length];
foreach (ManagementObject wQuery in s.Get())
{
foreach (string value in Values)
{
res[Count] = Convert.ToString(wQuery[value]);
Count++;
}
}
var result = new Tuple<string[], int, int> (res, Values.Length, Count);
return result;
}
else
{
ManagementObjectSearcher s = new ManagementObjectSearcher(Root, "SELECT " + Select + " FROM " + From);
string[] res = new string[Values.Length];
foreach (ManagementObject wQuery in s.Get())
{
foreach (string value in Values)
{
res[Count] = Convert.ToString(wQuery[value]);
Count++;
}
}
var result = new Tuple<string[], int, int>(res, Values.Length, Count);
return result;
}
}
}
}
I've been trying to get above in working order now for a weeks. Coming from basic string multi-dimensional array (return string[,] or string[][]) just started testing, if returning tuple (which I used few years ago successfully) would be better choice.
So, anyone know, if there is library already written?
if not, then best way to do above query from reference DLL library?
I know this question is old. But you can use ORMi library. I think it will just fit on your needs.
For example:
1) Define your class:
[WMIClass("Win32_Processor")]
public class Processor
{
public string Name { get; set; }
[WMIProperty("NumberOfCores")]
public int Cores { get; set; }
public string Description { get; set; }
}
2) Query:
WMIHelper helper = new WMIHelper("root\\CimV2");
List<Processor> processors = helper.Query<Processor>().ToList();
3) Or lazy coding option:
var processors = helper.Query("SELECT * FROM Win32_Processor");
You can find more information in here:
https://github.com/nicoriff/ORMi
https://medium.com/#luque.nicolas/compare-ormi-and-traditional-net-wmi-implementation-f00db26d10a3

Working with proxy list c#

I have 2 listbox,
lbProxy = contain proxy list
lbKeyword = contain keyword list.
I want to process the keyword list, 1 keyword using 1 proxy. If number of proxy list less than keyword list, then loop proxy list again.
I don't know how to change proxy after 1 keyword is processed.
Full Code
private void useproxy()
{
foreach (string prox in lbProxy.Items)
{
WebClient fetch = new WebClient();
string numResults = nudPages.Value.ToString();
int delay = Convert.ToInt32(nudDelay.Value);
if (lblStatusProxy.InvokeRequired)
{
lblStatusProxy.Invoke(new MethodInvoker(delegate
{
lblStatusProxy.Text = "Using: " + prox;
}));
}
WebProxy wp = new WebProxy(prox);
fetch.Proxy = wp;
foreach (string kw in lbKeyword.Items)
{
keywords = kw;
if (lblStatusKeyword.InvokeRequired)
{
lblStatusKeyword.Invoke(new MethodInvoker(delegate
{
lblStatusKeyword.Text = "Processing Keyword :" + kw;
}));
}
string downloadUrl = "https://www.google.com" + "/search?q=" + kw + "&num=" + numResults + "&as_qdr=all&ei=LrUVVf7UMrPfsAS7lICgCw&sa=N&biw=1440&bih=690";
fetch.Headers.Set(HttpRequestHeader.Host, "www.google.com");
string data = fetch.DownloadString(downloadUrl);
string[] results = TopUrls(data);
foreach (string lines in results)
{
if (lbBlog.InvokeRequired)
{
lbBlog.Invoke(new MethodInvoker(delegate
{
lbBlog.Items.Add(lines);
}
));
}
}
}
}
}
Thank you,
You can use a plain for and the modulus operand:
for(int buc = 0; buc < lbKeyword.Items.Count; buc++)
{
var proxy = lbProxy.Items[buc % lbProxy.Items.Count];
var keyword = lbKeyword.Items[buc];
//Now you have keyword and proxy to continue with your code.
}
The trick here is the modulus operand, as it's aplied over lbProxy.Items.Count it will give you a value between 0 and lbProxy.Items.Count - 1, just the index you were looking for.

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
...

C# Multi threading not starting worker/job?

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");
}
}

How to track application usage? (2)

I asked this question yesterday and got a great response/code example. The only problem is that I forgot to mention that I am forced to work with the .Net Framework 2.0 and can't use the List.Select ( I assume the linq namespace). Does anyone have a good work around for List.Select seen below:
class Program
{
struct ProcessStartTimePair
{
public Process Process { get; set; }
public DateTime StartTime { get; set; }
public DateTime ExitTime
{
get
{
return DateTime.Now; // approximate value
}
}
public ProcessStartTimePair(Process p) : this()
{
Process = p;
try
{
StartTime = p.StartTime;
}
catch (System.ComponentModel.Win32Exception)
{
StartTime = DateTime.Now; // approximate value
}
}
}
static void Main(string[] args)
{
SqlConnection cnn = new SqlConnection(#"Data Source=XXXXXX;Initial Catalog=XXXXXX;User ID=XXXX;Password=XXXX");
List<ProcessStartTimePair> knownProcesses = new List<ProcessStartTimePair>();
while (true)
{
foreach (Process p in Process.GetProcesses())
{
if (!knownProcesses.Select(x => x.Process.Id).Contains(p.Id))
{
knownProcesses.Add(new ProcessStartTimePair(p));
//Console.WriteLine("Detected new process: " + p.ProcessName);
}
}
for (int i = 0; i < knownProcesses.Count; i++)
{
ProcessStartTimePair pair = knownProcesses[i];
try
{
if (pair.Process.HasExited)
{
Console.WriteLine(pair.Process.ProcessName + " has exited (alive from {0} to {1}).", pair.StartTime.ToString(), pair.ExitTime.ToString());
knownProcesses.Remove(pair);
i--; // List was modified, 1 item less
// TODO: Store in the info in the database
String sql = "insert into procs (machine,login,process,start_time,end_time) ";
sql += "values ('" + Environment.MachineName + "','" + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Split('\\')[1] + "','" + pair.Process.ProcessName + "','" + pair.StartTime.ToString() + "','" + pair.ExitTime.ToString() + "');";
SqlCommand cmd = new SqlCommand(sql, cnn);
try
{
cnn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
finally
{
cnn.Close();
}
}
}
catch (System.ComponentModel.Win32Exception)
{
// Would have to check whether the process still exists in Process.GetProcesses().
// The process probably is a system process.
}
}
//Console.WriteLine();
System.Threading.Thread.Sleep(5000);
}
}
}
I'm not sure the datatype of Id. I'll assume an int, you get the idea:
List<int> idList = new List<int>();
foreach(ProcessStartTimePair proc in knownProcesses)
{
idList.Add(proc.Process.Id);
}
if(idList.Contains(p.Id))
{
// ...
}
You just have to do the work of getting the list of IDs yourself.
Also, it's generally a better idea to edit your original question, and leave comments on the answers of others.
Try this:
if(!knownProcesses.Exists(x => x.Process.Id == p.Id))
Or, if you are using Visual Studio 2005 (not 2008),
if(!knownProcesses.Exists(delegate(ProcessStartTimePair x) { return x.Process.Id == p.Id; }))

Categories

Resources