I have application that host WCF service and I want to return this class object:
namespace classes
{
[DataContract]
public class NetworkAdapter
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string ID { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public string IPAddress { get; set; }
[DataMember]
private string gatewayIpAddress;
[DataMember]
public string Speed { get; set; }
[DataMember]
public string NetworkInterfaceType { get; set; }
[DataMember]
public string MacAddress { get; set; }
[DataMember]
private LivePacketDevice livePacketDevice;
[DataMember]
public PacketDevice PacketDevice { get { return livePacketDevice; } }
public NetworkAdapter(LivePacketDevice packetDevice)
{
livePacketDevice = packetDevice;
}
public override string ToString()
{
return Description;
}
public static NetworkAdapter[] getAll()
{
List<NetworkAdapter> list = new List<NetworkAdapter>();
foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
foreach (UnicastIPAddressInformation uniCast in adapter.GetIPProperties().UnicastAddresses)
{
if (!System.Net.IPAddress.IsLoopback(uniCast.Address) && uniCast.Address.AddressFamily != AddressFamily.InterNetworkV6)
{
StringBuilder gatewayIPAddresses = new StringBuilder();
string gatewayIPAddressesDisplay = string.Empty;
foreach (var address in adapter.GetIPProperties().GatewayAddresses)
{
gatewayIPAddresses.Append(address.Address);
gatewayIPAddresses.Append(" ");
}
if (gatewayIPAddresses.Length > 0)
{
gatewayIPAddressesDisplay = gatewayIPAddresses.ToString().TrimEnd(' ');
}
if (!list.Any(l => l.ID == adapter.Id))
{
list.Add(new NetworkAdapter(getDevice(adapter.Id))
{
Name = adapter.Name,
ID = adapter.Id,
Description = adapter.Description,
IPAddress = uniCast.Address.ToString(),
NetworkInterfaceType = adapter.NetworkInterfaceType.ToString(),
Speed = adapter.Speed.ToString("#,##0"),
MacAddress = getMacAddress(adapter.GetPhysicalAddress().ToString()),
gatewayIpAddress = gatewayIPAddressesDisplay
});
}
}
}
//return list.GroupBy(n => n.ID).Select(g => g.FirstOrDefault()).ToArray();
return list.ToArray();
}
private static LivePacketDevice getDevice(string id)
{
return LivePacketDevice.AllLocalMachine.First(x => x.Name.Contains(id));
}
private static string getMacAddress(string oldMAC)
{
int count = 0;
string newMAC = oldMAC;
for (int i = 2; i < oldMAC.Length; i += 2)
{
newMAC = newMAC.Insert(i + count++, ":");
}
return newMAC;
}
public string defaultGateway
{
get
{
if (gatewayIpAddress != "")
{
return gatewayIpAddress;
}
return "n/a";
}
}
private static string getIpFourthSegment(string ipAddress)
{
try
{
string[] arr = ipAddress.Split('.');
return arr[3];
}
catch (Exception)
{
return null;
}
}
}
}
This is my service:
[ServiceContract()]
public interface IService1
{
[OperationContract]
NetworkAdapter[] GetAdapters();
[OperationContract]
string GetDate();
}
[ServiceBehavior(
ConcurrencyMode = ConcurrencyMode.Multiple,
InstanceContextMode = InstanceContextMode.PerSession)]
public class service1 : IService1
{
public NetworkAdapter[] GetAdapters()
{
IEnumerable<NetworkAdapter> adapters = NetworkAdapter.getAll();
return adapters.ToArray();
}
public string GetDate()
{
return DateTime.Now.ToString();
}
}
When I am try to run GetAdapters function got this error:
An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll
Additional information: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9599960'.
When try to run GetDate function it works fine and return simple string.
maybe I need to configure my class in other way ? I have added [DataMember] to each member
LivePacketDevice and PacketDevice need to be [DataContract]s, while it might also work if they are just [Serializable]. Otherwise WCF does not know how to transfer them to the client.
Also it is advisable to only transfer objects that just hold data, not functionality, as that functionality will not be available to the client. The stub created on the client side will only contain data fields, not methods, as code is not transferred/cloned.
Related
My problem How to change The ArrayOfResponse Element in SOAP XML WCF services
using Message class.... see image I want change the element in red box ....
any ideas ???
enter image description here
that my code to get this result !
my interface
[ServiceContract()]
public interface IEvaluationWebService
{
[OperationContract(ReplyAction = "Evaluations")]
Message GetEvaluations(EvaluationRequest evaluationRequest);
}
this method tasks one parameter EvaluationRequest class ,to return Message ( List of Evaluation class )
Message IEvaluationWebService.GetEvaluations(EvaluationRequest evaluationRequest)
{
SqlConnection cnn = new SqlConnection("");
DateTime dtstart = new DateTime();
DateTime.TryParseExact(evaluationRequest.PeriodStart, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out dtstart);
evaluationRequest.PeriodStart = dtstart.ToString("yyyy-MM-dd");
DateTime dtend = new DateTime();
DateTime.TryParseExact(evaluationRequest.PeriodEnd, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out dtend);
evaluationRequest.PeriodEnd = dtend.ToString("yyyy-MM-dd");
SqlCommand cmd = new SqlCommand("GetEmployeeEvaluation", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#PeriodStart", SqlDbType.VarChar, 10).Value = evaluationRequest.PeriodStart;
cmd.Parameters.Add("#PeriodEnd", SqlDbType.VarChar, 10).Value = evaluationRequest.PeriodEnd;
cnn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
List<Evaluation> evaluationList = new List<Evaluation>();
MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
while (sdr.Read())
{
Evaluation evaluation = new Evaluation();
evaluation.EstLaborOfficeId = Convert.ToInt32(sdr["EstLaborOfficeId"].ToString());
evaluation.EstSequenceNumber = Convert.ToInt32(sdr["EstSequenceNumber"].ToString());
evaluation.IdNumber =
evaluationList.Add(evaluation);
}
Evaluation eval = new Evaluation();
cnn.Close();
return Message.CreateMessage(ver, "Evaluations", evaluationList);
}
The request class to passing the dates for method and gets data ....
[MessageContract(IsWrapped = true, WrapperName = "GetEvaluation", WrapperNamespace = "http://tempuri.org/")]
[XmlType(Namespace = "http://tempuri.org/")]
public class EvaluationRequest
{
[MessageBodyMember(Order = 1)]
public string PeriodStart { get; set; }
[MessageBodyMember(Order = 2)]
public string PeriodEnd { get; set; }
}
request class(the parameters for GetEvaluations method )
[MessageContract(IsWrapped = true, WrapperName = "GetEvaluation", WrapperNamespace = "http://tempuri.org/")]
[XmlType(Namespace = "http://tempuri.org/")]
public class EvaluationRequest
{
[MessageBodyMember(Order = 1)]
public string PeriodStart { get; set; }
[MessageBodyMember(Order = 2)]
public string PeriodEnd { get; set; }
}
Evaluation class
[DataContract()]
public class Evaluation
{
private int _EstLaborOfficeId;
private int _EstSequenceNumber;
private long _IdNumber;
[DataMember]
public int EstLaborOfficeId
{
get { return _EstLaborOfficeId; }
set { _EstLaborOfficeId = value; }
}
[DataMember(Order = 2)]
public int EstSequenceNumber
{
get { return _EstSequenceNumber; }
set { _EstSequenceNumber = value; }
}
}
Anyone, who wants to consume your service, does not know what kind of result he will reveice. It is just "Message" and has not specific MessageContract.
As far as I can see from here, you want to give back a list of Evaluation.
What you could try is this: (Untested)
[MessageContract]
public class Evaluation
{
private int _EstLaborOfficeId;
private int _EstSequenceNumber;
private long _IdNumber;
[MessageBodyMember]
public int EstLaborOfficeId
{
get { return _EstLaborOfficeId; }
set { _EstLaborOfficeId = value; }
}
[MessageBodyMember]
public int EstSequenceNumber
{
get { return _EstSequenceNumber; }
set { _EstSequenceNumber = value; }
}
}
[MessageContract]
public class EvaluationList
{
[MessageBodyMember]
public List<Evaluation> Values {get;set}
}
[ServiceContract()]
public interface IEvaluationWebService
{
[OperationContract]
EvaluationList GetEvaluations(EvaluationRequest evaluationRequest);
}
...or just try use List as return and forget EvaluationList.
[ServiceContract()]
public interface IEvaluationWebService
{
[OperationContract]
List<Evaluation> GetEvaluations(EvaluationRequest evaluationRequest);
}
Now, EvaluationList and EvaluationRequest are both MessageContracts.
Please keep in mind, that you ONLY want to use MessageContract, if you want full control of the SOAP Message. This does not seem to be the case here.
So, the more easy way would be, to change your EvaluationRequest back to DataContract:
[DataContract()]
public class Evaluation
{
private int _EstLaborOfficeId;
private int _EstSequenceNumber;
private long _IdNumber;
[DataMember]
public int EstLaborOfficeId
{
get { return _EstLaborOfficeId; }
set { _EstLaborOfficeId = value; }
}
[DataMember(Order = 2)]
public int EstSequenceNumber
{
get { return _EstSequenceNumber; }
set { _EstSequenceNumber = value; }
}
}
[DataContract]
public class EvaluationRequest
{
[DataMember]
public string PeriodStart { get; set; }
[DataMember]
public string PeriodEnd { get; set; }
}
[ServiceContract()]
public interface IEvaluationWebService
{
[OperationContract]
List<Evaluation> GetEvaluations(EvaluationRequest evaluationRequest);
}
The GOLDEN RULE IS: Try not to mix DataContract and MessageContract in a service operation, because WCF will see this as security flaw.
So define BOTH classes, result AND parameter, as DataContract OR MessageContract, but don't mix it up.
This is a continuation of another post. I'm trying to create an interface that will let me walk through a collection of objects, and access the name of the properties of the object.
A Report object will have ReportSections. A ReportSection will have an ICollection of items which will change depending on usage.
Here's how I'm trying to define it now.
public interface IReport
{
string ReportName { get; set; }
ICollection<IReportSection> ReportSections { get; }
}
public interface IReportSection
{
string ReportSectionName { get; set; }
ICollection ReportItems { get; }
}
public abstract class ReportBase : IReport
{
virtual public string ReportType { get; set; }
virtual public string ReportName { get; set; }
virtual public ICollection<IReportSection> ReportSections { get; set; }
}
public abstract class ReportSectionBase : IReportSection
{
public string ReportSectionName { get; set; }
public ICollection ReportItems { get; set; }
}
In my code, I would do this:
public class BookAffiliates : ReportSectionBase
{
public override string ReportSectionName { get { return "Book Affiliates"; } }
public override ICollection ReportItems { get; set; }
}
public class SomeClass
{
public ICollection<AuthorsViewModel> Authors { get; set; }
public ICollection<ProjectSubmissionViewModel> Submissions { get; set; }
public string ProcessAuthorsReport()
{
var report = new ContribAuthorsReport{ ReportType = "CSV" };
var authorAffil = new BookAffiliates {ReportItems = Authors };
report.ReportSections.Add(chapAffil);
var submissionAffil = new BookAffiliates {ReportItems = Submissions};
report.ReportSections.Add(submissionAffil );
return RenderReport(report)
}
}
In RenderReport I would like to walk through the collections and use the PropertyNames:
private string RenderReport(ReportBase currentReport)
{
var reportBody = new StringBuilder();
reportBody.Append(currentReport.ReportName + Environment.NewLine + Environment.NewLine);
foreach (var thisSection in currentReport.ReportSections)
{
reportBody.Append(thisSection.ReportSectionName + Environment.NewLine);
/// ---- Here! Here! I don't know what type, I want the
/// code to get the type based on ReportSectionBase<T>
var firstItem = thisSection.ReportItems.OfType<???Type???>().FirstOrDefault();
// I would actually like to go through each property of
// the ReportItem type and list it here.
foreach(var prop in firstItem.GetType().GetProperties())
{
reportBody.AppendLine(string.Format("{0}:{1}" prop.Name, prop.Value));
}
}
return reportBody.ToString();
}
I'm not sure how to best define this. I'm pretty sure I've done it before, but it's not coming to me.
You would use Reflection to do it.
foreach(var prop in thisItem.GetType().GetProperties())
{
reportBody.AppendLine(string.Format("{0}:{1}" prop.Name, prop.Value));
}
Took a while, a lot of questions, and figuring out what I really wanted to ask. I came up with this.
Here are my interfaces and base classes:
public class ReportBase
{
public ReportBase()
{
ReportSections = new List<IReportSection>();
}
public string ReportType { get; set; }
public string ReportName { get; set; }
public ICollection<IReportSection> ReportSections { get; set; }
}
public interface IReportSection
{
string ReportSectionName { get; }
ICollection ReportItems { get; set; }
}
public class ReportSection<T> : IReportSection
{
public string ReportSectionName { get; set; }
public ICollection<T> ReportItems { get; set; }
ICollection IReportSection.ReportItems
{
get { return ReportItems as ICollection; }
set { ReportItems = value as ICollection<T>; }
}
}
I create my objects like this:
public ReportBase GetContribAuthorsReport
(
ICollection<ProjectAffiliateViewModel> projectAffiliates,
ICollection<SubmissionAffiliateViewModel> submissionAffiliates
)
{
//var caReport = new ContributingAffiliates("CSV", projectAffiliates, submissionAffiliates);
var caReport = new ReportBase { ReportType = "CSV", ReportName = "Reviewers' Contact Information" };
caReport.ReportSections.Add(new ReportSection<ProjectAffiliateViewModel> { ReportItems = projectAffiliates });
caReport.ReportSections.Add(new ReportSection<SubmissionAffiliateViewModel> { ReportItems = submissionAffiliates });
return caReport;//.Report;
}
Then I iterate through the objects like this:
public class DownloadCsvActionResult : ActionResult
{
public ReportBase Report { get; set; }
public string fileName { get; set; }
private string ReportData { get; set; }
public DownloadCsvActionResult(ReportBase report, string pFileName)
{
Report = report;
fileName = pFileName;
ReportData = RenderReport();
}
private string RenderReport()
{
var reportBody = new StringBuilder();
reportBody.AppendLine(Report.ReportName);
reportBody.Append(Environment.NewLine + Environment.NewLine);
foreach (var thisSection in Report.ReportSections)
{
reportBody.Append(thisSection.ReportSectionName + Environment.NewLine);
if (thisSection.ReportItems != null)
{
var itemType = thisSection.ReportItems.GetType().GetGenericArguments().Single();
var first = true;
foreach (var prop in itemType.GetProperties())
{
if (!first) reportBody.Append(",");
DisplayAttribute attribute = prop.GetCustomAttributes(typeof(DisplayAttribute), false)
.Cast<DisplayAttribute>()
.SingleOrDefault();
string displayName = (attribute != null) ? attribute.Name : prop.Name;
reportBody.Append(displayName);
first = false;
}
reportBody.Append(Environment.NewLine);
foreach (var thisItem in thisSection.ReportItems)
{
var firstData = true;
foreach (var prop in itemType.GetProperties())
{
if (!firstData) reportBody.Append(",");
reportBody.Append(prop.GetValue(thisItem,null));
firstData = false;
}
reportBody.Append(Environment.NewLine);
}
}
reportBody.Append(Environment.NewLine);
}
return reportBody.ToString();
}
public override void ExecuteResult(ControllerContext context)
{
//Create a response stream to create and write the Excel file
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "application/vnd.ms-excel";
//Write the stream back to the response
curContext.Response.Write(ReportData);
curContext.Response.End();
}
}
This gives me what I need for now. Sorry I wasn't as clear in the first place, and thank you for all your help.
Trying to get the result from a webservice call to return a Model. I eep getting the error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'CI.Models.Schedule' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
public Schedule getCourseSchedule()
{
var obj = new
{
States = new[] { new { State = "MX" } },
Zip = "",
Miles = "",
PaginationStart = 1,
PaginationLimit = 3
};
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "apoplication/json";
var url = "http://192.168.1.198:15014/ShoppingCart2/CourseSchedule";
var json = JsonConvert.SerializeObject(obj);
byte[] data = Encoding.UTF8.GetBytes(json);
byte[] result = client.UploadData(url, data);
string returnjson = Encoding.UTF8.GetString(result);
Schedule sched = JsonConvert.DeserializeObject<Schedule>(returnjson);
return sched;
}
}
Schedule Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
namespace CI.Models
{
public class Schedule
{
public IEnumerable<Course> Courses { get; set; }
}
public class Course
{
/*
JSON Data returned from web service:
{
"ProgramGroup":"MR",
"ProgramCode":"RM",
"EventCode":"20160901MXMR",
"FormalDate":"September 1-2, 2016",
"StartDate":"2016\/09\/01",
"Price":5,
"LocName":"WB Hotel",
"LocAddress":"Av. Speedy Gonzales 220",
"LocCity":"Monterrey",
"LocState":"MX",
"LocZipCode":null,
"LicenseeURL":null,
"AgendaURL":"NA",
"SeatsAreAvailable":"2",
"GeneralInfoHTML":"General Info goes here.",
"GateKeeperHTML":null,
"EventType":"SS",
"TotalCourses":3
}
*/
public string ProgramGroup { get; set; }
public string ProgramCode { get; set; }
public string EventCode { get; set; }
public string FormalDate { get { return FormalDate; } set { FormalDate = convertFormalDateToSpanish(value); } }
public string StartDate { get; set; }
public double Price { get; set; }
public string LocName { get; set; }
public string LocAddress { get; set; }
public string LocCity { get ; set; }
public string LocState { get; set; }
public string LocZipCode { get; set; }
public string LicenseeURL { get; set; }
public string AgendaURL { get { return AgendaURL; } set { AgendaURL = buildAgendaLink(value); } }
public string SeatsAreAvailable { get; set; }
public string GeneralInfoHTML { get; set; }
public string GateKeeperHTML { get; set; }
public string EventType { get; set; }
public int TotalCourses { get; set; }
public string convertFormalDateToSpanish(string val)
{
DateTime TheDate = DateTime.Parse(StartDate);
string[] FormalDate = val.Split(" ".ToCharArray());
CultureInfo ci = new CultureInfo("es-ES");
string _Date = FormalDate[1].Replace("-", " al ").Replace(",", "");
string _Month = ci.TextInfo.ToTitleCase(TheDate.ToString("MMMM", ci));
val = string.Concat(_Date, " ", _Month);
return val;
}
private string buildAgendaLink(string val)
{
if (val.Trim() != "")
{
val = string.Concat("Agenda");
}
else
{
val = "Agenda";
}
return val;
}
}
}
Your server returns an array. Just try
Course[] courses = JsonConvert.DeserializeObject<Course[]>(returnjson);
Note that this is not an answer to your original problem, but I added it like an answer in order to explain my comment above with some actual code.
First problem with your code is that FormalDate and AgendaUrl properties simply won't work. Accessing them will result in a StackOverflowException, because you basically defined them recursively.
A property is merely syntax sugar for two separate getter/setter methods, so by writing this:
public class Course
{
public string FormalDate
{
get { return FormalDate; }
}
}
You are basically writing this:
public class Course
{
public string GetFormalDate()
{
// recursive call, with no terminating condition,
// will infinitely call itself until there is no
// more stack to store context data (and CLR
// will then throw an exception)
return GetFormalDate();
}
}
To fix that, you need to add an actual backing field, e.g.:
public class Course
{
private string _formalDate; // <-- this is a backing field;
// and this property uses the backing field to read/store data
public string FormalDate
{
get { return _formalDate; }
set { _formalDate = convertFormalDateToSpanish(value); }
}
}
Additionally, it's unusual for a property getter to return a different value than the one set through a setter. In other words, I would never expect this from a class:
var course = new Course();
course.StartDate = "2016/09/01";
course.FormalDate = "September 1-2, 2016";
Console.WriteLine(course.FormalDate); // prints "1 al 2 Septiembre" ?
I would rather move this functionality into a different class, or at least create different properties which return these values:
public class CourseInfo
{
// this is now a "dumb" auto-implemented property
// (no need for a backing field anymore)
public string FormalDate { get; set; }
// this read-only property returns the converted value
public string LocalizedFormalDate
{
get
{
return convertFormalDateToSpanish(FormalDate);
}
}
}
How can I pass an entire defined class through a WCF service? I have the class defined on both the service and client side. I keep getting an error:
Best overloaded method match has some invalid arguments.
The whole class was copied from the client-side to the service-side.
Client side calling:
TransferProxy.PutTransferOnService(Transfer);
Defined on service:
[OperationContract]
bool PutTransferOnService(TypeTransfer Transfer);
I don't want to access individual items on the class from the client, I just want to move the WHOLE populated object through and do processing on the server side.
[DataContract]
public class TypeTransfer
{
private string userID;
private string transferNum;
private DateTime effectiveDate;
private int unitCount;
private int skuCount;
private string reason;
private string localStatus;
private string destStatus;
private string carrier;
private string sourceStore;
private string destinationStore;
private string inSeal;
private string outSeal;
[DataMember]
private List<TypeSOQ> correspondingSOQ = new List<TypeSOQ>();
[DataMember]
private List<TypeProductList> ProductList = new List<TypeProductList>();
public TypeTransfer() { }
// Function adds single item to transfer object
public void AddItem(int ProductID, string SKU, string PrimarySKU, string SCC, string ProductDescription, int TransferQty)
{
ProductList.Add(new TypeProductList
{
productID = ProductID,
sku = SKU,
primaryUPC = PrimarySKU,
scc = SCC,
description = ProductDescription,
transferQty = TransferQty
});
}
// Add SOQ to transfer object (can support multiple SOQ's)
public void AddSOQ(TypeSOQ soq)
{
correspondingSOQ.Add(soq);
}
// Function returns number of skus in Product List
public int GetSKUTotal()
{
return ProductList.Count();
}
// Function returns total number of items in transfer
public int GetItemTotal()
{
int itemtotal = 0;
for (int i = 0; i < ProductList.Count(); i++)
{
itemtotal += ProductList[i].transferQty;
}
return itemtotal;
}
// Return entire SOQ list
public List<TypeSOQ> GetSOQs()
{
return correspondingSOQ;
}
// Returns full product list in transfer object
public List<TypeProductList> GetProductList()
{
return ProductList;
}
[DataMember]
public string UserID
{
get { return userID; }
set { userID = value; }
}
[DataMember]
public string TransferNum
{
get { return transferNum; }
set { transferNum = value; }
}
[DataMember]
public DateTime EffectiveDate
{
get { return effectiveDate; }
set { effectiveDate = value; }
}
[DataMember]
public int UnitCount
{
get { return unitCount; }
set { unitCount = value; }
}
[DataMember]
public string Reason
{
get { return reason; }
set { reason = value; }
}
[DataMember]
public string LocalStatus
{
get { return localStatus; }
set { localStatus = value; }
}
[DataMember]
public string DestStatus
{
get { return destStatus; }
set { destStatus = value; }
}
[DataMember]
public string Carrier
{
get { return carrier; }
set { carrier = value; }
}
[DataMember]
public string SourceStore
{
get { return sourceStore; }
set { sourceStore = value; }
}
[DataMember]
public string DestStore
{
get { return destinationStore; }
set { destinationStore = value; }
}
[DataMember]
public string InSeal
{
get { return inSeal; }
set { inSeal = value; }
}
[DataMember]
public string OutSeal
{
get { return outSeal; }
set { outSeal = value; }
}
[DataMember]
public int SKUCount
{
get { return skuCount; }
set { skuCount = value; }
}
}
You said - The whole class was copied from the client-side to the service-side.
You don't need to copy your class to server side. just define your class in a separate library and give reference of that same library to both client and server.
public class OrderXml
{
public enum DeliveryType { FTP, Email, HDD, Tape, Aspera, MLT };
public class Order
{
public int UserId { get; private set; }
public int OrderBinId { get; private set; }
public int TenantId { get; private set; }
public Delivery Delivery { get; set; }
public Recipient Recipient { get; private set; }
public string[] AssetDmGuids { get; set; }
public Order(int orderBinId, string[] assetDmGuids, DeliveryType type, int recipientId, string recipientName)
{
Delivery = new Delivery(type);
Recipient = new Recipient(recipientId, recipientName);
// UserId = SessionHelper.Instance.GetUserId();
// TenantId = SessionHelper.Instance.GetTenantID().ToString();
OrderBinId = orderBinId;
AssetDmGuids = assetDmGuids;
}
public void GetXml()
{
}
}
public class Recipient
{
int _id;
string _name = string.Empty;
public Recipient(int id, string name)
{
this._id = id;
this._name = name;
}
public int Id { get { return _id; } }
public string Name { get { return _name; } }
}
public class Delivery
{
DeliveryType _deliveryType;
string _ftpLocation = string.Empty;
string _ftpPath = string.Empty;
string[] _emailAddresses;
string _deliveryAddress = string.Empty;
string _deliveryComments = string.Empty;
string _asperaLocation = string.Empty;
public string FtpPath
{
get { return _ftpPath; }
set { _ftpPath = value; }
}
public string[] EmailAddresses
{
get { return _emailAddresses; }
set { _emailAddresses = value; }
}
public string DeliveryAddress
{
get { return _deliveryAddress; }
set { _deliveryAddress = value; }
}
public string DeliveryComments
{
get { return _deliveryComments; }
set { _deliveryComments = value; }
}
public string AsperaLocation
{
get { return _asperaLocation; }
set { _asperaLocation = value; }
}
public string FtpLocation
{
get { return _ftpLocation; }
set { _ftpLocation = value; }
}
public Delivery(DeliveryType type)
{
_deliveryType = type;
}
}
public static void Main()
{
Order ord = new Order(1, new string[] { "123", "124", "125" }, DeliveryType.Tape, 1, "vh1");
}
}
public XmlDocument GetXml()
{
XmlDocument retValue = new XmlDocument();
try
{
XmlSerializer xs = new XmlSerializer(this.GetType());
Stream stream = new MemoryStream();
xs.Serialize( stream, toSerialize );
stream.Position = 0;
retValue.Load( stream );
}
catch (Exception ex)
{
}
return retValue;
}