Problem with Dependency Property - silverlight-4.0

I am using a websites code for reference, but what I am trying to do is not working. The backing property never changes...I dont know if what I am expecting to happen is wrong..
public class QuestionTemplateSelector : UserControl
{
public DataTemplate TemplateString { get; set; }
public DataTemplate TemplateBoolean { get; set; }
public DataTemplate TemplateSingleMultipleChoice { get; set; }
public DataTemplate TemplateAnyMultipleChoice { get; set; }
/// <summary>
/// The <see cref="QuestionType" /> dependency property's name.
/// </summary>
public const string QuestionTypePropertyName = "QuestionType";
/// <summary>
/// Gets or sets the value of the <see cref="QuestionType" />
/// property. This is a dependency property.
/// </summary>
public string QuestionType
{
get
{
return (string)GetValue(QuestionTypeProperty);
}
set
{
SetValue(QuestionTypeProperty, value);
}
}
/// <summary>
/// Identifies the <see cref="QuestionType" /> dependency property.
/// </summary>
public static readonly DependencyProperty QuestionTypeProperty = DependencyProperty.Register(
QuestionTypePropertyName,
typeof(string),
typeof(QuestionTemplateSelector), new PropertyMetadata(QuestionTypeChangedCallBack));
private static void QuestionTypeChangedCallBack(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine(string.Format("Old Value: {1}{0}New Value: {2}", " - ", e.OldValue, e.NewValue));
}
public QuestionTemplateSelector():base()
{
Loaded += new RoutedEventHandler(OnLoaded);
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
string questiontype = QuestionType;
Debug.WriteLine(sender);
if (questiontype == "Boolean")
{
Content = TemplateBoolean.LoadContent() as UIElement;
}
else if (questiontype == "Free Text")
{
Content = TemplateString.LoadContent() as UIElement;
}
else if (questiontype == "Single Multiple Choice")
{
Content = TemplateSingleMultipleChoice.LoadContent() as UIElement;
}
else if (questiontype == "Any Multiple Choice")
{
Content = TemplateAnyMultipleChoice.LoadContent() as UIElement;
}
else
{
Content = null;
}
}//onLoaded
}//QuestionTemplateSelector
I have a feeling it has to do with the onloaded. Where I really need code is in the Callback, but because its static I cant get access to the instance methods I need. How should I proceed? I can post more code if you need.
public QuestionTemplateSelector():base()
{
Loaded += new RoutedEventHandler(OnLoaded);
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
string questiontype = QuestionType;
Debug.WriteLine(sender);
if (questiontype == "Boolean")
{
Content = TemplateBoolean.LoadContent() as UIElement;
}
else if (questiontype == "Free Text")
{
Content = TemplateString.LoadContent() as UIElement;
}
else if (questiontype == "Single Multiple Choice")
{
Content = TemplateSingleMultipleChoice.LoadContent() as UIElement;
}
else if (questiontype == "Any Multiple Choice")
{
Content = TemplateAnyMultipleChoice.LoadContent() as UIElement;
}
else
{
Content = null;
}
}//onLoaded
I can verify that the code is actually changing in the callback, but the CLR property seems to never be updated.

