I have aproblem with windows service - c#

i have a problem with my windows service program
i try to create a windows service to read data from a database and insert them into an other database but when i read data from first db and copy it into a dataset i have a problem, i can't read those data from data set and insert it into an other dataset to insert it into the other database
here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Collections;
using System.Data.Sql;
namespace WindowSeriveDemo
{
public partial class Service1 : ServiceBase
{
string connection = #"Data Source=DEVELOPER-PC\DEVELOPER;Initial Catalog=NMSys;User ID=sa;Password=2649940931";
string connection2 = #"Data Source=DEVELOPER-PC\DEVELOPER;Initial Catalog=Dpardazesh;User ID=sa;Password=2649940931";
private Timer ServiceTimer = new Timer();
private int inProcess = 0;
public const string SP_dataRead = "usp_Read_Data_From_DpardazeshDB";
public const string SP_insertData = "usp_Write_Data_Into_NMSysDB";
private IEnumerable<DataRow> item;
//Timer timer1 = new Timer();
public Service1()
{
InitializeComponent();
setupTimer();
}
protected override void OnStart(string[] args)
{
//ServiceTimer.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
}
private void setupTimer()
{
ServiceTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
ServiceTimer.Interval = 10000;
ServiceTimer.Enabled = true;
ServiceTimer.Start();
}
protected override void OnStop()
{
//timer1.Enabled = false;
}
private void SyncDatabases()
{
inProcess = 1;
SqlConnection conn2 = new SqlConnection(connection2);
try
{
conn2.Open();
SqlCommand cmd = new SqlCommand(SP_dataRead);
winservDS dataSet = new winservDS();
cmd.CommandType = CommandType.StoredProcedure;
//AddParameter(cmd);
SqlDataAdapter adapter = new SqlDataAdapter(SP_dataRead, conn2);
adapter.Fill(dataSet, dataSet.usp_Read_Data_From_DpardazeshDB.TableName);
dataSet.AcceptChanges();
return ;
}
catch (Exception ex)
{
string text = ex.Message;
}
inProcess = 0;
}
private static SqlCommand cmdGetIdentity;
public winservDS InsertUsers(IDictionary ids)
{
inProcess = 1;
SqlConnection conn = new SqlConnection(connection);
SqlConnection conn2 = new SqlConnection(connection2);
conn.Open();
conn2.Open();
winservDS updates = new winservDS();
DataRow dr;
dr = updates.usp_Read_Data_From_DpardazeshDB.NewRow();
foreach (DictionaryEntry i in ids)
{
if (i.Value == null)
dr[i.Key.ToString()] = DBNull.Value;
else
dr[i.Key.ToString()] = i.Value;
}
updates.usp_Read_Data_From_DpardazeshDB.Rows.Add(dr);
try
{
winservDS.usp_Read_Data_From_DpardazeshDBDataTable tbl = updates.usp_Read_Data_From_DpardazeshDB;
//Create the adapter initial
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.InsertCommand = WriteDatabase(conn);
//Roll Back the changes if some one error have
dataAdapter.ContinueUpdateOnError = false;
cmdGetIdentity = new SqlCommand("SELECT ##IDENTITY", conn);
dataAdapter.RowUpdated += new SqlRowUpdatedEventHandler(HandleRowUpdated);
dataAdapter.Update(tbl.Select("", "", DataViewRowState.Added));
return updates;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
inProcess = 0;
}
private static void HandleRowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if ((e.Status == UpdateStatus.Continue) && (e.StatementType == StatementType.Insert))
{
e.Row["id"] = Convert.ToInt32 (cmdGetIdentity.ExecuteScalar());
e.Row.AcceptChanges();
}
}
private static SqlCommand WriteDatabase(SqlConnection conn)
{
SqlCommand cmd = new SqlCommand(SP_insertData);
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameterCollection pc = cmd.Parameters;
pc.Add(CreateParameter("#fHitType", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("#DateOfHit", System.Data.SqlDbType.DateTime));
pc.Add(CreateParameter("#TimeOfHit", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("#fEmpid", System.Data.SqlDbType.Int));
cmd.ExecuteNonQuery();
return cmd;
}
private static SqlParameter CreateParameter(string p, SqlDbType sqlDbType)
{
SqlParameter parameter = new SqlParameter("#" + p, sqlDbType);
parameter.SourceColumn = p;
return parameter;
}
private void ServiceTimer_Tick(object sender, EventArgs e)
{
if (inProcess == 0)
{
ServiceTimer.Stop();
SyncDatabases();
CopyData();
//InsertUsers(ids);
ServiceTimer.Start();
}
}
private void CopyData()
{
DataSet ds1 = new winservDS();
DataSet ds2 = new In_Out_RecordsDS();
foreach (DataRow item in ds1.Tables[0].Rows)
{
ds2.Tables[0].Rows.Add(item);
}
} here

Try to use a DataReader for the source recordsets, read all columns into variables and then insert them into second database with an INSERT Statement. Be avoid of your transaction log when copying thousands of records...

Related

How to Put Data in to Repeter Using Entity File in MVC ASP.NET

I want to get data from entity file and put into repeter so how can i put them.
Ignore the format.
Display.aspx.cs File
public partial class AdminSide_Display : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Int32 ind = 0;
DataSet ds = GetData(ind);
RptDis.DataSource = ds;
RptDis.DataBind();
}
private DataSet GetData(Int32 Index)
{
SubjectWiseTopicBAL baltopic = new SubjectWiseTopicBAL();
SubjectWiseTopicENT enttopic = new SubjectWiseTopicENT();
enttopic = baltopic.SelectByID(Index);
// enttopic.
//Index += 1;
//using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InterviewPrepration"].ConnectionString))
//{
// SqlDataAdapter da = new SqlDataAdapter("select * from IP_SubjectWiseTopic where Subject_ID='Index'", con);
// DataSet ds = new DataSet();
// da.Fill(ds);
// return ds;
//}
}
protected void SelectSubject_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 index = SelectSubject.SelectedIndex;
}
}
** This is the method in (BAL) Business Layer file **
#region SelectByID
public SubjectWiseTopicENT SelectByID(SqlInt32 subjectid)
{
SubjectWiseTopicDAL dalsubjectwisetopic = new SubjectWiseTopicDAL();
return dalsubjectwisetopic.PR_IP_SubjectWIseTopic_SelectBySubjectID(subjectid);
}
** This is (DAL) Data Access layer file**
#region PR_IP_SubjectWIseTopic_SelectBySubjectID
public SubjectWiseTopicENT PR_IP_SubjectWIseTopic_SelectBySubjectID(SqlInt32 SubjectID)
{
using (SqlConnection objConn = new SqlConnection(ConnectionString))
{
objConn.Open();
using (SqlCommand objCmd = objConn.CreateCommand())
{
try
{
#region Prepread Command
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.CommandText = "PR_IP_SubjectWIseTopic_SelectBySubjectID";
objCmd.Parameters.AddWithValue("#SubjectID", SubjectID);
#endregion
#region Read and set controls
SubjectWiseTopicENT entSubjectWiseTopic = new SubjectWiseTopicENT();
AddSubjectENT entsubject = new AddSubjectENT();
using (SqlDataReader objSDR = objCmd.ExecuteReader())
{
while (objSDR.Read())
{
if (!objSDR["Topic_ID"].Equals(DBNull.Value))
{
entSubjectWiseTopic.Topic_ID = Convert.ToInt32(objSDR["Topic_ID"]);
}
#region Doubut How to Pass Subject Name in This
if (!objSDR["Subject_Name"].Equals(DBNull.Value))
{
entsubject.Subject_Name = Convert.ToString(objSDR["Subject_Name"]);
}
#endregion
if (!objSDR["Topic_Description"].Equals(DBNull.Value))
{
entSubjectWiseTopic.Topic_Description = Convert.ToString(objSDR["Topic_Description"]);
}
if (!objSDR["Topic_Name"].Equals(DBNull.Value))
{
entSubjectWiseTopic.Topic_Name = Convert.ToString(objSDR["Topic_Name"]);
}
if (!objSDR["Sequence"].Equals(DBNull.Value))
{
entSubjectWiseTopic.Sequence = Convert.ToInt32(objSDR["Sequence"]);
}
}
return entSubjectWiseTopic;
}
#endregion
}
catch (Exception ex)
{
Message = ex.InnerException.Message;
return null;
}
finally
{
if (objConn.State == ConnectionState.Open)
{
objConn.Close();
}
}
}
}
}
#endregion
So all necessary code is here. so how can i get data from entity and put data in repeter.(using Dataset or any things else.)

SQL Server & C#: duplicate insert error from unique data

I insert unique data into SQL Server, but it is inserted twice. It happens one or twice time a year. When I delete inserted data and run procedure again, it doesn't happen on same data again. What is the reason and how to avoid it?
I use a SQL Server stored procedure, where is many select, use sequence, insert is in cursor. In procedure there is begin and commit transaction around insert. Duplicate happens for more orders, but after insert data for one order, there is commit. Error happens in one minute and another batch of inserts few minutes later, is OK.
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
//using System.
using System.Text;
using System.Timers;
using System.IO;
using System.Configuration;
namespace WindowsService
{
class WindowsService : ServiceBase
{
Timer myTimer;
bool _smyckaBezi;
public WindowsService()
{
this.ServiceName = "Windows Service Jobs OSTRA SAP";
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
static void Main()
{
ServiceBase.Run(new WindowsService());
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
myTimer = new Timer(5000); // Sets a 10 second interval
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);// Specifies The Event Handler
myTimer.Enabled = true; // Enables the control
myTimer.AutoReset = true; // makes it repeat
myTimer.Start();
}
protected void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_smyckaBezi) return;
_smyckaBezi = true;
SqlConnection conn = null;
string output = null;
List<string> list = new List<string>();
try
{
Config config = new Config();
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
conn = new SqlConnection(cs);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT TOP 1 procedure_name AS [procedure_name] FROM dbo.jobs_sap WHERE datediff(minute, next_execution, getdate())>=0 AND upper(procedure_name) IN (SELECT upper(s.name)+'.'+upper(o.name) FROM sys.objects o JOIN sys.schemas s ON o.schema_id=s.schema_id WHERE o.type='P') ORDER BY next_execution";
command.CommandType = CommandType.Text;
// execute the command that returns a SqlDataReader
SqlDataReader reader = command.ExecuteReader();
// display the results
while (reader.Read())
{
output = reader["procedure_name"].ToString();
list.Add(output);
}
reader.Close();
for (int i = 0; i < list.Count; i++) // Loop through List with for
{
string pname = list[i];
string sql = "UPDATE dbo.jobs_sap SET last_execution = next_execution WHERE execution_time is not null AND procedure_name= '" + pname + "';";
SqlCommand cmdu = new SqlCommand(sql, conn);
cmdu.ExecuteNonQuery();
sql = "UPDATE dbo.jobs_sap SET next_execution = convert(datetime,CAST(getdate()+1 AS DATE)) + CAST(execution_time AS DATETIME) WHERE execution_time is not null AND procedure_name= '" + pname + "';";
cmdu = new SqlCommand(sql, conn);
cmdu.ExecuteNonQuery();
string sql2 = "UPDATE dbo.jobs_sap SET last_execution = next_execution WHERE execute_every_min is not null AND procedure_name= '" + pname + "';";
SqlCommand cmdu2 = new SqlCommand(sql2, conn);
cmdu2.ExecuteNonQuery();
sql2 = "UPDATE dbo.jobs_sap SET next_execution = dateadd(minute, execute_every_min,getdate()) WHERE execute_every_min is not null AND procedure_name= '" + pname + "';";
cmdu2 = new SqlCommand(sql2, conn);
cmdu2.ExecuteNonQuery();
_smyckaBezi = false;
SqlCommand cmd = new SqlCommand(list[i], conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
}
}
catch(Exception ex)// catch (InvalidCastException e)
{
writeToLogFileService(ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
_smyckaBezi = false;
}
}
}
public static void writeToLogFileService(string logMessage)
{
string str_LogMessage = string.Empty;
string str_LogFile = "d:\\temp\\log_jobs_sap.txt";
StreamWriter swLog;
str_LogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);
if (!File.Exists(str_LogFile))
{
swLog = new StreamWriter(str_LogFile);
}
else
{
swLog = File.AppendText(str_LogFile);
}
swLog.WriteLine(str_LogMessage);
swLog.WriteLine();
swLog.Close();
}
protected override void OnStop()
{
base.OnStop();
}
protected override void OnPause()
{
base.OnPause();
}
protected override void OnContinue()
{
base.OnContinue();
}
protected override void OnShutdown()
{
base.OnShutdown();
}
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
}
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return base.OnPowerEvent(powerStatus);
}
protected override void OnSessionChange(
SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
}
}
}
using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace WindowsService
{
[RunInstaller(true)]
public class WindowsServiceInstaller : Installer
{
/// <summary>
/// Public Constructor for WindowsServiceInstaller.
/// - Put all of your Initialization code here.
/// </summary>
public WindowsServiceInstaller()
{
ServiceProcessInstaller serviceProcessInstaller =
new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Password = null;
//# Service Information
serviceInstaller.DisplayName = "Windows Service Jobs OSTRA SAP";
serviceInstaller.StartType = ServiceStartMode.Automatic;
//# This must be identical to the WindowsService.ServiceBase name
//# set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = "Windows Service Jobs OSTRA SAP";
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
}
}
Thanks for comments, it was helpfull. C# service fired procedure twice times. So I added second control directly into service (first check in procedure was not enough). Solution:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
//using System.
using System.Text;
using System.Timers;
using System.IO;
using System.Configuration;
using log4net;
namespace WindowsService
{
class WindowsService : ServiceBase
{
Timer myTimer;
bool _smyckaBezi;
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public WindowsService()
{
this.ServiceName = "Windows Service Jobs";
this.EventLog.Log = "Application";
// These Flags set whether or not to handle that specific
// type of event. Set to true if you need it, false otherwise.
this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
}
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
if (args.Length > 0 && args[0] == "/console")
{
WindowsService ws = new WindowsService();
ws.Start();
System.Threading.Thread.Sleep(int.MaxValue);
}
else
{
ServiceBase.Run(new WindowsService());
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
myTimer = new Timer(10000); // Sets a 10 second interval
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);// Specifies The Event Handler
myTimer.Enabled = true; // Enables the control
myTimer.AutoReset = true; // makes it repeat
myTimer.Start();
}
public void Start()
{
//base.OnStart(args);
myTimer = new Timer(10000); // Sets a 10 second interval
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);// Specifies The Event Handler
myTimer.Enabled = true; // Enables the control
myTimer.AutoReset = true; // makes it repeat
myTimer.Start();
}
protected void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
using (LogEx le = new LogEx(log))
{
if (_smyckaBezi) return;
_smyckaBezi = true;
SqlConnection conn = null;
string output = null;
List<string> list = new List<string>();
try
{
Config config = new Config();
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
conn = new SqlConnection(cs);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT TOP 1 procedure_name AS [procedure_name] FROM dbo.jobs_crm WHERE ISNULL(spusteno_WS,0)=0 AND datediff(minute, next_execution, getdate())>=0 AND upper(procedure_name) IN (SELECT upper(s.name)+'.'+upper(o.name) FROM sys.objects o JOIN sys.schemas s ON o.schema_id=s.schema_id WHERE o.type='P') ORDER BY next_execution";
command.CommandType = CommandType.Text;
// execute the command that returns a SqlDataReader
SqlDataReader reader = command.ExecuteReader();
// display the results
while (reader.Read())
{
output = reader["procedure_name"].ToString();
list.Add(output);
}
reader.Close();
for (int i = 0; i < list.Count; i++) // Loop through List with for
{
string pname = list[i];
try
{
string sql = "UPDATE dbo.jobs_crm SET spusteno_WS=1, last_execution = getdate(), next_execution = convert(datetime,CAST(getdate()+1 AS DATE)) + CAST(execution_time AS DATETIME) WHERE execution_time is not null AND procedure_name= '" + pname + "';";
SqlCommand cmdu = new SqlCommand(sql, conn);
cmdu.ExecuteNonQuery();
string sql2 = "UPDATE dbo.jobs_crm SET spusteno_WS=1, last_execution = getdate(), next_execution = dateadd(minute, execute_every_min,getdate()) WHERE execute_every_min is not null AND procedure_name= '" + pname + "';";
SqlCommand cmdu2 = new SqlCommand(sql2, conn);
cmdu2.ExecuteNonQuery();
_smyckaBezi = false;
//execute procedure
SqlCommand cmd = new SqlCommand(list[i], conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(pname + " > " + ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""));
//le.Exception(ex);
le.Error(pname + " > " + ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""));
}
finally
{
string sql3 = "UPDATE dbo.jobs_crm SET spusteno_WS=0 WHERE procedure_name= '" + pname + "';";
SqlCommand cmdu3 = new SqlCommand(sql3, conn);
cmdu3.ExecuteNonQuery();
}
}
}
catch (Exception ex)// catch (InvalidCastException e)
{
Console.WriteLine(ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""));
le.Error("Obecná chyba > " + ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""));
//writeToLogFileService(ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
_smyckaBezi = false;
} } } }
public static void writeToLogFileService(string logMessage)
{
string str_LogMessage = string.Empty;
string str_LogFile = "d:\\temp\\log_jobs_test_crm.txt";
StreamWriter swLog;
str_LogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);
if (!File.Exists(str_LogFile))
{
swLog = new StreamWriter(str_LogFile);
}
else
{
swLog = File.AppendText(str_LogFile);
}
swLog.WriteLine(str_LogMessage);
swLog.WriteLine();
swLog.Close();
}
protected override void OnStop()
{
base.OnStop();
}
protected override void OnPause()
{
base.OnPause();
}
protected override void OnContinue()
{
base.OnContinue();
}
protected override void OnShutdown()
{
base.OnShutdown();
}
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
}
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return base.OnPowerEvent(powerStatus);
}
protected override void OnSessionChange(
SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
}
}
}

