Unable to deserialize an encrypted array in c# - c#

The following code in my program serializes, encrypts and writes the byte array to disk. From the looks of it, the encryption works fine. The issue arises when the program decrypts and then deserializes the file.
Visual Studio displays the following error:
'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll
Additional information: There was an error deserializing the object of type Test.Store. The data at the root level is invalid.
I've been stuck on this one for two days, so any help would be greatly appreciated!
The following code has been trimmed down from its original form:
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
namespace Test
{
public class K
{
#region Non-Public Data Members
private string _n = string.Empty;
private string _u = string.Empty;
private string _p = string.Empty;
private string _u2 = null;
private string _n2 = string.Empty;
public K()
{
}
public string T
{
get { return _n; }
set { _n = value; }
}
public string U
{
get { return _u; }
set { _u = value; }
}
public string P
{
get { return _p; }
set { _p = value; }
}
public string U2
{
get { return _u2; }
set { _u2 = value; }
}
public string N2
{
get { return _n2; }
set { _n2 = value; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
//stuff
return sb.ToString();
}
#endregion
}
public class Group
{
private string _text = string.Empty;
private int _imageIndex = 0;
private List<K> _credentials = new List<K>();
public Group()
{
}
public Group(string text, int imageIndex)
{
_text = text;
_imageIndex = imageIndex;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public int ImageIndex
{
get { return _imageIndex; }
set { _imageIndex = value; }
}
public List<K> Ks
{
get { return _credentials; }
set { _credentials = value; }
}
public override string ToString()
{
return Text;
}
}
public class Store
{
private List<Group> _groups = new List<Group>();
private string _docname = string.Empty;
private bool _dirtyBit = false;
public bool DirtyBit
{
get { return _dirtyBit; }
set { _dirtyBit = value; }
}
public List<Group> Groups
{
get { return _groups; }
set { _groups = value; }
}
public string DocName
{
get { return _docname; }
set { _docname = value; }
}
}
public class Crypto
{
public static string secretKey = "abcdefgh";
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]
public static extern bool ZeroMemory(ref string Destination, int Length);
static string GenerateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
public static byte[] PerformCrypto(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
public static byte[] Decrypt(byte[] cipherTextBytes)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(secretKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(secretKey);
using (var decryptor = DES.CreateDecryptor(DES.Key, DES.IV))
{
return PerformCrypto(decryptor, cipherTextBytes);
}
}
public static byte[] Encrypt(byte[] plainTextBytes)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(secretKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(secretKey);
using (var encryptor = DES.CreateEncryptor(DES.Key, DES.IV))
{
return PerformCrypto(encryptor, plainTextBytes);
}
}
}
public static class StoreMgr
{
private static Store _doc = new Store();
public static void FileSaveAs(string fn)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Store));
serializer.WriteObject(ms, _doc);
byte[] byteArrayInput = ms.GetBuffer();
byte[] encryptedBuffer = Crypto.Encrypt(byteArrayInput);
File.WriteAllBytes(fn, encryptedBuffer);
}
}
public static void OpenFile(string fn)
{
StoreMgr._doc = new Store();
using (MemoryStream ms = new MemoryStream(Crypto.Decrypt(File.ReadAllBytes(fn))))
{
DataContractSerializer deserializer = new DataContractSerializer(typeof(Store));
StoreMgr._doc = (Store)new DataContractSerializer(typeof(Store)).ReadObject(ms);
}
}
}
}
I've been stuck on this for quite some time. Any help is greatly appreciated!

If you configure System.Diagnostics.XmlWriterTraceListener in your web.config, you may find more helpful information in *.svclog

The issue was in the FileSaveAs method. byte[] byteArrayInput = ms.GetBuffer() was returning unused bytes. After switching it to byte[] byteArrayInput = ms.ToArray() program ran fine. Thanks for everyone's help.

Related

Veracode Rest API is only returning 401 unauthorized