This is how I got it working. But I am not sure this is absolutely correct.
public class QuestionTemplateSelector : UserControl
{
public DataTemplate TemplateString { get; set; }
public DataTemplate TemplateBoolean { get; set; }
public DataTemplate TemplateSingleMultipleChoice { get; set; }
public DataTemplate TemplateAnyMultipleChoice { get; set; }
/// <summary>
/// The <see cref="QuestionType" /> dependency property's name.
/// </summary>
public const string QuestionTypePropertyName = "QuestionType";
/// <summary>
/// Gets or sets the value of the <see cref="QuestionType" />
/// property. This is a dependency property.
/// </summary>
public Int64 QuestionType
{
get
{
return (Int64)GetValue(QuestionTypeProperty);
}
set
{
SetValue(QuestionTypeProperty, value);
}
}
/// <summary>
/// Identifies the <see cref="QuestionType" /> dependency property.
/// </summary>
public static readonly DependencyProperty QuestionTypeProperty;
private static void QuestionTypeChangedCallBack(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((QuestionTemplateSelector)obj).QuestionType = (Int64)e.NewValue;
OnLoaded(obj, (Int64)e.NewValue);
}
static QuestionTemplateSelector()
{
QuestionTypeProperty = DependencyProperty.Register(
"QuestionType",
typeof(Int64),
typeof(QuestionTemplateSelector), new PropertyMetadata(QuestionTypeChangedCallBack));
//Loaded += new RoutedEventHandler(OnLoaded);
}
private static void OnLoaded(DependencyObject obj, Int64 e)
{
Int64 questiontype = e;
if (questiontype == 1)
{
Debug.WriteLine("Boolean");
((QuestionTemplateSelector)obj).Content = ((QuestionTemplateSelector)obj).TemplateBoolean.LoadContent() as UIElement;
}
else if (questiontype == 2)
{
Debug.WriteLine("FreeText");
((QuestionTemplateSelector)obj).Content = ((QuestionTemplateSelector)obj).TemplateString.LoadContent() as UIElement;
}
else if (questiontype == 3)
{
Debug.WriteLine("Single Multiple Choice");
((QuestionTemplateSelector)obj).Content = ((QuestionTemplateSelector)obj).TemplateSingleMultipleChoice.LoadContent() as UIElement;
}
else if (questiontype == 4)
{
Debug.WriteLine("Any Multiple Choice");
((QuestionTemplateSelector)obj).Content = ((QuestionTemplateSelector)obj).TemplateAnyMultipleChoice.LoadContent() as UIElement;
}
else
{
Debug.WriteLine("NONE");
((QuestionTemplateSelector)obj).Content = null;
}
}//onLoaded
}//QuestionTemplateSelector

Related

WCF SOAP service give an error An error occurred while receiving the HTTP response to http://localhost/Service1.svc

