Sending own data collection in WCF - c#

I have own collection DataContracts:
[DataContract]
public class DzieckoAndOpiekun
{
public DzieckoAndOpiekun() { }
public DzieckoAndOpiekun(string dzImie, string dzNazwisko, string opImie, string opNazwisko)
{
this.DzieckoImie = dzImie;
this.DzieckoImie = dzNazwisko;
this.OpiekunImie = opImie;
this.OpiekunNazwisko = opNazwisko;
}
/// <summary>
/// Field for Dziecko's Surname
/// </summary>
private string dzieckoNazwisko;
/// <summary>
/// Field for Dziecko's Name
/// </summary>
private string dzieckoImie;
/// <summary>
/// Field for Opiekun's Surname
/// </summary>
private string opiekunNazwisko;
/// <summary>
/// Field for Opiekun's Name
/// </summary>
private string opiekunImie;
/// <summary>
/// Gets or sets the dziecko nazwisko.
/// </summary>
/// <value>The dziecko nazwisko.</value>
[DataMember]
public virtual string DzieckoNazwisko
{
get { return this.dzieckoNazwisko; }
set { this.dzieckoNazwisko = value; }
}
/// <summary>
/// Gets or sets the dziecko imie.
/// </summary>
/// <value>The dziecko imie.</value>
[DataMember]
public virtual string DzieckoImie
{
get { return this.dzieckoImie; }
set { this.dzieckoImie = value; }
}
/// <summary>
/// Gets or sets the opiekun nazwisko.
/// </summary>
/// <value>The opiekun nazwisko.</value>
[DataMember]
public virtual string OpiekunNazwisko
{
get { return this.opiekunNazwisko; }
set { this.opiekunNazwisko = value; }
}
/// <summary>
/// Gets or sets the opiekun imie.
/// </summary>
/// <value>The opiekun imie.</value>
[DataMember]
public virtual string OpiekunImie
{
get { return this.opiekunImie; }
set { this.opiekunImie = value; }
}
}
[DataContract]
public class DzieckoAndOpiekunCollection : IEnumerable<DzieckoAndOpiekun>, IList<DzieckoAndOpiekun>
{
[DataMember]
List<DzieckoAndOpiekun> collection = new List<DzieckoAndOpiekun>();
[DataMember]
public List<DzieckoAndOpiekun> Collection
{
get { return collection; }
set { collection = value; }
}
public IEnumerator<DzieckoAndOpiekun> GetEnumerator()
{
return collection.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new System.NotImplementedException();
}
public int IndexOf(DzieckoAndOpiekun item)
{
return collection.IndexOf(item);
}
public void Insert(int index, DzieckoAndOpiekun item)
{
collection.Insert(index, item);
}
public void RemoveAt(int index)
{
collection.RemoveAt(index);
}
public DzieckoAndOpiekun this[int index]
{
get
{
return collection[index];
}
set
{
collection[index] = value;
}
}
public void Add(DzieckoAndOpiekun item)
{
this.collection.Add(item);
}
public void AddRange(IList<DzieckoAndOpiekun> collection)
{
this.collection.AddRange(collection);
}
public void Clear()
{
collection.Clear();
}
public bool Contains(DzieckoAndOpiekun item)
{
return collection.Contains(item);
}
public void CopyTo(DzieckoAndOpiekun[] array, int arrayIndex)
{
this.collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return this.collection.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(DzieckoAndOpiekun item)
{
return this.collection.Remove(item);
}
}
And use it in my ServiceContract implementation:
public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities();
DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection();
if (firstname == null && lastname != null)
{
IQueryable<DzieckoAndOpiekun> resultV = from p in db.Dziecko
where lastname == p.Nazwisko
select new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko);
List<DzieckoAndOpiekun> l = resultV.ToList();
result.AddRange(l);
}
if (firstname != null && lastname != null)
{
IQueryable<DzieckoAndOpiekun> resultV = from p in db.Dziecko
where firstname == p.Imie && lastname == p.Nazwisko
select new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko);
List<DzieckoAndOpiekun> l = resultV.ToList();
result.AddRange(l);
}
if (firstname != null && lastname == null)
{
IQueryable<DzieckoAndOpiekun> resultV = from p in db.Dziecko
where firstname == p.Imie
select new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko);
List<DzieckoAndOpiekun> l = resultV.ToList();
result.AddRange(l);
}
return result;
}
Do I something wrong in creating own data contract and sending it ? I ask cause I have errors when consuming method :/ :
An exception occurred during the operation, making the result invalid.
Check InnerException for exception
details.
at
System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
at
SecretaryAppNav.ClientService.GetChildAndOpiekunByFirstnameLastnameCompletedEventArgs.get_Result() at
SecretaryAppNav.Views.FindChild.Client_GetChildAndOpiekunByFirstnameLastnameCompleted(Object
sender,
GetChildAndOpiekunByFirstnameLastnameCompletedEventArgs
e)
at SecretaryAppNav.ClientService.Service1Client.OnGetChildAndOpiekunByFirstnameLastnameCompleted(Object
state)

