cassandra All hosts tried for query failed CassandraCSharpDriver - c#

I tried to connect cassandra from virtual machine to main machine and use it with CassandraCSharpDriver. The error is "All hosts tried for query failed (tried :: SocketException 'A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond')".
I already have cassandra tested on main machine (x.x.x.1) and it worked, then I create 3 virtual machine with cassandra on it (x.x.x.2),(x.x.x.3),(x.x.x.4) but none of them worked on main machine. I even tried add all of the IP in the .yaml config file but doesn't seem work, althought x2, x3, x4 connected to each others on virtualbox with the same way. Is there anything I need to check in order to connect 3 virtual machine to main machine. Here is what I have done: config virt machine network to host-only; config virt machine IP to static; config .yaml file both virt and main machine; create keyspace, table. Here is the code create ISession
public static DataConnection Ins
{
get
{
if (_Ins == null)
_Ins = new DataConnection();
return _Ins;
}
set
{
_Ins = value;
}
}
private static DataConnection _Ins;
private DataConnection()
{
session = getConnect();
session.Execute("use KeySpace;");
}
public ISession session;
private string IP = "x.x.x.4";
private string Datacenter = "datacenter1";
public ISession getConnect()
{
return session = Cluster.Builder()
.AddContactPoints(IP)
.WithPort(9042)
.WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy(Datacenter))
.Build()
.Connect();
}
And here the using part:
private void LoginBtnSubmit_Click(object sender, EventArgs e)
{
string query = "Query sth";
Cassandra.RowSet row = DataConnection.Ins.session.Execute(query);
if (row.FirstOrDefault() != null)
{
//Do sth
}
}

Related

Not able to connect Azure Cache for Redis in Private Subnet

We are trying to connect to Azure Cache for Redis using C# code. Its returns NULL object.
This started happing after we converting our public subnet to private subnet.
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
var redisConnectionString = ConfigurationManager.ConnectionStrings["RedisCacheCnStr"].ConnectionString;
return ConnectionMultiplexer.Connect(redisConnectionString);
});
public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } }
We checked logs we are getting object reference error as connected object is Null.
Check the below steps to connect Azure Cache for Redis in Private Subnet.
First create a Virtual Network.
Create a Subnet with the Virtual Network.
Initially you will have a default subnet. Create one more with your NSG.
Make sure you have selected the NSG.
Create Azure Cache for Redis
There is no change in the code which you are trying to connect.
string cacheConnection = ConfigurationManager.ConnectionStrings["CacheConnection"].ConnectionString;
connection = ConnectionMultiplexer.Connect(cacheConnection);
Just update the connection string with the IP address.
In web.config,add the connection string.
<connectionStrings>
<add name="CacheConnection" connectionString="IPAddress:PortNo,password=redis-cache-key,abortConnect=False" />
</connectionStrings>
Get the IPAddress from Virtual Network in Azure Cache for Redis.

Can't access the network drive while running the windows service

