UPDATE: I have saved the path in a string and sent it over to the other document,
I have made a small game for school and everything works as intended, but when the "ITAMons" (that's how we call them) level up an if statement is accessed and a streamwriter is trying to write onto a file which was used by a streamreader before, but the streamreader was closed and still it says I can't access the file, because it's still in use.
The StreamReaders are defined in the document itself and here they get defined and then used in the ITAMon constructor
sr = new StreamReader(Zielordner.Text + "\\" + ITAListe.CheckedItems[0].ToString());
sr2 = new StreamReader(Zielordner.Text + "\\" + ITAListe2.CheckedItems[0].ToString());
ITAMon1 = new ITAMon(sr);
ITAMon2 = new ITAMon(sr2);
which has at the end of it sr.Close().
Here's the entire constructor:
public ITAMon(StreamReader sr)
{
ITAName = sr.ReadLine();
if (ITAName == String.Empty)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
string[] Auslesung = sr.ReadLine().Split(';');
if (Auslesung.Length > 6)
{
switch (Auslesung[0])
{
case "Feuer":
Element = Element.Feuer;
break;
case "Wasser":
Element = Element.Wasser;
break;
case "Pflanze":
Element = Element.Pflanze;
break;
default:
Element = Element.Normal;
break;
}
Level = Convert.ToInt32(Auslesung[1]);
Leben = Convert.ToDouble(Auslesung[2]);
CurrentLife = Leben;
EXP = Convert.ToInt32(Auslesung[3]);
Look = Auslesung[4];
BaseDmg = Convert.ToInt32(Auslesung[5]);
Verteidigung = Convert.ToDouble(Auslesung[6]);
Geschwindigkeit = Convert.ToDouble(Auslesung[7]);
Erweitert = true;
}
else if (Auslesung.Length < 7)
{
switch (Auslesung[0])
{
case "Feuer":
Element = Element.Feuer;
break;
case "Wasser":
Element = Element.Wasser;
break;
case "Pflanze":
Element = Element.Pflanze;
break;
default:
Element = Element.Normal;
break;
}
Level = Convert.ToInt32(Auslesung[1]);
Leben = Convert.ToDouble(Auslesung[2]);
CurrentLife = Leben;
EXP = Convert.ToInt32(Auslesung[3]);
Look = Auslesung[4];
Erweitert = false;
}
string[] Attacke1 = sr.ReadLine().Split(';');
if (Attacke1.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[0] = new Attacke(Attacke1[0], Convert.ToInt32(Attacke1[1]), Convert.ToInt32(Attacke1[3]), Convert.ToInt32(Attacke1[2]));
string[] Attacke2 = sr.ReadLine().Split(';');
if (Attacke2.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[1] = new Attacke(Attacke2[0], Convert.ToInt32(Attacke2[1]), Convert.ToInt32(Attacke2[3]), Convert.ToInt32(Attacke2[2]));
string[] Attacke3 = sr.ReadLine().Split(';');
if (Attacke3.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[2] = new Attacke(Attacke3[0], Convert.ToInt32(Attacke3[1]), Convert.ToInt32(Attacke3[3]), Convert.ToInt32(Attacke3[2]));
string[] Attacke4 = sr.ReadLine().Split(';');
if (Attacke4.Length != 4)
{
bool falsch = false;
Debug.Assert(falsch, "Auslesefehler! Bitte überprüfen Sie Ihre Datei!");
}
Attacken[3] = new Attacke(Attacke4[0], Convert.ToInt32(Attacke4[1]), Convert.ToInt32(Attacke4[3]), Convert.ToInt32(Attacke4[2]));
sr.Close();
}
Despite the sr.Close() it still says the path in use when this if statement is accessed and a streamwriter is trying to use the path.
if (ITAMon1.CrtLife <= 0 || ITAMon1.GetAttacken[0].Mgz == 0 & ITAMon1.GetAttacken[1].Mgz == 0 & ITAMon1.GetAttacken[2].Mgz == 0 & ITAMon1.GetAttacken[3].Mgz == 0)
{
Pfad = Zielordner.Text + "\\" + ITAListe2.CheckedItems[0].ToString();
EventLog.Text = ITAMon2.GetName + " Gewinnt!";
ITAMon2.GetEXP += ITAMon2.GetGegner.GetLevel;
if(ITAMon2.LvlUp())
{
Gewinner = ITAMon2;
MessageBox.Show(ITAMon2.GetName + " hat das nächste Level erreicht!", "LevelUp", MessageBoxButtons.OK, MessageBoxIcon.Information);
LevelUp levelUp = new LevelUp();
levelUp.Show();
}
else
{
ITAMon2.Save(Pfad);
srG.Close();
this.Close();
MessageBox.Show(ITAMon2.GetName + " Gewinnt!", "Gewinner", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else if (ITAMon2.CrtLife <= 0 || ITAMon2.GetAttacken[0].Mgz == 0 & ITAMon2.GetAttacken[1].Mgz == 0 & ITAMon2.GetAttacken[2].Mgz == 0 & ITAMon2.GetAttacken[3].Mgz == 0)
{
Pfad = Zielordner.Text + "\\" + ITAListe.CheckedItems[0].ToString();
EventLog.Text = ITAMon1.GetName + " Gewinnt!";
ITAMon1.GetEXP += ITAMon1.GetGegner.GetLevel;
if (ITAMon1.LvlUp())
{
Gewinner = ITAMon1;
MessageBox.Show(ITAMon1.GetName + " hat das nächste Level erreicht!", "LevelUp", MessageBoxButtons.OK, MessageBoxIcon.Information);
LevelUp levelUp = new LevelUp();
levelUp.Show();
}
else
{
srG = new StreamWriter(Pfad);
ITAMon1.Save(Pfad);
srG.Close();
this.Close();
MessageBox.Show(ITAMon1.GetName + " Gewinnt!", "Gewinner", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Does anybody have any ideas how to fix that? It should be usable, even after I manually wrote sr.Close() into the document itself and it still wouldn't work, any help would be appreciated.
I have 2 methods. 1 - is validation and 2 - is uploading if validation; how to cancel uploading?
1 - CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo);
int skipRows = 0;
foreach (DataRow item in lotTable.Rows)
{
string filename = Convert.ToString(item["Filename"]);
if (filename == string.Empty || filename == "NA")
{
continue;
}
String[] data = filename.Split('_');
string measType = Convert.ToString(data[2]);
bool rowIsNA = true;
for (int j = 1; j <= 11; j++) // From I to S in AVG WorkSheet
{
string paramValue = Convert.ToString(item[7 + j]);
if (rowIsNA == true && paramValue != "NA")
{
rowIsNA = false;
}
}
if (rowIsNA && (MEAS_TYPE.ToUpper() == measType.ToUpper() || MEAS_TYPE.ToUpper() == "ALL"))
{
skipRows++;
}
}
string message = string.Empty;
string errMsg = string.Empty;
if (skipRows > 1)
{
MessageBox.Show("Measure different rowbar or adjacent slider. " + skipRows + " sliders have no data in MATLAB", "AFM Host Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
2 - public static bool SendData(LotInfo lotInfo, List<string> submitMessage)
string message = string.Empty;
string errMsg = string.Empty;
DataTable MQDataTable;
try
{
//this is method 1 CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo);
}
catch (Exception exception)
{
message = "Job: " + lotInfo.SubmissionID + " FAILED to convert data for MQ submission.";
submitMessage.Add(exception.Message);
Globals.Logger.Error(exception.Message);
return false;
}
try
{
foreach (DataRow row in MQDataTable.Rows)
{
PDBAXLib.PdbClass PDB = new PDBAXLib.PdbClass();
PDB.init(AppConfig.GetString("MQConfiguration", "MQ_ADDRESS"), "1", AppConfig.GetString("MQConfiguration", "MQ_Connection_File"));
while (PDB.reupload()) ;
PDB.format("Detail");
foreach (DataColumn col in MQDataTable.Columns)
{
if (!string.IsNullOrEmpty(row[col].ToString()))
PDB.field(col.ColumnName, row[col].ToString());
else if (row[col].ToString().Equals(" "))
PDB.field(col.ColumnName, row[col].ToString());
}
PDB.formatEnd("Detail");
PDB.transmit(null);
}
MessageBox.Show("Job " + lotInfo.SubmissionID + " uploaded successfully.", "AFM SA Host", MessageBoxButtons.OK, MessageBoxIcon.Information);
message = "Job " + lotInfo.SubmissionID + " - Data uploaded successfully. " + DateTime.Now;
submitMessage.Add(message);
}
catch (Exception exception)
{
message = "Job " + lotInfo.SubmissionID + " FAILED to upload data.";
submitMessage.Add(message);
submitMessage.Add(exception.Message);
Globals.Logger.Error(exception.Message);
}
return true;
This is my problem,
if (skiprows > 1) prompt message will appear and upload the data.
I want if (skiprows > 1) prompt message and will not upload.
Thank you.
This is just one way
bool CheckValidationByMEAS_TYPE(....)
{
. . . .
if (skipRows > 1)
{
MessageBox.Show(....);
return false;
}
}
. . . . . . . .
try
{
if (!CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo)
return;
}
catch (Exception exception)
{
. . . . .
}
my problem is that i have a WCF Service and multip
le clients can connect/subscribe to that service and get all Random Data
trough Callback with the service...a Timer starts when a clients subscribed to the service, the thing is that every client then gets all not the same data but thats what i want to achieve...what am i doing wrong?
This is what happens when one client subscribed to the service:
public SubscribeResult Subscribe()
{
SubscribeResult retVal = new SubscribeResult();
try
{
retVal.ClientID = Guid.NewGuid().ToString();
clientID = retVal.ClientID;
ServiceCallback = OperationContext.Current.GetCallbackChannel<ITraceCallback>();
ti = new Timer();
ti.Elapsed += Ti_Elapsed;
ti.Interval = 1000;
ti.Enabled = true;
ti.Start();
retVal.Success = true;
SubscribeClientList.Add(new SubscribeItem {CLIENTID = clientID, SENT = true });
connectedClients += 1;
}
catch (Exception ex)
{
retVal.Success = false;
Console.WriteLine("Something went horribly wrong! \n" + ex.Message);
}
return retVal;
}
And this is what happens when the timer hits zero :
private void Ti_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
if (isSending == false)
{
isSending = true;
// generate message
CreateRandomString crs = new CreateRandomString();
string msg = crs.CreateString(rnd.Next(15, 25));
// increase entry
entry += 1;
// create timestamp of creation
DateTime creation = DateTime.Now;
// generate level
int muchwow = rnd.Next(1, 4);
string lvl = "undefined";
switch (muchwow)
{
case 1:
lvl = "Error";
break;
case 2:
lvl = "Warning";
break;
case 3:
lvl = "Information";
break;
}
bool sucess = ServiceCallback.Message(entry, creation, lvl, msg);
if (sucess == true)
{
CreateRandomString messagePreview = new CreateRandomString();
string prev = messagePreview.TruncString(msg, 20);
Console.WriteLine("[" + DateTime.Now + "] : [" + clientID + "] : " + "'" + prev + "' : " + "(" + lvl + ")");
sucess = false;
}
isSending = false;
}
I have an ObservableCollection of items, which I need to be able to update and have the data represented still using an ICollectionView.
Here are relevant bits of code:
private ObservableCollection<Hero> heroesDBHeroes;
public ObservableCollection<Hero> HeroesDBHeroes
{
get
{
return heroesDBHeroes;
}
set
{
heroesDBHeroes = value;
OnPropertyChanged("HeroesDBHeroes");
}
}
private void HeroesDBAddHeroes()
{
if(HeroesDBHeroes != null)
{
HeroesDBHeroes.Clear();
}
HeroesDBHeroes = Hero.GetAllHeroes();
HeroesDBFilteredHeroes = new ListCollectionView(HeroesDBHeroes);
HeroesDBFilteredHeroes.Filter = new Predicate<object>(HeroesDBFilterHeroes);
HeroesDBFilteredHeroes.Refresh();
OnPropertyChanged("HeroesDBFilteredHeroes");
}
Here is the CollectionView and its filter:
public CollectionView HeroesDBFilteredHeroes { get; set; }
public bool HeroesDBFilterHeroes(object item)
{
Hero h = item as Hero;
bool ID, Name, GoldMinimum, GoldMaximum, PlatinumMinimum, PlatinumMaximum, DBTag, ReleaseDateStart, ReleaseDateEnd, Available, Sale, Featured, New, F2P, Homepage, Thumbnail, FeaturedThumbnail, ShortDescription, Description;
ID = Name = GoldMinimum = GoldMaximum = PlatinumMinimum = PlatinumMaximum = DBTag = ReleaseDateStart = ReleaseDateEnd = Available = Sale = Featured = New = F2P = Homepage = Thumbnail = FeaturedThumbnail = ShortDescription = Description = false;
if (h == null)
{
return false;
}
if (HeroesDBFilterID == null || HeroesDBFilterID == h.ID)
{
ID = true;
}
if (HeroesDBFilterName == "" || h.Name.IndexOf(HeroesDBFilterName, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
Name = true;
}
if (HeroesDBFilterGoldMinimum == null || HeroesDBFilterGoldMinimum <= h.Gold)
{
GoldMinimum = true;
}
if (HeroesDBFilterGoldMaximum == null || HeroesDBFilterGoldMaximum >= h.Gold)
{
GoldMaximum = true;
}
if (HeroesDBFilterPlatinumMinimum == null || HeroesDBFilterPlatinumMinimum <= h.Platinum)
{
PlatinumMinimum = true;
}
if (HeroesDBFilterPlatinumMaximum == null || HeroesDBFilterPlatinumMaximum >= h.Platinum)
{
PlatinumMaximum = true;
}
if (HeroesDBFilterDBTag == "" || h.DBTag.IndexOf(HeroesDBFilterDBTag, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
DBTag = true;
}
if (HeroesDBFilterReleaseDateStart == null || HeroesDBFilterReleaseDateStart <= h.ReleaseDate)
{
ReleaseDateStart = true;
}
if (HeroesDBFilterReleaseDateEnd == null || HeroesDBFilterReleaseDateEnd >= h.ReleaseDate)
{
ReleaseDateEnd = true;
}
switch(HeroesDBFilterAvailable)
{
case 0:
Available = true;
break;
case 1:
if(h.Available == true)
{
Available = true;
}
break;
case 2:
if (h.Available == false)
{
Available = true;
}
break;
}
switch (HeroesDBFilterSale)
{
case 0:
Sale = true;
break;
case 1:
if (h.Sale == true)
{
Sale = true;
}
break;
case 2:
if (h.Sale == false)
{
Sale = true;
}
break;
}
switch (HeroesDBFilterFeatured)
{
case 0:
Featured = true;
break;
case 1:
if (h.Featured == true)
{
Featured = true;
}
break;
case 2:
if (h.Featured == false)
{
Featured = true;
}
break;
}
switch (HeroesDBFilterNew)
{
case 0:
New = true;
break;
case 1:
if (h.NewTag == true)
{
New = true;
}
break;
case 2:
if (h.NewTag == false)
{
New = true;
}
break;
}
switch (HeroesDBFilterF2P)
{
case 0:
F2P = true;
break;
case 1:
if (h.F2P == true)
{
F2P = true;
}
break;
case 2:
if (h.F2P == false)
{
F2P = true;
}
break;
}
switch (HeroesDBFilterHomepage)
{
case 0:
Homepage = true;
break;
case 1:
if (h.Homepage == true)
{
Homepage = true;
}
break;
case 2:
if (h.Homepage == false)
{
Homepage = true;
}
break;
}
switch (HeroesDBFilterThumbnail)
{
case 0:
Thumbnail = true;
break;
case 1:
if (h.ThumbnailImage.Count<byte>() >= 5)
{
Thumbnail = true;
}
break;
case 2:
if (h.ThumbnailImage.Count<byte>() < 5)
{
Thumbnail = true;
}
break;
}
switch (HeroesDBFilterFeaturedThumbnail)
{
case 0:
FeaturedThumbnail = true;
break;
case 1:
if (h.FeaturedThumbnailImage.Count<byte>() >= 5)
{
FeaturedThumbnail = true;
}
break;
case 2:
if (h.FeaturedThumbnailImage.Count<byte>() < 5)
{
FeaturedThumbnail = true;
}
break;
}
if (HeroesDBFilterShortDescription == "" || h.ShortDescription.IndexOf(HeroesDBFilterShortDescription, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
ShortDescription = true;
}
if (HeroesDBFilterDescription == "" || h.Description.IndexOf(HeroesDBFilterDescription, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
Description = true;
}
return ID && Name && GoldMinimum && GoldMaximum && PlatinumMinimum && PlatinumMaximum && DBTag && ReleaseDateStart && ReleaseDateEnd && Available && Sale && Featured && New && F2P && Homepage && Thumbnail && FeaturedThumbnail && ShortDescription && Description;
}
I get the following error in the following code snippet:
An unhandled exception of type 'System.NotSupportedException' occurred
in PresentationFramework.dll
Additional information: This type of CollectionView does not support
changes to its SourceCollection from a thread different from the
Dispatcher thread.
private ICommand heroesDBAddEntry;
public ICommand HeroesDBAddEntry
{
get
{
if (heroesDBAddEntry == null)
{
heroesDBAddEntry = new RelayCommand(HeroesDBAddEntryEx, null);
}
return heroesDBAddEntry;
}
}
private void HeroesDBAddEntryEx(object p)
{
if (HeroesDBUpdateID != null)
{
HeroesDBUpdateEntryEx();
return;
}
int x;
var db = new SQLiteDatabase();
string query, changesQuery;
query = "INSERT INTO Heroes (Name,Description,ShortDescription,Gold,Platinum,DBTag,ReleaseDate,Available,Sale,Featured,NewTag,F2P,Homepage,ThumbnailImage,ThumbnailImageName," +
"FeaturedThumbnailImage,FeaturedThumbnailImageName) ";
query += "VALUES ('" + HeroesDBName.Replace("'", "''") + "','" + HeroesDBDescription.Replace("'", "''") + "','" + HeroesDBShortDescription.Replace("'", "''") + "'," +
HeroesDBGold + "," + HeroesDBPlatinum + ",'" + HeroesDBDBTag.Replace("'", "''") + "','" + HeroesDBReleaseDate.Date.ToString("yyyy-MM-dd") + "'," +
Convert.ToInt32(HeroesDBAvailable) + "," + Convert.ToInt32(HeroesDBSale) + "," + Convert.ToInt32(HeroesDBFeatured) + "," + Convert.ToInt32(HeroesDBNewTag) + "," +
Convert.ToInt32(HeroesDBF2P) + "," + Convert.ToInt32(HeroesDBHomepage) + ",'" + Convert.ToBase64String(HeroesDBThumbnailImage) + "','" +
HeroesDBThumbnailPath.Replace("'", "''") + "','" + Convert.ToBase64String(HeroesDBFeaturedThumbnailImage) + "','" + HeroesDBFeaturedThumbnailPath.Replace("'", "''") + "'); ";
changesQuery = "INSERT INTO Heroes_Changes (HeroID,Action,TimeStamp,User,Name,Description,ShortDescription,Gold,Platinum,DBTag,ReleaseDate,Available,Sale,Featured,NewTag,F2P," +
"Homepage,ThumbnailImage,ThumbnailImageName,FeaturedThumbnailImage,FeaturedThumbnailImageName) ";
changesQuery += "VALUES (" + HeroesDBNextID + ",'" + "INSERT" + "','" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "','" + Environment.UserName + "','" +
HeroesDBName.Replace("'", "''") + "','" + HeroesDBDescription.Replace("'", "''") + "','" + HeroesDBShortDescription.Replace("'", "''") + "'," +
HeroesDBGold + "," + HeroesDBPlatinum + ",'" + HeroesDBDBTag.Replace("'", "''") + "','" + HeroesDBReleaseDate.Date.ToString("yyyy-MM-dd") + "'," +
Convert.ToInt32(HeroesDBAvailable) + "," + Convert.ToInt32(HeroesDBSale) + "," + Convert.ToInt32(HeroesDBFeatured) + "," + Convert.ToInt32(HeroesDBNewTag) + "," +
Convert.ToInt32(HeroesDBF2P) + "," + Convert.ToInt32(HeroesDBHomepage) + ",'" + Convert.ToBase64String(HeroesDBThumbnailImage) + "','" +
HeroesDBThumbnailPath.Replace("'", "''") + "','" + Convert.ToBase64String(HeroesDBFeaturedThumbnailImage) + "','" + HeroesDBFeaturedThumbnailPath.Replace("'", "''") + "'); ";
try
{
x = db.ExecuteNonQuery(query);
HeroesDBStatus = x + " Record(s) Added.";
x = db.ExecuteNonQuery(changesQuery);
}
catch(Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message);
}
HeroesDBHeroes.Add(new Hero(
HID: HeroesDBNextID,
HName: HeroesDBName,
HDescription: HeroesDBDescription,
HShortDescription: HeroesDBShortDescription,
HGold: HeroesDBGold,
HPlatinum: HeroesDBPlatinum,
HDBTag: HeroesDBDBTag,
HReleaseDate: HeroesDBReleaseDate,
HAvailable: HeroesDBAvailable,
HSale: HeroesDBSale,
HFeatured: HeroesDBFeatured,
HNewTag: HeroesDBNewTag,
HF2P: HeroesDBF2P,
HHomepage: HeroesDBHomepage,
HThumbnailImage: HeroesDBThumbnailImage,
HThumbnailImageName: HeroesDBThumbnailPath,
HFeaturedThumbnailImage: HeroesDBFeaturedThumbnailImage,
HFeaturedThumbnailImageName: HeroesDBFeaturedThumbnailPath,
HForce: true
));
HeroesDBNextID++;
HeroesDBName = "";
HeroesDBDescription = "";
HeroesDBShortDescription = "";
HeroesDBGold = 0;
HeroesDBPlatinum = 0;
HeroesDBDBTag = "";
HeroesDBReleaseDate = DateTime.Today;
HeroesDBAvailable = false;
HeroesDBSale = false;
HeroesDBFeatured = false;
HeroesDBNewTag = false;
HeroesDBF2P = false;
HeroesDBHomepage = false;
HeroesDBThumbnailImage = new byte[] { 0x00 };
HeroesDBThumbnailPath = "";
HeroesDBFeaturedThumbnailImage = new byte[] { 0x00 };
HeroesDBFeaturedThumbnailPath = "";
HeroesDBUpdateID = null;
}
The error happens where I have the HeroesDB.Add(...) line, just after the try catch.
I have tried a ton of things, none of which have worked.
I have tried using another ObservableCollection as the filtered list and filtering that, but it still gives me an error. I have tried using MTObservableCollection and AsyncObservableCollection taken from the first page of google which others have posted, but they mess up in other ways as well.
How would I go about tackling this one? I need to be able to filter, I need a collection of them, and when the source changes I need to see those changes in the app right away.
Have you tried wrapping all your code which sets up the filter to a call to the WPF dispatcher?
Generally this has to be done if the collection bound to the view is modified in code of a thread different than the UI thread.
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => {
HeroesDBAddHeroes();
}));
I am having a problem this is my code`using System;
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+4);
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);
}
}
}
}
It is giving me the error at line quantity = rd.GetInt32(i+4)
I know the value is int 32 only from a database so why m i getting this error.?
`
It is probably because i+4 isn't a Int32 datatype. Trying printing the i+4 before and check what is the column type that matches in that position and fix your code accordingly.