XML serialization C#, not processing certain fields - c#

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.

Related

Protobuf-net Serializing Parent Class inherited object property marked as [ProtoIgnore()] throwing "No serializer defined for type: System.Object"

All the objects in our system inherit a base class which has got a property of type object.
I have tried adding protoignore attribute to all the properties of the base class as well but that doesn't seem to work as well.
class Program
{
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle();
vehicle.BodyStyleDescription = "4x4";
vehicle.BodyStyleText = "Prestige Medium";
dynamic protobufModel = TypeModel.Create();
AddTypeToModel<Vehicle>(protobufModel);
using (MemoryStream compressed = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(compressed, CompressionMode.Compress, true))
{
protobufModel.Serialize(gzip, vehicle);
}
string str = Convert.ToBase64String(compressed.GetBuffer(), 0, Convert.ToInt32(compressed.Length));
}
}
public static MetaType AddTypeToModel<T>(RuntimeTypeModel typeModel)
{
var properties = typeof(T).GetProperties().Select(p => p.Name).OrderBy(name => name);
return typeModel.Add(typeof(T), true).Add(properties.ToArray());
}
}
Following is the hierarchy of the object
public interface IObjectBaseClass
{
[ProtoIgnore()]
object Parent { get; set; }
[ProtoIgnore()]
bool IsSaved { get; set; }
[ProtoIgnore()]
string XmlAtLoad { get; set; }
}
public class ObjectBaseClass : IObjectBaseClass
{
public ObjectBaseClass()
{
}
[ProtoIgnore()]
internal object _Parent;
[ProtoIgnore()]
internal bool _IsSaved;
[ProtoIgnore()]
internal string _XmlAtLoad;
[ProtoIgnore()]
public bool IsSaved
{
get { return _IsSaved; }
set { _IsSaved = value; }
}
[ProtoIgnore()]
public object Parent
{
get { return _Parent; }
set { _Parent = value; }
}
[ProtoIgnore()]
public string XmlAtLoad
{
get { return _XmlAtLoad; }
set { _XmlAtLoad = value; }
}
}
public class Vehicle : ObjectBaseClass
{
private string _BodyStyleText;
private string _BodyStyleDescription;
public string BodyStyleDescription
{
get { return _BodyStyleDescription; }
set { _BodyStyleDescription = value; }
}
public string BodyStyleText
{
get { return _BodyStyleText; }
set { _BodyStyleText = value; }
}
}
Your problem is that when you do typeModel.Add(typeof(T), true).Add(properties.ToArray()) you are adding all properties of T to the runtime type model, including those marked with ProtoIgnore. You can see this by calling the debugging method protobufModel.GetSchema(typeof(Vehicle)) which returns:
message Object {
}
message Vehicle {
optional string BodyStyleDescription = 1;
optional string BodyStyleText = 2;
optional bool IsSaved = 3;
optional Object Parent = 4;
optional string XmlAtLoad = 5;
}
To avoid adding properties marked with [ProtoIgnore], you could do:
public static MetaType AddTypeToModel<T>(RuntimeTypeModel typeModel)
{
var properties = typeof(T)
.GetProperties()
.Where(p => !p.GetCustomAttributes<ProtoIgnoreAttribute>().Any())
.Select(p => p.Name)
.OrderBy(name => name);
return typeModel.Add(typeof(T), true).Add(properties.ToArray());
}
Alternatively, since you are manually annotating some of your models with protobuf attributes anyway, you could mark the derived types with [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)], e.g.:
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Vehicle : ObjectBaseClass
{
private string _BodyStyleText;
private string _BodyStyleDescription;
public string BodyStyleDescription
{
get { return _BodyStyleDescription; }
set { _BodyStyleDescription = value; }
}
public string BodyStyleText
{
get { return _BodyStyleText; }
set { _BodyStyleText = value; }
}
}
Using either method, the schema for Vehicle becomes:
message Vehicle {
optional string BodyStyleDescription = 1;
optional string BodyStyleText = 2;
}
This is what you require.

Custom web.config section not saving

