两个错误系统转换无效,读取器关闭 [英] two errors system cast not valid and reader is closed
问题描述
我正在编写代码并且它给我的错误系统强制转换是无效的。
I am writing a code and it is giving me error system cast is not valid.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Configuration;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Net;
using System.Timers;
namespace cm18b
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(40000);
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string machineID = config.AppSettings.Settings["MachineID"].Value;
//MessageBox.Show(machineID);
double time = Convert.ToDouble(config.AppSettings.Settings["time"].Value);
System.Timers.Timer timer = new System.Timers.Timer(time);
timer.Elapsed += OnTimer;
timer.Enabled = true;
this.WindowState = FormWindowState.Minimized;
}
private void OnTimer(object source, ElapsedEventArgs e)
{
var timer = (System.Timers.Timer)source;
timer.Stop();
//MessageBox.Show("trying");
BuildTransactionXML();
timer.Start();
}
public bool SendFTP(string file_name)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
String source = config.AppSettings.Settings["sourcelocation"].Value + "/" + file_name; //Change to new file name
String ftpusername = config.AppSettings.Settings["ftpusername"].Value;
String ftppassword = config.AppSettings.Settings["ftppassword"].Value;
String ftpfullpath = config.AppSettings.Settings["ftpurl"].Value + "/" + file_name;
try
{
string filename = Path.GetFileName(source);
//string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
return true;
}
catch (WebException ex)
{
WriteLog(ex);
return false;
}
}
public void BuildTransactionXML()
{
string xmlString = "";
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string transactioncounter = config.AppSettings.Settings["transactioncounter"].Value;
string BustaA = config.AppSettings.Settings["bagnumber"].Value;
string cm18string = ConfigurationManager.ConnectionStrings["CM18String"].ConnectionString;
SqlConnection con = null;
try
{
con = new SqlConnection(cm18string);
if (con.State != System.Data.ConnectionState.Open)
{
con.Open();
}
string currency = "";
string device = "";
string result = "";
string symbol = "";
string type = "";
string type1 = "";
string file_name = "";
string user = "";
string filesaved = "";
string date = "";
string time = "";
string cassette = "";
SqlCommand cmd = new SqlCommand("SELECT [IDP],[DateTimeOperazione],[Importo],[TipoOperazione],[Banconote_E500],[Banconote_E200],[Banconote_E100],[Banconote_E50],[Banconote_E20],[Banconote_E10],[Banconote_E5],[BustaA] FROM [DataBos].[dbo].[Operazioni] join [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef where TipoOperazione IN ('161','3', '1') and IDP > @idp", con);
cmd.Parameters.Add("@idp", transactioncounter);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
string filecounter = config.AppSettings.Settings["filecounter"].Value;
switch (rd.GetInt32(3))
{
case 161:
type = "out";
type1 = "out";
break;
case 1:
type = "outb";
type1 = "outb";
break;
case 3:
type = "in";
type1 = "in";
config.AppSettings.Settings["bagnumber"].Value = rd.GetString(11);
config.Save(ConfigurationSaveMode.Modified);
BustaA= rd.GetString(11);
break;
default:
type = "";
break;
}
cassette = BustaA;
currency = "Euro";
symbol = "€";
date = rd.GetDateTime(1).ToString("M/DD/YYYY");
time = rd.GetDateTime(1).ToString();
device = config.AppSettings.Settings["MachineId"].Value;
file_name = device + "_" + type1 + ".xml";
xmlString = "";
xmlString = "<transaction><device>" + device + "</device><status>" + @type1 + "</status><currency><description>" + currency + "</description><symbol>" + symbol + "</symbol></currency><date_time><date>" + date + "</date><time>" + time + "</time></date_time><cassette>" + cassette + "</cassette><<filename>" + file_name + "</filename>";
file_name = device + "_" + type1 + "_" + filecounter + ".xml";
if (type == "in")
{
config.AppSettings.Settings["HasMoney"].Value = "True";
int ttype = 0;
int value = 0;
int quantity = 0;
for (int i =1 ; i<=7;i++)
{
ttype = 0;
value = 0;
quantity = 0;
switch(i)
{
case 1:
ttype = 500;
break;
case 2:
ttype = 200;
break;
case 3:
ttype = 100;
break;
case 4:
ttype = 50;
break;
case 5:
ttype = 20;
break;
case 6:
ttype = 10;
break;
case 7:
ttype = 5;
break;
}
quantity = rd.GetInt32(i+3);
value = quantity * ttype;
if(quantity !=0)
{
xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00").Replace(',', '.') + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00").Replace(',', '.') + "</value></transactionline>";
}
}
}
else if ((type == "out") || ((config.AppSettings.Settings["HasMoney"].Value == "True") && (type == "outb")))
{
type= "out";
config.AppSettings.Settings["HasMoney"].Value = "False";
SqlConnection con1 = new SqlConnection(cm18string);
if (con1.State != System.Data.ConnectionState.Open)
{
con1.Open();
}
SqlCommand cmd1 = new SqlCommand("SELECT SUM([Banconote_E500]),SUM([Banconote_E200]),SUM([Banconote_E100]),SUM([Banconote_E50]),SUM([Banconote_E20]),SUM([Banconote_E10]),SUM([Banconote_E5])),[BustaA] FROM [DataBos].[dbo].[Operazioni] join [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef where TipoOperazione IN ('161','3', '1') and BustaA = @bag group by BustaA", con1);
cmd1.Parameters.Add("@bag",cassette);
SqlDataReader rd1 = cmd1.ExecuteReader();
rd1.Read();
long ttype = 0;
long value = 0;
long quantity = 0;
for (int i =1 ; i<=7;i++)
{
ttype = 0;
value = 0;
quantity = 0;
switch(i)
{
case 1:
ttype = 5;
break;
case 2:
ttype = 10;
break;
case 3:
ttype = 20;
break;
case 4:
ttype = 50;
break;
case 5:
ttype = 100;
break;
case 6:
ttype = 200;
break;
case 7:
ttype = 500;
break;
quantity = rd1.GetInt32(i - 1);
value = quantity * ttype;
if(quantity !=0)
{
// xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00").Replace(',', '.') + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00").Replace(',', '.') + "</value></transactionline>"; //Enable for CSExtra
xmlString = xmlString + "<transactionline type = \"" + ttype.ToString("##########0.00") + "\"><quantity>" + quantity.ToString() + "</quantity><value>" + value.ToString("##########0.00") + "</value></transactionline>";
}
}
rd1.Close();
con1.Close();
}
//else
//{
//}
xmlString = xmlString + "</transaction>";
string fout = config.AppSettings.Settings["destinationlocation"].Value;
System.IO.StreamWriter file = new System.IO.StreamWriter(fout + "\\"+ file_name);
file.WriteLine(xmlString);
file.Close();
if (SendFTP(file_name))
{
config.AppSettings.Settings["transactioncounter"].Value = rd.GetInt32(0).ToString();
transactioncounter = rd.GetInt32(0).ToString();
config.Save(ConfigurationSaveMode.Modified);
config.AppSettings.Settings["filecounter"].Value = Convert.ToInt32(config.AppSettings.Settings["filecounter"].Value) + 1 + "";
filecounter = config.AppSettings.Settings["filecounter"].Value;
config.Save(ConfigurationSaveMode.Modified);
WriteLog(file_name);
}
else
{
break;
}
}
rd.Close();
con.Close();
}}
catch (Exception e)
{
WriteLog(e);
}{
}}
public void WriteLog(string message)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
file1.WriteLine();
file1.WriteLine("Successfully completed");
file1.WriteLine(message);
file1.WriteLine("==================================================================================================");
file1.WriteLine("==================================================================================================");
file1.WriteLine();
file1.Close();
}
catch
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
}
}
public void WriteLog(WebException ex)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
file1.WriteLine();
file1.WriteLine("FTP Error");
file1.WriteLine("Error : " + ex.ToString());
file1.WriteLine("FTP Response : " + ((FtpWebResponse)ex.Response).StatusDescription);
file1.WriteLine("FileCounter : " + config.AppSettings.Settings["filecounter"].Value);
file1.WriteLine("==================================================================================================");
file1.WriteLine("==================================================================================================");
file1.WriteLine();
file1.Close();
}
catch
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
}
}
public void WriteLog(Exception ex)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
string logfilelocation = config.AppSettings.Settings["loglocation"].Value;
System.IO.StreamWriter file1 = new System.IO.StreamWriter(logfilelocation + "\\log.txt", true);
file1.WriteLine();
file1.WriteLine("XML File Error");
file1.WriteLine("Error : " + ex.ToString());
file1.WriteLine("FileCounter : " + config.AppSettings.Settings["filecounter"].Value);
file1.WriteLine("==================================================================================================");
file1.WriteLine("==================================================================================================");
file1.WriteLine();
file1.Close();
}
catch
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show("Please create folder: " + config.AppSettings.Settings["loglocation"].Value);
}
}
}
}
它在数量上给出了错误= rd.GetInt32(i + 3)系统转换错误,我知道它是来自数据库的int值
and it is giving me error on quantity = rd.GetInt32(i+3) system cast error and i know it is int value from a database
推荐答案
它给我的数量错误= rd.GetInt32(i + 3)系统转换错误,我知道它是来自数据库的int值
你怎么知道?
"it is giving me error on quantity = rd.GetInt32(i+3) system cast error and i know it is int value from a database"
How do you know?
SqlCommand cmd = new SqlCommand("SELECT [IDP],[DateTimeOperazione],[Importo],[TipoOperazione],[Banconote_E500],[Banconote_E200],[Banconote_E100],[Banconote_E50],[Banconote_E20],[Banconote_E10],[Banconote_E5],[BustaA] FROM [DataBos].[dbo].[Operazioni] join [DataBos].[dbo].[Buste] on [DataBos].[dbo].[Operazioni].SessioneRef = [DataBos].[dbo].[Buste].SessioneRef where TipoOperazione IN ('161','3', '1') and IDP > @idp", con);
...
for (int i =1 ; i<=7;i++)
{
...
quantity = rd.GetInt32(i+3);
我会说你正在读取所有Banconote_Enn值和BustaA列,因为你的循环小于或等于7。
所以使用调试器,看看发生异常时rd包含的i + 3列究竟是什么。
至于你的另一个问题......很难说你的缩进已经到处都是 - 但我会检查 rd.Close()
是否在这里循环或外部:
I'd say that you are reading all the "Banconote_Enn" values, and the "BustaA" column, since you loop on less than or equal 7.
So use the debugger and look at exactly what column i + 3 of rd contains when the exception happens.
And as for your other problem...it's hard to tell since your indentation is all over the place - but I'd check if rd.Close()
is inside the while loop, or outside:
while (rd.Read())
{
如果它在里面,那将导致你描述的问题。
但是你的代码排序了!得到缩进权 - 您只需键入CTRL + K,CTRL + D
If it's inside, that'll cause the problem you describe.
But sort your code out! Get the indentation right - all you have to do is type CTRL+K, CTRL+D
这篇关于两个错误系统转换无效,读取器关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!