unable to update the oracle DB using ExecuteNonQuery() - c#

Please find the source code below. I am not getting any error but
_oracleCommand.ExecuteNonQuery() is going infinite - debugger is not moving to next line. I am able to update the data using Toad. I am stuck with this.
public void UpdateNewResignationRequestInSynergy(string _employeeno, string _comment, string _changeby, string _changeddt, string _reason)
{
int rowsaffected = 0;
string returnStatus;
string _synquery = "";
DateTime dtDate;
_employeeno = "774647";
_comment = "contract eand";
dtDate = DateTime.Parse(_changeddt, System.Globalization.CultureInfo.CreateSpecificCulture("en-CA"));
_oracleCommand = new OracleCommand(_synquery, _synergyDb);
_synergyDb.Open();
_oracleCommand.CommandText = string.Format(#"update wipinfo.fms_resignation set str_comments = 'contract end' where STR_CONTRACTOR_ID = 774647");
_oracleCommand.CommandType = CommandType.Text;
try
{
_oracleCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
}
_synergyDb.Close();
}

You have to stop the oracle server and start again( do not restart it will not help you). I solved this problem by doing this process.

Related

How can I query the MySQL Max_Allowed_Packet through c#?

I am trying to check the value of the max_allowed_packet size. This is my code:
public int MaxAllowedPacket()
{
var max = 0;
using (var conn = new MySqlConnection(_ConnectionString))
{
var sql = conn.CreateCommand();
sql.CommandText = "SHOW VARIABLES like 'max_allowed_packet'";
try
{
conn.Open();
var reader = sql.ExecuteReader();
// not sure where to go from here
}
catch (Exception ex)
{
// I've got some logging here
}
}
return max;
}
I'm suspecting the format of the query or the execution is wrong because my result is always
-1
EDIT:
I have edited the code to use sql.ExecuteReader() but the result is now:
"Enumeration yielded no results".
Eventually figured it out myself, and thought to post it here, before this gets downvoted even more...
var reader = sql.ExecuteReader();
reader.Read();
max = reader.GetInt32(1);
It's best to put some try catches around and you can optionally query the first field through reader.GetString(0), which should return "max_allowed_packet".

C# Stops Executing When Opening A Connection To MySql

I am writing an application to transfer data from a simulated OPC server to a MySql Database. I am using some of the libraries from OPC Foundation - OPCNETAPI.DLL, OPCNETAPI.COM.DLL.
I have the program reading from the server happily, but it seems as soon as I open a connection inside the loop of reading data, it loops about 5 times and then stops executing.. There are no exceptions thrown and I have tried for hours to work it out and miserably failed.
I've also changed VisualStudio to break when an exception is thrown, and it doesn't
Hopefully some one may know whats going on, but there is nothing obvious, hopefully the following code will spark ideas!
Windows Forms Code
public void readplc()
{
Opc.URL url = new Opc.URL("opcda://localhost/Matrikon.OPC.Simulation.1");
Opc.Da.Server server = null;
OpcCom.Factory fact = new OpcCom.Factory();
server = new Opc.Da.Server(fact, null);
try
{
server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
}
catch (Exception ecy)
{
}
// Create a group
Opc.Da.Subscription group;
Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState();
groupState.Name = "Group";
groupState.Active = true;
group = (Opc.Da.Subscription)server.CreateSubscription(groupState);
// add items to the group.
Opc.Da.Item[] items = new Opc.Da.Item[2];
items[0] = new Opc.Da.Item();
items[0].ItemName = "Random.Int1";
items[1] = new Opc.Da.Item();
items[1].ItemName = "Random.Time";
items = group.AddItems(items);
group.DataChanged += new Opc.Da.DataChangedEventHandler(OnTransactionCompleted);
}
public void OnTransactionCompleted(object group, object hReq, Opc.Da.ItemValueResult[] items)
{
for (int i = 0; i < items.GetLength(0); i++)
{
try
{
string a = items[i].Value.ToString();
string b = items[i].ItemName;
string c = items[i].Key;
MySqlConnection conn = new MySqlConnection("server=localhost;user id=localhost;password=localhost;database=localhost;pooling=false");
conn.Open();
conn.Close();
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}
I have set break points throughout the code, stepped through everything possible and still nothing obvious that's causing the issue.

C# Nested Function Wont Trigger

Hello i would like to ask you about a small problem i have with a certain program. So basically the program(console app) reads packets from other Procees(Program) and delivers the packets so they can be analyzed. The problem i stumbeled upon is that One of my nested functions wont trigger (completely). Example:
This line is lying in the Main() function. Along with the rest , this is just a clip
captureDevice.OnPacketArrival += new PacketArrivalEventHandler(Program.device_OnPacketArrival);
After which i have some console.writeline etc. Nothing special.
device_OnPacketArrival() is Function with some other Nested Functions Inside.
private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
{
DateTime date = packet.Packet.Timeval.Date;
int length = packet.Packet.Data.Length;
..........
Program.ValidateItem(first_db_id, first_bin_id, out char_id, out user_id, out type, out valid);
............
The Function that causes problem is:ValidateItem()
public static void ValidateItem(int item_Id, int item_type, out int char_id, out int user_id, out int type, out int valid)
{
valid = type = user_id = char_id = 0;
string oString = "SELECT type,char_id,user_id FROM [DB].[dbo].[Table] WHERE id = #item_id";
SqlCommand oCmd = new SqlCommand(oString, Program.s_DB);
oCmd.Parameters.AddWithValue("#item_id", item_Id);
try
{
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
if (oReader.Read())
{
type = Convert.ToInt32(oReader["type"]);
char_id = Convert.ToInt32(oReader["char_id"]);
user_id = Convert.ToInt32(oReader["user_id"]);
if (type == item_type)
{
valid = 1;
}
else
{
valid = 0;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The Problem is that only the first line of the function is initialized - valid = type = user_id = char_id = 0; But if i run the function directly in Main() its working fine.
Not sure if answering your question
but in c# there is no "nested" functions , if you need to create that "illusion" try using annonymus
functions

Why would this query generate a file sharing violation?

The following code gives me the error (I get it from the MessageBox.Show() in the catch block)
"Exception in PopulateBla() : There is a file sharing violation. A
different process might be using the file [,,,,,,]
CODE
using (SqlCeCommand cmd = new SqlCeCommand(SQL_GET_VENDOR_ITEMS, new SqlCeConnection(SQLCE_CONN_STR)))
{
cmd.Parameters.Add("#VendorID", SqlDbType.NVarChar, 10).Value = vendorId;
cmd.Parameters.Add("#VendorItemID", SqlDbType.NVarChar, 19).Value = vendorItemId;
try
{
cmd.Connection.Open();
using (SqlCeDataReader SQLCEReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (SQLCEReader.Read())
{
itemID = SQLCEReader.GetString(ITEMID_INDEX);
packSize = SQLCEReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
}
catch (SqlCeException err)
{
MessageBox.Show(string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message));//TODO: Remove
}
finally
{
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
}
}
SQL_GET_VENDOR_ITEMS is my query string.
What file sharing problem could be happening here?
UPDATE
This is the kind of code that makes that sort of refactoring recommended by ctacke below difficult:
public void setINVQueryItemGroup( string ID )
{
try
{
dynSQL += " INNER JOIN td_item_group ON t_inv.id = td_item_group.id AND t_inv.pack_size = td_item_group.pack_size WHERE td_item_group.item_group_id = '" + ID + "'";
}
catch( Exception ex )
{
CCR.ExceptionHandler( ex, "InvFile.setINVQueryDept" );
}
}
A SQL statement is being appended to by means of a separate method, altering a global var (dynSQL) while possibly allowing for SQL Injection (depending on where/how ID is assigned). If that's not enough, any exception thrown could mislead the weary bughunter due to indicating it occurred in a different method (doubtless the victim of a careless copy-and-paste operation).
This is "Coding Horror"-worthy. How many best practices can you ignore in a scant few lines of code?
Here's another example:
string dynSQL = "SELECT * FROM purgatory WHERE vendor_item = '" + VendorItem + "' ";
if (vendor_id != "")
{
dynSQL += "AND vendor_id = '" + vendor_id + "' ";
}
It could be done by replacing the args with "?"s, but the code to then determine which/how many params to assign would be 42X uglier than Joe Garagiola's mean cleats.
I really like Chris' idea of using a single connection to your database. You could declare that global to your class like so:
public ClayShannonDatabaseClass
{
private SqlCeConnection m_openConnection;
public ClayShannonDatabaseClass()
{
m_openConnection = new SqlCeConnection();
m_openConnection.Open();
}
public void Dispose()
{
m_openConnection.Close();
m_openConnection.Dispose();
m_openConnection = null;
}
}
I'm guessing your code is crashing whenever you attempt to actually open the database.
To verify this, you could stick an integer value in the code to help you debug.
Example:
int debugStep = 0;
try
{
//cmd.Connection.Open(); (don't call this if you use m_openConnection)
debugStep = 1;
using (SqlCeDataReader SQLCEReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
debugStep = 2;
if (SQLCEReader.Read())
{
debugStep = 3;
itemID = SQLCEReader.GetString(ITEMID_INDEX);
debugStep = 4;
packSize = SQLCEReader.GetString(PACKSIZE_INDEX);
debugStep = 5;
recordFound = true;
}
}
}
catch (SqlCeException err)
{
string msg = string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message);
string ttl = string.Format("Debug Step: {0}", debugStep);
MessageBox.Show(msg, ttl); //TODO: Remove
}
// finally (don't call this if you use m_openConnection)
// {
// if (cmd.Connection.State == ConnectionState.Open)
// {
// cmd.Connection.Close();
// }
// }
I'm guessing your error is at Step 1.
Provided the file isn't marked read-only (you checked that, right?), then you have another process with a non-sharing lock on the file.
The isql.exe database browser that comes with SQL CE is a common culprit if it's running in the background.
Depending on your version of SQLCE, it's quite possible that another process has an open connection (can't recall what version started allowing multiple process connections), so if you have any other app in the background that has it open, that may be a problem too.
You're also using a boatload of connections to that database, and they don't always get cleaned up and released immediately up Dispose. I'd highly recommend building a simple connection manager class that keeps a single (or more like two) connections to the database and just reuses them for all operations.

Error in Calling SQL CLR function

I am writing a CLR function to parse a table column and write the results into another table. Basic requirement is parsing the Detail column, which contains a Time part and an ID part. Results will be the time difference between two Ids.
Ex: Time1,Id1;Time2,Id2;Time3,Id3... and so on
Time2-Time1 is time taken by Id1 in seconds.
Same function is working in normal console application but CLR function is throwing the exception when I call it from SQL server.
Error is
A .NET Framework error occurred during execution of user-defined routine or aggregate "Function1":
System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.
The protected resources (only available with full trust) were: All
The demanded resources were: UI
System.Security.HostProtectionException:
at UserDefinedFunctions.Function1(String msisdn, String promptdetails)
My code is:
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
int count = 0;
string PromptPart = string.Empty;
string PrevPromptPart = string.Empty;
DateTime TimePart;
TimePart = new DateTime();
DateTime PrevTimePart;
PrevTimePart = new DateTime();
TimeSpan difference;
try
{
count++;
conn.ConnectionString = "Context Connection=true";
cmd.Connection = conn;
String[] string1 = promptdetails.Split(";".ToCharArray());
foreach (var item1 in string1)
{
count++;
String[] string2 = item1.Split(",".ToCharArray());
PromptPart = string2[1];
TimePart = DateTime.ParseExact(string2[0], "M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
if (count > 1)
{
StringBuilder sbQuery = new StringBuilder(1024);
sbQuery.Append("INSERT INTO [Shami].[DBO].[data] (MSISDN,PromptID1,PromptID2,TimeDifference) VALUES");
sbQuery.Append("('");
sbQuery.Append(msisdn);
sbQuery.Append("',");
difference = TimePart.Subtract(PrevTimePart);
sbQuery.Append("'");
sbQuery.Append(PrevPromptPart);
sbQuery.Append("','");
sbQuery.Append(PromptPart);
sbQuery.Append("',");
sbQuery.Append(difference.Seconds);
sbQuery.Append(")");
string sub = string.Empty;
sub = sbQuery.ToString();
try
{
conn.Open();
cmd = new SqlCommand(sub);
SqlContext.Pipe.ExecuteAndSend(cmd);
}
catch (Exception ie)
{
Console.WriteLine("Error..");
}
}
if (count <= 1)
{
StringBuilder sbQuery = new StringBuilder(1024);
sbQuery.Append("INSERT INTO [Shami].[DBO].[data] (MSISDN,PromptID1,PromptID2,TimeDifference) VALUES");
sbQuery.Append("('");
sbQuery.Append(msisdn);
sbQuery.Append("',");
sbQuery.Append("'_'");
sbQuery.Append(",");
sbQuery.Append(PromptPart);
sbQuery.Append(",");
sbQuery.Append("'0'");
sbQuery.Append(")");
string sub = string.Empty;
sub = sbQuery.ToString();
try
{
conn.Open();
cmd = new SqlCommand(sub);
SqlContext.Pipe.ExecuteAndSend(cmd);
}
catch (Exception ie)
{
Console.WriteLine("Error..");
}
}
PrevPromptPart = PromptPart;
PrevTimePart = TimePart;
}
}
catch (Exception)
{ ;}
finally
{
conn.Close();
conn.Dispose();
cmd.Dispose();
}
return msisdn;
Please let me know where I'm going wrong. I can't debug in CLR.
You would just need to replace your line
Console.WriteLine("Error...");
with this line:
SqlContext.Pipe.Send("Error...");
This will do the same thing for you and it will run

Categories