ServiceStack Redis: given an arbitrary connection string, how do I test for connectivity to a Redis Cache server? - redis

I would like to know given an arbitrary connection string, how do I test if the connection to a Redis Server is established. Thanks!

Just run a command in a new client like PING, e.g:
try
{
using (var redis = new RedisClient(connectionString))
{
var connected = redis.Ping();
}
}
catch (Exception ex)
{
//connection failed
}

Related

Excel Add-in, connecting to a web service through both http and https protocol

I'm making changes to a Excel Add-in that reads data from a server through a web service interface. Previously the servers where the data is read from didn't support https protocol. In the future they will, but some servers for the same purpose may not be changed to support https for a long time.
So, I would like to maintain flexible logging into the server: I would like that the user doesn't need to make choice between protocols. The user could be totally unaware of the protocol and needs only to give credentials and server name. However, the default protocol would be https. If the server, where data is read, doesn't support that, then http would be used.
The current implementation for logging in is approximately like this:
public partial class AuthenticationService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public AuthenticationService() {
this.Url = global::ExcelAddInExtension.Base.Properties.Settings.Default.ExcelAddInExtension_Base_ServiceReference_AuthenticationService;
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
public new string Url {
get {
return base.Url;
}
set {
if ((((this.IsLocalFileSystemWebService(base.Url) == true)
&& (this.useDefaultCredentialsSetExplicitly == false))
&& (this.IsLocalFileSystemWebService(value) == false))) {
base.UseDefaultCredentials = false;
}
base.Url = value;
}
}
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://asp.net/ApplicationServices/v200/AuthenticationService/Login", RequestNamespace="http://asp.net/ApplicationServices/v200", ResponseNamespace="http://asp.net/ApplicationServices/v200", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void Login([System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] string username, [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] string password, [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] string customCredential, bool isPersistent, [System.Xml.Serialization.XmlIgnoreAttribute()] bool isPersistentSpecified, out bool LoginResult, [System.Xml.Serialization.XmlIgnoreAttribute()] out bool LoginResultSpecified) {
object[] results = this.Invoke("Login", new object[] {
username,
password,
customCredential,
isPersistent,
isPersistentSpecified});
LoginResult = ((bool)(results[0]));
LoginResultSpecified = ((bool)(results[1]));
}
}
The actual login is done like this:
using (var authenticationService = new ServiceReference.AuthenticationService())
{
authenticationService.Url = "https://server/AuthenticationService.svc";
authenticationService.CookieContainer = new CookieContainer();
bool loginResult;
bool loginResultSpecified;
try
{
authenticationService.Login(userName, password, "", true, true, out loginResult, out loginResultSpecified);
}
catch (Exception ex)
{
Debug.Write(string.Format("Authentication failed, Error message: {0}, \r\nerror inner exception \r\n{1}, \r\nerror stack trace \r\n{2}.", ex.Message, ex.InnerException, ex.StackTrace)));
loginResult = false;
}
}
So, when trying to login to a server that doesn't support https, I get error
System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it server_ip_number:443.
This is understandable.
My approach was to retry login using http -protocol in the catch block.
authenticationService.Url = "http://server/AuthenticationService.svc";
authenticationService.Login(userName, password, "", true, true, out loginResult, out loginResultSpecified);
Unfortunately I get the same error
System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it server_ip_number:443.
Seems like the authenticationService object keeps the port number after the first attempt somewhere.
How to refresh or reinitialize that? Or, what kind of approach do you suggest?
The login itself works regardless of the protocol (to a server that supports https or if I try logging in first through http to a server that doesn't support https).
EDIT:
I'm almost ashamed about my question, and specially not understanding that the error message I got second time was actually from the first exception.
Anyway, I solved my problem. Solution below as an answer.
So, I solved my problem by checking first if the server I'm contacting from Excel Add-In is capable of using https-protocol. Then, according to the result, I used either http or https -protocol in the actual authentication.
The solution is originally provided here: How can I check if a server has ssl enable or not
private bool DetectSslSupport(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 5000;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
//some sites like stackoverflow will perform a service side redirect to the http site before the browser/request can throw an errror.
return response.ResponseUri.Scheme == "https";
}
}
catch (WebException webex)//"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."}
{
return false;
}
}

How to specify a password for Redis and his sentinels?

