XMLAttribute is not working - c#

I am Deserializing my xml into C# class.
<?xml version="1.0" encoding="UTF-8"?>
<Applications>
<Application Name = "name1" MakerCheckerType="Operational" SanctionCheckNeeded="N" PreExistCheckNeeded="N" >
<InstrumentTypes>
<InstrumentType Version="1.0" PrimaryKeyExcel="Security Name" Name="Equity">
</InstrumentType>
<InstrumentType Name="Bond" Version="1.0" PrimaryKeyExcel="Security Name">
</InstrumentType>
</InstrumentTypes>
<ProcessSteps>
<ProcessStep VBAFunction="xyz" ExcelName="xyz" Name="Upload" />
<ProcessStep Name ="Approve_Reject" VBAFunction="xyz" ExcelName="xyz"/>
</ProcessSteps>
</Application>
<Application Name = "name2" MakerCheckerType="Real" SanctionCheckNeeded="Y" PreExistCheckNeeded="Y">
<InstrumentTypes>
<InstrumentType Version="1.0" PrimaryKeyExcel="Security Name" Name="Equity">
</InstrumentType>
<InstrumentType Name="Bond" Version="1.0" PrimaryKeyExcel="Security Name">
</InstrumentType>
</InstrumentTypes>
<ProcessSteps>
<ProcessStep VBAFunction="xyz" ExcelName="xyz" Name="Upload" />
<ProcessStep Name ="Approve_Reject" VBAFunction="xyz" ExcelName="xyz"/>
</ProcessSteps>
</Application>
</Applications>
classes are:
[XmlType("ProcessStep")]
public class IMAProcessStep
{
private string name;
private string vbaFunction;
private string excelName;
[XmlAttribute("Name")]
public string Name
{
get { return name; }
set { name = value; }
}
[XmlAttribute("VBAFunction")]
public string VBAFunction
{
get { return vbaFunction; }
set { vbaFunction = value; }
}
[XmlAttribute("ExcelName")]
public string ExcelName
{
get { return excelName; }
set { excelName = value; }
}
}
[XmlType("InstrumentType")]
public class IMAInstrumentType
{
[XmlAttribute("Name")]
public string Name
{
get;
set;
}
[XmlAttribute("Version")]
public string Version
{
get;
set;
}
[XmlAttribute("PrimaryKeyExcel")]
public string PrimaryKeyExcel
{
get;
set;
}
}
[XmlType("Application")]
public class IMAApplication
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("MakerCheckerType")]
public string MakerCheckerType { get; set; }
public bool IsMakerCheckerType
{
get
{
if (MakerCheckerType == "Real")
return true;
return false;
}
set
{
if (value)
MakerCheckerType = "Real";
else
MakerCheckerType = "Operational";
}
}
[XmlAttribute("SanctionCheckNeeded")]
public string SanctionCheckNeeded { get; set; }
[XmlAttribute("PreExistCheckNeeded")]
public string PreExistCheckNeeded { get; set; }
public bool IsSanctionCheckNeeded
{
get
{
return SanctionCheckNeeded == "Y";
}
set
{
SanctionCheckNeeded = value ? "Y" : "N";
}
}
public bool IsPreExistCheckNeeded
{
get
{
if (PreExistCheckNeeded == "Y")
return true;
return false;
}
set
{
if (value)
PreExistCheckNeeded = "Y";
else
PreExistCheckNeeded = "N";
}
}
[XmlArray("ProcessSteps")]
[XmlArrayItem(ElementName = "ProcessStep")]
public List<IMAInstrumentType> SupportedInstrumentTypes { get; set; }
[XmlArray("InstrumentTypes")]
[XmlArrayItem(ElementName = "InstrumentType")]
public List<IMAProcessStep> ProcessSteps { get; set; }
}
Here How I am De serializing it...
List<IMAApplication> appConfig = null;
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFilePath);
var xRoot = new XmlRootAttribute();
xRoot.ElementName = "Applications";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(List<IMAApplication>), xRoot);
using (var stream = File.OpenRead(path))
appConfig = (List<IMAApplication>)serializer.Deserialize(stream);
return appConfig;
IMAApplication Deserialize successfully but processSteps and InstrumentTypes get only their Name attribute values. Rest of attributes are null.
Can anyone tell me what wrong here.

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
IMAApplications applications = Deserialize(FILENAME);
}
static IMAApplications Deserialize(string configFilePath)
{
IMAApplications appConfig = null;
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFilePath);
var xRoot = new XmlRootAttribute();
xRoot.ElementName = "Applications";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(IMAApplications), xRoot);
using (var stream = File.OpenRead(path))
appConfig = (IMAApplications)serializer.Deserialize(stream);
return appConfig;
}
}
[XmlRoot("ProcessStep")]
public class IMAProcessStep
{
private string name;
private string vbaFunction;
private string excelName;
[XmlAttribute("Name")]
public string Name
{
get { return name; }
set { name = value; }
}
[XmlAttribute("VBAFunction")]
public string VBAFunction
{
get { return vbaFunction; }
set { vbaFunction = value; }
}
[XmlAttribute("ExcelName")]
public string ExcelName
{
get { return excelName; }
set { excelName = value; }
}
}
[XmlRoot("InstrumentType")]
public class IMAInstrumentType
{
[XmlAttribute("Name")]
public string Name
{
get;
set;
}
[XmlAttribute("Version")]
public string Version
{
get;
set;
}
[XmlAttribute("PrimaryKeyExcel")]
public string PrimaryKeyExcel
{
get;
set;
}
}
[XmlRoot("Applications")]
public class IMAApplications
{
[XmlElement("Application")]
public List<IMAApplication> applications { get; set; }
}
[XmlRoot("Application")]
public class IMAApplication
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("MakerCheckerType")]
public string MakerCheckerType { get; set; }
public bool IsMakerCheckerType
{
get
{
if (MakerCheckerType == "Real")
return true;
return false;
}
set
{
if (value)
MakerCheckerType = "Real";
else
MakerCheckerType = "Operational";
}
}
[XmlAttribute("SanctionCheckNeeded")]
public string SanctionCheckNeeded { get; set; }
[XmlAttribute("PreExistCheckNeeded")]
public string PreExistCheckNeeded { get; set; }
public bool IsSanctionCheckNeeded
{
get
{
return SanctionCheckNeeded == "Y";
}
set
{
SanctionCheckNeeded = value ? "Y" : "N";
}
}
public bool IsPreExistCheckNeeded
{
get
{
if (PreExistCheckNeeded == "Y")
return true;
return false;
}
set
{
if (value)
PreExistCheckNeeded = "Y";
else
PreExistCheckNeeded = "N";
}
}
[XmlArray("InstrumentTypes")]
[XmlArrayItem(ElementName = "InstrumentType")]
public List<IMAInstrumentType> SupportedInstrumentTypes { get; set; }
[XmlArray("ProcessSteps")]
[XmlArrayItem(ElementName = "ProcessStep")]
public List<IMAProcessStep> ProcessSteps { get; set; }
}
}