Oracle Query is not being executed

I'm trying to retrieve values from an Oracle database using C# WebMethod, ajax and JavaScript, I have another page with exactly all the same functions and methods (using MSSQL Database) and work fine, but now I want to do it with Oracle. This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Oracle.DataAccess.Client;
using System.Data;
using System.Configuration;
/// <summary>
/// Summary description for OracleConexion
/// </summary>
public class OracleConexion
{
OracleConnection conn;
DataTable dt;
OracleDataAdapter da;
OracleDataReader dr;
DataSet ds;
OracleCommand cmd;
public OracleConexion()
{
conn = new OracleConnection("Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = ***.**.**.***)(PORT = ****)))(CONNECT_DATA = (SERVER = DEDICATED)(SID = *****))); User Id = *****; Password = ****;");
}
private void Open()
{
string canConnect;
try
{
conn.Open();
canConnect = "Nice";
}
catch (Exception ex)
{
//Code Updated
canConnect = ex.Message.ToString();
}
Console.Write(canConnect);
}
private void Close()
{
try
{
conn.Close();
}
catch (Exception ex)
{
}
}
public DataTable ConsultarTablas(string opcion)
{
dt = new DataTable();
ds = new DataSet();
string sql = "";
switch (opcion)
{
case "Datos":
sql = "Select Component as Result from BOM_Explosion where TOP_MATERIAL = '-FHN7092A-EF' and ROWNUM <= 5;";
break;
}
try
{
Open();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception ex)
{
}
finally
{
Close();
}
return dt;
}
}
And this is my WebMethod
[WebMethod]
public string ObtenerDatosNumeroParte()
{
DataTable dt = new DataTable();
dt = conn.ConsultarTablas("Datos");
Ticket ti;
List<Ticket> lista = new List<Ticket>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ti = new Ticket();
ti.Vs = dt.Rows[i]["Result"].ToString();
lista.Add(ti);
ti = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lineas = js.Serialize(lista);
return lineas;
}
Testing it seems like my code do not execute my query and my List always is null, what I'm doing wrong and what can I do to solve it?
Update
Using my string canConnect I get ORA-6413: Connection not open.