I'm trying to create a windows service in C# that will copy all the files from a network drive and paste it into a local drive (let's say in C drive). When I run the test case, the program runs successfully but when I install and run the windows service, the 'Access is denied' error comes in the log file.
I tried Map Network Drive (API) solution but that solution didn't work. either.
Here's the sample code that I've used to get all the files from a network drive and paste it into the local drive folder
Service1.cs
public partial class Service1 : ServiceBase
{
private Timer _timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
DoWork();
}
catch (Exception e)
{
WriteErrorLog(e);
}
}
private void DoWork()
{
_timer = new Timer();
_timer.Interval = 5000;
_timer.Enabled = true;
_timer.Elapsed += _timer_Elapsed;
Update();
}
private void Update()
{
RevidAddinController.Update_AutodeskAddinFolder_With_ArchcorpUpdatedAddinFiles(Configuration.AutodeskVersion, Configuration.AutodeskRevitAddinFolderPath);
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
Update();
}
private void WriteErrorLog(Exception ex)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\Logfile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + " ; " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
sw.Flush();
sw.Close();
}
catch
{
}
}
protected override void OnStop()
{
}
}
RevidAddinController.cs
public static class RevidAddinController
{
public static IEnumerable<AddinStatus> Update_AutodeskAddinFolder_With_ArchcorpUpdatedAddinFiles(List<string> autoDeskVersion, string addinInstallationPath)
{
var networkDrive = ActivateNetworkDrive();
var allAutodeskVersionPath = Util.GetAllAutodeskAddinLibraryFolderPaths(autoDeskVersion, addinInstallationPath);
List<FileData> latestArchcorpAddins = new List<FileData>();
foreach (var autodeskAddinFolder in allAutodeskVersionPath)
{
var archorpAddinFiles = Util.GetAllExternalRevitAddinFilesFromArchcorpAddinFolderPath(Configuration.ArchcorpAddinFolderPath);
var autodeskAddinFiles = Util.GetAllExternalRevitAddinFilesLocationFromAutodeskAddinFolderPath(autodeskAddinFolder);
var latestAddins = Util.GetUpdatedRevitAddinFromArchcorpFolderPath(autodeskAddinFolder, archorpAddinFiles, autodeskAddinFiles)
.Where(addin => !addin.FileName.Contains(Configuration.DeleteAddinNamePrefix));
latestArchcorpAddins.AddRange(latestAddins);
}
List<AddinStatus> addinCopyStatus = new List<AddinStatus>();
foreach (var autodeskAddinPath in allAutodeskVersionPath)
{
foreach (var newArchcorpAddin in latestArchcorpAddins)
{
addinCopyStatus.Add(Util.InstallNewAddinFile(newArchcorpAddin, autodeskAddinPath));
}
}
return addinCopyStatus;
}
/// <summary>
/// Map the network drive path
/// </summary>
/// <returns></returns>
public static NetworkDrive ActivateNetworkDrive()
{
NetworkDrive oNetDrive = new aejw.Network.NetworkDrive();
try
{
oNetDrive.LocalDrive = "O:";
oNetDrive.ShareName = #"\\acdxbfs1\Organisation";
oNetDrive.Force = true;
oNetDrive.Persistent = true;
oNetDrive.MapDrive();
}
catch (Exception err)
{
throw err;
}
return oNetDrive;
}
}
The complete code can be found on the gist here. Would really appreciate if someone reviews the code and provides any feedback/solution to this problem.
Running a service under the default Local System Account, will have no concept of the share. These are set up under user accounts.
Your 2 options
Run your service under a User Account which has those shares mapped
Access your share via and ip address instead of the drive letter. However, you will need to set the file/folder permissions accordingly.
The service does run as Local System (as previously named). If you have a mapped network drive to a local drive letter, the service cannot use it (because a mapped network drive is always only mapped for the user context, not the whole computer/system). However the service can access the share by UNC \\server\share. You can view the UNC path if you only have a mapped network drive by typing 'net use' inside a command prompt.
If you run your program as a user Windows does automatically authenticate you at the remote share (if not already done by adding a mapped network drive). Therefor Local System is the computer account you need to set the access permissions of the target share to the computername eg workstation1$ (only available inside a domain cause a workgroup does not know the other computers). This has to be done for the file permissions and the share permissions because both are independent and can restrict you from the access.
As an alternative you can authenticate at the remote network share with an user and password - there is an excellent thread in stackoverflow which you can find here which does show how you can achieve this.
Naturally you can also set the service to a user/password in the services manager (services.msc - double click your service and go to the logon tab) who has access to the share. By doing this, the user will be granted the 'login as service' permission which is necessary for this.
If the network file is shared with the local system account then you need to Log In as "Local System Account",
The advantage of running your services as the "Local System account" is that the service has complete unrestricted access to local resources.
But there are some disadvantages also, so be careful to not install unauthorized services as service gets full unrestricted access. Also if the service has some bugs it may lead to performance issues.

C# MySql error: An established connection was aborted by the software in your host machine