I can't guarantee that this would work, but you are sending the collection twice:
[DataContract]
public class DzieckoAndOpiekunCollection :
IEnumerable<DzieckoAndOpiekun>, IList<DzieckoAndOpiekun>
{
[DataMember]
List<DzieckoAndOpiekun> collection = new List<DzieckoAndOpiekun>();
[DataMember]
public List<DzieckoAndOpiekun> Collection
{
get { return collection; }
set { collection = value; }
}
...
You should probably only place the DataMember attribute on the field or the property, but not both, since they are exposing the same value.

I solve the problem with CollectionDataContract attribute ;)

Related

Constructing GET Request using WSDL Service Reference

I'm connecting to the clothing distributor SanMar using their wsdl endpoint. I've created a service reference for it but where I'm hitting a roadblock is in a specific method I want to call. It requires two params, the one that's giving me issues is an item[]. The wsdl documentation has it's own definition of an item[] which I can't seem to satisfy.
The endpoint is https://ws.sanmar.com:8080/SanMarWebServices/SanMarNotificationServicePort?WSDL
The documentation for the item[] object is:
public partial class item : object, System.ComponentModel.INotifyPropertyChanged {
private double casePriceField;
private bool casePriceFieldSpecified;
private string colorField;
private double dozenPriceField;
private bool dozenPriceFieldSpecified;
private string inventoryKeyField;
private double myPriceField;
private bool myPriceFieldSpecified;
private double piecePriceField;
private bool piecePriceFieldSpecified;
private double salePriceField;
private bool salePriceFieldSpecified;
private string sizeField;
private int sizeIndexField;
private bool sizeIndexFieldSpecified;
private string styleField;
private string saleStartDateField;
private string saleEndDateField;
private double incentivePriceField;
private bool incentivePriceFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)]
public double casePrice {
get {
return this.casePriceField;
}
set {
this.casePriceField = value;
this.RaisePropertyChanged("casePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool casePriceSpecified {
get {
return this.casePriceFieldSpecified;
}
set {
this.casePriceFieldSpecified = value;
this.RaisePropertyChanged("casePriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)]
public string color {
get {
return this.colorField;
}
set {
this.colorField = value;
this.RaisePropertyChanged("color");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=2)]
public double dozenPrice {
get {
return this.dozenPriceField;
}
set {
this.dozenPriceField = value;
this.RaisePropertyChanged("dozenPrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool dozenPriceSpecified {
get {
return this.dozenPriceFieldSpecified;
}
set {
this.dozenPriceFieldSpecified = value;
this.RaisePropertyChanged("dozenPriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=3)]
public string inventoryKey {
get {
return this.inventoryKeyField;
}
set {
this.inventoryKeyField = value;
this.RaisePropertyChanged("inventoryKey");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=4)]
public double myPrice {
get {
return this.myPriceField;
}
set {
this.myPriceField = value;
this.RaisePropertyChanged("myPrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool myPriceSpecified {
get {
return this.myPriceFieldSpecified;
}
set {
this.myPriceFieldSpecified = value;
this.RaisePropertyChanged("myPriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=5)]
public double piecePrice {
get {
return this.piecePriceField;
}
set {
this.piecePriceField = value;
this.RaisePropertyChanged("piecePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool piecePriceSpecified {
get {
return this.piecePriceFieldSpecified;
}
set {
this.piecePriceFieldSpecified = value;
this.RaisePropertyChanged("piecePriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=6)]
public double salePrice {
get {
return this.salePriceField;
}
set {
this.salePriceField = value;
this.RaisePropertyChanged("salePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool salePriceSpecified {
get {
return this.salePriceFieldSpecified;
}
set {
this.salePriceFieldSpecified = value;
this.RaisePropertyChanged("salePriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=7)]
public string size {
get {
return this.sizeField;
}
set {
this.sizeField = value;
this.RaisePropertyChanged("size");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=8)]
public int sizeIndex {
get {
return this.sizeIndexField;
}
set {
this.sizeIndexField = value;
this.RaisePropertyChanged("sizeIndex");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool sizeIndexSpecified {
get {
return this.sizeIndexFieldSpecified;
}
set {
this.sizeIndexFieldSpecified = value;
this.RaisePropertyChanged("sizeIndexSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=9)]
public string style {
get {
return this.styleField;
}
set {
this.styleField = value;
this.RaisePropertyChanged("style");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=10)]
public string saleStartDate {
get {
return this.saleStartDateField;
}
set {
this.saleStartDateField = value;
this.RaisePropertyChanged("saleStartDate");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=11)]
public string saleEndDate {
get {
return this.saleEndDateField;
}
set {
this.saleEndDateField = value;
this.RaisePropertyChanged("saleEndDate");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=12)]
public double incentivePrice {
get {
return this.incentivePriceField;
}
set {
this.incentivePriceField = value;
this.RaisePropertyChanged("incentivePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool incentivePriceSpecified {
get {
return this.incentivePriceFieldSpecified;
}
set {
this.incentivePriceFieldSpecified = value;
this.RaisePropertyChanged("incentivePriceSpecified");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
Can anyone point me in the right direction or pm me to talk further?
Thank you
I tried creating an item[] from scratch but I believe I'm supposed to be using the methods to set the values.

Custom (Dynamic) Properties - WPF Xceed Property Grid

I need to add custom properties to the WPF Xceed Property Grid control during runtime. The best solution that I could find is the one presented here:
How to modify PropertyGrid at runtime (add/remove property and dynamic types/enums)
However it only works for the WinForms Property Grid control. See below for code, and the result that I am getting.
I'm not an expert in this field at all. Is it possible to make the code compatible with the Xceed Property Grid control?
CustomClass myProperties = new CustomClass();
propertyGrid.SelectedObject = myProperties;
myProperties.Add(new CustomProperty("Name", "Sven", typeof(string), false, true,"Cat1"));
myProperties.Add(new CustomProperty("Surname", "Bendo", typeof(string), false, true, "Cat1"));
myProperties.Add(new CustomProperty("Card", "Visa", typeof(string), false, true, "Cat2"));
myProperties.Add(new CustomProperty("Bank", "SB", typeof(string), false, true, "Cat2"));
propertyGrid.Update();
Custom class:
/// <summary>
/// CustomClass (Which is binding to property grid)
/// </summary>
public class CustomClass : CollectionBase, ICustomTypeDescriptor
{
/// <summary>
/// Add CustomProperty to Collectionbase List
/// </summary>
/// <param name="Value"></param>
public void Add(CustomProperty Value)
{
base.List.Add(Value);
}
/// <summary>
/// Remove item from List
/// </summary>
/// <param name="Name"></param>
public void Remove(string Name)
{
foreach (CustomProperty prop in base.List)
{
if (prop.Name == Name)
{
base.List.Remove(prop);
return;
}
}
}
/// <summary>
/// Indexer
/// </summary>
public CustomProperty this[int index]
{
get
{
return (CustomProperty)base.List[index];
}
set
{
base.List[index] = (CustomProperty)value;
}
}
#region "TypeDescriptor Implementation"
/// <summary>
/// Get Class Name
/// </summary>
/// <returns>String</returns>
public String GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
/// <summary>
/// GetAttributes
/// </summary>
/// <returns>AttributeCollection</returns>
public AttributeCollection GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
/// <summary>
/// GetComponentName
/// </summary>
/// <returns>String</returns>
public String GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
/// <summary>
/// GetConverter
/// </summary>
/// <returns>TypeConverter</returns>
public TypeConverter GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
/// <summary>
/// GetDefaultEvent
/// </summary>
/// <returns>EventDescriptor</returns>
public EventDescriptor GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
/// <summary>
/// GetDefaultProperty
/// </summary>
/// <returns>PropertyDescriptor</returns>
public PropertyDescriptor GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, true);
}
/// <summary>
/// GetEditor
/// </summary>
/// <param name="editorBaseType">editorBaseType</param>
/// <returns>object</returns>
public object GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
public EventDescriptorCollection GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
public EventDescriptorCollection GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
PropertyDescriptor[] newProps = new PropertyDescriptor[this.Count];
for (int i = 0; i < this.Count; i++)
{
CustomProperty prop = (CustomProperty)this[i];
newProps[i] = new CustomPropertyDescriptor(ref prop, attributes);
}
return new PropertyDescriptorCollection(newProps);
}
public PropertyDescriptorCollection GetProperties()
{
return TypeDescriptor.GetProperties(this, true);
}
public object GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
/// <summary>
/// Custom property class
/// </summary>
public class CustomProperty
{
private string sName = string.Empty;
private string sCategory = "";
private bool bReadOnly = false;
private bool bVisible = true;
private object objValue = null;
public CustomProperty(string sName, object value, Type type, bool bReadOnly, bool bVisible,string sCategory)
{
this.sName = sName;
this.objValue = value;
this.type = type;
this.bReadOnly = bReadOnly;
this.bVisible = bVisible;
this.sCategory = sCategory;
}
private Type type;
public Type Type
{
get { return type; }
}
public bool ReadOnly
{
get
{
return bReadOnly;
}
}
public string Name
{
get
{
return sName;
}
}
public string Category
{
get
{
return sCategory;
}
}
public bool Visible
{
get
{
return bVisible;
}
}
public object Value
{
get
{
return objValue;
}
set
{
objValue = value;
}
}
}
/// <summary>
/// Custom PropertyDescriptor
/// </summary>
public class CustomPropertyDescriptor : PropertyDescriptor
{
CustomProperty m_Property;
public CustomPropertyDescriptor(ref CustomProperty myProperty, Attribute[] attrs) : base(myProperty.Name, attrs)
{
m_Property = myProperty;
}
#region PropertyDescriptor specific
public override bool CanResetValue(object component)
{
return false;
}
public override Type ComponentType
{
get { return null; }
}
public override object GetValue(object component)
{
return m_Property.Value;
}
public override string Description
{
get { return m_Property.Name; }
}
public override string Category
{
get { return m_Property.Category; }
}
public override string DisplayName
{
get { return m_Property.Name; }
}
public override bool IsReadOnly
{
get { return m_Property.ReadOnly; }
}
public override void ResetValue(object component)
{
//Have to implement
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
public override void SetValue(object component, object value)
{
m_Property.Value = value;
}
public override Type PropertyType
{
get { return m_Property.Type; }
}
#endregion
}
If you want to add properties to the PropertyGrid att runtime, you should set the AutoGenerateProperties property to false and add PropertyDefinitions to the control itself, e.g.:
CustomClass myProperties = new CustomClass();
propertyGrid.AutoGenerateProperties = false;
propertyGrid.SelectedObject = myProperties;
propertyGrid.PropertyDefinitions.Add(new Xceed.Wpf.Toolkit.PropertyGrid.PropertyDefinition() { Category = "Cat1", DisplayName = "Name", TargetProperties = new string[] { "Name"} });
You can use propertyDescriptor and ICustomTypeDescriptor
Implement ICustomTypeDescriptor to your type binded to selected object
public class EntityProperties : ICustomTypeDescriptor
{
public List<MyProperty> myProperties = new List<MyProperty>();
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
// Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
for (int i = 0; i < myProperties.Count; i++)
{
pds.Add(new MyPropertyDescriptor(myProperties[i], this));
}
return pds;
}
#region Use default TypeDescriptor stuff
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, noCustomTypeDesc: true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, noCustomTypeDesc: true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, noCustomTypeDesc: true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, noCustomTypeDesc: true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, noCustomTypeDesc: true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return TypeDescriptor.GetDefaultProperty(this, noCustomTypeDesc: true);
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, noCustomTypeDesc: true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, noCustomTypeDesc: true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, noCustomTypeDesc: true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return TypeDescriptor.GetProperties(this, attributes, noCustomTypeDesc: true);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
Use PropertyDescriptor for your each properties that needed to be displayed
public class MyPropertyDescriptor: PropertyDescriptor
{
MyProperty _prop;
object _parent;
public MyPropertyDescriptor(MyProperty prop, object parent)
: base(prop.PropertyName, null)
{
_prop = prop;
_parent = parent;
}
public override AttributeCollection Attributes
{
get
{
var attributes = TypeDescriptor.GetAttributes(GetValue(null), false);
return attributes;
}
}
public override bool CanResetValue(object component)
{
return false;
}
public override object GetValue(object component)
{
switch (_prop.Type)
{
case MyProperty.PropertyType.String:
return _prop.StringValue;
case MyProperty.PropertyType.Number:
return _prop.NumberValue;
default:
break;
}
return null;
}
public override void ResetValue(object component)
{
throw new NotImplementedException();
}
public override void SetValue(object component, object value)
{
switch (_prop.Type)
{
case MyProperty.PropertyType.String:
_prop.StringValue = value as string;
break;
case MyProperty.PropertyType.Number:
_prop.NumberValue = (double)value;
break;
default:
break;
}
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
public override Type ComponentType
=> _parent.GetType();
public override bool IsReadOnly
=> false;
public override Type PropertyType
{
get
{
switch (_prop.Type)
{
case MyProperty.PropertyType.String:
return _prop.StringValue.GetType();
case MyProperty.PropertyType.Number:
return _prop.NumberValue.GetType();
default:
return typeof(string);
}
}
}
}
Add sample data as below and assign selectedObject
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
EntityProperties pp = new EntityProperties()
{
myProperties = new List<MyProperty>()
{
new MyProperty() { Type = MyProperty.PropertyType.String, StringValue = "simple", PropertyName = "EntityType" },
new MyProperty() { Type = MyProperty.PropertyType.Number, NumberValue = 123, PropertyName = "EntityID" }
}
};
_propertyGrid.SelectedObject = pp;
_propertyGrid.AutoGenerateProperties = true;
}
}
MyProperty class describes about the property.
public class MyProperty
{
public enum PropertyType
{
String,
Number
}
public PropertyType Type { get; set; }
public string StringValue { get; set; }
public double NumberValue { get; set; }
public string PropertyName { get; set; }
}

How to fix java.lang.ClassCastException?

Below is the portion of code from Propertyware API that is consumed.
public OwnerLedger appendOwnerLedgerItems(OwnerLedger ownerLedger, Owner owner) {
object[] results = this.Invoke("appendOwnerLedgerItems", new object[] {
ownerLedger,
owner});
return ((OwnerLedger)(results[0]));
}
public partial class OwnerLedger : Ledger {
}
public abstract partial class Ledger : ClientDataContainer {
private LedgerItem[] itemsField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public LedgerItem[] items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
public abstract partial class LedgerItem : FinancialTransaction {
}
public abstract partial class OwnerLedgerItem : LedgerItem {
}
public partial class OwnerContribution : OwnerLedgerItem {
private string commentsField;
private System.Nullable<System.DateTime> dateField;
private string paymentTypeField;
private string referenceNumberField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string comments {
get {
return this.commentsField;
}
set {
this.commentsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public System.Nullable<System.DateTime> date {
get {
return this.dateField;
}
set {
this.dateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string paymentType {
get {
return this.paymentTypeField;
}
set {
this.paymentTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string referenceNumber {
get {
return this.referenceNumberField;
}
set {
this.referenceNumberField = value;
}
}
}
In the above code i need to use the "appendOwnerLedgerItems" method to create an owner contribution entry in Propertyware. For that i try to use the below logic but it fails. The error message is "java.lang.ClassCastException: [Lcom.realpage.propertyware.web.service.soap.AbstractLedgerItemDTO; cannot be cast to [Lcom.realpage.propertyware.web.service.soap.AbstractOwnerLedgerItemDTO;"
OwnerContribution oc = new OwnerContribution();
oc.amount = 10;
oc.comments = "Test Entry";
oc.date = System.DateTime.Now;
oc.paymentType = "Check";
oc.referenceNumber = "12345";
Owner ow = new Owner();
ow.ID = 12345;
LedgerItem[] li = new LedgerItem[1];
li[0] = oc;
OwnerLedger owl = new OwnerLedger();
owl.items = li;
OwnerLedger owl1 = client.appendOwnerLedgerItems(owl,ow); // This is where i get the cast error
How to solve this issue?
I don't know much about Propertyware but can you try this, basically change the order of objects passed to the invoke method:
public OwnerLedger appendOwnerLedgerItems(OwnerLedger ownerLedger, Owner owner) {
object[] results = this.Invoke("appendOwnerLedgerItems", new object[] {
owner, ownerLedger});
return ((OwnerLedger)(results[0]));
}

How to send parameters to a webservice method that only accepts one argument in C#

I am new to webservices in general. I am trying to add 4 parameters to the rmc service CreateCar, and have attempted to do so in my Webservices.cs file. Unfortunately, the CreateCar method only takes 1 argument (request). Most of this code is based on similar processes that do accept all the parameters.
The call I am trying to make is the rmcService.CreateCar.
public bool CreateCar(string url, string viewedUserType, string userName, string accounts, string carName)
{
bool returnValue = false;
try
{
if (accounts.Length != 9)
{
if (accounts.Length == 8)
{
accounts = accounts + "0";
}
else
{
throw new ApplicationException("Invalid length for Account #");
}
}
// Initialize web service object
relationshipmgmtcentersvcdev.RmcService rmcService = new relationshipmgmtcentersvcdev.RmcService();
rmcService.Url = url;
// Attach credentials
rmcService.Credentials = _Credentials;
// Connection pooling
rmcService.ConnectionGroupName = _Credentials.UserName.ToString();
rmcService.UnsafeAuthenticatedConnectionSharing = true;
// Hard coding View User Type as None
viewedUserType = "None";
// Call to create CAR - Client Account Relation
rmcService.CreateCar(userName, viewedUserType, accounts, carName);
returnValue = true;
}
catch (Exception ex)
{
System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
eventLog.Source = "UAccCompWrapper";
eventLog.WriteEntry("Error in CreateCar Method: " + ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
}
return returnValue;
}
The error I receive is no overload for method CreateCar takes 4 arguments (which makes sense). I was just trying to illustrate what I was trying to do. This method only takes 1 argument it seems.
This is a snippet of the reference file with the information I found was relevant. It appears that I need to create a BaseServiceRequest with the parameters, but I am unsure how.
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://relationshipmgmtcenter.hfg.com/services/IRmcService/CreateCar", RequestNamespace="http://relationshipmgmtcenter.hfg.com/services/", ResponseNamespace="http://relationshipmgmtcenter.hfg.com/services/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void CreateCar([System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] CreateCarServiceRequest request) {
this.Invoke("CreateCar", new object[] {
request});
}
/// <remarks/>
public void CreateCarAsync(CreateCarServiceRequest request) {
this.CreateCarAsync(request, null);
}
/// <remarks/>
public void CreateCarAsync(CreateCarServiceRequest request, object userState) {
if ((this.CreateCarOperationCompleted == null)) {
this.CreateCarOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateCarOperationCompleted);
}
this.InvokeAsync("CreateCar", new object[] {
request}, this.CreateCarOperationCompleted, userState);
}
private void OnCreateCarOperationCompleted(object arg) {
if ((this.CreateCarCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateCarCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(UserProfileServiceRequest))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(RenameGroupServiceRequest))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CreateCarServiceRequest))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(DeleteGroupServiceRequest))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(GetMgrServiceRequest))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34234")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.datacontract.org/2004/07/HF.Rmc.Service.Library.Requests")]
public partial class BaseServiceRequest {
private string sessionIdField;
private string userNameField;
private string viewedUserField;
private ViewedUserType viewedUserTypeField;
private bool viewedUserTypeFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public string SessionId {
get {
return this.sessionIdField;
}
set {
this.sessionIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public string UserName {
get {
return this.userNameField;
}
set {
this.userNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public string ViewedUser {
get {
return this.viewedUserField;
}
set {
this.viewedUserField = value;
}
}
/// <remarks/>
public ViewedUserType ViewedUserType {
get {
return this.viewedUserTypeField;
}
set {
this.viewedUserTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool ViewedUserTypeSpecified {
get {
return this.viewedUserTypeFieldSpecified;
}
set {
this.viewedUserTypeFieldSpecified = value;
}
}
}
public partial class CreateCarServiceRequest : BaseServiceRequest {
private string accountsField;
private string carNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public string Accounts {
get {
return this.accountsField;
}
set {
this.accountsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public string CarName {
get {
return this.carNameField;
}
set {
this.carNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.18408")]
public delegate void CreateCarCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
Try this:
rmcService.CreateCar(new CreateCarServiceRequest
{
UserName = userName,
ViewedUserType = Enum.Parse(typeof(ViewedUserType), viewedUserType)
Accounts = accounts,
CarName = carName
});

LongListSelector acting strange

I’m experiencing a problem with the longlistselector witch is a bit strange... I’m reading a list asynchronously on a multi Pivot page, and if I don’t change the pivot until the resulto f the list Reading, it will create the contacts list successfuly ( in a longlistselector on the pivot item number 3 ) and when I go to that pivot the contacts list is displayed withou any problems, but when I open the Page and change the pivot before the longlistselector is created when the asychronous function returns the results and fills the longlistselector on pivot no.3 the contacts wont get updated ( when I go to pivot 3 no contacts are shown)...
I’ll post my code so you can have a clearer picture of the situation and maybe figure out what is happening.
The code is based in the PhoneToolkit LongListSelector example (buddies list)
public partial class Feeds : PhoneApplicationPage
{
bool isLoading = false;
bool loadingFilmates = true;
public Feeds()
{
InitializeComponent();
// ...
Loaded += FeedsPage_Loaded;
SystemTray.ProgressIndicator = new ProgressIndicator();
DataContext = this;
getFilmatesList();
longlistFilmates.SelectionChanged += FilmateSelectionChanged;
// ...
}
private async void getFilmatesList()
{
Feed userFilmates = await Feed.GetFilmates(App.Current.AppUser, App.Current.WSConfig, 0, "", 10000); // read feeds from webservice
Filmates = AlphaKeyGroup<StayObjectFilmates>.CreateGroups(AllFilmates.GetCurrent(userFilmates), CultureInfo.CurrentUICulture, (p) => { return p.Name; }, true);
//longlistFilmates.Visibility = System.Windows.Visibility.Collapsed;
longlistFilmates.Visibility = System.Windows.Visibility.Visible;
longlistFilmates.UseLayoutRounding = true;
pivotFeed.Visibility = System.Windows.Visibility.Collapsed;
pivotFeed.Visibility = System.Windows.Visibility.Visible;
}
}
Notice that I’ve even tried changing the Visibility property when it loads to force a re-render on the screen and it didn’t work.
This is the StayObjectFilmates class:
public class StayObjectFilmates
{
public string Img { get; private set; }
public string Name { get; private set; }
public string UserId { get; private set; }
public string Id { get; set; }
public User user { get; set; }
public StayObjectFilmates()
{
//Img = "";
//Name = "";
//Id = "";
}
public StayObjectFilmates(string p_img, string p_name, string p_Id)
{
Img = p_img;
Name = p_name;
UserId = p_Id;
}
public StayObjectFilmates(User p_user)
{
user = p_user;
}
public static string GetNameKey(StayObjectFilmates filmate)
{
char key = char.ToLower(filmate.Name[0]);
if (key < 'a' || key > 'z')
{
key = '#';
}
return key.ToString();
}
public static int CompareByName(object obj1, object obj2)
{
StayObjectFilmates p1 = (StayObjectFilmates)obj1;
StayObjectFilmates p2 = (StayObjectFilmates)obj2;
int result = p1.Name.CompareTo(p2.Name);
if (result == 0)
{
result = p1.Img.CompareTo(p2.Img);
}
return result;
}
}
This is the AllFilmates class:
public class AllFilmates : IEnumerable<StayObjectFilmates>
{
private static Dictionary<int, StayObjectFilmates> _filmateLookup;
private static AllFilmates _instance;
private Feed filmates;
// public List<StayObjectFilmates> Filmates { get; private set; }
public static AllFilmates GetCurrent(Feed p_filmates)
{
if (_instance == null)
{
_instance = new AllFilmates();
}
_instance.filmates = p_filmates;
return _instance;
}
public static AllFilmates Current
{
get
{
return _instance ?? (_instance = new AllFilmates());
}
}
public StayObjectFilmates this[int index]
{
get
{
StayObjectFilmates filmate;
_filmateLookup.TryGetValue(index, out filmate);
return filmate;
}
}
#region IEnumerable<StayObjectFilmates> Members
public IEnumerator<StayObjectFilmates> GetEnumerator()
{
EnsureData();
return _filmateLookup.Values.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
EnsureData();
return _filmateLookup.Values.GetEnumerator();
}
#endregion
private void EnsureData()
{
if (_filmateLookup == null)
{
_filmateLookup = new Dictionary<int, StayObjectFilmates>();
if (filmates != null)
{
int i = 0;
foreach (var item in filmates.itemsList)
{
User friend = item as User;
string userphoto = (friend.photo == null) ? "Images/avatar.jpg" : friend.photo;
StayObjectFilmates f = new StayObjectFilmates(userphoto, friend.fullName, i.ToString());
_filmateLookup[i] = f;
i++;
}
}
}
}
}
And this is the AlphaKeyGroup.cs file :
public class AlphaKeyGroup<T> : List<T>
{
private const string GlobeGroupKey = "\uD83C\uDF10";
/// <summary>
/// The delegate that is used to get the key information.
/// </summary>
/// <param name="item">An object of type T</param>
/// <returns>The key value to use for this object</returns>
public delegate string GetKeyDelegate(T item);
/// <summary>
/// The Key of this group.
/// </summary>
public string Key { get; private set; }
/// <summary>
/// Public constructor.
/// </summary>
/// <param name="key">The key for this group.</param>
public AlphaKeyGroup(string key)
{
Key = key;
}
public AlphaKeyGroup(IGrouping<string, T> grouping)
{
Key = grouping.Key;
this.AddRange(grouping);
}
/// <summary>
/// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
/// </summary>
/// <param name="slg">The </param>
/// <returns>Theitems source for a LongListSelector</returns>
private static List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg)
{
List<AlphaKeyGroup<T>> list = new List<AlphaKeyGroup<T>>();
foreach (string key in slg.GroupDisplayNames)
{
if (key == "...")
{
list.Add(new AlphaKeyGroup<T>(GlobeGroupKey));
}
else
{
list.Add(new AlphaKeyGroup<T>(key));
}
}
return list;
}
/// <summary>
/// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
/// </summary>
/// <param name="items">The items to place in the groups.</param>
/// <param name="ci">The CultureInfo to group and sort by.</param>
/// <param name="getKey">A delegate to get the key from an item.</param>
/// <param name="sort">Will sort the data if true.</param>
/// <returns>An items source for a LongListSelector</returns>
public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort)
{
SortedLocaleGrouping slg = new SortedLocaleGrouping(ci);
List<AlphaKeyGroup<T>> list = CreateGroups(slg);
foreach (T item in items)
{
int index = 0;
if (slg.SupportsPhonetics)
{
//check if your database has yomi string for item
//if it does not, then do you want to generate Yomi or ask the user for this item.
//index = slg.GetGroupIndex(getKey(Yomiof(item)));
}
else
{
index = slg.GetGroupIndex(getKey(item));
}
if (index >= 0 && index < list.Count)
{
list[index].Add(item);
}
}
if (sort)
{
foreach (AlphaKeyGroup<T> group in list)
{
group.Sort((c0, c1) => { return ci.CompareInfo.Compare(getKey(c0), getKey(c1)); });
}
}
return list;
}
}
The FilmatesInGroup.cs and FilmatesByName.cs is the same as PeopleInGroup.cs and PeopleByFirstName.cs in the PhoneToolKit example with the names adapted.
The longlistFilmates LongListSelector Object is inserted directly inside the PivotItem no.3 ( no Grid and no ScrollView )
Thanks in advance for any help!

Categories

Resources