DB2 ConnectionString error - c#

A button on the aspx page checks whether the connection with the DB2 database server is established or not. My connection String is :
Server=xx.xx.xx.xx:446; Database=dd_unit; UID=db2admin; PWD=Secure*888; CurrentSchema=ptdd;
It is throwing me a SQL30081N error message:
$exception {"ERROR [08001] [IBM] SQL30081N A communication error has been detected. Communication protocol being used: \"TCP/IP\".
Communication API being used: \"SOCKETS\". Location where the error
was detected: \"xx.xx.xx.xx\". Communication function detecting the
error: \"connect\". Protocol specific error code(s): \"10060\",
\"\", \"\". SQLSTATE=08001\r\n"} System.Exception
{IBM.Data.DB2.DB2Exception}
I looked for the SQL30081N error and it is due to connection was terminated by the network by the tcp-ip layer. Now, does the problem is with the Connection String or is it something else? Kindly help me solve this issue.
Code: (Its throwing error after connection is opened)
protected void Button3_Click(object sender, EventArgs e)
{
DB2Connection con = new DB2Connection("Server=xx.xx.xx.xx:446; Database=MyDb; UID=MyUser; PWD=MyPass; CurrentSchema=ptdd;");
try
{
con.Open();
Label1.Visible = true;
Label1.Text = "Conection done";
con.Close();
}
catch (Exception)
{
Label1.Text = "connection failed";
}
P.S. I'm using this to test my application

Port specified was incorrect. It must be 50000 as it is a tcp/ip connection

Related

Handshake failed due to an unexpected packet format

I am trying to have a stable connection to a MySQL database hosted on Amazon Web Services. Periodically when starting the application, I will get the exception:
Handshake failed due to an unexpected packet format
This is a WinForm C# application using MySQL.Data.dll V6.9.9
Here is my code for connecting:
using (var conn = new MySqlConnection(m_connectionString))
{
try
{
conn.Open();
Console.WriteLine("Connected to database");
}
catch (MySqlException ex)
{
validConnectionFound = false;
Console.WriteLine(ex);
MessageBox.Show("Unable to connect to Database. Check your network connection and try again", "Database connection Not Found");
}
catch (CryptographicException ex)
{
validConnectionFound = false;
MessageBox.Show("Cryptographic Exception: " + ex.Message);
Environment.Exit(0);
}
catch(IOException ex)
{
validConnectionFound = false;
DebugTrace.TraceWrite(m_defaultTraceSource, TraceEventType.Error, "Incorrect certificate. Please update security certificate. Exception: " + ex.Message);
MessageBox.Show("IO Exception: " + ex.Message);
Environment.Exit(0);
}
}
My connection string is in the following format:
"user id=user;password=1234;server=amazonserver.com;database=myDatabase;convertzerodatetime=True;port=3306;sslmode=VerifyCA"
I have tried both wireless and wired connections, changing the SSL mode required (VerifyCA, Required, VerifyFull, None), and adding Amazons CA to my computers trusted root certificates.
Any insight on why I am getting this exception is appreciated.
Turns out the issue was not code related. After sniffing packets with Wireshark, I found the problem was with a faulty network switch losing packets.

Network connection with UWP Apps

I got two Windows UWP Apps. One of them (the "server") is running on a Raspberry Pi 2 on Windows IoT (10586.0). The other (the "client") is running on any Windows 10 device within the same network.
What I want is to get the apps to "talk" to each other. For the moment I just want to send simple String from the client to the server. Later on, serialized data should be transferred trough the network.
This is the code for the server App:
namespace LCARSHomeAutomation
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
try {
EstablishNetworking();
txb_Events.Text += "Server Running";
}catch (Exception ex)
{
txb_Events.Text += ex.Message;
}
}
private async void EstablishNetworking()
{
await StartListener();
}
public async Task StartListener()
{
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
listener.Control.KeepAlive = true;
try
{
await listener.BindServiceNameAsync("5463");
}
catch (Exception ex)
{
if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
//Logs.Add(ex.Message);
txb_Events.Text += ex.Message;
}
}
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// Your UI update code goes here!
txb_Events.Text += (String)request;
});
}
private async Task ConnectSocket()
{
StreamSocket socket = new StreamSocket();
socket.Control.KeepAlive = false;
HostName host = new HostName("localhost");
try
{
await socket.ConnectAsync(host, "5463");
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "Test Self App \n";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
socket.Dispose();
}
catch (Exception ex)
{
txb_Events.Text += ex.Message;
//Logs.Add(ex.Message)
}
}
private async void btn_Send_Click(object sender, RoutedEventArgs e)
{
await ConnectSocket();
}
}
}
As you can see, I'm establishing a network connection with the same app on the same host and send the string "Test Self App". This works fine for quite some time but after a while I get the Error:
Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll
WinRT information: No connection could be made because the target machine actively refused it.
So, this is my first question: What is this Error and how can I fix this?
The other thing is: I'm not able to establish a network Connection between the server and the Client. I don't know, what I am doing wrong. This is the code of the "Client":
namespace LCARSRemote
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void btn_Send_Click(object sender, RoutedEventArgs e)
{
StreamSocket socket = new StreamSocket();
HostName host = new HostName("localhost"); //Replace with coorect hostname when running on RPi
try
{
try {
await socket.ConnectAsync(host, "5463");
}
catch(Exception ex)
{
txb_Events.Text += ex.Message;
}
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "Remote App Test";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
socket.Dispose();
}
catch (Exception ex)
{
txb_Events.Text += ex.Message;
//Logs.Add(ex.Message)
}
}
}
}
When I click on the btn_Send, I get the error message
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.
and
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
What am I doing wrong? Maybe I should say, that I'm relatively new in programming network connections, sockets etc.
Thanks for any help!
You should try using StreamSocket API in UWP. This sample repo contents both server and client code: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/StreamSocket
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
This error happened for me when I try to call ConnectAsync twice in a row, I think you can check your logic or debug to confirm in your case.
The first error
Exception thrown: 'System.Runtime.InteropServices.COMException' in
mscorlib.ni.dll
WinRT information: No connection could be made because the target
machine actively refused it.
This is because the socket is still open with a previous request and has not closed yet. So catch this error and try and to reconnect.
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.
This is because the server and client are on the same machine, I a running into this same problem supposedly you can run from an elevated command prompt
checknetisolation loopbackexempt -d -n= {package family}
to resolve it.
This solution did not work for me. So your server must run on a pi and client must run on your desktop PC for windows 10 UWP to be able to connect to it.
Windows 10 does not allow loopback connection for UWP applications as far as I can tell.
If you truly want to run a socket server/web server node.js windows universal apps might be a good approach
https://ms-iot.github.io/content/en-US/win10/samples/NodejsWU.htm
or
RestUP https://github.com/tomkuijsten/restup
Depending how much data you're talking about and what the end use case is, Amazon's AWS IoT Platform might be something to look at. It's pretty cool for a number of reasons. Specifically I like that the target device can be offline at the time of transmission.
It's free (250,000 messages) for the first year and $5 per one million messages after that. Every 512 byte block counts as 1 message credit.