We going to use ServiceStack.RedisClient, but I was not able figure out how to define a password for sentinels and masters.
I've tried pwd#ipv4:port but no result.
Our code is:
var sentinelHosts = new[] { "node1:26379", "node2:26379", "node3:26379" };
var sentinel = new RedisSentinel(sentinelHosts, "mymaster");
var manager = sentinel.Start();
while (true)
{
using (var client = manager.GetClient())
{
try
{
Console.WriteLine(client.IncrementValue("MyTestKey"));
}
catch (RedisException ex)
{
Console.WriteLine($"Error {ex.Message}");
}
}
Thread.Sleep(1000);
}
You can specify to use passwords for connecting to masters / slaves with an Custom Redis Connection String, e.g:
sentinel.HostFilter = host => "pwd#{0}".Fmt(host);

javax.jms.InvalidClientIDException: Broker: localhost - Client: FS_Proceduer already connected from /127.0.0.1:port

How do you resolve this JMSException? Thanks!
Broker: localhost - Client: FS_Proceduer already connected
javax.jms.InvalidClientIDException: Broker: localhost - Client: FS_Proceduer already connected from /127.0.0.1:56556
This is triggered by this method:
private void connectAndInitActiveMQ() throws JMSException{
logger.debug("It's ready to connect to jms service");
if(null != connection){
try{
logger.debug("Closing connection");
connection.close();
}catch(Exception e){
logger.error(e.getMessage(), e);
}
}
logger.debug("Creating a new connection");
logger.debug("Is queueConnectionFactory null? "+(queueConnectionFactory==null));
connection = queueConnectionFactory.createConnection();
logger.debug("Is the new connection null? "+(connection==null));
logger.debug("Starting the new connection");
connection.start();
logger.debug("Connected successfully: " + connection);
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
queue = session.createQueue(queueName);
messageProducer = session.createProducer(queue);
}
Is it the factory problem? Or some other source?
You would get this error if you configured your connections to have the same client ID. The JMS spec is explicit that only a single connection can connect to the remote with the same Client ID at any given time, resolve your configuration and things should work just fine.

using oPort option in Apache commons SFTP

I have a sftp server which i can connect manually using the command below
sftp -oport=4022 user#xxxxxx.com
but I am finding difficulty in doing the same with apache commons vfs.
Below is the method I am using to establish connection to the sftp server. But it not working and fails with the error "org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at xxxxxx.com"
public boolean connect(String host, String login, String password,
int port) throws Exception {
//If the client is already connected, disconnect
if (command != null) {
disconnect();
}
FileSystemOptions fso = new FileSystemOptions();
try {
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso,
"no");
session =
SftpClientFactory.createConnection(host, port, login.toCharArray(),
password.toCharArray(),
fso);
System.out.println("pass");
Channel channel = session.openChannel("ssh");
channel.connect();
command = (ChannelSftp)channel;
} catch (FileSystemException e) {
throw e;
// return false;
}
return command.isConnected();
}
Please help me with this

How to set a connection from eclipse to SQLServer?

I am trying to connect to SQL Server from eclipse and i get the following error. I mention that i verified and the SQL Server Browser is running on the host and i have no firewall active.
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host
LAURA-PC, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException:
Receive timed out". Verify the server and instance names and check that no firewall
is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that
the SQL Server Browser Service is running on the host.
This is the code i've written:
import java.sql.*;
public class ConnectSQLServer {
public void connect(String url){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
Statement statement = connection.createStatement();
String query = "select * from Vehicle where Mileage < 50000";
ResultSet rs = statement.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectSQLServer connServer = new ConnectSQLServer();
String url = "jdbc:sqlserver://LAURA-PC\\SQLEXPRESS;databaseName=Register;integratedSecurity=true";
connServer.connect(url);
}
}
First thing before DB programming. Test each "step". Before executing any query or even writing any other code, please check if you can connect to the DB. I assume that you are connecting to the local db. For steps on making your connection URL, see - http://technet.microsoft.com/en-us/library/ms378428.aspx
Try changing your URL to - jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=MyDB. I tried this code and it worked.
import java.sql.*;
public class ConnectSQLServer {
public void connect(String url){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectSQLServer connServer = new ConnectSQLServer();
String url = "jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=AdventureWorks";
connServer.connect(url);
}
}
Just ENABLE/START SQL Server Browser and copy sqljdbc_auth.dll file to Windows->System32 by extracting this file from ( Microsoft jdbc driver 9.2 for sql server )