I've been trying to use the Veracode API to trigger a dynamic analysis, but following the Veracode documentation all I'm getting is a 401 unauthorized. I've taken the example C# code provided by Veracode and plugged in my API key and ID but still no results. Any insight would be greatly appreciated.
Program.cs
{
private const string AuthorizationHeader = "Authorization";
private const string ApiId = "snip";
private const string ApiKey = "snip";
public static void Main(string[] args)
{
try
{
const string urlBase = "api.veracode.com/was/configservice/v1";
const string urlPath = "/analyses";
var urlParams = string.Empty;
const string httpVerb = "GET";
var webClient = new WebClient
{
BaseAddress = $"https://{urlBase}"
};
var authorization = HmacAuthHeader.HmacSha256.CalculateAuthorizationHeader(ApiId, ApiKey, urlBase, urlPath, urlParams, httpVerb);
webClient.Headers.Add(AuthorizationHeader, authorization);
var result = webClient.DownloadString(urlPath);
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
}
}
HmacAuthHeader.cs
public abstract class HmacAuthHeader
{
private static readonly RNGCryptoServiceProvider RngRandom = new RNGCryptoServiceProvider();
public static readonly HmacAuthHeader HmacSha256 = new HmacSha256AuthHeader();
private sealed class HmacSha256AuthHeader : HmacAuthHeader
{
protected override string GetHashAlgorithm() { return "HmacSHA256"; }
protected override string GetAuthorizationScheme() { return "VERACODE-HMAC-SHA-256"; }
protected override string GetRequestVersion() { return "vcode_request_version_1"; }
protected override string GetTextEncoding() { return "UTF-8"; }
protected override int GetNonceSize() { return 16; }
internal HmacSha256AuthHeader() { }
}
protected abstract string GetHashAlgorithm();
protected abstract string GetAuthorizationScheme();
protected abstract string GetRequestVersion();
protected abstract string GetTextEncoding();
protected abstract int GetNonceSize();
protected string CurrentDateStamp()
{
return ((long)((TimeSpan)(DateTime.UtcNow - new DateTime(1970, 1, 1))).TotalMilliseconds).ToString();
}
protected byte[] NewNonce(int size)
{
byte[] nonceBytes = new byte[size];
RngRandom.GetBytes(nonceBytes);
return nonceBytes;
}
protected byte[] ComputeHash(byte[] data, byte[] key)
{
HMAC mac = HMAC.Create(GetHashAlgorithm());
mac.Key = key;
return mac.ComputeHash(data);
}
protected byte[] CalculateDataSignature(byte[] apiKeyBytes, byte[] nonceBytes, string dateStamp, string data)
{
byte[] kNonce = ComputeHash(nonceBytes, apiKeyBytes);
byte[] kDate = ComputeHash(Encoding.GetEncoding(GetTextEncoding()).GetBytes(dateStamp), kNonce);
byte[] kSignature = ComputeHash(Encoding.GetEncoding(GetTextEncoding()).GetBytes(GetRequestVersion()), kDate);
return ComputeHash(Encoding.GetEncoding(GetTextEncoding()).GetBytes(data), kSignature);
}
public string CalculateAuthorizationHeader(string apiId, string apiKey, string hostName, string uriString, string urlQueryParams, string httpMethod)
{
try
{
if (urlQueryParams != null)
{
uriString += (urlQueryParams);
}
string data = $"id={apiId}&host={hostName}&url={uriString}&method={httpMethod}";
string dateStamp = CurrentDateStamp();
byte[] nonceBytes = NewNonce(GetNonceSize());
byte[] dataSignature = CalculateDataSignature(FromHexBinary(apiKey), nonceBytes, dateStamp, data);
string authorizationParam = $"id={apiId},ts={dateStamp},nonce={ToHexBinary(nonceBytes)},sig={ToHexBinary(dataSignature)}";
return GetAuthorizationScheme() + " " + authorizationParam;
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
public static string ToHexBinary(byte[] bytes)
{
return new SoapHexBinary(bytes).ToString();
}
public static byte[] FromHexBinary(string hexBinaryString)
{
return SoapHexBinary.Parse(hexBinaryString).Value;
}
public static bool IsValidHexBinary(string hexBinaryString)
{
if (hexBinaryString != null)
{
try
{
byte[] bytes = FromHexBinary(hexBinaryString);
return bytes != null;
}
catch (Exception) { }
}
return false;
}
public static bool IsValidAuthHeaderToken(string authHeaderToken)
{
if (authHeaderToken != null)
{
// For valid Authorization header token syntax see https://www.ietf.org/rfc/rfc2617.txt, https://www.ietf.org/rfc/rfc2068.txt
bool isMatch = Regex.IsMatch(authHeaderToken, "^[\\x21\\x23-\\x27\\x2A-\\x2B\\x2D-\\x2E\\x30-\\x39\\x41-\\x5A\\x5E-\\x7A\\x7C\\x7E]+$");
return isMatch;
}
return false;
}
private HmacAuthHeader() { }
}
}
The function you are calling is:
CalculateAuthorizationHeader(string apiId, string apiKey, string hostName, string uriString, string urlQueryParams, string httpMethod)
So your urlBase needs to be api.veracode.com rather than api.veracode.com/was/configservice/v1. Your urlPath should be /was/configservice/v1/analyses.

How do you assign only to a pointer in C# for my undo redo class

Im trying to create an undoredo manager that doesnt matter on what object you pass in. But I cant figure out how to do this in C#. I would like to do something like a pointer to the Original Object and only change where that pointer is pointing to.
C# code
public class UndoableObject<T> : IUndoableAction
{
private T UndoObject;
private T ClonedObject;
private readonly string _name;
public string Name
{
get { return _name; }
}
public UndoableObject(ref T ObjectToUndo, string name)
{
_name = name;
UndoObject = ObjectToUndo;
ClonedObject = ObjectExtensions.Copy<T>(ObjectToUndo);
}
public void Redo()
{
T temp = ObjectExtensions.Copy<T>(UndoObject);
UndoObject = ClonedObject;
ClonedObject = temp;
}
public void Undo()
{
T temp = ObjectExtensions.Copy<T>(UndoObject);
UndoObject = ClonedObject;
ClonedObject = temp;
}
}
A C++ implementation of what i would like to happen
template<typename T>
public class UndoableObject : IUndoableAction
{
private T *UndoObject;
private T *ClonedObject;
private string _name;
public string GetName
{
return _name;
}
public UndoableObject(T *ObjectToUndo, string name)
{
_name = name;
UndoObject = ObjectToUndo;
ClonedObject = &ObjectExtensions.Copy(*ObjectToUndo);
}
public void Redo()
{
T *temp = &ObjectExtensions.Copy(*UndoObject);
delete UndoObject;
UndoObject = ClonedObject;
ClonedObject = temp;
}
public void Undo()
{
T *temp = &ObjectExtensions.Copy(*UndoObject);
delete UndoObject;
UndoObject = ClonedObject;
ClonedObject = temp;
}
}
I know there are probably memory leaks in it but i wrote up the c++ without compiling it. Hopefully I made some sense.
Have a look at the following:
//using System;
//using Sytem.Collections.Generic
public class UndoableObject<T>
{
List<T> _list = new List<T>();
string _name;
int _step = 0;
public UndoableObject(T source, string name)
{
_list.Clear();
_list = new List<T>();
_list.Add(source);
_name = name;
_step = 0;
}
public string GetName
{
get { return _name; }
}
public void Record(T item)
{
_list.Add(item);
_step++;
}
public T Undo()
{
_step--;
if (_step >= 0)
{
return _list[_step];
}
else
{
_step = 0;
return _list[_step];
}
}
public T Redo()
{
_step++;
if (_step < _list.Count)
{
return _list[_step];
}
else
{
_step = _list.Count - 1;
return _list[_step];
}
}
}
Basic Usage:
var pictureBox1 = new PictureBox();
var _bitmap = new Bitmap(300, 300);
var uo = new UndoableObject<Bitmap>(_bitmap, "bitmap");
Undo:
pictureBox1.Image = uo.Undo();
Record:
uo.Record((Bitmap)pictureBox1.Image);
Redo:
pictureBox1.Image = uo.Redo();

XML serialization C#, not processing certain fields

I have a serialization method as follows:
public string SerializeObject(object obj, Type type)
{
var setting = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
var xml = new StringBuilder();
using (var writer = XmlWriter.Create(xml, setting))
{
var nsSerializer = new XmlSerializerNamespaces();
nsSerializer.Add(string.Empty, string.Empty);
var xmlSerializer = new XmlSerializer(type);
xmlSerializer.Serialize(writer, obj, nsSerializer);
}
return xml.ToString();
}
Which I call as follows:
requestXML = serializer.SerializeObject(InboundIterate, typeof(INBOUND));
The output is as expected for any field I have defined in my structure as a string, but all the decimal values are missing.
For example my output will look like:
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</SD_DIMENSION_UOM>
<SALES_UOM>CS</SD_SALES_UOM>
</PRODUCT_EXTENSION>
when I am expecting
<PRODUCT_EXTENSION>
<DIMENSION_UOM>IN</DIMENSION_UOM>
<DIMENSION>15.83</DIMENSION>
<SALES_UOM>CS</SALES_UOM>
<SALES>24</SALES>
</PRODUCT_EXTENSION>
any help would be appreciated, thank you.
class below
public partial class PRODUCT_EXTENSION {
private System.Nullable<decimal> LENGTHField;
private bool LENGTHFieldSpecified;
private System.Nullable<decimal> NET_WEIGHTField;
private bool NET_WEIGHTFieldSpecified;
private string SALES_UOMField;
private string WEIGHT_UOMField;
private List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEMField;
public PRODUCT_EXTENSION() {
this.SOURCE_SYSTEMField = new List<PRODUCT_EXTENSIONSOURCE_SYSTEM>();
}
public System.Nullable<decimal> LENGTH {
get {
return this.LENGTHField;
}
set {
this.LENGTHField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool SD_LENGTHSpecified {
get {
return this.LENGTHFieldSpecified;
}
set {
this.LENGTHFieldSpecified = value;
}
}
public System.Nullable<decimal> NET_WEIGHT {
get {
return this.NET_WEIGHTField;
}
set {
this.NET_WEIGHTField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool NET_WEIGHTSpecified {
get {
return this.NET_WEIGHTFieldSpecified;
}
set {
this.NET_WEIGHTFieldSpecified = value;
}
}
public string SALES_UOM {
get {
return this.SALES_UOMField;
}
set {
this.SALES_UOMField = value;
}
}
public string SD_WEIGHT_UOM {
get {
return this.WEIGHT_UOMField;
}
set {
this.WEIGHT_UOMField = value;
}
}
public List<PRODUCT_EXTENSIONSOURCE_SYSTEM> SOURCE_SYSTEM {
get {
return this.SOURCE_SYSTEMField;
}
set {
this.SOURCE_SYSTEMField = value;
}
}
}
I've tried your code snippet, and it works fine for me fine with public properties, but if i change the property protection to protected or private. These properties are missing from the XML.
Check your properties.

C# Xml Serialization & Deserialization

I am trying to serialize an object & save it into a Sql server 2008 xml field. I also have some deserialization code that re-hydrates the object. I am able to serialize & save the object into the db, but get a "Root element missing" exception.
[XmlRoot("Patient")]
public class PatientXml
{
private AddressXml _address = null;
private EmergencyContactXml _emergencyContact = null;
private PersonalXml _personal = null;
[XmlElement]
public PersonalXml Personal
{
get { return _personal; }
set { _personal = value; }
}
[XmlElement]
public AddressXml Address
{
get { return _address; }
set { _address = value; }
}
[XmlElement]
public EmergencyContactXml EmergencyContact
{
get { return _emergencyContact; }
set { _emergencyContact = value; }
}
public PatientXml(){}
public PatientXml(Patient patient)
{
_address = new AddressXml(patient.Address);
_emergencyContact = new EmergencyContactXml(patient.EmergencyInfo);
_personal = new PersonalXml(patient);
}
}
public class PersonalXml
{
private string _firstName = string.Empty, _lastName = string.Empty, _dateOfBirth = string.Empty, _phone = string.Empty;
[XmlAttribute]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
[XmlAttribute]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
[XmlAttribute]
public string DateOfBirth
{
get { return _dateOfBirth; }
set { _dateOfBirth = value; }
}
[XmlAttribute]
public string Phone
{
get { return _phone; }
set { _phone = value; }
}
public PersonalXml(){}
public PersonalXml(Patient patient)
{
_firstName = patient.FirstName;
_lastName = patient.LastName;
_dateOfBirth = patient.DateOfBirth.ToShortDateString();
_phone = patient.Phone;
}
}
public class AddressXml
{
private string _address1 = string.Empty, _address2 = string.Empty, _city = string.Empty, _state = string.Empty, _zip = string.Empty;
[XmlAttribute]
public string Address1
{
get { return _address1; }
set { _address1 = value; }
}
[XmlAttribute]
public string Address2
{
get { return _address2; }
set { _address2 = value; }
}
[XmlAttribute]
public string City
{
get { return _city; }
set { _city = value; }
}
[XmlAttribute]
public string State
{
get { return _state; }
set { _state = value; }
}
[XmlAttribute]
public string Zip
{
get { return _zip; }
set { _zip = value; }
}
public AddressXml(){}
public AddressXml(Address address)
{
_address1 = address.Address1;
_address2 = address.Address2;
_city = address.City;
_state = address.State;
_zip = address.ZipCode;
}
}
public class EmergencyContactXml
{
private string _name = string.Empty, _phone = string.Empty, _relationship = string.Empty;
[XmlAttribute]
public string Name
{
get { return _name; }
set { _name = value; }
}
[XmlAttribute]
public string Phone
{
get { return _phone; }
set { _phone = value; }
}
[XmlAttribute]
public string Relationship
{
get { return _relationship; }
set { _relationship = value; }
}
public EmergencyContactXml(){}
public EmergencyContactXml(EmergencyContact contact)
{
_name = contact.ContactName;
_phone = contact.Phone;
_relationship = contact.Relationship;
}
}
Serialized Xml output:
<Patient
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Personal FirstName="Test" LastName="User 1" DateOfBirth="3/13/1966" Phone="6304449866" />
<Address Address1="123 Some St" City="Bartlett" State="CT" Zip="60111" />
<EmergencyContact Name="Dr Chanduwarthana" Phone="6309769484" Relationship="Father" />
</Patient>
Serization & Deserialization code:
public static class XmlSerializer
{
public static string Serialize<T>(T item)
{
MemoryStream memStream = new MemoryStream();
using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
serializer.Serialize(textWriter, item);
memStream = textWriter.BaseStream as MemoryStream;
}
if (memStream != null)
return Encoding.Unicode.GetString(memStream.ToArray());
else
return null;
}
public static T Deserialize<T>(string xmlString)
{
if (string.IsNullOrWhiteSpace(xmlString))
return default(T);
using (MemoryStream memStream = new MemoryStream())
{
using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
{
memStream.Position = 0;
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)serializer.Deserialize(memStream);
}
}
}
}
In your deserialization code you're creating a MemoryStream and XmlTextWriter but you're not giving it the string to deserialize.
using (MemoryStream memStream = new MemoryStream())
{
using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
{
// Omitted
}
}
You can pass the bytes to the memory stream and do away with the XmlTextWriter altogether.
using (MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)serializer.Deserialize(memStream);
}
Looks like you got a handle on serializing to XML, so take my advice, store the XML in a string field (varchar, nvarchar, text, ntext) and not a specialized field.
If you do that little switch you will be ready to go... no further modification required.
XML field is subject to validations, and more than a few headaches, and if your application is only producer and consumer of that field, you might as well take that shortcut.
SQL2008 (even 2005) is strong enough to compensate for the resources you might save by it compiling the xml field.
HOWEVER ,
I would optimize your code a bit, looks like you wrote way more code than you had to.
For example, you no longer need to create a private field to store the data from your property, for example :
public PersonalXml Personal
{
get { return _personal; }
set { _personal = value; }
}
will work just fine if you wrote it like :
public PersonalXml Personal { get ; set ; }
there's more fat you could have cut...
I believe that you need to add the XML header:
<?xml version="1.0" encoding="utf-8" ?>
You could modify your serialize method to accept an optional parameter that would cause this to be added:
public static string Serialize<T>(T item, bool includeHeader = false)
{
MemoryStream memStream = new MemoryStream();
using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
serializer.Serialize(textWriter, item);
memStream = textWriter.BaseStream as MemoryStream;
}
if (memStream != null)
if (includeHeader)
{
return #"<?xml version=""1.0"" encoding=""utf-8"" ?>" + Environment.NewLine + Encoding.Unicode.GetString(memStream.ToArray());
}
else
{
return Encoding.Unicode.GetString(memStream.ToArray());
}
else
return null;
}

Deserialize XML file with objects to Array

This is my code so far:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Xml;
namespace Opgaver
{
class OpgaveController
{
static ArrayList _arrAktiveOpgaver = new ArrayList();
public ArrayList arrAktiveOpgaver
{
get { return _arrAktiveOpgaver; }
set { _arrAktiveOpgaver = value; }
}
static ArrayList _arrAfsluttedeOpgaver = new ArrayList();
public ArrayList arrAfsluttedeOpgaver
{
get { return _arrAfsluttedeOpgaver; }
set { _arrAfsluttedeOpgaver = value; }
}
static int _opgavenr = 100;
public int opgavenr
{
get { return _opgavenr; }
set { _opgavenr = value; }
}
public void opretOpgave(string opgavenavn, string opgavebeskrivelse, int opgaveprioritet, DateTime opgaveafsluttetdato)
{
DateTime oprettetdato = new DateTime();
oprettetdato = DateTime.Now;
bool opgaveafsluttet = false;
Opgave opgave = new Opgave(oprettetdato, _opgavenr, opgavenavn, opgavebeskrivelse, opgaveprioritet, opgaveafsluttet, opgaveafsluttetdato);
if (opgave.opgaveAfsluttet == false)
{
_arrAktiveOpgaver.Add(opgave);
}
else
{
_arrAfsluttedeOpgaver.Add(opgave);
}
_opgavenr++;
}
public OpgaveController()
{
}
}
public void test()
{
string outfile = #"C:\Folder\Tester.xml";
XmlSerializer xs;
Serialize<List<Opgave>>(arrAktiveOpgaver, outfile);
arrAktiveOpgaver = <List<Opgave>>(outfile);//deserialize data - Generates this error: Error 2 Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments P:\Programmerings opgaver\Opgaver\Opgaver\OpgaveController.cs 107 33 Opgaver
}
private void Serialize<T1>(ArrayList arrAktiveOpgaver, string outfile)
{
throw new NotImplementedException();
}
public static T DeserializeFromXml<T>(string inputFile)
{
XmlSerializer s = new XmlSerializer(typeof(T));
T deserializedObject = default(T);
using (TextReader textReader = new StreamReader(inputFile))
{
deserializedObject = (T)s.Deserialize(textReader);
textReader.Close();
}
return deserializedObject;
}
public static void SerializeToXml<T>(T objToSerialize, string outputFile)
{
XmlSerializer s = new XmlSerializer(objToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(outputFile))
{
s.Serialize(textWriter, objToSerialize);
textWriter.Close();
}
}
}
}
i need to serialize the arraylist, and deserialize it..
and here is my opgave class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Opgaver
{
[Serializable()] public class Opgave : IComparable
{
DateTime _oprettetDato = new DateTime();
public DateTime oprettetDato
{
get { return _oprettetDato; }
set { _oprettetDato = value; }
}
int _opgavenr;
public int opgavenr
{
get { return _opgavenr; }
set { _opgavenr = value; }
}
string _opgaveNavn;
public string opgaveNavn
{
get { return _opgaveNavn; }
set { _opgaveNavn = value; }
}
string _opgaveBeskrivelse;
public string opgaveBeskrivelse
{
get { return _opgaveBeskrivelse; }
set { _opgaveBeskrivelse = value; }
}
int _opgavePrioritet;
public int opgavePrioritet
{
get { return _opgavePrioritet; }
set { _opgavePrioritet = value; }
}
bool _opgaveAfsluttet = false;
public bool opgaveAfsluttet
{
get { return _opgaveAfsluttet; }
set { _opgaveAfsluttet = value; }
}
DateTime _opgaveAfsluttetDato = new DateTime();
public DateTime opgaveAfsluttetDato
{
get { return _opgaveAfsluttetDato; }
set { _opgaveAfsluttetDato = value; }
}
public Opgave()
{
}
public Opgave(DateTime oprettetdato, int opgavenr, string opgavenavn, string opgavebeskrivelse, int opgaveprioritet, bool opgaveafsluttet, DateTime opgaveafsluttetdato)
{
_oprettetDato = oprettetdato;
_opgavenr = opgavenr;
_opgaveNavn = opgavenavn;
_opgaveBeskrivelse = opgavebeskrivelse;
_opgavePrioritet = opgaveprioritet;
_opgaveAfsluttet = opgaveafsluttet;
_opgaveAfsluttetDato = opgaveafsluttetdato;
}
//Sorterings metode
public int CompareTo(object obj)
{
Opgave Compare = (Opgave)obj;
int result = this.opgavenr.CompareTo(Compare.opgavenr);
if (result == 0)
result = this.opgavenr.CompareTo(Compare.opgavenr);
return result;
}
}
}
Use this static methods whenver you want to serialize or deserialize data:
example:
public void test()
{
string outfile = #"C:\Folder\Tester.xml";
SerializeToXml<List<Opgaver>>(arrAktiveOpgaver, outfile);//serialize data
arrAktiveOpgaver = DeserializeFromXml<List<Opgaver>>(outfile);//deserialize data
}
public static T DeserializeFromXml<T>(string inputFile)
{
XmlSerializer s = new XmlSerializer(typeof(T));
T deserializedObject = default(T);
using (TextReader textReader = new StreamReader(inputFile))
{
deserializedObject = (T)s.Deserialize(textReader);
textReader.Close();
}
return deserializedObject;
}
public static void SerializeToXml<T>(T objToSerialize, string outputFile)
{
XmlSerializer s = new XmlSerializer(objToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(outputFile))
{
s.Serialize(textWriter, objToSerialize);
textWriter.Close();
}
}
Serialize array of Opgave instead of serializing them in loop.
XmlSerializer xs = new XmlSerializer(arrAktiveOpgaver.GetType());
xs.Serialize(sw, arrAktiveOpgaver);
And then deserialize as array of Opgave.

Categories