I'm having a rest connection(username and password protected) and I'd like to ignore SSL certificate check.
In C#:
public class TrustAllCertificatePolicy : ICertificatePolicy
{
private const uint CERT_E_UNTRUSTEDROOT = 0x800B0109;
public TrustAllCertificatePolicy()
{
}
public bool CheckValidationResult(ServicePoint sp,
X509Certificate cert, WebRequest req, int problem)
{
bool returnValue = problem == 0;
if ((uint)problem == CERT_E_UNTRUSTEDROOT)
returnValue = true;
return returnValue;
}
}
I want to do the same in Delphi 2007. Is it possible?
Actually I do:
URL:= 'https://hw1200122:8444/WsConduit/ConduitService/SyncData/1';
HttpClient := TIdHttp.Create(nil);
HttpClient.ConnectTimeout := 5000;
HttpClient.ReadTimeout := 5000;
HttpClient.OnAuthorization := httpAuthorization;
HttpClient.MaxAuthRetries := 0;
HttpClient.HTTPOptions := [hoInProcessAuth];
HttpClient.Request.RawHeaders.Clear;
HttpClient.Request.RawHeaders.AddStrings(Self.FHeaders);
HttpClient.Request.BasicAuthentication := true;
HttpClient.Request.Username := Self.FUsername;
HttpClient.Request.Password := Self.FPassword;
httpClient.Request.ContentType := 'application/zip';
LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
httpClient.IOHandler := LHandler;
try
respStr := httpClient.Get(URL);
Result.ResponseCode := httpClient.ResponseCode;
Result.ResponseStr := respStr;
except
on E: EIdHTTPProtocolException do
begin
Result.ResponseCode := httpClient.ResponseCode;
Result.ResponseStr := E.Message;
end;
end;
I get 404 error:
'HTTP/1.1 404 Not Found'
What's the problem?
Related
I've been having a problem while using Fast Reports in Delphi,
The Object I'm using is TfrxMailExport,
The problem I'm facing is that the values of the email server aren't getting filled properly.
The Code:
email := TfrxMailExport.Create(self);
email.Subject := 'Teste';
email.Lines.Clear;
email.Lines.Add('Linha 1');
email.Lines.Add('Linha 2');
email.Lines.Add('Linha 3');
email.Lines.Add('Linha 4');
email.Address := 'email#email.com';
email.SmtpHost := '0.0.0.0';
email.SmtpPort := 25;
email.FromMail := 'email.email#email.com';
email.FromName := 'NAME';
email.Login := 'Login';
email.Password := 'Password';
email.TimeOut := 30;
email.Report := Rela;
rela.Export(email);
email.Destroy;
Only the E-Mail side gets filled
Since the post is not likely to get an answer (if there is one), I'm gonna post my workaround as a solution in case someone is having the same problem.
I created a form similar to the one in Fast Reports, I export the FR file to PDF, this one works fine.
Procedure SomeProc();
var pdf : TfrxPDFExport;
begin
pdf := TfrxPDFExport.Create(self);
pdf.Compressed := True;
pdf.EmbeddedFonts := False;
pdf.Background := True;
pdf.PrintOptimized := False;
pdf.Outline := False;
pdf.Transparency := False;
pdf.Quality := 95;
pdf.ProtectionFlags := [eModify, eCopy, eAnnot];
pdf.OpenAfterExport := False;
pdf.ShowProgress := False;
pdf.ShowDialog := false;
pdf.FileName := 'C:\SomeFolder\'+fileName+'.pdf';
pdf.HideToolbar := False;
pdf.HideMenubar := False;
pdf.HideWindowUI := False;
pdf.FitWindow := False;
pdf.CenterWindow := False;
pdf.PrintScaling := False;
myReport.Export(pdf);
end;
Then for the email, I used a C# .Net DLL, and called it from the Delphi application.
The C# code:
using RGiesecke.DllExport;
[DllExport("SendEmail", CallingConvention = CallingConvention.StdCall)]
public static string SendEmail(string txtTo, string txtToCC, string txtToBCC, string txtSubject, string txtMessage, string txtFrom, string txtServer, string txtPort, string txtUtilizador, string txtPasse, string txtFile ,bool cbSSL)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(txtFrom);
Attachment attachment = new Attachment(txtFile, System.Net.Mime.MediaTypeNames.Application.Pdf);
message.From = fromAddress;
message.To.Add(txtTo);
if (txtToCC != "")
message.CC.Add(txtToCC);
if (txtToBCC != "")
message.Bcc.Add(txtToBCC);
message.Attachments.Add(attachment);
message.Subject = txtSubject;
message.IsBodyHtml = true;
message.Body = txtMessage;
smtpClient.Timeout = 5000;
smtpClient.Host = txtServer;
int.TryParse(txtPort, out int port);
smtpClient.Port = port;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(txtUtilizador, txtPasse);
smtpClient.EnableSsl = cbSSL;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(message);
message.Dispose();
return "Message Sent.";
}
catch (Exception ex)
{
return ex.Message;
}
}
And to finish, calling it in Delphi.
function SendEmail(txtTo, txtToCC, txtToBCC, txtSubject, txtMessage, txtFrom, txtServer, txtPort, txtUtilizador, txtPasse, txtFicheiro : PAnsiChar; cbSSL : Boolean) : PAnsiChar; stdcall; external 'SendEmail.dll';
showmessage(SendEmail(PAnsiChar(AnsiString('To'))
, PAnsiChar(AnsiString('ToCC'))
, PAnsiChar(AnsiString('ToBCC'))
, PAnsiChar(AnsiString('Subject'))
, PAnsiChar(AnsiString('Message'))
, PAnsiChar(AnsiString('From'))
, PAnsiChar(AnsiString('Server'))
, PAnsiChar(AnsiString('Port'))
, PAnsiChar(AnsiString('User'))
, PAnsiChar(AnsiString('Pass'))
, PAnsiChar(AnsiString('File'))
, SSL));
I made a couple mistakes, like using a function to convert the strings without having to write each one, it doesn't work for some reason.
The function needs to specify it's a stdcall.
I'm working on .net core web application. I want to listen my PostgreSQL database. And if there are any changes on table, I have to got it.
So according to my research, I have to use SignalR Core. I did some example application with SignalR like chat app but none of them listen database. I couldn't find any example for this.
-Does It have to be trigger on PostgreSQL database?
-Does It have to be listener on code side?
-How can I use SignalR Core?
Please show me a way.
Thanks a lot.
This example is work asp.net core 3.0+. Full code is below.
Step 1. Create a trigger on PostgreSql for listening actions
create trigger any_after_alarm_speed after
insert
or
delete
or
update
on
public.alarm_speed for each row execute procedure alarm_speedf();
Step 2. Create Procedur on Postgresql
CREATE OR REPLACE FUNCTION public.alarm_speedf()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF TG_OP = 'INSERT' then
PERFORM pg_notify('notifyalarmspeed', format('INSERT %s %s', NEW.alarm_speed_id,
NEW.alarm_speed_date));
ELSIF TG_OP = 'UPDATE' then
PERFORM pg_notify('notifyalarmspeed', format('UPDATE %s %s', OLD.alarm_speed_id,
OLD.alarm_speed_date));
ELSIF TG_OP = 'DELETE' then
PERFORM pg_notify('notifyalarmspeed', format('DELETE %s %s', OLD.alarm_speed_id,
OLD.alarm_speed_date));
END IF;
RETURN NULL;
END;
$function$;
Step 3. Create Hub
public class speedalarmhub : Hub
{
private IMemoryCache _cache;
`private IHubContext<speedalarmhub> _hubContext;
public speedalarmhub(IMemoryCache cache, IHubContext<speedalarmhub> hubContext)
{
_cache = cache;
_hubContext = hubContext;
}
public async Task SendMessage()
{
if (!_cache.TryGetValue("SpeedAlarm", out string response))
{
SpeedListener speedlist = new SpeedListener(_hubContext,_cache);
speedlist.ListenForAlarmNotifications();
string jsonspeedalarm = speedlist.GetAlarmList();
_cache.Set("SpeedAlarm", jsonspeedalarm);
await Clients.All.SendAsync("ReceiveMessage", _cache.Get("SpeedAlarm").ToString());
}
else
{
await Clients.All.SendAsync("ReceiveMessage", _cache.Get("SpeedAlarm").ToString());
}
}
}
Step 4. Create Listener Controller
public class SpeedListener :Controller
{
private IHubContext<speedalarmhub> _hubContext;
private IMemoryCache _cache;
public SpeedListener(IHubContext<speedalarmhub> hubContext,IMemoryCache cache)
{
_hubContext = hubContext;
_cache = cache;
}
static string GetConnectionString()
{
var csb = new NpgsqlConnectionStringBuilder
{
Host = "yourip",
Database = "yourdatabase",
Username = "yourusername",
Password = "yourpassword",
Port = 5432,
KeepAlive = 30
};
return csb.ConnectionString;
}
public void ListenForAlarmNotifications()
{
NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString());
conn.StateChange += conn_StateChange;
conn.Open();
var listenCommand = conn.CreateCommand();
listenCommand.CommandText = $"listen notifyalarmspeed;";
listenCommand.ExecuteNonQuery();
conn.Notification += PostgresNotificationReceived;
_hubContext.Clients.All.SendAsync(this.GetAlarmList());
while (true)
{
conn.Wait();
}
}
private void PostgresNotificationReceived(object sender, NpgsqlNotificationEventArgs e)
{
string actionName = e.Payload.ToString();
string actionType = "";
if (actionName.Contains("DELETE"))
{
actionType = "Delete";
}
if (actionName.Contains("UPDATE"))
{
actionType = "Update";
}
if (actionName.Contains("INSERT"))
{
actionType = "Insert";
}
_hubContext.Clients.All.SendAsync("ReceiveMessage", this.GetAlarmList());
}
public string GetAlarmList()
{
var AlarmList = new List<AlarmSpeedViewModel>();
using (NpgsqlCommand sqlCmd = new NpgsqlCommand())
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "sp_alarm_speed_process_get";
NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString());
conn.Open();
sqlCmd.Connection = conn;
using (NpgsqlDataReader reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
AlarmSpeedViewModel model = new AlarmSpeedViewModel();
model.alarm_speed_id = reader.GetInt32(0);
// you must fill your model items
AlarmList.Add(model);
}
reader.Close();
conn.Close();
}
}
_cache.Set("SpeedAlarm", SerializeObjectToJson(AlarmList));
return _cache.Get("SpeedAlarm").ToString();
}
public String SerializeObjectToJson(Object alarmspeed)
{
try
{
var jss = new JavaScriptSerializer();
return jss.Serialize(alarmspeed);
}
catch (Exception) { return null; }
}
private void conn_StateChange(object sender, System.Data.StateChangeEventArgs e)
{
_hubContext.Clients.All.SendAsync("Current State: " + e.CurrentState.ToString() + " Original State: " + e.OriginalState.ToString(), "connection state changed");
}
}
Step 5 Calling Hub
<script src="~/lib/signalr.js"></script>
<script type="text/javascript">
// Start the connection.
var connection = new signalR.HubConnectionBuilder()
.withUrl('/speedalarmhub')
.build();
connection.on('ReceiveMessage', function (message) {
var encodedMsg = message;
// Add the message to the page.
});
// Transport fallback functionality is now built into start.
connection.start()
.then(function () {
console.log('connection started');
connection.invoke('SendMessage');
})
.catch(error => {
console.error(error.message);
});
Step 6. Add below code Configuration Services at Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSignalR();
services.AddMemoryCache();
}
Step 7. add below code in Configure method
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapHub<speedalarmhub>("/speedalarmhub");
});
I want to listen my PostgreSQL database. And if there are any changes on table, I have to got it.
You can create a trigger associated with your specified table, and use the function pg_notify(text, text) to send a notification, like below.
Function
CREATE OR REPLACE FUNCTION mytestfunc() RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' then
PERFORM pg_notify('notifytesttable', 'new record inserted');
ELSIF TG_OP = 'UPDATE' then
PERFORM pg_notify('notifytesttable', 'updated');
ELSIF TG_OP = 'DELETE' then
PERFORM pg_notify('notifytesttable', 'deleted');
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Trigger
CREATE TRIGGER any_after_testtable
AFTER INSERT OR DELETE OR UPDATE
ON testtable
FOR EACH ROW
EXECUTE PROCEDURE mytestfunc();
In your client application code, you can listen and receive notifications from PostgreSQL.
conn.Open();
conn.Notification += Conn_Notification;
using (var cmd = new NpgsqlCommand("LISTEN notifytesttable", conn))
{
cmd.ExecuteNonQuery();
}
In Notification event handler, you can call SignalR hub method to push notifications to SignalR clients.
private static void Conn_Notification(object sender, NpgsqlNotificationEventArgs e)
{
var notification_payload = e.Payload;
//code logic here
//call hub method to push PostgreSQL notifications that you received to SignalR client users
}
Test result
For detailed information about PostgreSQL LISTEN and NOTIFY features, you can check following links.
https://www.postgresql.org/docs/current/sql-notify.html
https://www.npgsql.org/doc/wait.html#processing-of-notifications
In a VSIX package I have to get the debugger command for active startup configuration. In other words, the command that would be executed when 'sturt under debugger' is selected. Using the code below I was able to get active configuration for startup project, but I can't figure out how to get the debugger command from IVSHierarchy representing the startup project. Is this even possible without going back to DTE?
private void GetStartupProject()
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsSolutionBuildManager bm = Package.GetGlobalService(typeof(IVsSolutionBuildManager)) as IVsSolutionBuildManager;
int hr;
IVsHierarchy project;
hr = bm.get_StartupProject(out project);
if (hr == VSConstants.S_OK)
{
project.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_Name, out object projectName);
IVsProjectCfg[] activeCfgs = new IVsProjectCfg[1];
bm.FindActiveProjectCfg(IntPtr.Zero, IntPtr.Zero, project, activeCfgs);
activeCfgs[0].get_DisplayName(out string activeCfgName);
textOut.Text += String.Format("{0} {1}\r\n",(string)projectName, activeCfgName);
}
}
The IVsProjectCfg interface doesn't allow for enumerating the various configuration properties, or contain a method that would allow you to retrieve them. As you probably already suspect, the various project types expose their settings via automation, which for C# and VB.NET projects would correlate to using EnvDTE/VSLangProj interfaces to retrieve the specific debugger properties for a given configuration. For C#/VB.NET projects you'll want to retrieve/use the ProjectConfigurationProperties3 interface. For example:
private void OnGetDebuggerSettings(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsHierarchy vsHierarchy = null;
IVsSolutionBuildManager slnBuildMgr = (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager));
int hresult = slnBuildMgr.get_StartupProject(out vsHierarchy);
object objProject = null;
hresult = vsHierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out objProject);
Project startupProject = (Project)objProject;
// Note, cannot enumerate the ProjectConfigurationProperties, as it's not a collection interface
// Refer to the documentation for ProjetConfigurationProperties3, or set a BP on the WriteLine below
// and view the Dynamic View of the cfgProperties in the debugger's locals or watch window.
Configuration cfg = startupProject.ConfigurationManager.ActiveConfiguration;
ProjectConfigurationProperties3 cfgProperties = cfg.Object as ProjectConfigurationProperties3;
if (cfgProperties!=null)
{
System.Diagnostics.Debug.WriteLine(cfgProperties.StartArguments);
}
}
Hopefully that'll get you up and running.
After spending some time debugging and with help from Ed Dore, I was able to put together code that gets complete debugging command and working dir for native C++ and managed code projects:
private void ListStartupProperties()
{
ThreadHelper.ThrowIfNotOnUIThread();
IVsHierarchy vsHierarchy = null;
int hresult = bm.get_StartupProject(out vsHierarchy);
object objProject = null;
if(vsHierarchy != null)
hresult = vsHierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out objProject);
Project startupProject = (Project)objProject;
if (startupProject != null)
{
foreach (Property prop in startupProject.Properties)
{
try
{
textOut.Text += string.Format("{0} = {1}\r\n", prop.Name, prop.Value);
}
catch (Exception e)
{
textOut.Text += e.Message + "\r\n";
}
}
string cmd = "";
string args = "";
string wd = "";
VCProject vcp = startupProject.Object as VCProject;
if (vcp != null)
{ // This is VC project
VCConfiguration vcc = vcp.ActiveConfiguration;
VCDebugSettings dbg = vcc.DebugSettings;
cmd = vcc.Evaluate(dbg.Command);
args = vcc.Evaluate(dbg.CommandArguments);
wd = vcc.Evaluate(dbg.WorkingDirectory);
}
else
{ // Probably C# or VB
Configuration cfg = startupProject.ConfigurationManager.ActiveConfiguration;
ProjectConfigurationProperties cfgProperties = cfg.Object as ProjectConfigurationProperties;
if (cfgProperties != null)
{
string outPath = cfgProperties.OutputPath;
string localPath = startupProject.Properties.Item("FullPath").Value as string;
string outputName = startupProject.Properties.Item("OutputFileName").Value as string;
cmd = cfgProperties.StartProgram != "" ?
cfgProperties.StartProgram :
localPath + outPath + outputName;
args = cfgProperties.StartArguments;
wd = cfgProperties.StartWorkingDirectory;
}
}
textOut.Text += string.Format("StartProgram = {0}\r\n", cmd);
textOut.Text += string.Format("StartArguments = {0}\r\n", args);
textOut.Text += string.Format("WorkingDir = {0}\r\n", wd);
}
}
I'm experimenting with Drools backward chaining mechanism and some simple Web Ontology Language (OWL)-RL logic. OWL supports inverse properties, which means I have to generate recursive queries from my TBox. The Drools documentation states that "The algorithm uses stacks to handle recursion, so the method stack will not blow up.", but when invoking my query, the CPU usage goes to 100% and the stack grows to infinity. I have three queries for the two inverse properties "tsEquivalen" and "phxEquivalent". The invoked query is the "bind_tsEquivalent_value" query.
query "bind_tsEquivalent_value"(Resource $subject, Resource $object)
#Abductive(target=ObjectPropertyQueryResult.class)
Statement(subject == $subject, predicate == tsEquivalent, $object := object)
or
$object := bind_phxEquivalent_inverse_value($subject;)
end
query "bind_tsEquivalent_inverse_value"(Resource $subject, Resource $object)
#Abductive(target=ObjectPropertyQueryResult.class)
Statement($object := subject, predicate == tsEquivalent, object == $subject)
or
$object := bind_phxEquivalent_inverse_value($subject;)
end
query "bind_phxEquivalent_inverse_value"(Resource $subject, Resource $object)
#Abductive(target=ObjectPropertyQueryResult.class)
Statement($object := subject, predicate == phxEquivalent, object == $subject)
or
$object := bind_tsEquivalent_inverse_value($subject;)
end
My ObjectPropertyQueryResult looks like this:
import com.hp.hpl.jena.rdf.model.Resource;
public class ObjectPropertyQueryResult {
private Resource subject;
private Resource object;
public ObjectPropertyQueryResult() {
super();
}
public ObjectPropertyQueryResult(Resource subject, Resource object) {
this.subject = subject;
this.object = object;
}
public Resource getSubject() {
return subject;
}
public void setSubject(Resource subject) {
this.subject = subject;
}
public Resource getObject() {
return object;
}
public void setObject(Resource object) {
this.object = object;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((object == null) ? 0 : object.hashCode());
result = prime * result + ((subject == null) ? 0 : subject.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ObjectPropertyQueryResult other = (ObjectPropertyQueryResult) obj;
if (object == null) {
if (other.object != null)
return false;
} else if (!object.equals(other.object))
return false;
if (subject == null) {
if (other.subject != null)
return false;
} else if (!subject.equals(other.subject))
return false;
return true;
}
}
I think that this query combination is (if you pardon the expression) a wash-out. Running
bind_tsEquivalent_value"(sub, obj)
without a matching Statement leads to an evaluation of
bind_phxEquivalent_inverse_value(sub)
and this delegates to
bind_tsEquivalent_inverse_value(sub)
and then to
bind_phxEquivalent_inverse_value(sub)
and now you are caught in an infinite recursive loop.
A logical "or" without a constraint condition on the non-terminal branch is inadequate for breaking recursion. It is possible that the DRL compiler should terminate recursion when being caught in a loop like this, but basically (I think) this is a programmer's error.
"the CPU usage goes to 100% and the stack grows to infinity."
The heap or the stack? If your query never returns, it will recurse until you run out of heap space.
If it's a stack error, can you paste the trace.
Custom error lose custom properties
What steps will reproduce the problem:
create function
CREATE OR REPLACE FUNCTION public.utils ()
RETURNS void AS
$body$
this.dbError = function(message){
this.message = (message || '');
};
dbError.prototype = Error.prototype;
$body$
LANGUAGE 'plv8'
VOLATILE
RETURNS NULL ON NULL INPUT
SECURITY DEFINER
COST 100;
create trigger function
CREATE OR REPLACE FUNCTION public.test_trigger func ()
RETURNS trigger AS
$body$
var fn = plv8.find_function('public.utils');
fn();
var err = new dbError('this is a dbError');
err.someProp = 'lalala';
throw err;
return NEW;
$body$
LANGUAGE 'plv8'
VOLATILE
CALLED ON NULL INPUT
SECURITY DEFINER
COST 100;
set this trigger on any table on insteadof event and try to execute it
DO $$
plv8.find_function('public.utils')();
try{
plv8.execute('insert into Temp (field) value ($1)', [100]);
} catch(ex){
plv8.elog(NOTICE, ex instanceof dbError);
plv8.elog(NOTICE, ex.message);
plv8.elog(NOTICE, ex.someProp);
}
$$ LANGUAGE plv8;
we will see
true
this is a dbError
undefined
What is the expected output?
true
this is a dbError
lalala
if I do this in one scope - I get right result
DO $$
this.dbError = function(message){
this.message = (message || '');
};
dbError.prototype = Error.prototype;
try{
var err = new dbError('this is a dbError');
err.someProp = 'lalala';
throw err;
} catch(ex){
plv8.elog(NOTICE, ex instanceof dbError);
plv8.elog(NOTICE, ex.message);
plv8.elog(NOTICE, ex.someProp);
}
$$ LANGUAGE plv8;
the result:
true
this is a dbError
lalala