Related

Fixing WCF Deserialization Error : Invalid Message Body

I'm setting up a new WCF service on a new server I got, but when I try to access the service through a xamarin application I get the following error
"Error in deserializing body of request message for operation 'GetString'. OperationFormatter encountered an invalid Message body. Expected to find node type 'Element' with name 'GetString' and namespace 'http://tempuri.org/'. Found node type 'Element' with name 'GetStringAsync' and namespace 'http://tempuri.org/'"
I have used the method of creating a proxy (with a class library and connected service) for creating the client to be used in my xamarin application. I have used this exact method before without any problems, but now I can't seem to get this to work.
I have tried googling this, but the only similar errors I could find were where the methods name were the same, but the namespace as mentioned above was different which does not apply in my specific error. I have recreated the project, and redeployed a few times without any success.
IService
[ServiceContract]
public interface IPM_Service
{
[OperationContract]
List<dbUsersModel> GetUsers();
[OperationContract]
int InsertUser(dbUsersModel user, int userid);
[OperationContract]
string GetString(string test);
}
IService Implementation
public class PM_Service : IPM_Service
{
xamPropertyManagementEntities Entity = new xamPropertyManagementEntities();
public List<dbUsersModel> GetUsers()
{
var data = Entity.SP_SELECT_USERS().ToList();
List<dbUsersModel> users = new List<dbUsersModel>();
foreach (var item in data)
{
users.Add(new dbUsersModel() { dbUserID = item.USR_ID, dbUserName = item.USR_NAME, dbUserSurname = item.USR_SURNAME, dbUserUsername = item.USR_USERNAME, dbUserPassword = item.USR_PASSWORD, dbUserIDNo = item.USR_IDNO, dbUserContactNo = item.USR_CONTACTNO, dbUserEmail = item.USR_EMAIL, dbUserAddress1 = item.USR_ADDRESS1, dbUserAddress2 = item.USR_ADDRESS2, dbUserAddress3 = item.USR_ADDRESS3, dbUserAddress4 = item.USR_ADDRESS4 });
}
return users;
}
public int InsertUser(dbUsersModel user, int userid)
{
var insert = Entity.SP_INSERT_USER(user.dbUserUsername, user.dbUserPassword, user.dbUserName, user.dbUserSurname, user.dbUserIDNo, user.dbUserContactNo, user.dbUserEmail, user.dbUserAddress1, user.dbUserAddress2, user.dbUserAddress3, user.dbUserAddress4, userid);
decimal? returnID = insert.SingleOrDefault().Value;
int id = (int)returnID.DefaultIfEmpty(0);
return id;
}
public string GetString(string test)
{
return test;
}
}
public class dbUsersModel
{
public int dbUserID { get; set; }
public string dbUserUsername { get; set; }
public string dbUserPassword { get; set; }
public string dbUserName { get; set; }
public string dbUserSurname { get; set; }
public string dbUserIDNo { get; set; }
public string dbUserContactNo { get; set; }
public string dbUserEmail { get; set; }
public string dbUserAddress1 { get; set; }
public string dbUserAddress2 { get; set; }
public string dbUserAddress3 { get; set; }
public string dbUserAddress4 { get; set; }
}
Proxy Code
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// //
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PMProxy
{
using System.Runtime.Serialization;
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.0.1")]
[System.Runtime.Serialization.DataContractAttribute(Name="dbUsersModel", Namespace="http://schemas.datacontract.org/2004/07/PM_Service")]
public partial class dbUsersModel : object
{
private string dbUserAddress1Field;
private string dbUserAddress2Field;
private string dbUserAddress3Field;
private string dbUserAddress4Field;
private string dbUserContactNoField;
private string dbUserEmailField;
private int dbUserIDField;
private string dbUserIDNoField;
private string dbUserNameField;
private string dbUserPasswordField;
private string dbUserSurnameField;
private string dbUserUsernameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserAddress1
{
get
{
return this.dbUserAddress1Field;
}
set
{
this.dbUserAddress1Field = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserAddress2
{
get
{
return this.dbUserAddress2Field;
}
set
{
this.dbUserAddress2Field = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserAddress3
{
get
{
return this.dbUserAddress3Field;
}
set
{
this.dbUserAddress3Field = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserAddress4
{
get
{
return this.dbUserAddress4Field;
}
set
{
this.dbUserAddress4Field = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserContactNo
{
get
{
return this.dbUserContactNoField;
}
set
{
this.dbUserContactNoField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserEmail
{
get
{
return this.dbUserEmailField;
}
set
{
this.dbUserEmailField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public int dbUserID
{
get
{
return this.dbUserIDField;
}
set
{
this.dbUserIDField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserIDNo
{
get
{
return this.dbUserIDNoField;
}
set
{
this.dbUserIDNoField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserName
{
get
{
return this.dbUserNameField;
}
set
{
this.dbUserNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserPassword
{
get
{
return this.dbUserPasswordField;
}
set
{
this.dbUserPasswordField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserSurname
{
get
{
return this.dbUserSurnameField;
}
set
{
this.dbUserSurnameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string dbUserUsername
{
get
{
return this.dbUserUsernameField;
}
set
{
this.dbUserUsernameField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.0.1")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="PMProxy.IPM_Service")]
public interface IPM_Service
{
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IPM_Service/GetUsers", ReplyAction="http://tempuri.org/IPM_Service/GetUsersResponse")]
System.Threading.Tasks.Task<PMProxy.dbUsersModel[]> GetUsersAsync();
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IPM_Service/InsertUser", ReplyAction="http://tempuri.org/IPM_Service/InsertUserResponse")]
System.Threading.Tasks.Task<int> InsertUserAsync(PMProxy.dbUsersModel user, int userid);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IPM_Service/GetString", ReplyAction="http://tempuri.org/IPM_Service/GetStringResponse")]
System.Threading.Tasks.Task<string> GetStringAsync(string test);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.0.1")]
public interface IPM_ServiceChannel : PMProxy.IPM_Service, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.0.1")]
public partial class PM_ServiceClient : System.ServiceModel.ClientBase<PMProxy.IPM_Service>, PMProxy.IPM_Service
{
/// <summary>
/// Implement this partial method to configure the service endpoint.
/// </summary>
/// <param name="serviceEndpoint">The endpoint to configure</param>
/// <param name="clientCredentials">The client credentials</param>
static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials);
public PM_ServiceClient() :
base(PM_ServiceClient.GetDefaultBinding(), PM_ServiceClient.GetDefaultEndpointAddress())
{
this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_IPM_Service.ToString();
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
public PM_ServiceClient(EndpointConfiguration endpointConfiguration) :
base(PM_ServiceClient.GetBindingForEndpoint(endpointConfiguration), PM_ServiceClient.GetEndpointAddress(endpointConfiguration))
{
this.Endpoint.Name = endpointConfiguration.ToString();
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
public PM_ServiceClient(EndpointConfiguration endpointConfiguration, string remoteAddress) :
base(PM_ServiceClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress))
{
this.Endpoint.Name = endpointConfiguration.ToString();
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
public PM_ServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) :
base(PM_ServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress)
{
this.Endpoint.Name = endpointConfiguration.ToString();
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
public PM_ServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
{
}
public System.Threading.Tasks.Task<PMProxy.dbUsersModel[]> GetUsersAsync()
{
return base.Channel.GetUsersAsync();
}
public System.Threading.Tasks.Task<int> InsertUserAsync(PMProxy.dbUsersModel user, int userid)
{
return base.Channel.InsertUserAsync(user, userid);
}
public System.Threading.Tasks.Task<string> GetStringAsync(string test)
{
return base.Channel.GetStringAsync(test);
}
public virtual System.Threading.Tasks.Task OpenAsync()
{
return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndOpen));
}
public virtual System.Threading.Tasks.Task CloseAsync()
{
return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndClose));
}
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IPM_Service))
{
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
return result;
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IPM_Service))
{
return new System.ServiceModel.EndpointAddress("http://localhost:8733/Design_Time_Addresses/PM_Service/PM_Service/");
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
private static System.ServiceModel.Channels.Binding GetDefaultBinding()
{
return PM_ServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_IPM_Service);
}
private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress()
{
return PM_ServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_IPM_Service);
}
public enum EndpointConfiguration
{
BasicHttpBinding_IPM_Service,
}
}
}
The only thing that I can possibly think of, is that my IIS may not be set up correctly, since this is the first time I have had to set up IIS by myself. The server is a VPS running Windows Server 2016. I may very well be wrong about the cause, and it may be something I have missed in the config of the service itself, or the proxy client I created.
Any ideas that might be able to help?

Best way to write application data to a file in WPF

I am using the Caliburn.Micro MVVM pattern.
I am writing an application that has 2 DataGrids, one holds a BindableCollection of RepairOrder, the other a BindableCollection WriteOff.
BindableCollection_WriteOff is property of BindableCollection_RepairOrder. (See the below code).
I need to find a way to write all the RepairOrder including the WriteOff associated with each RO. Besides RepairOrder class holding the WriteOff class, the WriteOff class does not have a way to tie the WriteOff to a RepairOrder.
Repair Order Class:
public class RepairOrder
{
public string Schedule { get; set; }
public string ControlNumber { get; set; }
public int Age { get; set; }
public double Value { get; set; }
public string Note { get; set; }
public double OrgValue { get; set; }
private List<WriteOff> _myWriteOffs;
public List<WriteOff> GetMyWriteOffs()
{
return _myWriteOffs;
}
public void AddMyWriteOff(WriteOff value)
{ _myWriteOffs.Add(value); }
public void DeleteMyWriteOff(WriteOff value)
{ _myWriteOffs.Remove(value); }
public RepairOrder(string CN, string SC, double VL)
{
ControlNumber = CN;
Schedule = SC;
Value = Math.Round(VL, 2);
Note = null;
_myWriteOffs = new List<WriteOff>();
}
public RepairOrder()
{
_myWriteOffs = new List<WriteOff>();
}
public static RepairOrder FromCSV(string CSVLine, string Sched)
{
string[] values = CSVLine.Split(',');
RepairOrder rep = new RepairOrder();
rep.ControlNumber = values[2];
rep.Value = Math.Round(double.Parse(values[5]),2);
rep.Age = int.Parse(values[4]);
rep.Schedule = Sched;
return rep;
}
}
Write Off Class:
public class WriteOff
{
private string _store;
public string Account { get; set; }
public string Description { get; set; }
public double WriteOffAmount { get; set; }
public string Schedule { get; set; }
public string Store
{
get {
if (String.IsNullOrEmpty(_store)) return "";
string temp = _store.Substring(0, 3);
return temp;
}
set { _store = value; }
}
public string Note { get; set; }
public WriteOff(string Acct, string Desc, double Amount, string _store)
{
Account = Acct;
Description = Desc;
WriteOffAmount = Amount;
Store = _store;
}
public string GetWOAccount() {
string SchedAccountNumber = "";
//{ "Navistar", "Cummins", "Misc", "Kenworth", "Mack/Volvo" }
switch (Account)
{
case "Navistar":
SchedAccountNumber = "222000";
break;
case "Cummins":
SchedAccountNumber = "223000";
break;
case "Misc":
SchedAccountNumber = "224500";
break;
default:
SchedAccountNumber = "";
break;
}
return SchedAccountNumber;
}
}

How to fix 'System.StackOverflowException?

I have a project programmed in C# NET 3.5 in WPF which start very well in debug. However for example, in my TemplateColor.cs class I have this:
using System;
using System.Windows.Media;
namespace EWIN_THEME_MAKER.ThemeMaker
{
public class TemplateColor
{
private int _id;
private string _name;
private string _toneName;
public int ID
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
public int AllVerticalPos
{
get;
set;
}
public int AllHorizontalPos
{
get;
set;
}
public int HuePageNum
{
get;
set;
}
public int HuePos
{
get;
set;
}
public int TonePaneNum
{
get;
set;
}
public int TonePos
{
get;
set;
}
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
string[] array = this._name.Split(new char[]
{
'_'
});
this._toneName = array[0];
if (array.Length > 1)
{
this.HuePageNum = int.Parse(array[1]);
}
}
}
public string ToneName
{
get
{
return this._toneName;
}
set
{
this._toneName = value;
}
}
public Color DarkColor
{
get;
set;
}
public Color MainColor
{
get;
set;
}
public Color LightColor
{
get;
set;
}
public Color ShadowColor
{
get;
set;
}
public byte ShadowA
{
get;
set;
}
public Color GrowColor
{
get;
set;
}
public Color TextShadowColor
{
get;
set;
}
public Color TextMainColor
{
get;
set;
}
public Color TextSelectColor
{
get;
set;
}
public double TextShadowPosition
{
get;
set;
}
public Brush DarkColorBrush
{
get
{
return new SolidColorBrush(this.DarkColor);
}
}
public Brush MainColorBrush
{
get
{
return new SolidColorBrush(this.MainColor);
}
}
public Brush LightColorBrush
{
get
{
return new SolidColorBrush(this.LightColor);
}
}
public Brush ShadowColorBrush
{
get
{
return new SolidColorBrush(this.ShadowColor);
}
}
public Brush GrowColorBrush
{
get
{
return new SolidColorBrush(this.GrowColor);
}
}
public Brush TextShadowColorBrush
{
get
{
return new SolidColorBrush(this.TextShadowColor);
}
}
public Brush TextMainColorBrush
{
get
{
return new SolidColorBrush(this.TextMainColor);
}
}
public Brush TextSelectColorBrush
{
get
{
return new SolidColorBrush(this.TextSelectColor);
}
}
public TemplateColor()
{
this.ID = -1;
this.AllVerticalPos = -1;
this.AllHorizontalPos = -1;
this.HuePageNum = -1;
this.HuePos = -1;
this.TonePaneNum = -1;
this.TonePos = -1;
this.Name = "---";
this.DarkColor = default(Color);
this.MainColor = default(Color);
this.LightColor = default(Color);
this.ShadowColor = default(Color);
this.ShadowA = 0;
this.GrowColor = default(Color);
this.TextShadowColor = default(Color);
this.TextMainColor = default(Color);
this.TextSelectColor = default(Color);
this.TextShadowPosition = 0.0;
}
}
}
In this code, there are multiple errors of this kind:
An exception of type 'System.StackOverflowException
For example I take this part of the code there:
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
string[] array = this._name.Split(new char[]
{
'_'
});
this._toneName = array[0];
if (array.Length > 1)
{
this.HuePageNum = int.Parse(array[1]);
}
}
}
So, in the next lines of this code there is an infinite call? I do not know how to correct this error.
string[] array = this._name.Split(new char[]
And...
this.HuePageNum = int.Parse(array[1]);
How do we predict and correct these errors?
My problem is now solved.
Solution: Increasing the size of the stack
Thanks to all!

Serialization woes

I have an issue with serialization. I understand that methods can not be serialized for good reason, so I created a factory class to convert my existing class into a more manageable class.
This is the original class:
using Assets.Components;
using Assets.Data;
using IO.Components;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Assets
{
[Serializable]
public class Asset
{
#region Fields
Metadata _metadata;
string _fileName;
string _companyId;
#endregion
#region Properties
[Required]
public string DisplayName { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public AssetType Type { get; set; }
public int LanguageId { get; set; }
public int StatusId { get; set; }
public DateTime DateCreated { get; set; }
public long DateCreatedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public int Views { get; set; }
public int Downloads { get; set; }
public string ThumbNail { get; set; }
public string Filename
{
set { _fileName = value; }
}
[Required]
public string CompanyId
{
set { _companyId = value; }
}
public string GetBaseDirectory
{
get { return "/Public/Uploads/" + this._companyId + "/0"; }
}
public double Rating
{
get
{
List<int> Score = new List<int>();
foreach (IRating oRating in this.Ratings())
{
Score.Add(oRating.Score);
}
return (Score.Count > 0) ? Score.Average() : 0;
}
}
public Metadata Metadata
{
get
{
if (_metadata == null)
{
_metadata = new Metadata(this.Id);
if (_metadata.AssetId == 0)
{
try
{
if (GetFilename() != null)
{
string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath(this.GetBaseDirectory), GetFilename());
if (!System.IO.File.Exists(path))
_metadata = new Metadata();
else
{
_metadata = MetadataExtractor.Create(path, this.Id);
_metadata.save();
}
}
else
{
_metadata = new Metadata();
}
}
catch
{
_metadata = new Metadata();
}
}
}
return _metadata;
}
}
public bool IsConverted { get; set; }
public string UserId { get; set; }
public DateTime DateModified { get; set; }
public long DateModifiedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public string Culture { get; set; }
public string Language { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public int CategoryCount { get; set; }
public int AssetCount { get; set; }
public bool IgnoreRights { get; set; }
#endregion
#region Contructors
/// <summary>
/// Default constructor
/// </summary>
public Asset()
{
}
/// <summary>
/// Get's the asset from the database, but set's the status to the profiles Requires Approval state.
/// </summary>
/// <param name="Id">Asset Id</param>
/// <param name="IsViewing">Boolean to update the reports table</param>
/// <param name="IsDownloading">Boolean to update the reports table</param>
public Asset(int Id, string UserId, string CompanyId, bool IsViewing, bool IsDownloading)
{
try
{
Asset oAsset = AssetData.GetAsset(Id, IsViewing, IsDownloading, UserId, CompanyId);
// Assign the values to this class
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.IsConverted = oAsset.IsConverted;
this.StatusId = oAsset.StatusId;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.UserName = oAsset.UserName;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
catch (Exception ex)
{
Stars.BLL.Error.Handling.LogError("Skipstone", "Asset", "Asset", ex.Message, ex.ToString()); // Record our error
}
}
/// <summary>
/// Used for executing some of the public methods
/// </summary>
/// <param name="Id">Id of the asset to retrieve</param>
/// <param name="CompanyId">The CompanyId of the company for the User</param>
public Asset(int Id, string CompanyId)
{
this.Id = Id;
this.CompanyId = CompanyId;
}
#endregion
#region Public methods
public string GetCompanyId()
{
return _companyId;
}
public string GetFilename()
{
return _fileName;
}
public string GetThumbnail()
{
return this.GetBaseDirectory + "/" + this.ThumbNail;
}
public string GetSmallThumbnail()
{
return this.GetBaseDirectory + "/sml_" + this.ThumbNail;
}
public Collection<IRating> Ratings()
{
Collection<IRating> oRatings = new Collection<IRating>();
try
{
oRatings = RatingData.get(this.Id);
}
catch
{
// record our error
}
return oRatings;
}
public Collection<IComment> Comments()
{
Collection<IComment> oComments = new Collection<IComment>();
try
{
oComments = CommentData.getAssetComments(this.Id);
}
catch (Exception ex)
{
// record our error
}
return oComments;
}
public void SaveMetadata()
{
}
public Collection<GenericType> Categories()
{
return MiscellaneousManager.AssetCategories(this.Id, GetCompanyId());
}
public void Save()
{
if (this.Id > 0)
{
AssetData.update(this);
}
else
{
Asset oAsset = AssetData.create(this);
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
}
public void delete()
{
AssetData.delete(this.Id);
AssetManager.RemoveFromCache(this);
}
#endregion
}
}
and this is my factory method:
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
which is part of my audittrailmanager class:
using Assets;
using Core;
using Reports.Objects;
using System;
using System.IO;
using System.Xml.Serialization;
namespace Reports.Components
{
public static class AuditTrailManager
{
#region Public methods
public static Audit AuditTrailFactory(Profile Profile, Object Object, Event Event)
{
Audit Audit = new Audit(SerializeObject(Object))
{
UserId = Profile.UserId,
UserName = Profile.UserName,
CompanyId = Profile.CompanyId,
ObjectName = GetObjectNameFromType(Object.GetType().ToString()),
Event = Event
};
return Audit;
}
#endregion
#region Private methods
private static string GetObjectNameFromType(string Type)
{
switch (Type)
{
case "Assets.Asset": return "Asset";
case "Core.SiteSetting": return "CompanySettings";
}
return "";
}
private static string SerializeObject(Object Object)
{
string ObjectType = Object.GetType().ToString();
switch (ObjectType)
{
case "Assets.Asset": return Serialize(AssetFactory((Asset)Object));
}
return ""; // If we fail
}
private static string Serialize(Object Object)
{
XmlSerializer ser = new XmlSerializer(Object.GetType());
using (StringWriter Xml = new StringWriter())
{
ser.Serialize(Xml, Object);
return (Xml.ToString());
}
}
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
#endregion
}
}
What I am trying to do is create an audit trail which records the object I am working on (in this case an asset) and I am serializing the class and inserting it into the database for use in reporting, etc.
My question is; is this the way to do it. Is there a better way?

what is the best way to dynamicly load classes and invoke them

This is what I came up with, but it feels bloated and well, untidy. And I don't like that I have created an instance of each class just to get the right one.
class FileHasher
{
private readonly List<IHasher> _list;
public FileHasher()
{
_list = new List<IHasher>();
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
if(typeof(IHasher).IsAssignableFrom(type) && type.IsClass)
_list.Add((IHasher) Activator.CreateInstance(type));
}
}
public HashReturn GetHashFromFile(string file, HashFileType hashType)
{
var hashReturn = new HashReturn();
IHasher iHasher = _list.Find(hasher => hasher.HashType == hashType);
hashReturn.Hash = iHasher.FileToHash(file);
return hashReturn;
}
public HashReturn GetHashFromString(string str, HashFileType hashType)
{
var hashReturn = new HashReturn();
IHasher iHasher = _list.Find(hasher => hasher.HashType == hashType);
hashReturn.Hash = iHasher.StringToHash(str);
return hashReturn;
}
}
internal class HashReturn
{
public Exception Error { get; set; }
public string Hash { get; set; }
public bool Success { get; set; }
}
enum HashFileType
{
CRC32,
MD5
}
internal interface IHasher
{
HashFileType HashType { get; }
string FileToHash(string file);
string StringToHash(string str);
}
class MD5Hasher : IHasher
{
public HashFileType HashType { get { return HashFileType.MD5; } }
public string FileToHash(string file)
{
return "";
}
public string StringToHash(string str)
{
return "";
}
}
class CRC32Hasher : IHasher
{
public HashFileType HashType { get { return HashFileType.CRC32; } }
public string FileToHash(string file)
{
return "";
}
public string StringToHash(string str)
{
return "";
}
}
MEF solves this nicely for you.
http://mef.codeplex.com/
It is included in .NET 4.

Categories

Resources