socketio4net error initializing handshake

I'm using Xamarin(mono 3.2.5) on OSX to create a C# console app that connects to the blockchain.info websocket stream. I've included the socketio4net library from NuGet and thought I followed the specs correctly, but I'm a bit new to socket.io connections in general, so please correct me on what I'm doing wrong. I get an error immediately after calling the socket.Connect() method below.
I have created a few event handlers like so:
static void SocketOpened(object sender, EventArgs e)
{
Console.WriteLine ("opened event handler");
Console.WriteLine (e.ToString());
}
static void SocketError(object sender, SocketIOClient.ErrorEventArgs e)
{
Console.WriteLine ("error event handler");
Console.WriteLine (e.Message);
}
static void SocketMessage(object sender, MessageEventArgs e)
{
Console.WriteLine ("message event handler");
Console.WriteLine (e.Message);
}
and my code is as follows:
var socket = new Client (#"ws://ws.blockchain.info:8335/inv");
socket.Opened += SocketOpened;
socket.Error += SocketError;
socket.Message += SocketMessage;
socket.Connect ();
Console.WriteLine ("handshake: " + socket.HandShake.ErrorMessage);
socket.On("connect", (fn) => {
Console.WriteLine("On.connect msg: " + fn.MessageText);
});
socket.On ("open", (fn) => {
Console.WriteLine("On.open msg: " + fn.MessageText);
});
my console output from this:
error event handler
Error initializing handshake with ws://ws.blockchain.info:8335/inv
handshake: Error getting handsake from Socket.IO host instance: An error occurred performing a WebClient request.
What have I done incorrectly? The blockchain API documentation is here: https://blockchain.info/api/api_websocket and I've tried both URLs they specify. Omitting the port number in the URL generates a different error. Instead of "error performing WebClient request", it appears to hunt for a local path to the socket server, which clearly is incorrect.
Any help from a more experienced programmer would be much appreciated
I face the same problem, on my case, its because of default internet connection at office must go through proxy.
Simply set the proxy to none with the code below, solved my problem.
System.Net.WebRequest.DefaultWebProxy = null;

How to check if the connection has been established using SAP.net coonector

I am trying to connect to my clients SAP system. I am using the following code to connect, but how do i come to know that the connection has been successfully established.
protected void Page_Load(object sender, EventArgs e)
{
try
{
SAPSystemConnect sapCfg = new SAPSystemConnect();
RfcDestinationManager.RegisterDestinationConfiguration(sapCfg);
RfcDestination rfcDest = null;
rfcDest = RfcDestinationManager.GetDestination("Dev");
}
catch (Exception ex)
{
lbl.Text=ex.Message;
}
}
If the connection doesn't throw an exception, you'll know that the connection has been established. If there is a problem with the connection, the class will throw an appropriate exception.

How to check SQL connection in C#.Net?

I want check my SQL server connection before to connect with DB, and I need to update the status of SQL Server connection in my GUI.
Here is the code I am checking SQL connection, but I couldn't able to get status frequently
Scenario :
Stop the sql server service from services window
Running the project and will show status "Connection Not Available"
Start Sql server service and displaying "Connection Live"
And Again Stop SQL server service and i am not getting the status as ""Connection Not
Available". It's returning status as "Connection Live"
It's not getting to the catch block
Code:
private void timer1_Tick(object sender, EventArgs e)
{
bool Flag = false;
try
{
using (SqlConnection con = new SqlConnection(strcon))
{
con.Open();
}
}
catch (SqlException s)
{
Flag = true;
label1.Text = "Connection Not available";
}
finally
{
if (Flag == false)
{
label1.Text = "Connection Live";
}
}
}
If there server is unavailable, your application will hang while it tries to connect. This should be run in a background worker and the status updated with a callback.
Wrap your connection attempt in a try..catch (it should be using a using statement at the very least). [The precise location of a try..catch in your code depends somewhat on the structure of your code.]
It is unusual for an application to maintain whether a SQL Server is available. After all, it might be unavailable milliseconds after you test and display that it is available.

Categories

Resources