I'm looking for the best way to connect to a Heroku Postgres database from an outside application. The application is in asp.net. I am trying to use NpgSQL but am getting a certificate unknown error. Has anyone done that? Do you have any pointers?
I use this to "translate" the DATABASE_URL to a connection string
var databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
var databaseUri = new Uri(databaseUrl);
var userInfo = databaseUri.UserInfo.Split(':');
var builder = new NpgsqlConnectionStringBuilder
{
Host = databaseUri.Host,
Port = databaseUri.Port,
Username = userInfo[0],
Password = userInfo[1],
Database = databaseUri.LocalPath.TrimStart('/')
};
return builder.ToString();
I am using the following connection string to connect to Heroku Postgres Database:
string connString = "User ID=<user>;Password=<pass>;Host=<host>;Port=<port>;Database=<database>;Pooling=true;Use SSL Stream=True;SSL Mode=Require;TrustServerCertificate=True;"
where <user>, <pass>, <host>, <port> and <database> are values from heroku postgres app settings. Port is 5432 by default.
Then using NpgSql I create instance of NpgsqlConnection:
var conn = new NpgsqlConnection(connString);
Dafault sample: http://www.npgsql.org/doc/index.html
Related
I am trying to connect (dotnet client) to RabbitMQ. I enabled the Peer verification option from the RabbitMQ config file.
_factory = new ConnectionFactory
{
HostName = Endpoint,
UserName = Username,
Password = Password,
Port = 5671,
VirtualHost = "/",
AutomaticRecoveryEnabled = true
};
sslOption = new SslOption
{
Version = SslProtocols.Tls12,
Enabled = true,
AcceptablePolicyErrors = System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors
| System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch,
ServerName = "", // ?
Certs = X509CertCollection
}
Below are my client certification details which I am passing through "X509CertCollection".
CertSubject: CN=myhostname, O=MyOrganizationName, C=US // myhostname is the name of my client host.
So, if I pass "myhostname" value into sslOption.ServerName, it works. If I pass some garbage value, it still works.
As per documentation of RabbitMQ, these two value should be match i.e. certCN value and serverName. What will be the value of sslOption.ServerName here and why?
My Bad. I found the reason. Posting as it might help someone.
Reason: As I set a policy "System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch".
We have several asp.net web apps that send emails, and the MailMessage object is configured with an SMTP server, username and password. The emails are sent with no problems.
In an SSIS package, I added an SMTP connection manager, and I configured the smtp server. I set UseWindowsAuthentication=True because I don't see where I type in username/password.
When I run the package from SQL Server Agent, the SSIS sends the email correctly, so apparently, the user/password is not needed.
So how can the SMTP package send an email without the user credentials? Does it make sense that the asp.net don't need the credentials either?
We're all under the same company network and we use Exchange Server.
Thanks.
Create a SMTP Connection Manager with a parameterized ConnectionString property with a string which contains the smtp user and password.
Create connection using New Connection... option selecting SMTP as type.
Save without any connection settings. Give it any name you want.
Right click the connection and select Parameterize...
Select Property = ConnectionString
Select Create new parameter (e.g. SMTPConnectionManager_ConnectionString)
Set Value to connection string (e.g. SmtpServer=aspmx.l.google.com; port=25; UseWindowsAuthentication=False;EnableSsl=False; user=user#gmail.com; password=password123)
Set scope at appropriate level for your deployment method (Package or Project).
Click OK
Check out this link.
It explains that the package is using the Sql Server Agent account to connect to the host.
Furthermore, the SMTP connection manager supports only anonymous authentication and Windows Authentication. It does not support basic authentication - as stated in the documentation.
The answer from Alan Gaylor didn't work for me, but doing the following in a script task, not an email task, worked:
using System.Diagnostics;
using System.Net;
using System.Net.Mail;
public void Main()
{
string UserName = Dts.Variables["UserName"].Value.ToString();
string Password = Dts.Variables["Password"].Value.ToString();
string EmailRecipient = Dts.Variables["EmailRecipient"].Value.ToString();
string EmailSender = Dts.Variables["EmailSender"].Value.ToString();
string SMTPEndPoint = Dts.Variables["SMTPEndPoint"].Value.ToString();
Int32.TryParse(Dts.Variables["SMTPPort"].Value.ToString(), out int SMTPPort);
string MessageSubject = Dts.Variables["MessageSubject"].Value.ToString();
string MessageBody = Dts.Variables["MessageBody"].Value.ToString();
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(EmailRecipient));
msg.From = new MailAddress(EmailSender);
msg.Subject = MessageSubject;
msg.Body = MessageBody +
"\n" +
"\n" +
"DISCLAIMER: The information contained in this transmission may contain privileged and confidential information. " +
"It is intended only for the use of the person(s) named above.If you are not the intended recipient, " +
"you are hereby notified that any review, dissemination, distribution or duplication of this communication " +
"is strictly prohibited. If you are not the intended recipient, please contact the sender by reply email and destroy all copies of the original message.";
SmtpClient client = new SmtpClient(SMTPEndPoint, SMTPPort)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(UserName, Password)
};
try
{
client.Send(msg);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Follow Below steps
Create a Send Mail Task, then create a new smtpConnection.
Type your Mail server name and click OK
Right-click on the SMTP Connection Manager and click Parameterize.
Select ConnectionString from the property list
Add username, password and port to your connection string value
SmtpServer=mail.yourServerName.com;UseWindowsAuthentication=False;EnableSsl=False;port=portnumber;user=YourUserName;Password=YourPassword;
I'm attempting to upload a file to my Amazon S3 bucket and all the code examples give me something like this:
///////////////////////////////////
using System;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
string accessKey = "put your access key here!";
string secretKey = "put your secret key here!";
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "objects.dreamhost.com";
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(
accessKey,
secretKey,
config
);
////////////////////////////////////
The problem is that the Amazon S3 client doesn't find the assembly or reference and when I click on the options to help bind it the only option that pops up is to generate a class for AmazonS3. I have the amazon aws for sdk.net installed through nuget. Besides "AmazonS3", everything else references fine.
////////////////UPDATE///////////////////
This has not been fun, it has wasted away the first half of my day :( I'm going to post this so that maybe someone else can use the code. I don't know why I couldn't find anything on the internet about it. Here it is:
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "http://s3-us-west-2.amazonaws.com(your service URL)";
Amazon.S3.IAmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client("Id", "Key", config);
String S3_KEY = "Test.txt";
PutObjectRequest request = new PutObjectRequest();
request.BucketName = "Your Bucket Name";
request.Key = S3_KEY;
request.ContentBody = "This is body of S3 object.";
s3Client.PutObject(request);
It appears in the AWS template console app using the AWS SDK, they do not actually call AmazonS3 class directly. What they do is call the interface IAmazonS3 instead. Try replacing AmazonS3 with IAmazonS3 and it should work.
Is there a way to configure the .NET client so that it will work with a IIS hosted SingalR that uses Windows authentication?
If I disable windows authentication it works, but this is not an option
setting connection.Credentials = CredentialCache.DefaultCredentials does not help.
The code
public EventProxy(IEventAggregator eventAggregator, string hubUrl)
{
typeFinder = new TypeFinder<TProxyEvent>();
subscriptionQueue = new List<EventSubscriptionQueueItem>();
this.eventAggregator = eventAggregator;
var connection = new HubConnection(hubUrl);
connection.Credentials = CredentialCache.DefaultCredentials;
proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
connection.Start().ContinueWith(o =>
{
SendQueuedSubscriptions();
proxy.On<object>("onEvent", OnEvent);
});
}
ContinueWith triggerst directly after Start and when the first subscription comes in I get a
The Start method must be called before data can be sent.
If I put a watch on the DefaultCredentials I can see that Username, Domain and Password are all String.Empty. Its a standard Console program, Enviroment.Username returns my username
Sure, set connection.Credentials = CredentialCache.DefaultCredentials. More details about credentials here http://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials.aspx.
i am trying to host a wcf service which has a following attribute;
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
and i am creating host class like this;
var uri = new Uri("net.tcp://localhost:7951");
var binding = new NetTcpBinding();
host = new ServiceHost(typeof(ChatService), uri);
ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null) host.Description.Behaviors.Add(new ServiceMetadataBehavior());
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
host.AddServiceEndpoint(typeof(IChat), new NetTcpBinding(), "");
host.Open();
So, on developer computer and dedicated server this is working. However, what i need to do is, host this on a VPS (vitual private server).
I thought making a web project and adding this code block to global.asax application start method. but this failed. I suspect problem that the port is closed from firewall maybe.
What solution should I follow?