I have the below program that receives socket streams in form of XML and inserts them into SQL database. My problem is the following:
- When the program is launched in debug mode, all the xml streams are inserted successfully into the database.
- When it is launched normally (no debug mode), the program will insert one xml stream and miss the other (So if I had 20 streams, only 10 will be inserted).
What could be the error in this code?
client = Listener.AcceptTcpClient();
netstream = client.GetStream();
Status = "Connected to a client\n";
byte[] bytes = new byte[client.ReceiveBufferSize + 1];
netstream.Read(bytes, 0, Convert.ToInt32(client.ReceiveBufferSize));
// Return the data received from the client
string clientdata = System.Text.Encoding.ASCII.GetString(bytes);
Status="Client sent: " + clientdata ;
StorePolicy(clientdata);
Query = clientdata;
Query = Query.Replace("\0", "");
StorePolicy(Query);
Status="Received Query: " + Query;
StorePolicy("Received Query: " + Query);
netstream.Close();
client.Close();
///////////////insert into database/////////
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand Cmd = new SqlCommand();
string[] words = Query.Split(new[] { "</RECORD>" }, StringSplitOptions.None);
StorePolicy(Query);
foreach (string word in words)
{
if (!string.IsNullOrEmpty(word))
{
record = word.Replace("'", "''") + "</RECORD>";
StorePolicy(record);
StrQuery = "INSERT INTO SMSListenner(XMLText) VALUES ('" + record.Replace("'", "''") + "')";
Cmd = new SqlCommand(StrQuery, conn);
conn.Open();
Cmd.ExecuteReader();
conn.Close();
StorePolicy(StrQuery);
}
}
}
MSDN clearly says:
The TcpListener class provides simple methods that listen for and
accept incoming connection requests in blocking synchronous mode.
This means once one client is connected, it blocks every other client until your "poor man web server" finished with the stream. Other clients that wait in the queue might timeout in mean time. Mind yourself that you are doing a hell of a lot to process request. This means that you will block other clients for a significant amount of time.
Also, you have no exception handling, so one client can kill your entire "server".
My advice, if it's not a student's project to learn how sockets work, use proper web server with isolation between connections, and capable of processing multiple connections at the same time.
Related
I am connecting my application with a remote database (SQL Server 2012) and I faced the issue "Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=211; handshake=14787;"
Thing to notice is that application is working fine with the remote database but this error occurs only few times a day (e.g. 5 times out of 100 attempts in a day), rest all application is working fine with this database.
Below given is the C# code to connect with the SQL Server database and execute query.
List<string> lstDuplicateSNames = new List<string>();
string commaSeparatedStudentNames = "X,Y,Z,A,B,C";
string query = "SELECT DISTINCT(Student_NAME) FROM V_STUDENT_RECORDS WHERE Student_NAME IN ('" + commaSeparatedStudentNames + "')";
using (SqlConnection myConnection = new SqlConnection("Database=Student_DB;Server=nkj-connect.com;Integrated Security=true;"))
{
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.Connection = myConnection;
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = query;
myCommand.CommandTimeout = 0;
myCommand.Connection.Open();
using (SqlDataReader reader = myCommand.ExecuteReader())
{
// Check is the reader has any rows at all before starting to read.
if (reader.HasRows)
{
while (reader.Read())
{
lstDuplicateSNames.Add(reader.GetString(0));
}
}
}
}
}
Please suggest what I am missing here.
I have faced scenario similar to this. What worked for me was changing connection server to IPAddress from server name, in your case nkj-connect.com
I'm using the following code to execute a query in C#:
// Create Connection String
AdomdConnection testConnection = new AdomdConnection("Data Source=*****;User ID=******;Provider=MSOLAP.6;Persist Security Info=True;Impersonation Level=Impersonate;Password=******");
// Test Open
testConnection.Open();
// Make Query
AdomdCommand cmd = new AdomdCommand(#"SELECT { [Measures].[Payment Amount] } ON COLUMNS,
{ [Charging Low Orgs].[Charging Division].[Charging Division] } ON ROWS
FROM [Payments]", testConnection);
AdomdDataReader dataReader = cmd.ExecuteReader();
// Close Connection
testConnection.Close();
And I keep getting this error on the cmd.ExecuteReader() call:
{"XML for Analysis parser: The CurrentCatalog XML/A property was not specified."}
The only literature that I could find that was relavent to this was that the query isn't resolving because impersonation wasn't set, but I specified that in the connection string.
Another article which I don't think is related, said to enable BAM on Excel, but I don't have that option in Excel, and I fail to see how that would make a difference for a web service.
Please help!
The following example includes a catalog parameter in the connection string:
static void Main(string[] args)
{
AdomdConnection conn = new AdomdConnection(
"Data Source=localhost;Catalog=Adventure Works DW Standard Edition");
conn.Open( );
string commandText = "SELECT {[Measures].[Sales Amount], " +
"[Measures].[Gross Profit Margin]} ON COLUMNS, " +
"{[Product].[Product Model Categories].[Category]} ON ROWS " +
"FROM [Adventure Works] " +
"WHERE ([Sales Territory Country].[United States])";
AdomdCommand cmd = new AdomdCommand(commandText, conn);
AdomdDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
I created a small application that queries a db2 database and returns information. I created a windows form that accepts input and returns the information from the query. My closing statement is a:
finally
{
conn.close();
}
I was curious -- does the connection (conn) actually close when I hit the little red box on the form? I searched the other questions here and the web but could not really find a definitive answer.
Here's the full try-catch-finally block (with some info obfuscated --> *****):
`try
{
conn.Open();
string queryString = String.Format("SELECT * " +
"FROM ***** " +
"WHERE USERPRF LIKE '%{0}%' " +
"ORDER BY TIMESTMP DESC " +
"FETCH FIRST 1 ROWS ONLY", userNameInput);
using (OdbcCommand com = new OdbcCommand(queryString, conn))
{
using (OdbcDataReader reader = com.ExecuteReader())
{
if (reader.Read())
{
string ***** = reader["*****"].ToString();
string ***** = reader["*****"].ToString();
string user = reader["USERPRF"].ToString();
string timeStamp = reader["TIMESTMP"].ToString();
listBox1.Items.Clear();
listBox1.Items.Add("Username: " + user);
listBox1.Items.Add("*****" + *****);
listBox1.Items.Add("*****: " + *****);
listBox1.Items.Add("Last Changed: " + timeStamp);
}
else
{
listBox1.Items.Clear();
listBox1.Items.Add("There was no data to return! Try again.");
}
}
}
}
catch (Exception ex)
{
string errorMessage = ex.Message;
}
finally
{
conn.Close();
}`
If the connection is owned by the application, then yes - it should close.
It is generally bad practice to leave a connection open for long duration's as it constitutes a security risk. (Someone could inject code into your application to reuse the open the connection, to do dodgy stuff)
using (SqlConnection cn = new SqlConnection(strConnectString))
{
// Stuff
}
I would make sure that you handle the onClosing event of your windows form, and tell it to dispose of the SqlConnection explicitly, or at least attempt to do so.
Better safe than sorry.
Note - I have heard some talk that SqlConnections can be shared in the SQLConnectionPool. If this is the case, you can modify your connection string to disable or enable ConnectionPooling.
We have two servers. An application server and a SQL server.
When running this simple program from the application server:
static void Main(string[] args)
{
OleDbCommand cmd;
OleDbConnection cnn;
string connectionString = "Provider=SQLNCLI10;Integrated Security=SSPI;User ID=***;Password=***;Persist Security Info=False;Initial Catalog=MCS_BATCH;Data Source=CD6S01;Initial File Name=;";
string sql = "EXEC [msp].[MasterMSP] #BTYPE = N'B_PVM_KNN', #AC_KEY = NULL, #RUN_TS = '2014-05-02 17:29:31.1400555', #CHUNK_ID = 8794";
System.IO.StreamWriter file = new System.IO.StreamWriter("MasterMSP_output.txt");
cnn = new OleDbConnection(connectionString);
try
{
cnn.Open();
cmd = new OleDbCommand(sql, cnn);
try
{
OleDbDataReader reader = cmd.ExecuteReader();
int numberOfFields = reader.VisibleFieldCount;
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
for (int i = 0; i < (numberOfFields - 1); i++)
{
file.Write(reader[i].ToString());
}
file.WriteLine("");
}
file.Close();
}
catch (Exception ex)
{
file.Write("Execption ex at : {0}", System.DateTime.Now);
file.Write(ex.Message.ToString());
Console.WriteLine("Exception ex time is : {0}", System.DateTime.Now);
throw;
}
cmd.Dispose();
cnn.Close();
}
catch (Exception exx)
{
file.Write("Execption exx at : {0}", System.DateTime.Now);
file.Write(exx.Message.ToString());
Console.WriteLine("Exception exx time is : {0}", System.DateTime.Now);
throw;
}
}
We get - after some time - a "Protocol error in TDS stream" error:
We ran a network trace, and we can see that the "TCP Window size" is decreasing after 10 mins and then it's sending a TCP Window size = 0 (close window).
This means that the SQL server can't send more data until it has gotten a update window size, bigger than 0, from the application server.(right?):
The SQL server is trying to send 1 byte keepalive, but the application server is never responding. (The problem is that the application server never raise TCP Windows Size again. At the end the application server is terminating the session.)
We except that it's the application server fault and it could be that the networks buffer is not being empty(flushed) anymore. The only thing the TCP stack can do is to close the TCP Windows Size until the application again empties the buffer - but it never does that.
Any hints, ideas on what the issue can be?
The problem actually came up in 3rd party program. This program is calling a stored procedure on the SQL server. So I just tried to reproduce the logic in a C# program and was able to reproduce the error.
Any help, ideas or comments are highly appreciated.
Thanks
Adding this to the connectionstring fixed the error: MARS Connection=True
Link
I've been tasked with a one time migration from a 4D database to our MSSQL structure. I've got a datasource set up in the ODBC administrator and I was able to connect to it without issues.
I 'reverse engineered' the schema in Visio so I can get a good visual of the relationships between the tables and plan out how I'm going to re-structure the 4D data to fit into our schema. I created a simple console application as this will be a one time run, and I'm able to make the connection to the data source, but as soon as I execute anything, the connection drops or is disabled.
System.Data.Odbc.OdbcConnection conn =
new System.Data.Odbc.OdbcConnection("Dsn=4D v12 datasource");
try
{
conn.Open();
Console.WriteLine("Status of Connection:" + conn.State.ToString());
//Here it says the connection to the DB is open and ready for action
Console.ReadLine();
//pause to visually confirm the connection is open
OdbcCommand com = new OdbcCommand("SELECT * FROM ATable", conn);
com.CommandType = CommandType.Text;
Console.Write(com.ExecuteNonQuery());
//Right here it blows up and closes the connection
}
I also tried to do something with data set and data adapter, but to no avail.
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection("Dsn=4D v12 datasource");
try
{
conn.Open();
Console.WriteLine("Status of Connection:" + conn.State.ToString());
Console.ReadLine();
OdbcCommand com = new OdbcCommand("SELECT * FROM ATable", conn);
com.CommandType = CommandType.Text;
//Also tried using data sets and data adapters
DataSet dsTest = new DataSet();
OdbcDataAdapter dataAdapter = new OdbcDataAdapter(com);
//but right at this line the connection suddenly disconnects
dataAdapter.Fill(dsTest);
}
catch (Exception e)
{
Console.WriteLine("Failure:" + e.Message.ToString());
// the exception message reads simply connection has been disabled.
Console.WriteLine("Status of Connection: " + conn.State.ToString());
Console.ReadLine();
}
finally
{
Console.Write("Closing connection.");
conn.Close();
Console.Write(".");
conn.Dispose();
Console.WriteLine(".");
Console.WriteLine("Connection Closed and Disposed");
Console.ReadLine();
}
I've tried to look for anyone experiencing this same difficulty, but the documentation I've found has been scarce and not very helpful in this specific regard. There is a good amount of information about executing queries on the 4D product, but not from across the digital divide. Anyone with experience please advise. Thanks for your time and for any help you may be able to give, avid reader.
Apparently the root cause of the issue was in the driver. Upon replacing the driver I got from the website with one sent from the proprietor, the connections ceased being disabled and all is working as intended.