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.
Related
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 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?
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me
SendMail("xyz#gmail.com","hi","heloo");
public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
{
string smtphost ="smtp.gmail.com";
int smtpport = 100;
string smtpuser ="xyz";
string smtppwd = "xyz";
SmtpClient client = null;
string MessageBody = string.Empty;
try
{
message = new MailMessage();
message.From = new MailAddress(smtpuser);
message.To.Add(toMailAddress);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = mailSubject;
message.Body = mailMessage.ToString();
message.IsBodyHtml = true;
client = new SmtpClient();
client.Host = smtphost;
client.Port = smtpport;
client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
client.Send(message);
}
catch (Exception ex)
{
string x = ex.Message;
}
return true;
}
Your "from" user must be in the form of a valid email address.
message.From = new MailAddress(smtpuser);
Also, you will need to use the MailAddress constructor for the .To property as well.
Try, with port as 25 and IsSSLEnabled as true since gmail server is SSL enabled
Make sure the toMailAddress, and smtpuser are valid email address.
Try, Using smtpport = 587; provided by Gmail for Outgoing Mails (SMTP).
Hope this will make it work fine. Please list out the errors you encounter.
This code will work. What i have done are
proper smtphost
proper smtpport - 587
Enable SSL
set UseDefaultCredentials to false before setting the credentials
set DeliveryMethod
public static bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
{
string smtphost = "smtp.gmail.com";
int smtpport = 587;
string smtpuser = "youremail#gmail.com";
string smtppwd = "password";
SmtpClient client = null;
string MessageBody = string.Empty;
try
{
var message = new MailMessage();
message.From = new MailAddress(smtpuser);
message.To.Add(toMailAddress);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = mailSubject;
message.Body = mailMessage.ToString();
message.IsBodyHtml = true;
client = new SmtpClient();
client.Host = smtphost;
client.EnableSsl = true;
client.Port = smtpport;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
client.Send(message);
}
catch (Exception ex)
{
string x = ex.InnerException.Message;
Console.WriteLine(x);
}
return true;
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Sending Email in .NET Through Gmail
I have so many problems with sending mail through C#. I have tried forever on multiple apps and it never works....
Could someone PLEASE post some sample code that clearly labels where the sender and recipient go and offers help with the smtp sever dat or whatever!!
Something like this:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("sender#gmail.com", "recipient#example.com", "subject", "body");
System.Net.Mail.SmtpClient emailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 465);
emailClient.Credentials = new System.Net.NetworkCredential("yourgmailusername", "yourpassword");
emailClient.Send(message);
Some code that I wrote some time ago for sending email through a webform:
//using System.Net.Mail;
MailMessage msg = new MailMessage();
msg.To.Add(RECIPIENT_ADDRESS); //note that you can add arbitrarily many recipient addresses
msg.From = new MailAddress(SENDER_ADDRESS, RECIPIENT_NAME, System.Text.Encoding.UTF8);
msg.Subject = SUBJECT
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = //SOME String
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(ADDRESS, PASSWORD);
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (SmtpException ex)
{
throw; //or handle here
}
I made this class to send via my gmail account when in my dev environment and use the SMTP in my Web.Config when in production. Essentially the same as noblethrasher with some deployment comfort.
There is a flag for "mailConfigTest"
/// <summary>
/// Send Mail to using gmail in test, SMTP in production
/// </summary>
public class MailGen
{
bool _isTest = false;
public MailGen()
{
_isTest = (WebConfigurationManager.AppSettings["mailConfigTest"] == "true");
}
public void SendMessage(string toAddy, string fromAddy, string subject, string body)
{
string gmailUser = WebConfigurationManager.AppSettings["gmailUser"];
string gmailPass = WebConfigurationManager.AppSettings["gmailPass"];
string gmailAddy = WebConfigurationManager.AppSettings["gmailAddy"];
NetworkCredential loginInfo = new NetworkCredential(gmailUser, gmailPass);
MailMessage msg = new MailMessage();
SmtpClient client = null;
if (_isTest) fromAddy = gmailAddy;
msg.From = new MailAddress(fromAddy);
msg.To.Add(new MailAddress(toAddy));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
if (_isTest)
{
client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
}
else
{
client = new SmtpClient(WebConfigurationManager.AppSettings["smtpServer"]);
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
}
Folks, I am new to writing testcases for the methods. Here I have a InsertMethod for which I want to write testcase using NUnit testing framework. Help me in writing the testcase for the method below :
public bool insertUser(String FirstName, String LastName)
{
bool result = false;
SqlConnection myconn = new SqlConnection();
SqlCommand mycmd = new SqlCommand();
try
{
myconn.ConnectionString = "Data Source=BABU-PC;Initial Catalog=contacts;Integrated Security=True";
myconn.Open();
mycmd.Connection = myconn;
mycmd.CommandText = "InsertUser";
mycmd.CommandType = CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#FirstName";
param1.DbType = DbType.AnsiString;
param1.Size = 8000;
param1.Value = FirstName;
mycmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#LastName";
param2.DbType = DbType.AnsiString;
param2.Size = 8000;
param2.Value = LastName;
mycmd.Parameters.Add(param2);
int i = 0;
i = mycmd.ExecuteNonQuery();
if (i > 0)
{
result = true;
}
else
{
result = false;
}
}
catch (Exception err)
{
Console.WriteLine(err.Message.ToString());
return false;
}
finally
{
mycmd.Dispose();
myconn.Close();
myconn = null;
}
return result;
}
Thanks
SBM
Cellfish is right. Don't think about the code, think about what the method is supposed to do. Without even looking at your code, I'd do this kind of test:
1- Preparation
lastName = "LastName"
firstName = "FirstName"
Then try to fetch a user with firstName and lastName and make sure that it's not already there.
2- Execute
InsertUser(firstName, lastName)
3- Check
Make sure InsertUser return true
Try to fetch a user with firstName and lastName and make sure that it is there with the correct values.