So far I am able to communicate with prolog with sample code available at prolog website.
But when I am trying to extract result from my prolog file it does not get the file and ended without any error.
Well the sample code I tested is as below:
if (!PlEngine.IsInitialized)
{
String[] param = { "-q" }; // suppressing informational and banner messages
PlEngine.Initialize(param);
PlQuery.PlCall("assert(father(martin, inka))");
PlQuery.PlCall("assert(father(uwe, gloria))");
PlQuery.PlCall("assert(father(uwe, melanie))");
PlQuery.PlCall("assert(father(uwe, ayala))");
using (PlQuery q = new PlQuery("father(P, C), atomic_list_concat([P,' is_father_of ',C], L)"))
{
foreach (PlQueryVariables v in q.SolutionVariables)
Console.WriteLine(v["L"].ToString());
Console.WriteLine("all child's from uwe:");
q.Variables["P"].Unify("uwe");
foreach (PlQueryVariables v in q.SolutionVariables)
Console.WriteLine(v["C"].ToString());
}
PlEngine.PlCleanup();
Console.WriteLine("finshed!");
Console.ReadLine();
}
And the code I am trying to use is as, my prolog file "OT.pl" is placed in swi-prolog folder:
String[] param = { "-q", "-f", #"OT.pl" };
if (!PlEngine.IsInitialized)
{
try
{
PlEngine.Initialize(param);
PlQuery carrega = new PlQuery("carrega('OT.bd')");
carrega.NextSolution();
PlQuery listQuery= new PlQuery("list(X)");
foreach (PlQueryVariables v in listQuery.SolutionVariables)
listBox1.Items.Add(v["X"].ToString());
}
catch (System.Exception ex)
{
Console.WriteLine("Failure: " + ex.Message);
// return;
}
}
Console.WriteLine("Finished!");
Console.ReadLine();
Kindly ignore any indentation mistakes. Thank you in advance.
Related
I'm using the following C# code to show real time data in my desktop application
string strQuery = "AbcD";
string socketURI = "https://mysocketio.com/";
Dictionary<string, string> dictQS = new Dictionary<string, string>();
dictQS.Add("token", strQuery);
dictQS.Add("transport", "websocket");
try
{
IO.Options options = new IO.Options() { AutoConnect = true, ForceNew = true, Path = "/socket/", Query = dictQS };
var cSocket = IO.Socket(socketURI, options); //An item with the same key has already been added
cSocket.Connect();
cSocket.On(Socket.EVENT_CONNECT, () =>
{
Console.WriteLine("success");
});
cSocket.On("change", (data) => {
MessageBox.Show("change");
});
cSocket.On(Socket.EVENT_DISCONNECT, () =>
{
Console.WriteLine("Disconnected");
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
But I got an error An item with the same key has already been added. Please provide a solution.
Thanks.
Maybe you should check if the key exists in dictionary?
if (!dictQS.ContainsKey(yourKey))
dictQS.Add(yourKey, yourValue);
else
dictQS[yourKey] = yourValue;
I'm writing a code to figure out the missing data and where i am having a mismatch or where it is not present.
There are 3 scenarios.
Images present as per db and in server (positive)
Images present in DB but not in Server.(Negative)
Images present in server but not in DB (Negative)
I have written a code using else if and i am able to capture only two scenario
Positive
Negative
How do i classify the two negative scenarios
(ie)Images present in DB but not in Server(Negative) and Images present in server but not in DB (Negative) to this code
namespace DataTableColumnCommaSeperated
{
class Program
{
static void Main(string[] args)
{
fileOperation();
}
private static void fileOperation()
{
try
{
string main_directory = #"D:\DMSArchivalPhase1\";//src_directory location
string[] lead_list = File.ReadAllLines(main_directory + #"list.txt");//first input
string[] image_list = File.ReadAllLines(main_directory + #"image_list.txt");//image name as per DB
foreach(string lead_id in lead_list)
{
Console.WriteLine(lead_id);
string[] src_list = File.ReadAllLines(main_directory + #"src_list.txt");
foreach (string src_dir in src_list)
{
string final_path = src_dir + lead_id;
if (Directory.Exists(final_path))
{
var filePaths = Directory.GetFiles(final_path, "*.*", SearchOption.AllDirectories).Where(name => !name.EndsWith(".gz"));//images present as per server
foreach (string path in filePaths)
{
FileInfo f = new FileInfo(path);
string strNewName = Path.GetFileNameWithoutExtension(f.Name);
if (Array.Exists(image_list, element => element == strNewName))
{
Console.WriteLine("File exist");
}
else if (Array.Exists(image_list, element => element != strNewName))
{
Console.WriteLine(strNewName + "File name doesnot exist in DMS/Databse");
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
I am using System.Management.Automation.Runspaces.Pipleline to create a powershell pipeline instance and execute my powershell scripts in c# console application, the problem is that if the script end up with an error, then i don't know how to print that error on the console screen.
This is my code,
System.Management.Automation.Runspaces.Runspace PowershellRunspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowershellRunspace.Open();
System.Management.Automation.RunspacesPipeline PowershellPipeline = PowershellRunspace.CreatePipeline();
PowershellPipeline.Commands.AddScript(PowershellScript);
PowershellPipeline.Commands.AddScript("Out-String");
foreach (string IpAddress in ActiveSystemIPAddresses)
{
PowershellPipeline.Commands.AddScript("Stop-Computer -ComputerName \"" + IpAddress + "\" -Credential $Credentials");
}
try
{
Collection<PSObject> output = PowershellPipeline.Invoke();
if (PowershellPipeline.HadErrors)
{
Console.WriteLine("Cannot shutdown this server IP");
}
PowershellPipeline.Stop();
StringBuilder results = new StringBuilder();
foreach (PSObject obj in output)
{
results.AppendLine(obj.ToString());
}
Console.WriteLine(results);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
PowershellRunspace.Close();
I can see the property Pipeline.HadErrors but it only rake me to the loop if there are errors detected, its doing anyhting to get the error message. My problem is how to get the actual error on the console screen?
Something like this should get you the errors.
var rs = RunspaceFactory.CreateRunspace();
rs.Open();
var ps = rs.CreatePipeline();
ps.Commands.AddScript("Get-Member");
ps.Commands.AddScript("ps");
try
{
var result = ps.Invoke();
if (ps.HadErrors)
{
var errors = ps.Error.ReadToEnd();
foreach (var error in errors)
{
Console.WriteLine(error);
}
}
foreach (var r in result)
{
Console.WriteLine(r);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
ps.Stop();
}
With the recent changes, following works with Microsoft.powershell.5.referenceAssemblies in C#
var result = ps.Invoke();
if (ps.HadErrors)
{
foreach (ErrorRecord error in ps.Streams.Error.ReadAll())
{
Console.WriteLine(error.ToString());
// You can access error.FullyQualifiedErrorId or error.Exception if you needed to
// be specific in what you were looking for when it failed.
}
}
To see the errors you can look at the collection PowerShell.Streams.Error.
If you wanted to do this natively in a PowerShell script and return the error you could wrap it in a try/catch and return the $error variable.
$error is a PowerShell variable where all errors are automatically added in an array. The first item in the array is always the newest error.
I am trying to use ClrMD to dump the stacktrace of all threads running within a specific process. The code works fine in my devlopment enviornment but not on the production server.
The server is running: Windows Server 2012 R2 Standard
The error I recieve is:
Could not attach to process. Error 0.
This post asks how to attach ClrMD to another users process, which was what I was trying to do. I terminated the process (which is running as a windows service) and started it as the same user that I am trying to execute ClrMD with. I still get the error.
Tried giving the user debugging privlidges but that didnt help either.
I bet the problem has something to do with how to production server is configured. I have administrator rights.
Any suggestions on what to do next?
Code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Diagnostics.Runtime;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int pid = 0;
var result = new Dictionary<int, string[]>();
var targetProcessName = "Dist.TingbogScraper.Business.TingbogScraperService.vshost";
// Change this to the process you are looking for
var outputPath = "C:\\temp\\ClrMDresult.txt";
var exceptionOutput = "C:\\temp\\ClrMDdump.txt";
var processes = Process.GetProcesses();
foreach (var process in processes)
{
if (process.ProcessName.Contains(targetProcessName))
{
pid = process.Id;
}
}
try
{
using (var dataTarget = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive))
{
ClrRuntime runtime = dataTarget.ClrVersions.First().CreateRuntime();
foreach (var t in runtime.Threads)
{
try
{
if (t.StackTrace != null)
{
result.Add(
t.ManagedThreadId,
t.StackTrace.Select(f =>
{
if (f.Method != null)
{
return f.Method.Type.Name + "." + f.Method.Name;
}
return null;
}).ToArray()
);
}
}
catch (Exception ex)
{
}
}
}
foreach (var kvp in result)
{
var value = kvp.Value;
foreach (var stacktrace in value)
{
System.IO.File.AppendAllText(outputPath,
string.Format("{0} {1} {2}", kvp.Key, stacktrace, Environment.NewLine));
}
}
}
catch (ClrDiagnosticsException ex)
{
System.IO.File.AppendAllText(outputPath,
string.Format("{0} {1} {2}", ex.Message, ex.StackTrace, ex.Source));
}
}
}
}
Found out that the name of the process was different on my development environment compared to production.
Correcting the name of the process fixed the error.
I want to read an Item from a Document Library and then Delete it. The problem I get a Security Exception: "The security validation for this page is invalid"
What am I doing wrong? I'm executing the commands with Elevated Privilages!
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSiteCollection = new SPSite(SharePointInfo.SubSiteUrl))
{
using (SPWeb oWebsite = oSiteCollection.OpenWeb())
{
SPList uploadFilesLibrary = oWebsite.Lists[SharePointInfo.UploadFilesLibraryName];
if (files.Count > 0)
{
foreach (var fileToSend in files)
{
try{
/*SPFile file = uploadFilesLibrary.Items.Cast<SPListItem>()
.Where(x => x.Name.Equals(fileToSend))
.Select(x => x.File).First();*/
SPListItem p = uploadFilesLibrary.Items.Cast<SPListItem>()
.Where(x => x.Name.Equals(fileToSend)).First();
byte[] binaryFile = p.File.OpenBinary();
p.Delete();
aux = new FileAttachesForm(fileToSend, System.Convert.ToBase64String(binaryFile));
rtn.Add(aux);
}catch (Exception ex){
string errMessage = string.Format("Error al descargar el fichero desde SP: {0} - Pila: {1}", ex.Message, ex.StackTrace);
Logger.LogError(errMessage, ex);
throw ex;
}
}
}
}
}
});
return rtn;
}
Try adding this inside of your if:
oSiteCollection.AllowUnsafeUpdates = true;
And take a look at this related question:
SharePoint Security Validation Issue while updating metadata (The security validation for this page is invalid)