I have a strange problem when working with MySql in C#. When executing the command sometimes(not always) I get "An established connection was aborted by the software in your host machine" error. I cannot solve this problem and can't find any solution in web.
As a workaround I developed simple ReConnection class. When this exception occurs I simply call ReOpen() method. It works perfectly with ADO.NET and I am using this trick more than 2 year.
public class ReConnection : DbConnection
{
private readonly int _reconnectAttempts;
private readonly int _reconnectInterval;
private bool _isOpened;
private int _reConnectSessions;
private readonly object _syncRoot = new object();
private readonly DbCommand _pingCommand;
private readonly DbConnection _innerConnection;
public ReConnection(DbConnection innerConnection,
int reconnectAttempts = 4, int reconnectInterval = 1000)
{
_innerConnection = innerConnection;
_pingCommand = _innerConnection.CreateCommand();
_pingCommand.CommandText = "SELECT 1 FROM DUAL";
_reconnectAttempts = reconnectAttempts;
_reconnectInterval = reconnectInterval;
}
public override void Open()
{
_innerConnection.Open();
_isOpened = true;
}
public override void Close()
{
_isOpened = false;
while (_reConnectSessions > 0)
Thread.Sleep(100);
_innerConnection.Close();
}
internal bool ReOpen()
{
var restored = false;
lock (_syncRoot)
{
_reConnectSessions++;
var retries = _reconnectAttempts;
try
{
_pingCommand.ExecuteNonQuery();
restored = true;
}
catch (Exception)
{
while (_isOpened &&
((retries > 0) || (_reconnectAttempts == -1)) &&
!restored)
{
if ((retries < _reconnectAttempts) || (_reconnectAttempts == -1))
Thread.Sleep(_reconnectInterval);
try
{
_innerConnection.Close();
try
{
_innerConnection.Open();
}
catch{}
//here ecception occurs. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.
_innerConnection.Close(); // closing the corrupted connection
_innerConnection.Open(); // opening the new connection
//tut vnezapno poyavlaetsya transport connection, kuda mojno pisat' dannie
_pingCommand.ExecuteNonQuery();
restored = true;
}
catch (Exception){}
retries--;
}
}
}
}
}
}
But recently I have developed an app with Entity Framework and similar exception occurs here also. I can't develop previous workaround for Entity Framework.
Does anyone encounter such problem with MySql ?
What is the actual reason behind this exception?
Where the error occurs
Error Details
The connection will expire and terminated by the host after some time. This is managed by MySql so nothing you can do in the code.
If particular query takes a long time to execute (some of my queries takes ~ 20 mins to return), you can set the timeout via the connection string - just add this to you connection string "ConnectionIdleTimeout=1800;Command Timeout=0;".
The Connection idle time out stops the mySql server from killing the connection until the given time (it's not recommended to set it to 0, otherwise eventually the host will be swamped with the open connections, and report an error or max open connections exceeding the limit), while the command timeout = 0 stops any command to timeout by itself. A combination of the two should help with the error.
However, I don't personally like to cache the DbConnection, given the timeout behavior from the server side. I prefer to rely solely on the server to time out the connections, and on C# side, I usually just use:
using MySqlConnection connection = new MySqlConnection("yourConnectionString"); connection.Open();

Grapevine REST server , I could not reach from other PC with IP or host name

I am using VS2012 and Grapevine 3.0.4 , when i use the Grapevine same machine with localhost
hostname , everything works well.
If I want to reach from other PC with client , Server could not be start listening with hostname ip address or Computername
If i try server pc set hostname to localhost , it starts listening but when reached from other PC with IP or name server returns bad request 400
Is it something wrong with my code or library.
My Server code is
public class embeddedHTTP
{
private RESTServer Server;
public void ServerStart()
{
try
{
Server = new RESTServer();
Server.Port = GlobalVars.HttpHostPort;
Server.Host = GlobalVars.HttpHostAdress; // THIS ONLY WORKS FOR LOCALHOST
Server.MaxThreads = 20;
Server.Start();
while (Server.IsListening)
{
Thread.Sleep(GlobalVars.HttpHostRespTime);
}
}
catch (Exception ex)
{
messenger.logque("embedded HTTP server not started, Error ID : 52", 3, null);
}
}
public void ServerStop()
{
Server.Stop();
}
public sealed class MyResource : RESTResource
{
//d+$^ [a-zA-Z]+
[RESTRoute(Method = Grapevine.HttpMethod.GET, PathInfo = #"/")]
public void HandleFooRequests(HttpListenerContext context)
{
//String RawuR = context.Request.RawUrl;
String URL = Convert.ToString(context.Request.Url);
String ResultXML = brain.HTTPCMD(URL);
this.SendTextResponse(context, ResultXML);
}
}
}
If you can't reach the server from a remote machine, you are likely running a firewall that is blocking inbound traffic to the port you are listening on. Try opening the port on your firewall, and see if that works for you.
How to Open a Port in the Windows 7 Firewall
Also, you can listen on all hosts by using the asterisk (*) as your hostname.

Client Bluetooth connection with 32feet.NET fails all the time

I'm trying to get a Bluetooth socket connection up and running but for some reason my client will not connect.
More precisely I get an exception when I try to connect to the stream:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
All examples I found online didn't really solve my problem and I'm currently not really sure where the problem comes from.
The scanning and pairing works fine - I see that the Bluetooth device in question gets successfully paired.
I try to connect via first setting the Client and then call connect
Client Bluetooth name, address and pin are known:
public bool SetClient(String clientName, String btAddress, String pin)
{
bool retVal = false;
m_remoteBluetoothClient = new BluetoothDeviceInfo(BluetoothAddress.Parse(btAddress));
m_localBluetoothClient.SetPin(pin);
if (m_remoteBluetoothClient.Authenticated)
{
//m_localBluetoothClient.Authenticate = true;
retVal = true;
}
else
{
if (BluetoothSecurity.PairRequest(m_remoteBluetoothClient.DeviceAddress, pin))
{
retVal = true;
}
}
return retVal;
}
Then an async connect:
private void ClientConnectThread()
{
m_localBluetoothClient.BeginConnect(m_remoteBluetoothClient.DeviceAddress, BluetoothService.SerialPort, Connect, m_localBluetoothClient);
}
private void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
m_localBluetoothClient.EndConnect(result);
mBtStream = m_localBluetoothClient.GetStream();
}
}
The locals m_localBluetoothEndpoint and m_localBluetoothClient are created like this although the Endpoint is more or less new (before I used BluetoothCLient without parameter):
m_localBluetoothEndpoint = new BluetoothEndPoint(BluetoothRadio.PrimaryRadio.LocalAddress, BluetoothService.SerialPort);
m_localBluetoothClient = new BluetoothClient(m_localBluetoothEndpoint);
I also tried to work with a Listener in case the remote devices wants to connect but the callback gets never called:
public void SetupListener()
{
var listener = new BluetoothListener(BluetoothService.SerialPort);
listener.Start();
listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallbackTwo, listener);
}
Can anyone tell me if there is anything wrong with my connection approach above and how I can figure out why I get the exception mentioned above?
The exception gets thrown here:
m_localBluetoothClient.EndConnect(result);
A thing I also don't understand is that the SupportedServices call to the remoteCLient returned 0 guids - so the device did not list any Bluetooth services.
m_remoteBluetoothClient.InstalledServices()
Thank you

Categories