I have a problem with reading and writing data into file notepad using serialization
Basically that's about login and sign up
I'll give my code here
This is the part for sign up form :
public partial class formSignUp : Form
{
List<data> game = new List<data>();
data dt = new data();
public formSignUp()
{
InitializeComponent();
}
private void write()
{
try
{
using (Stream stream = File.OpenWrite("game.txt"))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, dt);
}
}
catch (IOException)
{
}
}
private void butRegister_Click(object sender, EventArgs e)
{
write();
dt = new data(tbUName.Text, tbPass1.Text);
game.Add(dt);
}
}
and then this is the class data code :
[Serializable()]
class data
{
private string username;
private string password;
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public data(string username, string password)
{
this.username = username;
this.password = password;
}
public data()
{
}
}
i put the file notepad inside folder "bin" with name "game.txt"
the problem is, everytime i call "write()" the character which is written into file "game.txt" is so strange character. so far i got like :
ÿÿÿÿ <Login, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Login.data usernamepassword
Anybody can help me?
Thanks a lot in advance
Regards
That's because you're using a BinaryFormatter, it outputs binary data. You should use one of the textual formatters. There's SoapFormatter and the DataContractJsonSerialized, although it may not be suitible for you.
Related
Please see my first Persistent Subscription below:
namespace PersistentSubscription
{
internal class Program
{
private static void Main()
{
var subscription = new PersistentSubscriptionClient();
subscription.Start();
}
}
public class PersistentSubscriptionClient
{
private IEventStoreConnection _conn;
private const string STREAM = "$ce-customer";
private const string GROUP = "a_test_group";
private const int DEFAULTPORT = 1113;
private static readonly UserCredentials User = new UserCredentials("admin", "changeit");
private EventStorePersistentSubscriptionBase _subscription;
public void Start()
{
var settings = ConnectionSettings.Create();
using (_conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
{
_conn.ConnectAsync().Wait();
CreateSubscription();
ConnectToSubscription();
Console.WriteLine("waiting for events. press enter to exit");
Console.ReadLine();
}
}
private void ConnectToSubscription()
{
var bufferSize = 10;
var autoAck = true;
Action<EventStorePersistentSubscriptionBase, ResolvedEvent> eventAppeared = EventAppeared;
_subscription = _conn.ConnectToPersistentSubscription(STREAM, GROUP, eventAppeared, SubscriptionDropped, User, bufferSize, autoAck);
}
private void SubscriptionDropped(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
SubscriptionDropReason subscriptionDropReason, Exception ex)
{
ConnectToSubscription();
}
private static void EventAppeared(EventStorePersistentSubscriptionBase eventStorePersistentSubscriptionBase,
ResolvedEvent resolvedEvent)
{
MemoryStream stream = new MemoryStream(resolvedEvent.Event.Data);
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
try
{
CustomerCreated customerCreated = (CustomerCreated)formatter.Deserialize(stream);
Console.WriteLine(customerCreated);
}
catch (Exception e)
{
var test = "test";
}
}
private void CreateSubscription()
{
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos()
.StartFromCurrent();
try
{
_conn.CreatePersistentSubscriptionAsync(STREAM, GROUP, settings, User).Wait();
}
catch (AggregateException ex)
{
if (ex.InnerException.GetType() != typeof(InvalidOperationException)
&& ex.InnerException?.Message != $"Subscription group {GROUP} on stream {STREAM} already exists")
{
throw;
}
}
}
}
}
and my first client below:
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using EventStore.ClientAPI;
namespace WritingEvents
{
class Program
{
static void Main(string[] args)
{
const int DEFAULTPORT = 1113;
var settings = ConnectionSettings.Create();
using (var conn = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT)))
{
conn.ConnectAsync().Wait();
CustomerCreated c1 = new CustomerCreated { Id = Guid.NewGuid(), Name = "Maria" };
EventData customerCreated1 = GetEventDataFor(c1);
conn.AppendToStreamAsync("customer-100", ExpectedVersion.Any, customerCreated1).Wait();
}
}
private static EventData GetEventDataFor(CustomerCreated customerCreated)
{
IFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, customerCreated);
byte[] customerCreatedEventByteArray = stream.ToArray();
return new EventData(
Guid.NewGuid(),
"eventType",
true,
customerCreatedEventByteArray,
null
);
}
}
[Serializable]
public class CustomerCreated
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
I run the server and then then the client. I see an error when deserializing the CustomerCreated event on the server side. The error is: "End of stream was encountered before parsing was completed".
If I change this line:
private const string STREAM = "$ce-customer";
to this:
private const string STREAM = "customer-100";
Then deserialization works correctly on the server side.
How do I handle all customer events - not just customer 100?
I have --run-projections=all when starting Event Store. I have also enabled all projections:
This question helped me: Using the Event Store Client API (.NET), how to I write to a stream and link one event to another?
I simply had to change this:
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.DoNotResolveLinkTos() //Specifically this line
.StartFromCurrent();
to this:
PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
.ResolveLinkTos() //Specifically this line
.StartFromCurrent();
DoNotResolveLinkTos gets a link to the original event, whereas ResolveLinkTos gets the actual event itself. Therefore I was trying to deserialize the link object, which was causing the exception.
I have created a Class called "VNCVars.cs" and I want to be able to Save the data associated with all the Variables inside VNCVars to a XML file so I can load them back in on startup. I have another class called "SaveData.cs" which contains the code to generate the XML file.
I have code written that runs but my XML file is always empty.....can somebody point out what I have missed out??
public class VNCVars
{
//Global Variables for VNC 1 Location
//VNC File Location 1 Get and Set routines
private static string strVNC1Location;
public static string VNC1Location
{
get { return strVNC1Location; }
set { strVNC1Location = value; }
}
//Global Variables for VNC 2 Location
//VNC File Location 2 Get and Set routines
private static string strVNC2Location;
public static string VNC2Location
{
get { return strVNC2Location; }
set { strVNC2Location = value; }
}
//Global Variables for VNC 3 Location
//VNC File Location 3 Get and Set routines
private static string strVNC3Location;
public static string VNC3Location
{
get { return strVNC3Location; }
set { strVNC3Location = value; }
}
}
public class SaveXML
{
public static void SaveData()
{
var SaveData = new VNCVars();
XmlSerializer sr = new XmlSerializer(typeof(VNCVars));
TextWriter writer = new StreamWriter(#"c:\Fanuc\SetupVars.xml");
sr.Serialize(writer, SaveData);
writer.Close();
}
}
Then finally on my form I currently just have a button and on the click the following occurs...
private void button2_Click(object sender, EventArgs e)
{
SaveXML.SaveData();
}
Any help greatly appreciated....
You should use instance properties instead of static properties.
You can then use the singleton pattern to keep only one instance of this class.
If you need to have static variables and don't want to make this class a singleton, the way around is to wrap static variables:
[XmlElement("VNC1Location")]
public string VNC1LocationLocal
{
get
{
return VNC1Location;
}
set
{
VNC1Location = value;
}
}
In writing a program where I need to serialize an AppSettings object which consists of several properties including one that will be used to store a last used filename, I have found that the FileName property is placed into my object (by assignment) but it does not serialize to the xml file. No exceptions are thrown and no data is written.
But conversely, if I programmtically modify the object
tc.TheDataFile = "c:\\Documents And Settings\\SomeUser\\Sample\\a test file.txt";
instead of
tc.TheDataFile = theDialog.FileName;
That will work. Can someone please provide some insight with regard to what I am missing?
Here is a simple version of the program that is directly related to the problem.
The test class which will theoretically hold the AppSettings ---
[Serializable()]
public class TestClass
{
private string m_TheDataFile;
private bool m_UseLastKnownDataFile = true;
public bool UseLastKnownDataFile
{
get
{
return m_UseLastKnownDataFile;
}
set
{
m_UseLastKnownDataFile = value;
}
}
public string TheDataFile
{
get
{
return m_TheDataFile;
}
set
{
m_TheDataFile = value;
}
}
}
public class TestClassHelper
{
public static TestClass Load()
{
XmlSerializer serializer = new XmlSerializer(typeof(TestClass));
TestClass retVal;
TextReader reader = null;
bool fileNotFound = false; ;
try
{
reader = new StreamReader("TestClassConfig.xml");
}
catch (FileNotFoundException)
{
fileNotFound = true;
}
if (fileNotFound)
{
retVal = new TestClass();
}
else
{
retVal = (TestClass)serializer.Deserialize(reader);
reader.Close();
}
return retVal;
}
public static void Save(TestClass settings)
{
XmlSerializer serializer = new XmlSerializer(typeof(TestClass));
TextWriter writer = new StreamWriter("TestClassConfig.xml");
serializer.Serialize(writer, settings);
writer.Close();
}
}
And here is the form which will prompt the user for a filename. In this test, there is a form with one button.
public partial class Form1 : Form
{
TestClass tc = null;
public Form1()
{
InitializeComponent();
tc = TestClassHelper.Load();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
string fileName = string.Empty;
theDialog.CheckFileExists = true;
theDialog.CheckPathExists = true;
theDialog.Multiselect = false;
theDialog.FileName = string.Empty;
if (theDialog.ShowDialog() == DialogResult.OK)
{
tc.TheDataFile = theDialog.FileName;
}
else
{
tc.TheDataFile = string.Empty;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
TestClassHelper.Save(tc);
}
}
Edit To Add:
I'm using Microsoft Visual Studio 2005 Team Edition w/Dot Net 2.0.50727 SP1, with no options to upgrade the development environment.
Solution
I'm not exactly sure why this happens, but the OpenFileDialog control must change the current operating directory of the program. When the object is deserialized to the xml file, it no longer writes where it originally opened. Rather it is created in the new directory.
I corrected the problem by making the XML read and write location more specific.
The problem is that you are setting tc.TheDataFile = fileName; after the if block, but you never assign anything to fileName except when you initialize it to string.Empty. One fix would be:
if (theDialog.ShowDialog() == DialogResult.OK)
{
fileName = theDialog.FileName;
}
// record last used data file
tc.TheDataFile = fileName;
or just
if (theDialog.ShowDialog() == DialogResult.OK)
{
tc.TheDataFile = theDialog.FileName;
}
Note that running your test in the debugger and "watch"ing the variables would have made the problem fairly easy to spot.
I am making an application to store tickets for boarding a place for a imaginary airline.
I have created a Ticket class see below
public class ticket
{
String lastName;
String firstName;
String origin;
String destination;
String flightNumber;
String seatNumber;
String date;
public ticket()
{
}
public ticket(String lastname, String firstName, String origin, String destination,
String flightNumber, String seatNumber, String date)
{
}
I have two ticket classes, first and economy. The plane can only hold 10 seats. So my structure is having two arrays of ticket objects, one containing 4 ticket objects "first class" and one containing 6 ticket objects "economy class". See below
ticket[] ticketFirst = new ticket[4];
ticket[] ticketEcon = new ticket[6];
I have to assign the seats randomly within their respective ticket arrays. I am calling my get method (example below) to check for duplicates, that is, that the randomly assigned seat is already filled or not.
public String getLastName()
{
return this.lastName;
}
When I run my program I get the Error WindowsFormsApplication1.ticket' is a 'type' but is used like a 'variable' (relevant code below)
private void btnSubmit_Click(object sender, EventArgs e)
{
Random random = new Random();
int rand = random.Next(0, 4);
if (ticket[rand].getLastName = null)
{
ticket[rand].setLastName = txbLastName.Text;
ticket[rand].setFirstName = txbFirstName.Text;
ticket[rand].setOrigin = txbOrigin.Text;
ticket[rand].setDestination = txbDestination.Text;
ticket[rand].setFlightNumber = txbFlightNumber.Text;
ticket[rand].setSeatNumber = txbSeatNumber.Text;
ticket[rand].setDate = txbDate.Text;
}
else
{
MessageBox.Show("Seat Assignment Failed, try again.", "Seat Assignment");
}
}
What my intention was is to assign the new ticket object a random seat (position) in the array, and most of my experience is with java. I think this is a syntax error from me using java-like syntax. Any pointers to get this to work properly?
Full Program Below
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ticket[] ticketFirst = new ticket[4];
ticket[] ticketEcon = new ticket[6];
}
private void btnSubmit_Click(object sender, EventArgs e)
{
Random random = new Random();
int rand = random.Next(0, 4);
if (ticket[rand].getLastName = null)
{
ticket[rand].setLastName = txbLastName.Text;
ticket[rand].setFirstName = txbFirstName.Text;
ticket[rand].setOrigin = txbOrigin.Text;
ticket[rand].setDestination = txbDestination.Text;
ticket[rand].setFlightNumber = txbFlightNumber.Text;
ticket[rand].setSeatNumber = txbSeatNumber.Text;
ticket[rand].setDate = txbDate.Text;
}
else
{
MessageBox.Show("Seat Assignment Failed, try again.", "Seat Assignment");
}
}
}
public class ticket
{
String lastName;
String firstName;
String origin;
String destination;
String flightNumber;
String seatNumber;
String date;
public ticket()
{
}
public ticket(String lastname, String firstName, String origin, String destination,
String flightNumber, String seatNumber, String date)
{
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return this.lastName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return this.firstName;
}
public void setOrigin(String origin)
{
this.origin = origin;
}
public String getOrigin()
{
return this.origin;
}
public void setDestination(String destination)
{
this.destination = destination;
}
public String getDestination()
{
return this.destination;
}
public void setFlightNumber(String flightNumber)
{
this.flightNumber = flightNumber;
}
public String getFlightNumber()
{
return this.flightNumber;
}
public void setSeatNumber(String seatNumber)
{
this.seatNumber = seatNumber;
}
public String getSeatNumber()
{
return this.seatNumber;
}
public void setDate(String date)
{
this.date = date;
}
public String getDate()
{
return this.date;
}
}
}
Your ticket[rand] needs to be either ticketFirst[rand] or ticketEcon[rand]. They also need to be defined outside of the Form1 constructor to be able to access them elsewhere in the form.
e.g.
public partial class Form1 : Form
{
ticket[] ticketFirst = new ticket[4];
ticket[] ticketEcon = new ticket[6];
public Form1()
{
InitializeComponent();
ticketFirst = new ticket[4];
ticketEcon = new ticket[6];
}
private void btnSubmit_Click(object sender, EventArgs e)
{
Random random = new Random();
int rand = random.Next(0, 4);
if (ticketFirst[rand].getLastName = null)
{
ticketFirst[rand].setLastName = txbLastName.Text;
ticketFirst[rand].setFirstName = txbFirstName.Text;
ticketFirst[rand].setOrigin = txbOrigin.Text;
ticketFirst[rand].setDestination = txbDestination.Text;
ticketFirst[rand].setFlightNumber = txbFlightNumber.Text;
ticketFirst[rand].setSeatNumber = txbSeatNumber.Text;
ticketFirst[rand].setDate = txbDate.Text;
}
else
{
MessageBox.Show("Seat Assignment Failed, try again.", "Seat Assignment");
}
}
}
Your ticket arrays only exist in the form constructor. In order to use it in events, methods... you must create a field on the class...
public partial class Form1 : Form
{
private Ticket[] tickets = new Ticket[5];
...
}
In C# you should:
Use Properties rather than methods for gets and sets.
Use TitleCase for class names (instead of ticket, name as Ticket)
In .NET, the convention is to give types TitleCase names, but your class ticket is lowercased, which causes the compiler to be confused between a variable named ticket and your class, also named ticket.
Change the name of the class to the title-cased Ticket and it will work.
I have the code below to allow me to add data from a excel sheet directly into a sing given database, now I would like to know how I would be able to call the method multiple times to add data from two different excel file at once, the is a button which calls this method once clicked, using multi-threading.
private void AddToDatabase()
{
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
connection.Open();
CheckNumeberOfSheets(connection);
}
}
Button code;
private void button1_Click(object sender, EventArgs e)
{
AddToDatabase();
}
May be you can pass a string to your method AddToDatabse like
private void AddToDatabase(string fileName){
if(fileName.Equals("yourfirstFile"))
{
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
connection.Open();
CheckNumeberOfSheets(connection);
}
}
else if(fileName.Equals("yoursecondfile"))
{
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString2))
{
connection.Open();
CheckNumeberOfSheets(connection);
}
}
}
and then call it like this
private void button1_Click(object sender, EventArgs e)
{
AddToDatabase("yourfirstFile");
AddToDatabase("yoursecondFile");
}
Step 1: create a class named "ClassFiles"
public class ClassFiles
{
private String fileName;
private String excelConnectionString;
public String getFileName()
return fileName;
public void setFileName(String fileName)
{
this.fileName=fileName;
}
public String getExcelConnectionString()
return excelConnectionString;
public void setExcelConnectionString(String excelConnectionString)
{
this.excelConnectionString=excelConnectionString;
}
}
Step 2: In your main class, add the fileName along with excelConnection String like:
public class MainClass{
private void AddFilesToDB(List<ClassFiles>fileDetails){
for(ClassFiles fileDeteil : fileDetails){
using (OleDbConnection connection =
new OleDbConnection(fileDeteil.getExcelConnectionString))
{
connection.Open();
CheckNumeberOfSheets(connection);
}
// as well as u can get the file name..
String fileName=fileDeteil.getFileName();
}
}
public Static void main(string args[]){
List<ClassFiles> addDetails =new ArrayList<ClassFiles>();
//now add the no of files into the list
ClassFiles objFile1=new ClassFiles();
objFile1.setFileName("filename1");
objFile1.setExcelConnectionString("excelConnectionString1");
addDetails.add(objFile1);
ClassFiles objFile2=new ClassFiles();
objFile2.setFileName("filename2");
objFile2.setExcelConnectionString("excelConnectionString2");
addDetails.add(objFile2);
and so on..
then call the function for further process.,
new MainClass().AddFilesToDB(addDetails);
}
hope it ll help you..