I have implemented custom section in web.config and want to save data there, in runtime debug when you check it contains all values that you put there and save without any exception. But web.config file didn't get updated at all.
I have following custom section in web.config
public class PrintersSection : ConfigurationSection
{
[ConfigurationProperty("PrintForm", Options = ConfigurationPropertyOptions.IsRequired)]
public PrintFormElement PrintForm
{
get
{
return (PrintFormElement)this["PrintForm"];
}
set { this["PrintForm"] = value; }
}
[ConfigurationProperty("Printers", Options = ConfigurationPropertyOptions.IsRequired)]
public PrintersCollection Printers
{
get
{
return (PrintersCollection)this["Printers"];
}
set { this["Printers"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
public class PrintFormElement : ConfigurationElement
{
[ConfigurationProperty("xmlPath")]
public string XmlPath
{
get
{
return (string)base["xmlPath"];
}
set { base["xmlPath"] = value; }
}
[ConfigurationProperty("formName")]
public string FormName
{
get
{
return (string)base["formName"];
}
set { base["formName"] = value; }
}
[ConfigurationProperty("sdateFormat")]
public string SDateFormat
{
get
{
return (string)base["sdateFormat"];
}
set { base["sdateFormat"] = value; }
}
[ConfigurationProperty("createOnTechpadMarkAsComplete")]
public bool CreateOnTechpadMarkAsComplete
{
get
{
return (bool)base["createOnTechpadMarkAsComplete"];
}
set { base["createOnTechpadMarkAsComplete"] = value; }
}
[ConfigurationProperty("createOnSurveySubmit")]
public bool CreateOnSurveySubmit
{
get
{
return (bool)base["createOnSurveySubmit"];
}
set { base["createOnSurveySubmit"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
[ConfigurationCollection(typeof(PrinterElement), AddItemName = "printer", CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public class PrintersCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new PrinterElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return ((PrinterElement)element).Location;
}
[ConfigurationProperty("default", IsRequired = false)]
public string Default
{
get
{
return (string)base["default"];
}
set { base["default"] = value; }
}
public new PrinterElement this[string location]
{
get { return base.BaseGet(location) as PrinterElement; }
}
public void Add(PrinterElement element)
{
base.BaseAdd(element);
}
public void Clear()
{
base.BaseClear();
}
public override bool IsReadOnly()
{
return false;
}
}
public class PrinterElement : ConfigurationElement
{
[ConfigurationProperty("location", IsRequired = true, IsKey = true)]
public string Location
{
get
{
return (string)base["location"];
}
set { base["location"] = value; }
}
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)base["name"];
}
set { base["name"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
Here how it looks in web.config:
<printers>
<PrintForm xmlPath="H:\Temp\print3.txt" formName="test-form"
sdateFormat="MM-dd-yyyy" createOnTechpadMarkAsComplete="true"
createOnSurveySubmit="true" />
<Printers default="PrinterA">
<clear />
<printer location="1" name="PrinterA" />
<printer location="2" name="PrinterB" />
</Printers>
</printers>
This is how I editing it:
webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var printXmlConfig = (PrintersSection)ConfigurationManager.GetSection("printers");
printXmlConfig.PrintForm.XmlPath = model.PrintXMLPath;
printXmlConfig.PrintForm.FormName = model.PrintXMLFormName;
printXmlConfig.Printers.Default = model.PrintXMLPrinterName;
printXmlConfig.PrintForm.SDateFormat = model.PrintXMLSDateFormat;
printXmlConfig.PrintForm.CreateOnTechpadMarkAsComplete = model.PrintXMLCreateOnTechpadMarkAsComplete;
printXmlConfig.PrintForm.CreateOnSurveySubmit = model.PrintXMLCreateOnSurveySubmit;
printXmlConfig.Printers.Clear();
model.PrinterPerLocation.ForEach(p => printXmlConfig.Printers.Add(new PrinterElement { Location = p.Key, Name = p.Value}));
webConfig.Save();
But nothing updates in web.config, what I am doing wrong here?
Try
printXmlConfig.SectionInformation.ForceSave = true;
or
webConfig.SectionInformation.ForceSave = true;
before
webConfig.Save(ConfigurationSaveMode.Full);

Custom Collection/List To Store Custom Objects

I have a customer object class:
public class customerObject
{
private string _address1;
private string _address2;
private string _address3;
private string _category;
private string _country;
private string _county;
private string _custcode;
private string _fullname;
private string _int_rep_hou;
private string _int_rep_key;
private double _lat;
private double _lng;
private string _postcode;
private string _rep_code;
private string _telephone;
public customerObject()
{
}
public string Address1
{
get { return _address1; }
set { _address1 = value; }
}
public string Address2
{
get
{
return _address2;
}
set { _address2 = value; }
}
public string Address3 { get { return _address3; } set { _address3 = value; } }
public string Category
{
get { return _category; }
set { _category = value; }
}
public string Country { get { return _country; } set { _country = value; } }
public string County { get { return _county; } set { _county = value; } }
public string Custcode
{
get { return _custcode; }
set { _custcode = value; }
}
public string Fullname
{
get { return _fullname; }
set { _fullname = value; }
}
public string Int_rep_hou
{
get { return _int_rep_hou; }
set { _int_rep_hou = value; }
}
public string Int_rep_key
{
get { return _int_rep_key; }
set { _int_rep_key = value; }
}
public double Lat { get { return _lat; } set { _lat = value; } }
public double Lng { get { return _lng; } set { _lng = value; } }
public string Postcode { get { return _postcode; } set { _postcode = value; } }
public string Rep_code
{
get { return _rep_code; }
set { Rep_code = value; }
}
public string Telephone { get { return _telephone; } set { _telephone = value; }
}
}
I have a CustomCollections class
public class CustomerCollection
{
public List<customerObject> Customers { get; set; }
}
My method that loops through dt rows and converts to a customer object
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//Create Collection Object
Valueobjects.CustomerCollection Collection = new Valueobjects.CustomerCollection();
foreach (DataRow row in temptablename.Rows)
{
//Create Customer Object
Valueobjects.customerObject Customer = new Valueobjects.customerObject();
//set values of customer object
Customer.Rep_code = "";
Customer.Int_rep_key = "";
Customer.Int_rep_hou = "";
Customer.Fullname = row["Fullname"].ToString().Trim();
Customer.Custcode = row["Custcode"].ToString().Trim();
Customer.Category = row["Category"].ToString().Trim();
Customer.Address1 = row["Address1"].ToString().Trim();
Customer.Address2 = row["Address2"].ToString().Trim();
Customer.Address3 = row["Address3"].ToString().Trim();
Customer.Postcode = row["Postcode"].ToString().Trim();
Customer.Country = row["Country"].ToString().Trim();
Customer.Telephone = row["Telephone"].ToString().Trim();
Customer.Lat = Convert.ToDouble(row["Lat"]);
Customer.Lng = Convert.ToDouble(row["Lng"]);
Customer.County = row["County"].ToString().Trim();
//add to the collection (list)
Collection.Customers.Add(Customer);
}
temptablename = null;
return Collection;
}
However when I create a new Customer object and a new CustomerCollection object I am getting an error when adding the customer to the collection list.
Error:
Error 32 Cannot implicitly convert type
'Classes.Valueobjects.CustomerCollection' to
'System.Collections.Generic.List'
Your method is returning a List<CustomerCollection>:
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//...
}
But the code is trying to return a CustomerCollection:
return Collection;
Just as the error says, these two types are different.
If a CustomerCollection is already a collection of customers, then semantically what is a List<Valueobjects.CustomerCollection>? A collection of collections? It seems like you're over-pluralizing your objects :)
There are two approaches here. Either return a CustomerCollection from the method:
public CustomerCollection dolist(DataTable temptablename)
{
//...
}
Or use a List<Customer> if you want to use generic lists as your collection containers:
public List<Customer> dolist(DataTable temptablename)
{
//...
var Collection = new List<Customer>();
//...
Collection.Add(Customer);
//...
return Collection;
}
Side note: You may want to stick to C# conventions for variable naming. As you can see from the code highlighting here on Stack Overflow, your variable names can easily be mistaken for classes/types, which can cause confusion when supporting the code.
Return a CustomerCollection instead of a List<Valueobjects.CustomerCollection>:
public Valueobjects.CustomerCollection Dolist(DataTable temptablename)
{
// ...
Your object has a list, it is not a list.
MSDN: Inheritance

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;
}

C# - Marshall by value problem!

Here is the thing, I have a problem creating a new object using the remote mechanism "marshal by value".
Here is my class:
[Serializable]
internal class Empleado_MBV
{
public Empleado_MBV()
{
Id = 123456789;
Nombres = "NotEntry";
Apellidos = "NotEntry";
FechaNacimiento = DateTime.MinValue;
Direccion = "NotEntry";
Metapreferencias = "NotEntry";
}
private List<Multas> _multas;
internal List<Multas> Multas
{
get { return _multas; }
set { _multas = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _nombres;
public string Nombres
{
get { return _nombres; }
set { _nombres = value; }
}
private string _apellidos;
public string Apellidos
{
get { return _apellidos; }
set { _apellidos = value; }
}
private DateTime _FecNac;
public DateTime FechaNacimiento
{
get { return _FecNac; }
set { _FecNac = value; }
}
private string _direccion;
public string Direccion
{
get { return _direccion; }
set { _direccion = value; }
}
private string _metapreferencias;
public string Metapreferencias
{
get { return _metapreferencias; }
set { _metapreferencias = value; }
}
public string _AppDomainHost
{
get { return AppDomain.CurrentDomain.FriendlyName.ToString(); }
}
}
But when I try to create an object in another "appdomain", the property "_AppDomainHost" of "Empleado" does not show the "appdomain" I had created, but show the "appdomain" by default. Some ideas?
AppDomain ad1 = AppDomain.CreateDomain("NewAppDomain");
//Crear new object in my new AD.
Empleado_MBV mbv_emp = (Empleado_MBV)ad1.CreateInstanceFromAndUnwrap("DEMO_MBV_MBR.exe", "DEMO_MBV_MBR.Empleado_MBV");
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName.ToString());
Console.WriteLine("MBV : {0}",mbv_emp._AppDomainHost.ToString());
Console.ReadLine();
Result:
DEMO_MBV_MBR.vshost.exe
MBV : DEMO_MBV_MBR.vshost.exe
The result that I want:
DEMO_MBV_MBR.vshost.exe
MBV : NewAppDomain
You need to store AppDomain in Empleado_MBV's constructor.
What you are doing right now is displaying current AppDomain using its Current static property. It will return the AppDomain where current code is being executed.
Example:
private string _appDomainHost;
public string _AppDomainHost
{
get { return _appDomainHost; }
}
and in constructor:
_appDomainHost = AppDomain.CurrentDomain.FriendlyName.ToString();

Categories