when i make the client and call the getNews it goes into service but after the return its give me this error
System.ServiceModel.CommunicationException: 'An error occurred while receiving the HTTP response to http://localhost/Service1.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.'
Interface is :
[ServiceContract , XmlSerializerFormat]
public interface IService1
{
[OperationContract]
// string getNews(getNewsRequest request);
// GetNewsOutputStructure getNews (getNewsRequest request);
// getNewsResponseStructure getNews(getNewsRequest request);
getNewsResponse getNews();
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
the implementation is
public getNewsResponse getNews()
{
getNewsResponse response = null;
List<NewsListStructure> newsList = new List<NewsListStructure>();
NewsStructure news = null;
for (int i = 0; i < 2; i++)
{
news = new NewsStructure();
news.NewsText = "Test";
news.NewsId = "22";
news.NewsDate = DateTime.Now;
MediaExtentionsArrayStructure[] mediaExtentionsArrayStructures = null;
news.MediaExtentionsArrayObject = mediaExtentionsArrayStructures; //nnList[i].NewsDate;
news.NewsClassificationObject = new NewsClassificationStructure { NewsClassificationId = 1.ToString(), NewsClassificationDescription = "g" };
// news.MediaArrayObject = nnList[i].NewsDate;
NewsListStructure newsStructure = new NewsListStructure();
newsStructure.NewsObject = news;
newsList.Add(newsStructure);
}
// return newsList;
GetNewsOutputStructure getNewsOutputStructure = new GetNewsOutputStructure();
getNewsOutputStructure.NewsListObject = newsList.ToArray();
getNewsOutputStructure.ResponseStatus = ResponseStatusType.Success;
getNewsOutputStructure.DataSchemaVersion = 1;
getNewsOutputStructure.FaildReasonListObject = new FaildReasonListStructure[1] ;
var fdf = new ErrorStructure() { Item = "hh" , ItemElementName = ItemChoiceType.ErrorMessage};
getNewsOutputStructure.FaildReasonListObject[0] = new FaildReasonListStructure();
getNewsOutputStructure.FaildReasonListObject[0].Item = fdf;
// return getNewsOutputStructure;
getNewsResponseStructure getNewsResponseStructure = new getNewsResponseStructure();
getNewsResponseStructure.Item = getNewsOutputStructure;
// return getNewsResponseStructure;
// response = new getNewsResponse(getNewsResponseStructure);
response = new getNewsResponse();
response.getNewsResponseObject = getNewsResponseStructure;
response.getNewsResponseObject.Item = newsList;
return response;
}
after return response i got an error
and this is the object i will return
[DataContract]
public class getNewsResponse
{
// [System.ServiceModel.MessageBodyMemberAttribute()]
[XmlElement]
[DataMember]
public getNewsResponseStructure getNewsResponseObject;
public getNewsResponse()
{
}
public getNewsResponse(getNewsResponseStructure getNewsResponseObject)
{
this.getNewsResponseObject = getNewsResponseObject;
}
}
[DataContract]
public class getNewsResponseStructure
{
// [DataMember]
private object itemField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("getNewsResponseDetailObject", typeof(GetNewsOutputStructure))]
// [System.Xml.Serialization.XmlElementAttribute("ServiceError", typeof(CommonErrorStructure))]
[XmlElement]
[DataMember]
public object Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class GetNewsOutputStructure
{
private ResponseStatusType responseStatusField;
private NewsListStructure[] newsListObjectField;
private FaildReasonListStructure[] faildReasonListObjectField;
private decimal dataSchemaVersionField;
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[XmlElement]
/// <remarks/>
[DataMember]
public ResponseStatusType ResponseStatus
{
get
{
return this.responseStatusField;
}
set
{
this.responseStatusField = value;
}
}
[XmlElement]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("NewsListObject", Order = 1)]
[DataMember]
public NewsListStructure[] NewsListObject
{
get
{
return this.newsListObjectField;
}
set
{
this.newsListObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("FaildReasonListObject", Order = 2)]
[DataMember]
[XmlElement]
public FaildReasonListStructure[] FaildReasonListObject
{
get
{
return this.faildReasonListObjectField;
}
set
{
this.faildReasonListObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 3)]
[DataMember]
[XmlElement]
public decimal DataSchemaVersion
{
get
{
return this.dataSchemaVersionField;
}
set
{
this.dataSchemaVersionField = value;
}
}
}
[DataContract]
[Flags]
public enum ResponseStatusType
{
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
Success,
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
Fail,
}
[DataContract]
public partial class NewsListStructure
{
private NewsStructure newsObjectField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[XmlElement]
public NewsStructure NewsObject
{
get
{
return this.newsObjectField;
}
set
{
this.newsObjectField = value;
}
}
}
[DataContract]
public partial class FaildReasonListStructure
{
private ErrorStructure itemField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("ErrorObject", Order = 0)]
[XmlElement]
public ErrorStructure Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class ErrorStructure
{
private string itemField;
private ItemChoiceType itemElementNameField;
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("ErrorCode", typeof(string), Order = 0)]
// [System.Xml.Serialization.XmlElementAttribute("ErrorMessage", typeof(string), Order = 0)]
// [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
[DataMember]
[XmlElement]
public string Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
// [System.Xml.Serialization.XmlIgnoreAttribute()]
[XmlElement]
public ItemChoiceType ItemElementName
{
get
{
return this.itemElementNameField;
}
set
{
this.itemElementNameField = value;
}
}
}
[DataContract]
[Flags]
public enum ItemChoiceType
{
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
ErrorCode,
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
ErrorMessage,
}
[DataContract]
public partial class NewsStructure
{
private string newsIdField;
private NewsClassificationStructure newsClassificationObjectField;
private string newsTextField;
private MediaArrayStructure[] mediaArrayObjectField;
private MediaExtentionsArrayStructure[] mediaExtentionsArrayObjectField;
private System.DateTime newsDateField;
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[DataMember]
[XmlElement]
public string NewsId
{
get
{
return this.newsIdField;
}
set
{
this.newsIdField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
[DataMember]
[XmlElement]
public NewsClassificationStructure NewsClassificationObject
{
get
{
return this.newsClassificationObjectField;
}
set
{
this.newsClassificationObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 2)]
[DataMember]
[XmlElement]
public string NewsText
{
get
{
return this.newsTextField;
}
set
{
this.newsTextField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("MediaArrayObject", Order = 3)]
[DataMember]
[XmlElement]
public MediaArrayStructure[] MediaArrayObject
{
get
{
return this.mediaArrayObjectField;
}
set
{
this.mediaArrayObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("MediaExtentionsArrayObject", Order = 4)]
[DataMember]
[XmlElement]
public MediaExtentionsArrayStructure[] MediaExtentionsArrayObject
{
get
{
return this.mediaExtentionsArrayObjectField;
}
set
{
this.mediaExtentionsArrayObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(DataType = "date", Order = 5)]
[DataMember]
[XmlElement]
public System.DateTime NewsDate
{
get
{
return this.newsDateField;
}
set
{
this.newsDateField = value;
}
}
}
[DataContract]
public partial class MediaExtentionsArrayStructure
{
private string itemField;
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("MediaExtentions", Order = 0)]
[DataMember]
[XmlElement]
public string Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class MediaArrayStructure
{
private byte[] itemField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("Media", DataType = "base64Binary", Order = 0)]
[XmlElement]
public byte[] Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class NewsClassificationStructure
{
private string newsClassificationIdField;
private string newsClassificationDescriptionField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[XmlElement]
public string NewsClassificationId
{
get
{
return this.newsClassificationIdField;
}
set
{
this.newsClassificationIdField = value;
}
}
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
[XmlElement]
public string NewsClassificationDescription
{
get
{
return this.newsClassificationDescriptionField;
}
set
{
this.newsClassificationDescriptionField = value;
}
}
}
//[System.Diagnostics.DebuggerStepThroughAttribute()]
//[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
//[System.Xml.Serialization.XmlSchemaProviderAttribute("ExportSchema")]
//[System.Xml.Serialization.XmlRootAttribute]
[DataContract]
public partial class CommonErrorStructure : object, System.Xml.Serialization.IXmlSerializable
{
private System.Xml.XmlNode[] nodesField;
private static System.Xml.XmlQualifiedName typeName = new System.Xml.XmlQualifiedName();
[DataMember]
[XmlElement]
public System.Xml.XmlNode[] Nodes
{
get
{
return this.nodesField;
}
set
{
this.nodesField = value;
}
}
public void ReadXml(System.Xml.XmlReader reader)
{
this.nodesField = System.Runtime.Serialization.XmlSerializableServices.ReadNodes(reader);
}
public void WriteXml(System.Xml.XmlWriter writer)
{
System.Runtime.Serialization.XmlSerializableServices.WriteNodes(writer, this.Nodes);
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public static System.Xml.XmlQualifiedName ExportSchema(System.Xml.Schema.XmlSchemaSet schemas)
{
System.Runtime.Serialization.XmlSerializableServices.AddDefaultSchema(schemas, typeName);
return typeName;
}
}
client code is
ServiceReference2.Service1Client client = new ServiceReference2.Service1Client();
ServiceReference2.getNewsRequest k = new ServiceReference2.getNewsRequest();
k.getNewsRequestObject = new ServiceReference2.GetNewsRequestStructure();
k.getNewsRequestObject.LastReceivedNewsItemId = "10000";
k.getNewsRequestObject.NumberOfRequestedNews = "5";
k.getNewsRequestObject.ServiceToken = "";
k.getNewsRequestObject.SPAGovernmentSectorKey = "";
k.getNewsRequestObject.SubServiceObject = new ServiceReference2.SubServicesStructure { SubServiceId = "1", SubServiceDescription = "desc" };
k.getNewsRequestObject.TypeOfData = ServiceReference2.TypeOfDataType.All;
k.yefiSOAPHeaderElement = new ServiceReference2.YefiHeader();
k.yefiSOAPHeaderElement.ServiceID = "1";
k.yefiSOAPHeaderElement.SourceID = "2";
k.yefiSOAPHeaderElement.SourceName = "genral";
var t = client.getNews( k);
// Always close the client.
client.Close();
This is because you pass List<NewsListStructure> to response.getNewsResponseObject.Item. According to the definition of your class, response.getNewsResponseObject.Item can only accept Object type, not List<Object> type.
There are two solutions. The first is to modify the getNewsResponseStructure class, as shown below:
public class getNewsResponseStructure
{
// [DataMember]
private List<Object> itemField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("getNewsResponseDetailObject", typeof(GetNewsOutputStructure))]
// [System.Xml.Serialization.XmlElementAttribute("ServiceError", typeof(CommonErrorStructure))]
[XmlElement]
[DataMember]
public List<Object> Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
The second is to create NewsListStructure and pass it to response.getNewsResponseObject.Item:
NewsListStructure news = new NewsListStructure();
response.getNewsResponseObject.Item = news;
the problem was in my Client i tried to sent a diffrent type of object that i cast it in the service
this the wrong
response.getNewsResponseObject.Item = newsList;
this is true
response.getNewsResponseObject.Item = getNewsOutputStructure;
becouse in service i told it i will sent to you an
GetNewsOutputStructure object not List<NewsListObject>
in service
[System.Xml.Serialization.XmlElementAttribute("getNewsResponseDetailObject", typeof(GetNewsOutputStructure), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]

custom file validation for .net core 2.0

I am trying to make a custom file validation for my project which is based on .net core 2.
I want to validate file size and also file extension in order to prevent users from uploading large files and for example .png files.
I have searched a lot but I could not find anything that works.
Here is my file validation class :
public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
{
private const int MaxSize = 1048576;
private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
private IEnumerable<string> _ValidTypes { get; set; }
public string ValidTypes { get; set; }
public string ErrorMessageExtension { get; set; }
public string ErrorMessageSize { get; set; }
public FileTypeAttribute(string errorExtension, string errorSize, string vt)
{
ErrorMessageExtension = errorExtension;
ErrorMessageSize = errorSize;
_ValidTypes = vt.Split(',');
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IFormFile file = value as IFormFile;
if (file != null)
{
if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
{
return new ValidationResult(ErrorMessageExtension);
}
if (file.Length > MaxSize)
{
return new ValidationResult(ErrorMessageSize);
}
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
}
private bool MergeAttribute(
IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
and here is the javascript code in my view:
$.validator.addMethod("FileType",
function (value, element, param) {
for (var i = 0; i < element.files.length; i++) {
var extension = getFileExtension(element.files[0].name);
if ($.inArray(extension, param.validtypes) === -1) {
return false;
}
}
return true;
});
$.validator.unobtrusive.adapters.add('FileType', ['validtypes'], function (options) {
console.log("value:");
options.rules.cannotbered = {};
options.messages["FileType"] = options.message;
});
function getFileExtension(fileName) {
if (/[.]/.exec(fileName)) {
return /[^.]+$/.exec(fileName)[0].toLowerCase();
}
return null;
}
and here is the entity class code in my project:
public class MyEntityClass
{
public int MyEntityClassId { get; set; }
[FileType("invalid format", "invalid size", "jpg,png,gif")]
public IFormFile Photo { get; set; }
}
Can anyone help me to know where the problem is?
Thanks in advance.

xamarin.forms binding to class property not working

In my XamarinForms project I am trying to bind a label text to a property of a class. when I pass in the object to my view the label is not being populated. can someone see what I am doing wrong?
In my view model I have
class ManagerLevelPageViewModel : INotifyPropertyChanged
{
private UserSelections _MyUserSelections;
public UserSelections MyUserSelections
{
get { return _MyUserSelections; }
set {
_MyUserSelections = value;
NotifyPropertyChanged();
}
}
public ManagerLevelPageViewModel(UserSelections _temp)
{
MyUserSelections = _temp;
MyUserSelections.selectedClientName = _temp.selectedClientName;
//myUserSelections = _myUserSelections;
//SetValues();
}
here is the class
public class UserSelections
{
public int selectedClientId { get; set; }
public string selectedClientName { get; set; }
public string selectedClientShortCode { get; set; }
public decimal selectedClientPL { get; set; }
public string TopdayIdentifier { get; set; }
}
here is the view.cs
ManagerLevelPageViewModel vm;
public ManagerLevelPage (UserSelections _myUserSelections)
{
vm = new ManagerLevelPageViewModel(_myUserSelections);
InitializeComponent ();
BindingContext = vm;
DownloadData();
}
lastly here is the xaml
<Label Text="{Binding MyUserSelections.ClientName}"/>
notify property changed
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

Windows Phone 8.1 RT view not updating (MVVM)

I'm designing a profile page for users where they can edit their personal info. I'm using a PersonViewModel (which contains the current signed in person) to display the current info about the User. The fields to edit the user's info are bound to a validation model. After pressing the 'execute changes' button and I get a response of the server (HTTPStatusCode Ok + the altered user object), I alter the fields of the existing object according to the changes. Then I used setter injection to update my PersonViewModel... When debugging, I can see that my objects are all up-to-date but my view is still displaying the old info... What am I doing wrong?`
This is the code that get's executed when I press the button to execute my changes:
private async void ChangeInfoButton(object sender, RoutedEventArgs e)
{
User user;
List<ErrorInfo> errors;
if (_profileInformationValidationModel.TryGetUser(out user, out errors))
{
var response = await Session.Instance.DataProvider.UpdaterUserInfo(user);
if (response.IsSuccess)
{
/*SignedInUserInfo = AlteredUserInfo*/
Session.Instance.User.Information = user.Information;
_personViewModel.SetPerson(user.Information);
var d1 = new MessageDialog("Uw gegevens werden succesvol gewijzigd.");
d1.ShowAsync();
AnnulInfoButton(sender, e);
}
`
And this is the PersonViewModel:
public class PersonViewModel
{
private Person _person;
public void SetPerson(Person p)
{
_person = p;
}
public PersonViewModel(Person person)
{
_person = person;
}
public string Street
{
get { return _person.Street; }
}
public string HouseNumber
{
get { return _person.HouseNumber; }
}
public string Bus
{
get { return _person.Bus; }
}
public string Email
{
get { return _person.Email; }
}
Your view model should implement the INotifyPropertyChanged interface.
Look into using a framework like MVVM Light which does most of this work for you.
You can add it to your project using NuGet.
This is how your model and view-model should look:
public class Person
{
public string Street { get; set; }
public string HouseNumber { get; set; }
public string Bus { get; set; }
public string Email { get; set; }
}
public class PersonViewModel : System.ComponentModel.INotifyPropertyChanged
{
private Person _person;
public void SetPerson(Person person)
{
_person = person;
Street = person.Street;
HouseNumber = person.HouseNumber;
Bus = person.Bus;
Email = person.Email;
}
public PersonViewModel(Person person)
{
SetPerson(person);
}
#region Street (INotifyPropertyChanged Property)
private string _street;
public string Street
{
get { return _street; }
set
{
if (_street != value)
{
_street = value;
RaisePropertyChanged("Street");
}
}
}
#endregion
#region HouseNumber (INotifyPropertyChanged Property)
private string _houseNumber;
public string HouseNumber
{
get { return _houseNumber; }
set
{
if (_houseNumber != value)
{
_houseNumber = value;
RaisePropertyChanged("HouseNumber");
}
}
}
#endregion
#region Bus (INotifyPropertyChanged Property)
private string _bus;
public string Bus
{
get { return _bus; }
set
{
if (_bus != value)
{
_bus = value;
RaisePropertyChanged("Bus");
}
}
}
#endregion
#region Email (INotifyPropertyChanged Property)
private string _email;
public string Email
{
get { return _email; }
set
{
if (_email != value)
{
_email = value;
RaisePropertyChanged("Email");
}
}
}
#endregion
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string p)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(p));
}
}
}

MVC RequiredIf Attribute - IsValid value parameter always null

I am implementing a RequiredIf validation attribute and the value being passed to the IsValid method is always null.
RequiredIfAttribute Class
public class RequiredIfAttribute : ValidationAttribute
{
private RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override bool IsValid(object value)
{
return innerAttribute.IsValid(value);
}
}
ViewModel
[Required]
[Display(Name = "Are You A Student?")]
public bool? IsStudent { get; set; }
[RequiredIf("IsStudent", true, ErrorMessage = "You must upload a photo of your student ID if you wish to register as a student.")]
[Display(Name = "Student ID")]
[FileExtensions("jpg|jpeg|png|pdf", ErrorMessage = "File is not in the correct format.")]
[MaxFileSize(2 * 1024 * 1024, ErrorMessage = "You may not upload files larger than 2 MB.")]
public HttpPostedFileBase StudentId { get; set; }
EditorTemplate
#model bool?
#using System.Web.Mvc;
#{
var options = new List<SelectListItem>
{
new SelectListItem { Text = "Yes", Value = "true", Selected = Model.HasValue && Model.Value },
new SelectListItem { Text = "No", Value = "false", Selected = Model.HasValue && Model.Value }
};
string defaultOption = null;
if (ViewData.ModelMetadata.IsNullableValueType)
{
defaultOption = "(Select)";
}
}
#Html.DropDownListFor(m => m, options, defaultOption)
Every time the form is submitted, the RequiredIf error message is thrown and I have a feeling it has to do with the null value I described initially. What am I doing wrong? Thanks!
NOTE: The HTML appears to be rendering properly, so I don't think that's the problem.
<select data-val="true" data-val-required="The Are You A Student? field is required." id="IsStudent" name="IsStudent"><option value="">(Select)</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
Because this is your code -
public class RequiredIfAttribute : ValidationAttribute
{
private RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override bool IsValid(object value)
{
return innerAttribute.IsValid(value);
}
}
You are using a RequriedAtrribute. So to simulate that it behaves life a RequiredIf you have to implement some logic that will check whether the target property value is true or false. But you are not doing that and returning just from the innerattribute. So it is just a mere Required not RequiredIf -
public override bool IsValid(object value)
{
return innerAttribute.IsValid(value);
}
modify this function to do some checking like -
public override bool IsValid(object value)
{
//if the referred property is true then
return innerAttribute.IsValid(value);
//else
return True
}
I use the following code:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class StefAttribute : ValidationAttribute
{
public WDCIAttribute()
: base()
{
this.ErrorMessageResourceType = typeof(GlobalResources);
}
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class StefRequiredIfAttribute : StefAttribute
{
private RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public WDCIRequiredIfAttribute()
{
}
public WDCIRequiredIfAttribute(string dependentProperty, object targetValue)
: base()
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override bool IsValid(object value)
{
return innerAttribute.IsValid(value);
}
}
public class RequiredIfValidator : DataAnnotationsModelValidator<StefRequiredIfAttribute>
{
public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, StefRequiredIfAttribute attribute)
: base(metadata, context, attribute)
{
}
public override IEnumerable<ModelValidationResult> Validate(object container)
{
// get a reference to the property this validation depends upon
var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);
if (field != null)
{
// get the value of the dependent property
object value = field.GetValue(container, null);
// compare the value against the target value
if (IsEqual(value) || (value == null && Attribute.TargetValue == null))
{
// match => means we should try validating this field
if (!Attribute.IsValid(Metadata.Model))
{
// validation failed - return an error
yield return new ModelValidationResult { Message = ErrorMessage };
}
}
}
}
private bool IsEqual(object dependentPropertyValue)
{
bool isEqual = false;
if (Attribute.TargetValue != null && Attribute.TargetValue.GetType().IsArray)
{
foreach (object o in (Array)Attribute.TargetValue)
{
isEqual = o.Equals(dependentPropertyValue);
if (isEqual)
{
break;
}
}
}
else
{
if (Attribute.TargetValue != null)
{
isEqual = Attribute.TargetValue.Equals(dependentPropertyValue);
}
}
return isEqual;
}
}
Which can be used in the model as follows:
public class PersonnelVM : EntityVM
{
// . . .
[DisplayName("Name")]
[StefRequiredIf("IndividualOrBulk", PersonnelType.Bulk, ErrorMessageResourceName = GlobalResourceLiterals.Name_Required)]
public string Name { get; set; }
[DisplayName("PersonnelType")]
public PersonnelType IndividualOrBulk { get; set; }
// . . .
}