The connection is open

A few months ago I made a test program for a project and everything worked fine there.
Now I am working on the program itself, so I copied the code from the test program and
changed the the names of the columns,buttons etc. so it would fit the current program.
When I try to add something into the database it does nothing on the first click, on the
second pops up an error which says that the connection is open.. I really got no idea what's
the problem. I tried to check again if I made a mistake in a column name or the database name
but everything seems to be correct.
Note: I also have a function that show data from the database and it works without any problem.
private void InsertData()
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
Connection.Open();
DataAdd.ExecuteNonQuery();
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
string NewRowNum()
{
string Row = RowFind();
int CalcRow = int.Parse(Row) + 1;
Row = CalcRow.ToString();
return Row;
}
The connection that appears to be open is the one in the string RowFind().
Here are the other related things to the database:
public partial class frmShop : Form
{
System.Data.SqlClient.SqlConnection Connection;
public frmShop()
{
string DatabaseConnection = WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1;
Connection = new System.Data.SqlClient.SqlConnection();
Connection.ConnectionString = DatabaseConnection;
InitializeComponent();
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
Connection.Open();
SqlDataReader ReadSentence = null;
Int32 BinaryInt = Int32.Parse(txtBinaryString.Text);
string CommandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
SqlCommand Command = new SqlCommand(CommandString, Connection);
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
ReadSentence = Command.ExecuteReader();
while (ReadSentence.Read())
{
txtSentence.Text = (ReadSentence["Sentence"].ToString());
Fit = 1;
}
Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You are getting errors because you are reusing the same connection Connection.Open(); several times.
Your method InsertData() is doing this 3 times in the same method.
You should create a new instance of the connection object and dispose it on your methods.
Using Statement are the way to go.
private void InsertData()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
string NewCode = GenerateCode();
string NewSentence = txtSentence.Text;
string NewRow = NewRowNum();
try
{
Connection.Open();
string AddData = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
SqlCommand DataAdd = new SqlCommand(AddData, Connection);
DataAdd.Parameters.AddWithValue("#NewBinaryString", NewCode);
DataAdd.Parameters.AddWithValue("#NewNewSentence", NewSentence);
DataAdd.Parameters.AddWithValue("#NewRowNumber", NewRow);
DataAdd.ExecuteNonQuery();
//Connection.Close(); no need to close
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
You can save one more connection if you store the row returned by RowFind()
string RowFind()
{
using (var Connection = new SqlConnection(DatabaseConnection))
{
Connection.Open();
string queryString = string.Format("SELECT * FROM ShopSentences");
SqlDataAdapter sda = new SqlDataAdapter(queryString, Connection);
DataTable dt = new DataTable("ShopSentences");
sda.Fill(dt);
//Connection.Close();
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
So you would connect once instead of twice:
var Row = RowFind();
string NewCode = GenerateCode(Row);
string NewRow = NewRowNum(Row);
string NewSentence = txtSentence.Text;
Declare your connection string variable to a property so you can reuse it:
private string DatabaseConnection {get; set;}
Instead using an instance level SqlConnection you should only provide a common factory for creating a connection:
public partial class frmShop : Form
{
private string ConnectionString
{
get { return WindowsFormsApplication1.Properties.Settings.Default.BinaryStringsDictionaryConnectionString1; }
}
public frmShop()
{
InitializeComponent();
}
private SqlConnection CreateConnection()
{
var conn = new SqlConnection(ConnectionString);
conn.Open();
return conn;
}
private void frmShop_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'binaryStringsDictionaryDataSet.ShopSentences' table. You can move, or remove it, as needed.
this.shopSentencesTableAdapter.Fill(this.binaryStringsDictionaryDataSet.ShopSentences);
}
private void GetSentence()
{
try
{
using (var conn = CreateConnection())
{
var BinaryInt = int.Parse(txtBinaryString.Text);
var commandString = "SELECT Sentence FROM ShopSentences WHERE BinaryStrings = #BinaryString";
using (var Command = new SqlCommand(commandString, conn))
{
Command.Parameters.Add("#BinaryString", System.Data.SqlDbType.Int).Value = BinaryInt;
using (var readSentence = Command.ExecuteReader())
{
while (readSentence.Read())
{
txtSentence.Text = (readSentence["Sentence"].ToString());
Fit = 1;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void InsertData()
{
try
{
using (var conn = CreateConnection())
{
var commandString = "INSERT INTO ShopSentences (BinaryStrings,Sentence,RowNumber) VALUES (#NewBinaryString,#NewSentence,#NewRowNumber)";
using (var comm = new SqlCommand(commandString, conn))
{
comm.Parameters.AddWithValue("#NewBinaryString", GenerateCode());
comm.Parameters.AddWithValue("#NewNewSentence", txtSentence.Text);
comm.Parameters.AddWithValue("#NewRowNumber", NewRowNum());
comm.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
//Checking the banary code in the last row
string GenerateCode()
{
string RowNo = RowFind();
int Row = int.Parse(RowNo);
int Code = Row + 1;
string Cd = Convert.ToString(Code, 2);
int Ln = Cd.Trim().Length;
if (Ln == 3)
{
Cd = "100" + Cd;
}
else if (Ln == 4)
{
Cd = "10" + Cd;
}
else if (Ln == 5)
{
Cd = "1" + Cd;
}
return Cd;
}
//Finding the last row
string RowFind()
{
using (var conn = CreateConnection())
{
var commandString = "SELECT * FROM ShopSentences";
using (var comm = new SqlCommand(commandString, conn))
{
using (var sda = new SqlDataAdapter(queryString, Connection))
{
using (DataTable dt = new DataTable("ShopSentences"))
{
sda.Fill(dt);
return dt.Rows[dt.Rows.Count - 1]["RowNumber"].ToString();
}
}
}
}
}
string NewRowNum()
{
var Row = RowFind();
var CalcRow = int.Parse(Row) + 1;
return CalcRow.ToString();
}
}
But this is just the beginning you should not have any hard SQL dependency in your Form classes.
When sharing same SqlConnection instance several times in your code, instead of directly opening the you can rather check the connection state first and then open it if not already opened. For example:
if(Connection.State!= ConnectionState.Open)
Connection.Open();

How to retrieve the value of first index through ComboBox in C#.Net?

I kept getting "FormatException was unhandled by user Code"
Following is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Eventmanagement
{
public partial class Registration : Form
{
SqlConnection aConnection;
string firstname= string.Empty;
string lastname= string.Empty;
int aid;
string date = DateTime.Now.ToShortDateString();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dta;
public Registration(string fname, string lname, int attID)
{
this.firstname = fname;
this.lastname = lname;
this.aid = attID;
InitializeComponent();
}
//--------------------------------------------//
private void Registration_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'insertEventDataSet.Events' table. You can move, or remove it, as needed.
populateEventSalesPersonList();
populateEventNameIdTypeList();
//+++++++++++++++++++++++++++++++++++++++++++//
txtSalesTaxRate_Registration.Text = Convert.ToString( SalesTaxRate());
txtRegistrationID_Registration.Text = regID().ToString();
//+++++++++++++++++++++++++++++++++++++++++++//
//+++++++++++++++++++++++++++++++++++++++++++//
txtAttendee_Registration.Text = (this.firstname+" "+this.lastname);
txtRegistrationDate_Registration.Text = date.ToString();
}
//--------------------------------------------//
public string getConnectionString()
{
try
{
string sConnection = "";
// Get the mapped configuration file.
System.Configuration.ConnectionStringSettingsCollection ConnSettings = ConfigurationManager.ConnectionStrings;
sConnection = ConnSettings["DBConnectionString"].ToString();
return sConnection;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return "";
}
}
//--------------------------------------------//
public void populateEventNameIdTypeList()
{
try
{
cmbEvent_Registration.DataSource = getDataTable4();
//----------------------------
cmbEvent_Registration.ValueMember = "EventID";
cmbEvent_Registration.DisplayMember = "EventName";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//--------------------------------------------//
public void populateEventSalesPersonList()
{
try
{
cmbSalesPerson_Registration.DataSource = getDataTable5();
cmbSalesPerson_Registration.ValueMember = "EmployeeID";
cmbSalesPerson_Registration.DisplayMember = "SalesPerson";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
//--------------------------------------------------//
//saleTax();
//txtSalesTax_Registration.Text = Convert.ToString(saleTax());
//txtTotalCharges_Registration.Text = Convert.ToString(totalCharges());
//txtAmountDue_Registration.Text = Convert.ToString(amountDue());
//--------------------------------------------------//
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//------------------------------------------//
//------------------------------------------//
private void btnclose_Registration_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnInsert_Registration_Click(object sender, EventArgs e)
{
try
{
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
//Calling the Stored Procedure
da.InsertCommand = new SqlCommand("RegistrationInsert", aConnection);
da.InsertCommand.CommandType = CommandType.StoredProcedure;
//da.InsertCommand.Parameters.Add(#"RegistrationID", SqlDbType.Int).Value = Convert.ToInt16( txtRegistrationID_Registration.Text);
da.InsertCommand.Parameters.Add(#"AttendeeID", SqlDbType.Int).Value = Convert.ToInt16( aid);
da.InsertCommand.Parameters.Add(#"RegistrationDate", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtRegistrationDate_Registration.Text=date.ToString());
da.InsertCommand.Parameters.Add(#"PurchaseOrderNumber", SqlDbType.VarChar).Value = txtPoNumber_Registration.Text;
// da.InsertCommand.Parameters.Add(#"SalesPerson", SqlDbType.Int).Value = Convert.ToInt64(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"EventID", SqlDbType.Int).Value = cmbEvent_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"FeeScheduleID", SqlDbType.Int).Value = cmbFeeSchedule_Registration.SelectedValue.ToString();
da.InsertCommand.Parameters.Add(#"RegistrationFee", SqlDbType.Money).Value = txtRegistrationFee_Registration.Text;
da.InsertCommand.Parameters.Add(#"EmployeeID", SqlDbType.Int).Value = Convert.ToInt16(cmbSalesPerson_Registration.SelectedValue.ToString());
da.InsertCommand.Parameters.Add(#"SalesTaxRate", SqlDbType.Float).Value = txtSalesTaxRate_Registration.Text;
//da.InsertCommand.Parameters.Add(#"EndTime", SqlDbType.SmallDateTime).Value = Convert.ToDateTime(txtEndTime.Text.ToString());
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Inserted successfully!!!");
aConnection.Close();
da.InsertCommand.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
//-------------------------------------------//
public DataTable getDataTable4()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("EventsSelectAll", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable5()
{
try
{
dta = new DataTable();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("sp_RegistrationSalesPerson", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
dta.Clear();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
public DataTable getDataTable6()
{
try
{
dta = new DataTable();
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
aConnection.Open();
da.SelectCommand = new SqlCommand("sp_FeeScheduleSelectAllByEventID", aConnection);
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dta);
aConnection.Close();
return dta;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
return null;
}
}
private void cmbEvent_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
populateFeeScheduleByEventList();
txtRemainingSeats_Registration.Text = Convert.ToString(spaces());
}
public double saleTax()
{
double regFee = Convert.ToDouble(cmbFeeSchedule_Registration.SelectedText);
double sTR = Convert.ToDouble(SalesTaxRate());
double sr = regFee * (sTR / 100);
return sr;
}
public int totalRegisteredAttendees()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationSelectAllByEventID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int val = (int)da.SelectCommand.ExecuteScalar();
aConnection.Close();
return val;
}
public int spaces()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("EventsSelect", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("EventID", SqlDbType.Int).Value = Convert.ToInt32(cmbEvent_Registration.SelectedValue.ToString());
aConnection.Open();
int spaces = Convert.ToInt16(da.SelectCommand.ExecuteScalar());
aConnection.Close();
int value = totalRegisteredAttendees();
int totalspaces = spaces - value;
return totalspaces;
}
public double SalesTaxRate()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("CompanyInfo", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
double sale = Convert.ToDouble(da.SelectCommand.ExecuteScalar());
aConnection.Close();
return sale;
}
public double totalCharges()
{
double tc = Convert.ToDouble(txtRegistrationFee_Registration.Text) + (saleTax());
return tc;
}
public double amountDue()
{
double aD;
if (txtTotalPaid_Registration.Text == string.Empty)
{
aD = Convert.ToDouble(txtTotalCharges_Registration.Text.ToString());
}
else
{
double a = Convert.ToDouble(txtTotalPaid_Registration.Text.ToString());
double b= (Convert.ToDouble(txtTotalCharges_Registration.Text.ToString()));
aD = b-a;
}
return aD;
}
public int regID()
{
da = new SqlDataAdapter();
aConnection = new SqlConnection(getConnectionString());
da.SelectCommand = new SqlCommand("RegistrationID", aConnection);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
aConnection.Open();
int id = ((int)da.SelectCommand.ExecuteScalar())+1;
aConnection.Close();
return id;
}
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
saleTax();
}
//------------------------------------------//
}
}
When I call SaleTax() Method in following
private void cmbFeeSchedule_Registration_SelectedIndexChanged(object sender, EventArgs e)
{
saleTax();
}
I get "FormatException was unhandled by user Code" Error
I debugged the Code and find out that it is happening because cmbFeeSchedule_Registration is not selecting the first index, hence it is giving the error. I am confused what to do?
How I get around this Problem?
Edit:
Well I resolved the issue. It was the problem of in ` public void populateFeeScheduleByEventList()
{
try
{
cmbFeeSchedule_Registration.DataSource = getDataTable6();
cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID";
cmbFeeSchedule_Registration.DisplayMember = "Fee";
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}`
When SaleTax() was called, pointer leaves the DisplayMember and ValueMember. Hence I readjusted the code little bit and placed cmbFeeSchedule_Registration.ValueMember = "FeeScheduleID"; cmbFeeSchedule_Registration.DisplayMember = "Fee"; before
cmbFeeSchedule_Registration.DataSource = getDataTable6(); and it resolved the Problem. :)
If it is required that index 0 be selected in your ComboBox then you need to do some basic checking. In your SelectedIndexChanged EventHandler wire-up, you need to add:
if (cmbFeeSchedule_Registration.SelectedIndex == 0) {
salesTax();
}
Also if the user is able to change the text in the ComboBox, you are not doing any error handling to handle the FormatException that will be caused by Convert.ToDouble when trying to convert a non-double value that is not parsable.
double regFee = Convert.ToDouble(cmbFeeSchedule_Registration.SelectedText);
double sTR = Convert.ToDouble(SalesTaxRate());
Furthermore, you could actually use double.Parse or double.TryParse instead of ConvertTo, which seems more proper. On another note, if the user cannot edit the text in the ComboBox (say you have it set to DropDownList), you should use the SelectedObject or SelectedValue property instead of SelectedText depending if it is DataBound or not.
Bottom line is you need to make sure you are checking that the correct index is selected before calling salesTax() or any operation that will potentially throw an exception, and do error checking to ensure that your values are what they should be. If regFee is anything but a double, because the correct index is not selected, ConvertTo will fail. (Use double.Parse/TryParse instead, anyway)
A tip of advice when posting questions is to only post the affected segment of code, and provide a StackTrace when one is available. It's too difficult to navigate all of your code on here, and using a StackTrace it is easy to break down.
you have to make selectedindex = 0 in your form
Just do this:
if(((ComboBox)sender).SelectedIndex > -1) saleTax();
instead. If you want to select the first item when the form loads, set SelectedIndex in the Load event.

Categories

Resources