I'm doing some WPF project where I want to make a method, which deletes element from ObservableCollection when I click on it. But for some reason is not doing right. I check with debugger and when it comes to the statement where I call method for the removing element, it shows that my object (on which I call all methods) is empty or. null.
I know it's dumb question and for sure very dumb mistake, which I overlooked but I can't find the solution how to fix it.
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace facebook {
/// <summary>
/// Interaction logic for prikazObjave.xaml
/// </summary>
public partial class prikazObjave : UserControl {
Oseba oseba = new Oseba();
public prikazObjave() {
InitializeComponent();
}
public prikazObjave(Oseba os) {
InitializeComponent();
oseba = os;
}
private void item_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
var TextBlockName = ((TextBlock)sender).Name;
string newValue = Interaction.InputBox("Vnesi novo vrednost", "New value", "", 0, 0);
if (newValue != "" && newValue != null) {
((TextBlock)sender).Text = newValue;
}
}
private void delete_post_event(object sender, MouseButtonEventArgs e) {
var temp = (StackPanel)sender;
Objava objava = (Objava)(temp.DataContext);
if(oseba.posts.Count > 1) { //<---here, oseba is null
try {
oseba.izbrisiObjavo(oseba, objava);
MessageBox.Show("Objava uspešno izbrisana");
}
catch (Exception ex) {
Console.WriteLine("Napaka pri brisanju objave\n\n" + ex.Message + "\n" + ex.StackTrace);
}
}
else {
Console.WriteLine("Seznam objav je prazen");
return;
}
}
private void dodajKomentarBtn_Click(object sender, RoutedEventArgs e) {
string vsebina = Interaction.InputBox("Vnesi komentar", "Komentiraj", "", 0, 0);
if (vsebina != "" && vsebina != null) {
oseba.dodajKomentar(vsebina);
}
}
}
}
And this is the class method for removing the element from the Collection:
public void izbrisiObjavo(Oseba oseba, Objava objava) {
if(objava != null) {
//posts.Remove(objava);
try {
//posts.Remove(posts.Where(i => i.Vsebina == objava.Vsebina).Single());
Objava temp = objava;
oseba.posts.Remove(temp);
}
catch(Exception e) {
Console.WriteLine("Napaka pri brisanju objave (Oseba)\n\n" + e.Message + "\n" + e.StackTrace);
}
}
else {
Console.WriteLine("objava je null\n");
return;
}
}
Oseba class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Windows.Forms;
namespace facebook {
[Serializable()]
public class Oseba : INotifyPropertyChanged {
private string ime;
private string priimek;
private int starost;
private string spol;
private string oMeni;
private string zaposlitev;
private string profilnaSlika;
private string naslovnaSlika;
ObservableCollection<String> solanje = new ObservableCollection<string>(); //vse vrste šolanja
ObservableCollection<Prijatelj> friends = new ObservableCollection<Prijatelj>(); //seznam prijateljev
ObservableCollection<Objava> posts = new ObservableCollection<Objava>(); //seznam objav
ObservableCollection<String> pocutje = new ObservableCollection<string>();
public Oseba() { }
public Oseba(string ime, string priimek, int starost, string spol, string oMeni, string zaposlitev) {
this.ime = ime;
this.priimek = priimek;
this.starost = starost;
this.spol = spol;
this.oMeni = oMeni;
this.zaposlitev = zaposlitev;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName) {
if(PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void dodajPrijatelja(Prijatelj prijatelj) {
friends.Add(prijatelj);
}
public void dodajSolo(string sola) {
solanje.Add(sola);
}
public void dodajObjavo(string vsebina, string zasebnost, ObservableCollection<String> prijatelji, string datoteka, string kraj, string pocutje) {
posts.Add(new Objava(vsebina, zasebnost, prijatelji, datoteka, kraj, pocutje));
}
public void dodajPocutje(string path) {
pocutje.Add(path);
}
public void dodajKomentar(string vsebina) {
if(vsebina != null) {
try {
//posts[0].ko
}
catch (Exception e) {
MessageBox.Show("Napaka pri dodajanju komentarja!\n\n" + e.Message + "\n" + e.StackTrace);
}
}
else {
MessageBox.Show("Vnesite komentar!");
return;
}
}
public void izbrisiObjavo(Oseba oseba, Objava objava) {
if(objava != null) {
//posts.Remove(objava);
try {
//posts.Remove(posts.Where(i => i.Vsebina == objava.Vsebina).Single());
Objava temp = objava;
oseba.posts.Remove(temp);
}
catch(Exception e) {
Console.WriteLine("Napaka pri brisanju objave (Oseba)\n\n" + e.Message + "\n" + e.StackTrace);
}
}
else {
Console.WriteLine("objava je null\n");
return;
}
}
public void serialize(Oseba os) {
string dataFile = (#"C:\Users\Admin\Desktop\uv\data.xml");
profilnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_profile_pic.jpg";
naslovnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_timeline_pic.jpg";
try {
XmlSerializer mySerializer = new XmlSerializer(typeof(Oseba));
StreamWriter myWritter = new StreamWriter(dataFile);
mySerializer.Serialize(myWritter, os);
myWritter.Close();
}
catch(Exception ex) {
Console.WriteLine("Napaka pri serializaciji(metoda Serialize - razred Oseba)\n\n" + ex.Message + "\n" + ex.StackTrace);
}
}
public Oseba deserialize(string path = #"C:\Users\Admin\Desktop\uv\data.xml") {
Oseba os = new Oseba();
string dataFile = path;
try {
using (var sr = new StreamReader(dataFile)) {
var deserializer = new XmlSerializer(typeof(Oseba));
os = (Oseba)deserializer.Deserialize(sr);
}
}
catch (Exception ex) {
Console.WriteLine("Napaka pri deserializaciji\n\n" + ex.Message + "\n" + ex.StackTrace);
}
return os;
}
public void shrani() {
string dataFile = (#"C:\Users\Admin\Desktop\data.xml");
profilnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_profile_pic.jpg";
naslovnaSlika = #"E:\Šola\2. letnik\Zimski semester\Uporabniski vmesniki\facebook\images\tony_stark_timeline_pic.jpg";
using (var stream = new FileStream(dataFile, FileMode.Create)) {
var XML = new XmlSerializer(typeof(Oseba));
XML.Serialize(stream, this);
}
}
public Oseba nalozi() {
Oseba os = new Oseba();
string dataFile = (#"C:\Users\Admin\Desktop\data.xml");
try {
using (var sr = new StreamReader(dataFile)) {
var deserializer = new XmlSerializer(typeof(Oseba));
os = (Oseba)deserializer.Deserialize(sr);
}
}
catch (Exception ex) {
var msg = ex.Message;
}
return os;
}
public void odstraniPrijatelja(int index) {
friends.RemoveAt(index);
}
/*
public void sortAsc() {
ObservableCollection<string> prijatelji = new ObservableCollection<string>(friends.OrderBy(i => i));
friends = prijatelji;
}
public void sortDecs() {
ObservableCollection<string> prijatelji = new ObservableCollection<string>(friends.OrderByDescending(i => i));
friends = prijatelji;
}
*/
public string Ime {
get { return ime; }
set {
ime = value;
OnPropertyChanged("Ime");
}
}
public string Priimek {
get { return priimek; }
set {
priimek = value;
OnPropertyChanged("Priimek");
}
}
public int Starost {
get { return starost; }
set {
starost = value;
OnPropertyChanged("Starost");
}
}
public string Spol {
get { return spol; }
set {
spol = value;
OnPropertyChanged("Spol");
}
}
public string OMeni {
get { return oMeni; }
set {
oMeni = value;
OnPropertyChanged("OMeni");
}
}
public string Zaposlitev {
get { return zaposlitev; }
set {
zaposlitev = value;
OnPropertyChanged("Zaposlitev");
}
}
public string ProfilnaSlika {
get { return profilnaSlika; }
set {
profilnaSlika = value;
OnPropertyChanged("ProfilnaSlika");
}
}
public string NaslovnaSlika {
get { return naslovnaSlika; }
set {
naslovnaSlika = value;
OnPropertyChanged("NaslovnaSlika");
}
}
public ObservableCollection<Prijatelj> Friends {
get { return friends; }
set { friends = value;
OnPropertyChanged("Friends");
}
}
public ObservableCollection<String> Solanje {
get { return solanje; }
set {
solanje = value;
OnPropertyChanged("Solanje");
}
}
public ObservableCollection<Objava> Posts {
get { return posts; }
set {
posts = value;
OnPropertyChanged("Posts");
}
}
[XmlIgnore]
public ObservableCollection<String> Pocutje {
get { return pocutje; }
set {
pocutje = value;
OnPropertyChanged("Pocutje");
}
}
}
}
I feel like the silly thing that could possibly lead to this is creating a new prikazObjave (which should be Capitalized class name) as:
var po = new prikazObjave(null);
This would lead to the internal oseba to be null, unless you're explicitly setting po.oseba = null; somewhere.
I debugged my program in chunks and I found that every global variable in userControl named PrikazObjave is null after constructor call is finish.
Related
I have a requirement of executing a C# class in the string format and populate an object with the properties of that class. To achieve the requirement I was doing a POC and that's failed.
Following code is failing to evaluate where i was trying to update the input model.
Program.cs
using Microsoft.CodeAnalysis.CSharp.Scripting;
using System;
namespace CSCodeExecuter
{
class Program
{
static void Main(string[] args)
{
Model input = new Model();
string scriptId = "123";
ScriptManager sriptMgr = new ScriptManager();
sriptMgr.ExecuteScript<Model>(scriptId, ref input);
Console.WriteLine(input.ToString());
Console.ReadKey();
}
}
}
ScriptManager.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSCodeExecuter
{
public class ScriptManager
{
public void ExecuteScript<T>(string scriptId, ref T input)
{
try
{
string inputSript = GetStriptById(scriptId);
var scriptOptions = ScriptOptions.Default;
scriptOptions.AddReferences("CSCodeExecuter");
Execute(inputSript, scriptOptions);
var result = Execute("new ScriptedClass().input", scriptOptions);
}
catch (Exception ex)
{
throw;
}
}
private string GetStriptById(string id)
{
string csSript = #" public class ScriptedClass
{
public CSCodeExecuter.Model input {get;set;}
public void ScriptedClass()
{
{" + GetInternalScript() + #"}
}
}";
return csSript;
}
private string GetInternalScript()
{
return "input.Id = \"1111\"; " + "input.Name = \"test\"; " + "input.Phone = \"1234567890\"; ";
}
private static ScriptState<object> scriptState = null;
public static object Execute(string code, dynamic scriptOptions)
{
scriptState = scriptState == null ? CSharpScript.RunAsync(code).Result : scriptState.ContinueWithAsync(code).Result;
if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString()))
return scriptState.ReturnValue;
return null;
}
}
}
Model.CS
namespace CSCodeExecuter
{
public class Model
{
public string Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
}
Now it works:
using System;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
namespace CSCodeExecuter
{
public class ScriptManager
{
public void ExecuteScript<T>(string scriptId, ref T input)
{
try
{
string inputSript = GetStriptById(scriptId);
var scriptOptions = ScriptOptions.Default.AddReferences("CSCodeExecuter");
var result = Execute(inputSript, scriptOptions);
}
catch (Exception ex)
{
throw;
}
}
private string GetStriptById(string id)
{
string csSript =
#"
public class ScriptedClass
{
public CSCodeExecuter.Model input {get;set;}
public ScriptedClass()
{
" + GetInternalScript() + #"
}
}
return (new ScriptedClass()).input;";
return csSript;
}
private string GetInternalScript()
{
return "input = new CSCodeExecuter.Model(); input.Id = \"1111\"; input.Name = \"test\"; input.Phone = \"1234567890\"; ";
}
private static ScriptState<object> scriptState = null;
public static object Execute(string code, dynamic scriptOptions)
{
scriptState = scriptState == null ? CSharpScript.RunAsync(code, scriptOptions).Result : scriptState.ContinueWithAsync(code).Result;
if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString()))
return scriptState.ReturnValue;
return null;
}
}
}
You had several errors:
not use options(second parameter) in Execute
extra parentheses in ctor
ctor should not has a result type(void)
input property was not initialized
scripts with creating of class and using of it was separated
I tried to write an autoupdater for a program from me.
I already got rid of a stackOverflow and such but now my Program seems to run endless when he comes to a variable. And do nothing.
I tried to get info with cw and check where it is hanging but i get nothing and can not find it.
My main
{
updater = new Updater(this);
updater.DoUpdate();
}
public string ApplicationName {
get { return "MyProgram"; }
}
public string ApplicationID {
get { return "MyProgramID"; }
}
public Assembly ApplicationAssembly {
get { return System.Reflection.Assembly.GetExecutingAssembly(); }
}
public Icon ApplicationIcon {
get { return this.Icon; }
}
public Uri UpdateXmlLocation {
get { return new Uri("UrlToXml"); }
}
public Form Context {
get { return this; }
}
in my XML class
public class UpdateXml
{
private Version version;
public Uri uri;
private string fileName;
private string md5;
private string description;
private string launchArgs;
internal Version Version {
get { return this.Version; }
}
internal Uri Uri {
get { return this.Uri; }
}
internal string FileName {
get { return this.fileName; }
}
internal string MD5 {
get { return this.md5; }
}
internal string Description {
get { return this.description; }
}
internal string LaunchArgs {
get { return this.launchArgs; }
}
after a while (code running fine it come to the part that crash)
private void DwnloadUpdate(UpdateXml update)
{
updateDownloadForm form = new updateDownloadForm(update.Uri, this.applicationInfo.ApplicationIcon);
after this code I expect that my dl windows open and the dl starts and the program get update
My Updater class
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace updater
{
public class Updater
{
private Iupdater applicationInfo;
private BackgroundWorker bgWorker;
public Updater(Iupdater applicationInfo)
{
this.applicationInfo = applicationInfo;
this.bgWorker = new BackgroundWorker();
this.bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
this.bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
}
public void DoUpdate()
{
if (!this.bgWorker.IsBusy)
this.bgWorker.RunWorkerAsync(this.applicationInfo);
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
Iupdater application = (Iupdater)e.Argument;
if (!UpdateXml.ExistOnServer(application.UpdateXmlLocation))
{
e.Cancel = true;
}
else
{
UpdateXml ux = UpdateXml.Parse(application.UpdateXmlLocation, application.ApplicationID);
if (ux == null)
{
e.Cancel = true;
}
else
{
e.Result = ux;
}
}
}
void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(!e.Cancelled)
{
UpdateXml update = (UpdateXml)e.Result;
if(update == null)
{
Console.WriteLine("Update NULL");
}
Console.WriteLine("test3.1");
Console.WriteLine(this.applicationInfo.ApplicationAssembly.GetName().Version);
if(this.applicationInfo.ApplicationAssembly.GetName().Version != null)
{
Console.WriteLine("YES!");
} else
{
Console.WriteLine("NO!");
}
Console.WriteLine("test3.2");
if (update != null && update.IsNewerThan(this.applicationInfo.ApplicationAssembly.GetName().Version))
{
Console.WriteLine("test4");
if (new updateInformation(applicationInfo, update).ShowDialog(this.applicationInfo.Context) == DialogResult.Yes)
this.DwnloadUpdate(update);
}
}
}
private void DwnloadUpdate(UpdateXml update)
{
Console.WriteLine(update.Uri);
if(update.Uri == null)
Console.WriteLine("null");
updateDownloadForm form = new updateDownloadForm(update.Uri, this.applicationInfo.ApplicationIcon);
Console.WriteLine("ich bin hier drinnen");
DialogResult result = form.ShowDialog(this.applicationInfo.Context);
if(result == DialogResult.OK)
{
string currentPath = this.applicationInfo.ApplicationAssembly.Location;
string newPath = Path.GetDirectoryName(currentPath) + "\\" + update.FileName;
UpdateApplication(form.TempFilePath, currentPath, newPath, update.LaunchArgs);
Application.Exit();
}
else if(result == DialogResult.Abort)
{
MessageBox.Show("The update download was cancelled. \nThis programm has not been modified.", "Update Download Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("There was a Problem downloading the Updat. \nThis programm has not been modified.", "Update Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateApplication(string tempFilePath, string currentPath, string newPath, string launchArgs)
{
string argument = "/C Choice /C Y /N /D Y /T 4 & Del /F /Q \"{0}\" & Choice /C Y /N /D Y /T 2 & Move /Y \"{1}\" \"{2}\" & Start \"\" /D \"{3}\" \"{4}\"{5}";
ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = string.Format(argument, currentPath, tempFilePath, newPath, Path.GetDirectoryName(newPath), Path.GetFileName(newPath), launchArgs);
info.CreateNoWindow = true;
info.FileName = "cmd.exe";
Process.Start(info);
}
}
}
my XML Updater class
using System;
using System.Net;
using System.Xml;
namespace updater
{
public class UpdateXml
{
private Version version;
public Uri uri;
private string fileName;
private string md5;
private string description;
private string launchArgs;
internal Version Version {
get { return this.Version; }
}
internal Uri Uri {
get { return this.Uri; }
}
internal string FileName {
get { return this.fileName; }
}
internal string MD5 {
get { return this.md5; }
}
internal string Description {
get { return this.description; }
}
internal string LaunchArgs {
get { return this.launchArgs; }
}
internal UpdateXml(Version version, Uri uri, string fileName, string md5, string description, string launchArgs)
{
Console.WriteLine("run in1");
this.version = version;
this.uri = uri;
this.fileName = fileName;
this.md5 = md5;
this.description = description;
this.launchArgs = launchArgs;
Console.WriteLine("run out 1");
}
internal bool IsNewerThan(Version version)
{
Console.WriteLine("run in 2");
return this.version > version;
}
internal static bool ExistOnServer(Uri location)
{
try
{
Console.WriteLine("run in 3");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(location.AbsoluteUri);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Console.WriteLine("run out 3");
return res.StatusCode == HttpStatusCode.OK;
}
catch { return false; }
}
internal static UpdateXml Parse(Uri location, string appID)
{
Console.WriteLine("run in 4");
Version version = null;
string url = "", fileName = "", md5 = "", description = "", launchArgs = "";
try
{
XmlDocument doc = new XmlDocument();
doc.Load(location.AbsoluteUri);
XmlNode node = doc.DocumentElement.SelectSingleNode("//update");
if(node == null)
{
return null;
}
version = Version.Parse(node["version"].InnerText);
url = node["url"].InnerText;
fileName = node["fileName"].InnerText;
md5 = node["md5"].InnerText;
description = node["description"].InnerText;
launchArgs = node["launchArgs"].InnerText;
Console.WriteLine("run out 4");
return new UpdateXml(version, new Uri(url), fileName, md5, description, launchArgs);
}
catch
{
return null;
}
}
}
}
My interfaces
using System;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;
namespace updater
{
public interface Iupdater
{
string ApplicationName { get; }
string ApplicationID { get; }
Assembly ApplicationAssembly { get; }
Icon ApplicationIcon { get; }
Uri UpdateXmlLocation { get; }
Form Context { get; }
}
}
my update start form where it seems to go into a loop
using System;
using updater;
using System.Windows.Forms;
namespace updater
{
internal partial class updateInformation : Form
{
private Iupdater applicationInfo;
private UpdateXml updateInfo;
private UpdateInoForm updateInoForm;
public updateInformation(Iupdater applicationInfo, UpdateXml updateInfo)
{
InitializeComponent();
this.applicationInfo = applicationInfo;
this.updateInfo = updateInfo;
this.Text = this.applicationInfo.ApplicationName + " - Update in Process";
if (this.applicationInfo.ApplicationIcon != null)
this.Icon = this.applicationInfo.ApplicationIcon;
//this.lblNewVersion.Text = String.Format("New Version: {0}", this.updateInfo.Version.ToString());
Timer wait = new Timer();
wait.Interval = 5000;
wait.Tick += new EventHandler(wait_Tick);
wait.Start();
}
void wait_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
}
private void Details_Click(object sender, EventArgs e)
{
if (this.updateInfo == null)
this.updateInoForm = new UpdateInoForm(this.applicationInfo, this.updateInfo);
this.updateInoForm.ShowDialog(this);
}
}
}
You need to return the field values, instead of the properties returning the property value. Do not write properties like this:
/// THIS PROPERTY TRIES TO RETURN ITSELF!!
internal Version Version {
get {
return this.Version; // you wanted to return 'this.version'
}
}
You can use auto-properties like this:
// No more private fields
public class UpdateXml
{
public Version Version { get; set; }
public string FileName { get; } // Only expose a getter, can be set in the ctor
public Uri Uri { get; set; }
// add more properties here...
public UpdateXml(string filename)
{
FileName = filename;
}
}
Or learn to use a convention seen allot in C#. Prefix the private variable names:
public class UpdateXml
{
private Version _version;
private string _fileName;
private Uri _uri;
public Version Version => _version;
public string FileName => _filename;
public Uri Uri {
get => _uri;
set => _uri = value;
}
// add more properties here...
// use the ctor to set some field values
public UpdateXml(string filename)
{
_filename = filename;
}
// fields allow setting values later on
public void SetLatestVersion(Version v)
{
if (_version == null || v > _version)
_version = v;
}
}
All in all, take care when writing code. Case does matter ;-)
i am trying to insert the value from control into xml but the record is getting overwriting with the previous one that is only one entry remains in xml file.plz give me solution,my code is like:
namespace StudentApplicationForm
{
public class information
{
private String txtbox1;
private String txtbox2;
private String txtbox3;
public String StudentName
{
get { return txtbox1; }
set{ txtbox1 = value; }
}
public String StudentId
{
get { return txtbox2; }
set{ txtbox2 = value; }
}
public String StudentBranch
{
get { return txtbox3; }
set { txtbox3 = value; }
}
}
}//getter and setter methods
and the file actual insert logic is written is:
public void ok_Click(object sender, EventArgs e)
{
try
{
information info = new information();
List<information> i1 = new List<information>();
XmlSerializer serial = new XmlSerializer(typeof(List<information>));
info.StudentName = textBox1.Text;//id of control
info.StudentId = textBox2.Text;
if (radioButton1.Checked)
{
info.StudentBranch = radioButton1.Text;
}
if (radioButton2.Checked)
{
info.StudentBranch = radioButton2.Text;
}
if (radioButton3.Checked)
{
info.StudentBranch = radioButton3.Text;
}
i1.Add(info);
using (FileStream fs = newFileStream(Environment.CurrentDirectory + "\\mynew.xml", FileMode.Create, FileAccess.Write))
{
serial.Serialize(fs, i1);
MessageBox.Show("Created");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Are you tried like this,
i1.Add(new information{ StudentName = info.StudentName, StudentId = info.StudentId, StudentBranch = info.StudentBranch});
Would be great if somebody could point out what is different between my customermanager and my employee manager which prevents the customer to get deserialized properly.
I create this xml with my program with the serializer with this call:
XmlSerializer bf = new XmlSerializer(typeof(ProjectConfiguration));
<?xml version="1.0"?>
<ProjectConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Title />
<UtcLastEdited>0001-01-01T00:00:00</UtcLastEdited>
<UtcLastChange>0001-01-01T00:00:00</UtcLastChange>
<customerManager>
<list>
<Customer>
<Firstname>Hans </Firstname>
<LastName>meser</LastName>
<ID>1</ID>
<Contry>deutschland</Contry>
<Town>berlin</Town>
<Street>poststraße 2</Street>
</Customer>
</list>
</customerManager>
<employeeManager>
<list>
<Employee>
<Firstname>hans </Firstname>
<LastName>Meyer</LastName>
<ID>1</ID>
<Contry>Deutschland</Contry>
<Town>Hamburg</Town>
<Street>Bahofstraße 4</Street>
</Employee>
</list>
</employeeManager>
<Projects>
<Project>
<ID>1</ID>
<Title>NewProjekt</Title>
<StartDate>2018-03-14T21:49:58.5540372+01:00</StartDate>
<Enddate>2018-03-29T21:49:58</Enddate>
<ListOfProjectActions>
<ProjectAction>
<Title>Implemtierung</Title>
<Day>2</Day>
<AsstimatedTime />
<Employee>1</Employee>
<Projektwork>Implementierung</Projektwork>
<ID>0</ID>
</ProjectAction>
</ListOfProjectActions>
<Description>aweeqweqe</Description>
<EmployeeToProject>
<int>1</int>
</EmployeeToProject>
<Customer>0</Customer>
<ProjektLeader>0</ProjektLeader>
</Project>
</Projects>
</ProjectConfiguration>
but when I deserialize with the same type
XmlSerializer bf = new XmlSerializer(typeof(ProjectConfiguration));
ProjectConfiguration obj = bf.Deserialize(file) as ProjectConfiguration;
it somehow fails to create a valid CustomerManager even though it works well with the Employeemanager with are pretty much same build up
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
//using Projektverwaltung.Interfaces;
namespace Projektverwaltung.Klassen
{
[Serializable()]
public class CustomerManager
{
public CustomerManager()
{
}
[XmlIgnore]
EventHandler m_EditHandle = new EventHandler(DefaultHandle);
[XmlIgnore]
Dictionary<int, Customer> m_CustomerList = new Dictionary<int, Customer>();
[XmlIgnore]
public Dictionary<int, Customer> CustomerList { get { return m_CustomerList; } set { m_CustomerList = value; } }
List<Customer> listtemp = new List<Customer>();
public List<Customer> list
{
get
{
try
{
listtemp.Clear();
foreach (var item in CustomerList.Values)
{
listtemp.Add(item);
}
}
catch (Exception ex)
{
Program.Log(ex);
}
return listtemp;
}
set
{
listtemp = value;
}
}
private static void DefaultHandle(object sender, EventArgs e) { }
[XmlIgnore]
public EventHandler EditCostumerEvent { get { return m_EditHandle; } set { m_EditHandle = value; } }
public int IncrementID()
{
int defaultindex = 0;
try
{
foreach (var item in CostumerList.Keys)
{
defaultindex = defaultindex < item ? item : defaultindex;
}
}
catch (Exception ex)
{
Program.Log(ex);
}
return defaultindex + 1;
}
}
}
but the employeemanager is pretty much the same
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
// using Projektverwaltung.Interfaces;
namespace Projektverwaltung.Klassen
{
[Serializable()]
public class EmployeeManager// : IEmployeeManager
{
[XmlIgnore]
EventHandler m_DeleteHandle = new EventHandler(DefaultHandle);
[XmlIgnore]
EventHandler m_EditHandle = new EventHandler(DefaultHandle);
[XmlIgnore]
Dictionary<int, Employee> m_EmployeeList = new Dictionary<int, Employee>();
List<int> m_usedIds = new List<int>();
private static void DefaultHandle(object sender, EventArgs e) { }
[XmlIgnore]
public Dictionary<int, Employee> ListofIEmployee { get { return m_EmployeeList; }set { m_EmployeeList = value; } }
[XmlIgnore]
public EventHandler DeleteOfEmployee { get { return m_DeleteHandle; } set { m_DeleteHandle = value; } }
[XmlIgnore]
public EventHandler EditOfEmployee { get { return m_EditHandle; } set { m_EditHandle = value; } }
public EmployeeManager()
{
}
public int IncrementID()
{
int defaultindex = 0;
try
{
foreach (var item in ListofIEmployee.Keys)
{
defaultindex = defaultindex < item ? item : defaultindex;
}
foreach (var item in m_usedIds)
{
defaultindex = defaultindex < item ? item : defaultindex;
}
}
catch (Exception ex)
{
Program.Log(ex);
}
return defaultindex + 1;
}
public void DeleteEmployee(Employee employee)
{
try
{
if (ListofIEmployee.Remove(employee.ID))
{
m_usedIds.Add(employee.ID);
DeleteOfEmployee.Invoke(employee, new EventArgs());
}
else
{
// could not delete employeee
}
}
catch (Exception ex )
{
Program.Log(ex);
}
}
public void EditEmployee(Employee employee)
{
try
{
m_EditHandle.Invoke(employee, new EventArgs());
}
catch (Exception ex)
{
Program.Log(ex);
}
}
List<Employee> listtemp = new List<Employee>();
public List<Employee> list
{
get
{
try
{
foreach (var item in ListofIEmployee.Values)
{
listtemp.Add(item);
}
}
catch (Exception ex)
{
Program.Log(ex);
}
return listtemp;
}
set
{
listtemp = value;
}
}
}
}
here the class with are the type who requested to deserialize
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Projektverwaltung.Interfaces;
using System.Windows.Forms;
namespace Projektverwaltung.Klassen
{
[Serializable()]
public class ProjectConfiguration //: ProjectConfiguration
{
List<Project> m_list;
CostumerManager m_costumerManager;
EmployeeManager m_employeeManager;
public string Title { get; set;}
public DateTime UtcLastEdited { get ; set ;}
public DateTime UtcLastChange { get ; set ;}
public ProjectConfiguration (List<Project> list,CostumerManager costumerManger,EmployeeManager employeeManagercar ,string strTitle,IWin32Window owner)
{
Title = strTitle;
m_list = list;
costumerManager = costumerManger;
employeeManager = employeeManagercar;
}
public ProjectConfiguration()
{
}
public CostumerManager costumerManager
{
get
{
return m_costumerManager;
}
set
{
m_costumerManager = value;
}
}
public EmployeeManager employeeManager
{
get
{
return m_employeeManager;
}
set
{
m_employeeManager = value;
}
}
public List<Project> Projects { get { return m_list; }set { m_list = value; } }
}
}
Edit with edited name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Projektverwaltung.Interfaces;
namespace Projektverwaltung.Klassen
{
[Serializable()]
public class Customer //: ICostumer
{
string m_strFirstName = string.Empty;
string m_strLastName = string.Empty;
string m_strContry = string.Empty;
string m_strStreet = string.Empty;
string m_strTown = string.Empty;
int m_nId = 0;
public Customer()
{
}
public string Firstname { get {return m_strFirstName;} set { m_strFirstName = value; }}
public string LastName { get {return m_strLastName;} set { m_strLastName=value; }}
public int ID { get {return m_nId;} set {m_nId=value; }}
public string Contry { get { return m_strContry;} set {m_strContry = value; }}
public string Town { get {return m_strTown;} set {m_strTown=value;} }
public string Street { get {return m_strStreet;} set {m_strStreet=value; }}
public string CombindedName { get{return string.Format("Kunde: {0} {1}", LastName, Firstname); } }
}
}
i tried to make a list since the diconarys do not serialize well the temp list is just a list that gets emptyed on each save so multiply saves make not redunant costumers on load the list get writed to the dictonarys with the id as key
ok the clear was it in combination with and exit chek solved the problem even though i do not check the cause it. thx marc for pointing t out that s was a bit senseless
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
//using Projektverwaltung.Interfaces;
namespace Projektverwaltung.Klassen
{
[Serializable()]
public class CustomerManager//: IXmlSerializable
{
public CustomerManager()
{
}
[XmlIgnore]
EventHandler m_EditHandle = new EventHandler(DefaultHandle);
[XmlIgnore] Dictionary<int, Customer> m_CostumerList = new Dictionary<int, Customer>();
[XmlIgnore] public Dictionary<int, Customer> CostumerList { get { return m_CostumerList; } set { m_CostumerList = value; } }
[XmlArray(ElementName = "CostumerList",IsNullable =true)]
List<Customer> listtemp = new List<Customer>();
public List<Customer> list
{
get
{
try
{
foreach (var item in CostumerList.Values)
{
if (!listtemp.Exists(match=>match.ID==item.ID))
{
listtemp.Add(item);
}
}
}
catch (Exception ex)
{
Program.Log(ex);
}
return listtemp;
}
set
{
}
}
private static void DefaultHandle(object sender, EventArgs e) { }
[XmlIgnore] public EventHandler EditCostumerEvent { get { return m_EditHandle; } set { m_EditHandle = value; } }
public int IncrementID()
{
int defaultindex = 0;
try
{
foreach (var item in CostumerList.Keys)
{
defaultindex = defaultindex < item ? item : defaultindex;
}
}
catch (Exception ex)
{
Program.Log(ex);
}
return defaultindex + 1;
}
}
}
sorry for bugging you guys with such a small problem, but I cannot find a solution. I have created one class for getting attachments from exchange server and Form for adding server configuration and textbox which I attend to use for the log output. I have added backgroundWorker to create separate thread and when class gets right attachment and collect info for the output, it redirects to backgroundWorker DoWork method. The problem is that UI of the textbox is simply doesn't want to append text
Class for downloading attachment looks like:
namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
private string path_ = "";
private string filterSender_ = "";
private string subject_ = "";
private string id_ = "";
private string username_ = "";
private string password_ = "";
private string exchange_ = "";
private string filterExcel_ = "";
private string filterCSV_ = "";
private string attachmentName_ = "";
private int emailFetch_ = 0;
private DateTime current_;
ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
public string Path
{
get { return path_; }
set { path_ = value; }
}
public string FilterSender
{
get { return filterSender_; }
set { filterSender_ = value; }
}
public string Subject
{
get { return subject_; }
set { subject_ = value; }
}
public string ID
{
get { return id_; }
set { id_ = value; }
}
public string Username
{
get { return username_; }
set { username_ = value; }
}
public string Password
{
get { return password_; }
set { password_ = value; }
}
public string Exchange
{
get { return exchange_; }
set { exchange_ = value; }
}
public string FilterExcel
{
get { return filterExcel_; }
set { filterExcel_ = value; }
}
public string FilterCsv
{
get { return filterCSV_; }
set { filterCSV_ = value; }
}
public string AttachementName
{
get { return attachmentName_; }
set { attachmentName_ = value; }
}
public int EmailFetch
{
get { return emailFetch_; }
set { emailFetch_ = value; }
}
public DateTime CurrentDate
{
get { return current_; }
set { current_ = value; }
}
public void GetAttachments()
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl(Exchange);
ItemView view = new ItemView(10);
FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));
if (result != null && result.Items != null && result.Items.Count > 0)
{
foreach (Item item in result.Items)
{
EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
if (msg.Sender.ToString().Contains(FilterSender) && msg.From.ToString().Contains(FilterSender))
{
foreach (Attachment att in msg.Attachments)
{
if (att is FileAttachment)
{
FileAttachment file = att as FileAttachment;
if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
{
Form1 form = new Form1();
file.Load(Path +"\\"+ file.Name);
AttachementName = file.Name.ToString();
Subject = item.Subject.ToString();
ID = item.Id.ToString();
CurrentDate = DateTime.Now;
form.date = CurrentDate.ToString();
form.subject = Subject;
form.attachment = AttachementName;
form.backgroundWorker1.RunWorkerAsync();
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Form looks like this:
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string date = "";
public string attachment = "";
public string subject = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
private void button3_Click(object sender, EventArgs e)
{
if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
exchange.Path = path;
pathTxt.Text = path;
}
}
private void onBtn_Click(object sender, EventArgs e)
{
exchange.Username = userTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.FilterSender = fromFilterTxt.Text;
exchange.EmailFetch = Convert.ToInt32(fetchUpDown.Value);
exchange.Exchange = exchangeTxt.Text;
exchange.GetAttachments();
}
private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterExcelCheck.CheckState == CheckState.Checked)
{
exchange.FilterExcel = ".xlsx";
}
else
{
exchange.FilterExcel = "";
}
}
private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterCSVCheck.CheckState == CheckState.Checked)
{
exchange.FilterCsv = ".csv";
}
else
{
exchange.FilterCsv = "";
}
}
private void exchangeTxt_MouseHover(object sender, EventArgs e)
{
tipLbl.Visible = true;
tipLbl.Text = "It is usually same as email address...";
}
private void exchangeTxt_MouseLeave(object sender, EventArgs e)
{
tipLbl.Visible = false;
}
//("\n" + CurrentDate.ToString() + " , Message id: " + ID + " , Message subject: " + Subject + " , Attachment name: " + AttachementName + "\r");
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//e.Result = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
//private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// if (e.Cancelled)
// {
// logOutputTxt.Text = "Thread is somehow cancelled, please contact developer for this issue...!";
// }
// else if (e.Error != null)
// {
// logOutputTxt.Text = e.Error.Message;
// }
// else
// {
// logOutputTxt.Text += e.Result;
// }
//}
}
}
as you can see I'm calling background worker from class ExchangeDwnClass which I believe is OK, by using:
form.backgroundWorker1.RunWorkerAsync();
and when I run debugger it really jumps to background worker
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
for some reason Form textbox control is not refreshing output.
p.s. I have created also on RunWorkerCompleted method but also without luck...
Any clue how can I work things out?
OK, the problem was that I have created another object in form ExchangeDowClass for Form1, instead of passing a reference object into method GetAttachments
complete code for Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string subject = "";
public string attachment = "";
public string date = "";
public string sender = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
BackgroundWorker bgrWorker = new BackgroundWorker();
private void button3_Click(object sender, EventArgs e)
{
if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
exchange.Path = path;
pathTxt.Text = path;
}
}
private void onBtn_Click(object sender, EventArgs e)
{
exchange.EmailFetch=Convert.ToInt32(fetchUpDown.Value);
exchange.FilterSender = fromFilterTxt.Text;
exchange.Exchange = exchangeTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.Username = userTxt.Text;
backgroundWorker1.RunWorkerAsync();
}
private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterExcelCheck.CheckState == CheckState.Checked)
{
exchange.FilterExcel = ".xlsx";
}
else
{
exchange.FilterExcel = "";
}
}
private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterCSVCheck.CheckState == CheckState.Checked)
{
exchange.FilterCsv = ".csv";
}
else
{
exchange.FilterCsv = "";
}
}
private void exchangeTxt_MouseHover(object sender, EventArgs e)
{
tipLbl.Visible = true;
tipLbl.Text = "It is usually same as email address...";
}
private void exchangeTxt_MouseLeave(object sender, EventArgs e)
{
tipLbl.Visible = false;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//logOutputTxt.Text += "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r"
//backgroundWorker1.ReportProgress(0);
exchange.GetAttachments(this);
}
private void Form1_Load(object sender, EventArgs e)
{
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
logOutputTxt.Text += "\n" + date + " , Sender: "+sender+" , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
}
}
}
and for ExchangeDwnClass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using System.Threading;
namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
private string path_ = "";
private string filterSender_ = "";
private string subject_ = "";
private string id_ = "";
private string username_ = "";
private string password_ = "";
private string exchange_ = "";
private string filterExcel_ = "";
private string filterCSV_ = "";
private string attachmentName_ = "";
private int emailFetch_ = 0;
private DateTime current_;
ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
public string Path
{
get { return path_; }
set { path_ = value; }
}
public string FilterSender
{
get { return filterSender_; }
set { filterSender_ = value; }
}
public string Subject
{
get { return subject_; }
set { subject_ = value; }
}
public string ID
{
get { return id_; }
set { id_ = value; }
}
public string Username
{
get { return username_; }
set { username_ = value; }
}
public string Password
{
get { return password_; }
set { password_ = value; }
}
public string Exchange
{
get { return exchange_; }
set { exchange_ = value; }
}
public string FilterExcel
{
get { return filterExcel_; }
set { filterExcel_ = value; }
}
public string FilterCsv
{
get { return filterCSV_; }
set { filterCSV_ = value; }
}
public string AttachementName
{
get { return attachmentName_; }
set { attachmentName_ = value; }
}
public int EmailFetch
{
get { return emailFetch_; }
set { emailFetch_ = value; }
}
public DateTime CurrentDate
{
get { return current_; }
set { current_ = value; }
}
public void GetAttachments(Form1 form)
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl("username#domain.lan");
ItemView view = new ItemView(EmailFetch);
FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));
if (result != null && result.Items != null && result.Items.Count > 0)
{
foreach (Item item in result.Items)
{
EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
if (msg.Sender.ToString().ToLower().Contains(FilterSender) && msg.From.ToString().ToLower().Contains(FilterSender))
{
foreach (Attachment att in msg.Attachments)
{
if (att is FileAttachment)
{
FileAttachment file = att as FileAttachment;
if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
{
file.Load(Path +"\\"+ file.Name);
form.attachment = file.Name.ToString();
form.subject = item.Subject.ToString();
//ID = item.Id.ToString();
form.date = DateTime.Now.ToString();
form.sender = msg.Sender.ToString();
form.backgroundWorker1.ReportProgress(0);
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Plus I had to use ProgressChanged method to refresh control...
I still have some minor bugs like double output in textbox form, but this is basically small issue.
I hope this code will be useful to others.
Cheers.