Search Results

Search found 255 results on 11 pages for 'propertyname'.

Page 1/11 | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • How to get the PropertyName of a class?

    - by Mike108
    How to get the PropertyName of a class? For example, How can I get the PropertyName "StudentName" of a Student class instance. public class Student { public string StudentName{get;set;} } Student student = new Student(); //I want to get the PropertyName "StudentName" student.StudentName.GetName();

    Read the article

  • Binding PropertyName of CollectionViewSource SortDescription in Xaml

    - by Faisal
    Here is my xaml that tells the collectionviewsource sort property name. <CollectionViewSource Source="{Binding Contacts}" x:Key="contactsCollection" Filter="CollectionViewSource_Filter"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="DisplayName" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource> The xaml above works fine but problem I have is that I don't know how to give a variable value to SortDescription PropertyName. I have a property in my viewmodel that tells which property to sort on but I am not able to bind this property to SortDescription's PropertyName field. Is there any way?

    Read the article

  • Calling Property Methods from the e.PropertyName property

    - by user275561
    void TheSettings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { var settings = IsolatedStorageSettings.ApplicationSettings[StorageSettings] as Dictionary<string, string>; settings[e.PropertyName]= //call the method that has the same property name to get what the value is LoadData(); } Here is What I am trying to do. This is for a Windows Phone 7 series App. I am trying to determine what values got changed when the user changes the settings on the settings page and just save that.

    Read the article

  • Deserializing JSON data to C# using JSON.NET

    - by Derek Utah
    I'm relatively new to working with C# and JSON data and am seeking guidance. I'm using C# 3.0, with .NET3.5SP1, and JSON.NET 3.5r6. I have a defined C# class that I need to populate from a JSON structure. However, not every JSON structure for an entry that is retrieved from the web service contains all possible attributes that are defined within the C# class. I've been being doing what seems to be the wrong, hard way and just picking out each value one by one from the JObject and transforming the string into the desired class property. JsonSerializer serializer = new JsonSerializer(); var o = (JObject)serializer.Deserialize(myjsondata); MyAccount.EmployeeID = (string)o["employeeid"][0]; What is the best way to deserialize a JSON structure into the C# class and handling possible missing data from the JSON source? My class is defined as: public class MyAccount { [JsonProperty(PropertyName = "username")] public string UserID { get; set; } [JsonProperty(PropertyName = "givenname")] public string GivenName { get; set; } [JsonProperty(PropertyName = "sn")] public string Surname { get; set; } [JsonProperty(PropertyName = "passwordexpired")] public DateTime PasswordExpire { get; set; } [JsonProperty(PropertyName = "primaryaffiliation")] public string PrimaryAffiliation { get; set; } [JsonProperty(PropertyName = "affiliation")] public string[] Affiliation { get; set; } [JsonProperty(PropertyName = "affiliationstatus")] public string AffiliationStatus { get; set; } [JsonProperty(PropertyName = "affiliationmodifytimestamp")] public DateTime AffiliationLastModified { get; set; } [JsonProperty(PropertyName = "employeeid")] public string EmployeeID { get; set; } [JsonProperty(PropertyName = "accountstatus")] public string AccountStatus { get; set; } [JsonProperty(PropertyName = "accountstatusexpiration")] public DateTime AccountStatusExpiration { get; set; } [JsonProperty(PropertyName = "accountstatusexpmaxdate")] public DateTime AccountStatusExpirationMaxDate { get; set; } [JsonProperty(PropertyName = "accountstatusmodifytimestamp")] public DateTime AccountStatusModified { get; set; } [JsonProperty(PropertyName = "accountstatusexpnotice")] public string AccountStatusExpNotice { get; set; } [JsonProperty(PropertyName = "accountstatusmodifiedby")] public Dictionary<DateTime, string> AccountStatusModifiedBy { get; set; } [JsonProperty(PropertyName = "entrycreatedate")] public DateTime EntryCreatedate { get; set; } [JsonProperty(PropertyName = "entrydeactivationdate")] public DateTime EntryDeactivationDate { get; set; } } And a sample of the JSON to parse is: { "givenname": [ "Robert" ], "passwordexpired": "20091031041550Z", "accountstatus": [ "active" ], "accountstatusexpiration": [ "20100612000000Z" ], "accountstatusexpmaxdate": [ "20110410000000Z" ], "accountstatusmodifiedby": { "20100214173242Z": "tdecker", "20100304003242Z": "jsmith", "20100324103242Z": "jsmith", "20100325000005Z": "rjones", "20100326210634Z": "jsmith", "20100326211130Z": "jsmith" }, "accountstatusmodifytimestamp": [ "20100312001213Z" ], "affiliation": [ "Employee", "Contractor", "Staff" ], "affiliationmodifytimestamp": [ "20100312001213Z" ], "affiliationstatus": [ "detached" ], "entrycreatedate": [ "20000922072747Z" ], "username": [ "rjohnson" ], "primaryaffiliation": [ "Staff" ], "employeeid": [ "999777666" ], "sn": [ "Johnson" ] }

    Read the article

  • Console Hangs when Attempting to Deploy Software Updates

    - by JCardenas
    When in the SCCM 2012 console under Software Updates, I click Deploy on a Software Update Group and the console hangs indefinitely. It just stops; I click away and back and Windows does not recognize that the console has stopped responding. I end up having to kill the console through Task Manager. I have left the console for hours and it never becomes responsive again. I have tried removing and reinstalling the SUP, without success. Server reboots do not help, either. The issue with the console occurs both on my desktop, and directly on the site server itself. Any ideas? I've checked server logs and found nothing that would be indicative of a problem. Update: I managed to find something from the SMSAdminUI.log file: [1, PID:820][10/12/2012 08:59:26] :Disposed ResultObject was passed to update delegate, ignoring but refresh operation may not complete correctly [14, PID:820][10/12/2012 13:53:57] :System.Management.ManagementException\r\nNot found \r\n at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) at System.Management.ManagementObject.Initialize(Boolean getObject) at System.Management.ManagementBaseObject.get_wbemObject() at System.Management.PropertyData.RefreshPropertyInfo() at System.Management.PropertyDataCollection.get_Item(String propertyName) at System.Management.ManagementBaseObject.GetPropertyValue(String propertyName) at System.Management.ManagementBaseObject.get_Item(String propertyName) at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager.GetInstance(String objectPath)\r\nManagementException details: instance of __ExtendedStatus { Operation = "GetObject"; ParameterInfo = "SMS_PackageToContent.ContentID=16794374,PackageID=\"CA100065\""; ProviderName = "WinMgmt"; }; \r\n [14, PID:820][10/12/2012 13:53:57] :(SMS_PackageToContent.ContentID=16794374,PackageID='CA100065') does not exist or its IsContentValid returns false. We will (re)download this content. [14, PID:820][10/12/2012 13:54:01] :Successfully validated or downloaded update fcadb0ea-90ce-4aad-bc95-192450f05211! [14, PID:820][10/12/2012 13:54:02] :System.Management.ManagementException\r\nNot found \r\n at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) at System.Management.ManagementObject.Initialize(Boolean getObject) at System.Management.ManagementBaseObject.get_wbemObject() at System.Management.PropertyData.RefreshPropertyInfo() at System.Management.PropertyDataCollection.get_Item(String propertyName) at System.Management.ManagementBaseObject.GetPropertyValue(String propertyName) at System.Management.ManagementBaseObject.get_Item(String propertyName) at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager.GetInstance(String objectPath)\r\nManagementException details: instance of __ExtendedStatus { Operation = "GetObject"; ParameterInfo = "SMS_PackageToContent.ContentID=16787459,PackageID=\"CA100065\""; ProviderName = "WinMgmt"; }; \r\n [14, PID:820][10/12/2012 13:54:02] :(SMS_PackageToContent.ContentID=16787459,PackageID='CA100065') does not exist or its IsContentValid returns false. We will (re)download this content. [14, PID:820][10/12/2012 13:54:03] :Successfully validated or downloaded update eec264ac-fbc7-4cc4-891b-7cc6ab5bfe0e! [14, PID:820][10/12/2012 13:54:03] :System.Management.ManagementException\r\nNot found \r\n at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) at System.Management.ManagementObject.Initialize(Boolean getObject) at System.Management.ManagementBaseObject.get_wbemObject() at System.Management.PropertyData.RefreshPropertyInfo() at System.Management.PropertyDataCollection.get_Item(String propertyName) at System.Management.ManagementBaseObject.GetPropertyValue(String propertyName) at System.Management.ManagementBaseObject.get_Item(String propertyName) at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager.GetInstance(String objectPath)\r\nManagementException details: instance of __ExtendedStatus { Operation = "GetObject"; ParameterInfo = "SMS_PackageToContent.ContentID=16784547,PackageID=\"CA100065\""; ProviderName = "WinMgmt"; }; \r\n [14, PID:820][10/12/2012 13:54:03] :(SMS_PackageToContent.ContentID=16784547,PackageID='CA100065') does not exist or its IsContentValid returns false. We will (re)download this content. [14, PID:820][10/12/2012 13:54:05] :Successfully validated or downloaded update 8d780338-eec1-4d31-b1cd-6187400c02f3! [14, PID:820][10/12/2012 13:54:05] :System.Management.ManagementException\r\nNot found \r\n at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) at System.Management.ManagementObject.Initialize(Boolean getObject) at System.Management.ManagementBaseObject.get_wbemObject() at System.Management.PropertyData.RefreshPropertyInfo() at System.Management.PropertyDataCollection.get_Item(String propertyName) at System.Management.ManagementBaseObject.GetPropertyValue(String propertyName) at System.Management.ManagementBaseObject.get_Item(String propertyName) at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager.GetInstance(String objectPath)\r\nManagementException details: instance of __ExtendedStatus { Operation = "GetObject"; ParameterInfo = "SMS_PackageToContent.ContentID=16787423,PackageID=\"CA100065\""; ProviderName = "WinMgmt"; }; \r\n [14, PID:820][10/12/2012 13:54:05] :(SMS_PackageToContent.ContentID=16787423,PackageID='CA100065') does not exist or its IsContentValid returns false. We will (re)download this content.

    Read the article

  • Why is Html.DropDownList() producing <select name="original_name.name"> instead of just <select name

    - by DanM
    I have an editor template whose job is to take a SelectList as its model and build a select element in html using the Html.DropDownList() helper extension. I'm trying to assign the name attribute for the select based on a ModelMetadata property. (Reason: on post-back, I need to bind to an object that has a different property name for this item than the ViewModel used to populate the form.) The problem I'm running into is that DropDownList() is appending the name I'm providing instead of replacing it, so I end up with names like categories.category instead of category. Here is some code for you to look at... SelectList.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.Mvc.SelectList>" %> <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model) %> Resulting HTML <select id="SkillLevels_SkillLevel" name="SkillLevels.SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Expected HTML <select id="SkillLevels_SkillLevel" name="SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Also tried <%= Html.Encode((string)ViewData.ModelMetadata.AdditionalValues["PropertyName"])%> ...which resulted in "SkillLevel" (not "SkillLevels.SkillLevel"), proving that the data stored in metadata is correct. and <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model, new { name = (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"] }) %> ...which still resulted in <select name=SkillLevels.Skilllevel>. Questions What's going on here? Why does it append the name instead of just using it? Can you suggest a good workaround? Update: I ended up writing a helper extension that literally does a find/replace on the html text: public static MvcHtmlString BindableDropDownListForModel(this HtmlHelper helper) { var propertyName = (string)helper.ViewData.ModelMetadata.AdditionalValues["PropertyName"]; var compositeName = helper.ViewData.ModelMetadata.PropertyName + "." + propertyName; var rawHtml = helper.DropDownList(propertyName, (SelectList)helper.ViewData.Model); var bindableHtml = rawHtml.ToString().Replace(compositeName, propertyName); return MvcHtmlString.Create(bindableHtml); }

    Read the article

  • ASP.NET MVC localization DisplayNameAttribute alternatives: a better way

    - by Brian Schroer
    In my last post, I talked bout creating a custom class inheriting from System.ComponentModel.DisplayNameAttribute to retrieve display names from resource files: [LocalizedDisplayName("RememberMe")] public bool RememberMe { get; set; } That’s a lot of work to put an attribute on all of my model properties though. It would be nice if I could intercept the ASP.NET MVC code that analyzes the model metadata to retrieve display names to make it automatically get localized text from my resource files. That way, I could just set up resource file entries where the keys are the property names, and not have to put attributes on all of my properties. That’s done by creating a custom class inheriting from System.Web.Mvc.DataAnnotationsModelMetadataProvider: 1: public class LocalizedDataAnnotationsModelMetadataProvider : 2: DataAnnotationsModelMetadataProvider 3: { 4: protected override ModelMetadata CreateMetadata( 5: IEnumerable<Attribute> attributes, 6: Type containerType, 7: Func<object> modelAccessor, 8: Type modelType, 9: string propertyName) 10: { 11: var meta = base.CreateMetadata 12: (attributes, containerType, modelAccessor, modelType, propertyName); 13:   14: if (string.IsNullOrEmpty(propertyName)) 15: return meta; 16:   17: if (meta.DisplayName == null) 18: GetLocalizedDisplayName(meta, propertyName); 19:   20: if (string.IsNullOrEmpty(meta.DisplayName)) 21: meta.DisplayName = string.Format("[[{0}]]", propertyName); 22:   23: return meta; 24: } 25:   26: private static void GetLocalizedDisplayName(ModelMetadata meta, string propertyName) 27: { 28: ResourceManager resourceManager = MyResource.ResourceManager; 29: CultureInfo culture = Thread.CurrentThread.CurrentUICulture; 30:   31: meta.DisplayName = resourceManager.GetString(propertyName, culture); 32: } 33: } Line 11 calls the base CreateMetadata method. Line 17 checks whether the metadata DisplayName property has already been populated by a DisplayNameAttribute (or my LocalizedDisplayNameAttribute). If so, it respects that and doesn’t use my custom localized text lookup. The GetLocalizedDisplayName method checks for the property name as a resource file key. If found, it uses the localized text from the resource files. If the key is not found in the resource file, as with my LocalizedDisplayNameAttribute, I return a formatted string containing the property name (e.g. “[[RememberMe]]”) so I can tell by looking at my web pages which resource keys I haven’t defined yet. It’s hooked up with this code in the Application_Start method of Global.asax: ModelMetadataProviders.Current = new LocalizedDataAnnotationsModelMetadataProvider();

    Read the article

  • NHibernate.QueryException with dynamic-component

    - by Ken
    OK, this is going to be kind of a long shot, since it's a big system (which I don't claim to fully understand, yet), and the problem might not be with NHibernate itself, and I'm even having trouble reproducing it, but... I've got a class with a <dynamic-component section, and when I run a query on it (through my ASP.NET MVC app), it fails, but only sometimes. (Yeah, the worst kind!) The exception I'm seeing is: NHibernate.QueryException: could not resolve property: Attributes.MyAttributeName of: MyClassName at NHibernate.Persister.Entity.AbstractPropertyMapping.GetColumns(String propertyName) at NHibernate.Persister.Entity.AbstractPropertyMapping.ToColumns(String alias, String propertyName) at NHibernate.Persister.Entity.BasicEntityPropertyMapping.ToColumns(String alias, String propertyName) at NHibernate.Persister.Entity.AbstractEntityPersister.ToColumns(String alias, String propertyName) at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumns(String propertyName, ICriteria subcriteria) at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumnsUsingProjection(ICriteria subcriteria, String propertyName) at NHibernate.Criterion.CriterionUtil.GetColumnNamesUsingPropertyName(ICriteriaQuery criteriaQuery, ICriteria criteria, String propertyName, Object value, ICriterion critertion) at NHibernate.Criterion.CriterionUtil.GetColumnNamesForSimpleExpression(String propertyName, IProjection projection, ICriteriaQuery criteriaQuery, ICriteria criteria, IDictionary`2 enabledFilters, ICriterion criterion, Object value) at NHibernate.Criterion.SimpleExpression.ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary`2 enabledFilters) at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetWhereCondition(IDictionary`2 enabledFilters) at NHibernate.Loader.Criteria.CriteriaJoinWalker..ctor(IOuterJoinLoadable persister, CriteriaQueryTranslator translator, ISessionFactoryImplementor factory, CriteriaImpl criteria, String rootEntityName, IDictionary`2 enabledFilters) at NHibernate.Loader.Criteria.CriteriaLoader..ctor(IOuterJoinLoadable persister, ISessionFactoryImplementor factory, CriteriaImpl rootCriteria, String rootEntityName, IDictionary`2 enabledFilters) at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) at NHibernate.Impl.CriteriaImpl.List(IList results) at NHibernate.Impl.CriteriaImpl.UniqueResult[T]() ...my code below here... Can anybody explain exactly what this QueryException means, i.e., so I can have an idea of what exactly it thinks is going wrong? Thanks!

    Read the article

  • VS2010's "Public Property <PropertyName> As <DataType> vs. Public var

    - by Velika2
    In VS2008, I used to type Public Property <PropName> As <dataType> and hit the Enter key and the IDE editor would automatically expand it out to a full blown property block. Now, from what I understand, a new feature of 2010 is that the compiler automatically "expands" the short syntax above into the same IL code that you would get with the full property GET AND SET sub methods that were are accustomed to seeing before in the editor. But functionality, how the heck is this any different than just having a Public class level variable? If the only diff is what it compiles to and if otehrwise there is no functional difference, isn't the new way less efficient than the old since it involves more code than just having a class level memory variable? Public as I thought that if you weren't going to have code behind your properties that they were essentially the same. I guess the diffrenece is that they just added the keyword "Property" but functionality, their is no diff, eh?

    Read the article

  • Generic IEqualityComparer

    - by Nettuce
    A generic equality comparer that takes a property expression or a comparison Func public class GenericComparer<T> : IEqualityComparer<T> where T : class         {             private readonly Func<T, T, bool> comparerExpression;             private readonly string propertyName;             public GenericComparer(Func<T, T, bool> comparerExpression)             {                 this.comparerExpression = comparerExpression;             }             public GenericComparer(Expression<Func<T, object>> propertyExpression)             {                 propertyName = (propertyExpression.Body is UnaryExpression ? (MemberExpression)((UnaryExpression)propertyExpression.Body).Operand : (MemberExpression)propertyExpression.Body).Member.Name;             }             public bool Equals(T x, T y)             {                 return comparerExpression == null ? x.GetType().GetProperty(propertyName).GetValue(x, null).Equals(y.GetType().GetProperty(propertyName).GetValue(y, null)) : comparerExpression.Invoke(x, y);             }             public int GetHashCode(T obj)             {                 return obj.ToString().GetHashCode();             }         }

    Read the article

  • Lists NotifyPropertyChanging

    - by Carlo
    Well BindingList and ObservableCollection work great to keep data updated and to notify when one of it's objects has changed. However, when notifying a property is about to change, I think these options are not very good. What I have to do right now to solve this (and I warn this is not elegant AT ALL), is to implement INotifyPropertyChanging on the list's type object and then tie that to the object that holds the list PropertyChanging event, or something like the following: // this object will be the type of the BindingList public class SomeObject : INotifyPropertyChanging, INotifyPropertyChanged { private int _intProperty = 0; private string _strProperty = String.Empty; public int IntProperty { get { return this._intProperty; } set { if (this._intProperty != value) { NotifyPropertyChanging("IntProperty"); this._intProperty = value; NotifyPropertyChanged("IntProperty"); } } } public string StrProperty { get { return this._strProperty; } set { if (this._strProperty != value) { NotifyPropertyChanging("StrProperty"); this._strProperty = value; NotifyPropertyChanged("StrProperty"); } } } #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion public void NotifyPropertyChanging(string propertyName) { if (this.PropertyChanging != null) PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } public void NotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public class ObjectThatHoldsTheList : INotifyPropertyChanging, INotifyPropertyChanged { public BindingList<SomeObject> BindingList { get; set; } public ObjectThatHoldsTheList() { this.BindingList = new BindingList<SomeObject>(); } // this helps notifie Changing and Changed on Add private void AddItem(SomeObject someObject) { // this will tie the PropertyChanging and PropertyChanged events of SomeObject to this object // so it gets notifies because the BindingList does not notify PropertyCHANGING someObject.PropertyChanging += new PropertyChangingEventHandler(someObject_PropertyChanging); someObject.PropertyChanged += new PropertyChangedEventHandler(someObject_PropertyChanged); this.NotifyPropertyChanging("BindingList"); this.BindingList.Add(someObject); this.NotifyPropertyChanged("BindingList"); } // this helps notifies Changing and Changed on Delete private void DeleteItem(SomeObject someObject) { if (this.BindingList.IndexOf(someObject) > 0) { // this unlinks the handlers so the garbage collector can clear the objects someObject.PropertyChanging -= new PropertyChangingEventHandler(someObject_PropertyChanging); someObject.PropertyChanged -= new PropertyChangedEventHandler(someObject_PropertyChanged); } this.NotifyPropertyChanging("BindingList"); this.BindingList.Remove(someObject); this.NotifyPropertyChanged("BindingList"); } // this notifies an item in the list is about to change void someObject_PropertyChanging(object sender, PropertyChangingEventArgs e) { NotifyPropertyChanging("BindingList." + e.PropertyName); } // this notifies an item in the list has changed void someObject_PropertyChanged(object sender, PropertyChangedEventArgs e) { NotifyPropertyChanged("BindingList." + e.PropertyName); } #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion public void NotifyPropertyChanging(string propertyName) { if (this.PropertyChanging != null) PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } public void NotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } Sorry, I know this is a lot of code, which takes me back to my main point IT'S A LOT OF CODE to implement this. So my question is, does anyone know a better, shorter, more elegant solution? Thanks for your time and suggestions.

    Read the article

  • Implementing INotifyPropertyChanged with PostSharp 1.5

    - by no9
    Hello all. Im new to .NET and WPF so i hope i will ask the question correctly. I am using INotifyPropertyChanged implemented using PostSharp 1.5: [Serializable, DebuggerNonUserCode, AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = false), MulticastAttributeUsage(MulticastTargets.Class, AllowMultiple = false, Inheritance = MulticastInheritance.None, AllowExternalAssemblies = true)] public sealed class NotifyPropertyChangedAttribute : CompoundAspect { public int AspectPriority { get; set; } public override void ProvideAspects(object element, LaosReflectionAspectCollection collection) { Type targetType = (Type)element; collection.AddAspect(targetType, new PropertyChangedAspect { AspectPriority = AspectPriority }); foreach (var info in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(pi => pi.GetSetMethod() != null)) { collection.AddAspect(info.GetSetMethod(), new NotifyPropertyChangedAspect(info.Name) { AspectPriority = AspectPriority }); } } } [Serializable] internal sealed class PropertyChangedAspect : CompositionAspect { public override object CreateImplementationObject(InstanceBoundLaosEventArgs eventArgs) { return new PropertyChangedImpl(eventArgs.Instance); } public override Type GetPublicInterface(Type containerType) { return typeof(INotifyPropertyChanged); } public override CompositionAspectOptions GetOptions() { return CompositionAspectOptions.GenerateImplementationAccessor; } } [Serializable] internal sealed class NotifyPropertyChangedAspect : OnMethodBoundaryAspect { private readonly string _propertyName; public NotifyPropertyChangedAspect(string propertyName) { if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); _propertyName = propertyName; } public override void OnEntry(MethodExecutionEventArgs eventArgs) { var targetType = eventArgs.Instance.GetType(); var setSetMethod = targetType.GetProperty(_propertyName); if (setSetMethod == null) throw new AccessViolationException(); var oldValue = setSetMethod.GetValue(eventArgs.Instance, null); var newValue = eventArgs.GetReadOnlyArgumentArray()[0]; if (oldValue == newValue) eventArgs.FlowBehavior = FlowBehavior.Return; } public override void OnSuccess(MethodExecutionEventArgs eventArgs) { var instance = eventArgs.Instance as IComposed<INotifyPropertyChanged>; var imp = instance.GetImplementation(eventArgs.InstanceCredentials) as PropertyChangedImpl; imp.OnPropertyChanged(_propertyName); } } [Serializable] internal sealed class PropertyChangedImpl : INotifyPropertyChanged { private readonly object _instance; public PropertyChangedImpl(object instance) { if (instance == null) throw new ArgumentNullException("instance"); _instance = instance; } public event PropertyChangedEventHandler PropertyChanged; internal void OnPropertyChanged(string propertyName) { if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); var handler = PropertyChanged as PropertyChangedEventHandler; if (handler != null) handler(_instance, new PropertyChangedEventArgs(propertyName)); } } } Then i have a couple of classes (user and adress) that implement [NotifyPropertyChanged]. It works fine. But what i want would be that if the child object changes (in my example address) that the parent object gets notified (in my case user). Would it be possible to expand this code so it automaticly creates listeners on parent objects that listen for changes in its child objets?

    Read the article

  • Select column value that matches a combination of other columns values on the same table

    - by Ala
    I have a table called Ads and another Table called AdDetails to store the details of each Ad in a Property / Value style, Here is a simplified example with dummy code: [AdDetailID], [AdID], [PropertyName], [PropertyValue] 2 28 Color Red 3 28 Speed 100 4 27 Color Red 5 28 Fuel Petrol 6 27 Speed 70 How to select Ads that matches many combinations of PropertyName and PropertyValue, for example : where PropertyName='Color' and PropertyValue='Red' And where PropertyName='Speed' and CAST(PropertyValue AS INT) > 60

    Read the article

  • WPF ListView as a DataGrid – Part 2

    - by psheriff
    In my last blog post I showed you how to create GridViewColumn objects on the fly from the meta-data in a DataTable. By doing this you can create columns for a ListView at runtime instead of having to pre-define each ListView for each different DataTable. Well, many of us use collections of our classes and it would be nice to be able to do the same thing for our collection classes as well. This blog post will show you one approach for using collection classes as the source of the data for your ListView.  Figure 1: A List of Data using a ListView Load Property NamesYou could use reflection to gather the property names in your class, however there are two things wrong with this approach. First, reflection is too slow, and second you may not want to display all your properties from your class in the ListView. Instead of reflection you could just create your own custom collection class of PropertyHeader objects. Each PropertyHeader object will contain a property name and a header text value at a minimum. You could add a width property if you wanted as well. All you need to do is to create a collection of property header objects where each object represents one column in your ListView. Below is a simple example: PropertyHeaders coll = new PropertyHeaders(); coll.Add(new PropertyHeader("ProductId", "Product ID"));coll.Add(new PropertyHeader("ProductName", "Product Name"));coll.Add(new PropertyHeader("Price", "Price")); Once you have this collection created, you could pass this collection to a method that would create the GridViewColumn objects based on the information in this collection. Below is the full code for the PropertyHeader class. Besides the PropertyName and Header properties, there is a constructor that will allow you to set both properties when the object is created. C#public class PropertyHeader{  public PropertyHeader()  {  }   public PropertyHeader(string propertyName, string headerText)  {    PropertyName = propertyName;    HeaderText = headerText;  }   public string PropertyName { get; set; }  public string HeaderText { get; set; }} VB.NETPublic Class PropertyHeader  Public Sub New()  End Sub   Public Sub New(ByVal propName As String, ByVal header As String)    PropertyName = propName    HeaderText = header  End Sub   Private mPropertyName As String  Private mHeaderText As String   Public Property PropertyName() As String    Get      Return mPropertyName    End Get    Set(ByVal value As String)      mPropertyName = value    End Set  End Property   Public Property HeaderText() As String    Get      Return mHeaderText    End Get    Set(ByVal value As String)      mHeaderText = value    End Set  End PropertyEnd Class You can use a Generic List class to create a collection of PropertyHeader objects as shown in the following code. C#public class PropertyHeaders : List<PropertyHeader>{} VB.NETPublic Class PropertyHeaders  Inherits List(Of PropertyHeader)End Class Create Property Header Objects You need to create a method somewhere that will create and return a collection of PropertyHeader objects that will represent the columns you wish to add to your ListView prior to binding your collection class to that ListView. Below is a sample method called GetProperties that builds a list of PropertyHeader objects with properties and headers for a Product object. C#public PropertyHeaders GetProperties(){  PropertyHeaders coll = new PropertyHeaders();   coll.Add(new PropertyHeader("ProductId", "Product ID"));  coll.Add(new PropertyHeader("ProductName", "Product Name"));  coll.Add(new PropertyHeader("Price", "Price"));   return coll;} VB.NETPublic Function GetProperties() As PropertyHeaders  Dim coll As New PropertyHeaders()   coll.Add(New PropertyHeader("ProductId", "Product ID"))  coll.Add(New PropertyHeader("ProductName", "Product Name"))  coll.Add(New PropertyHeader("Price", "Price"))   Return collEnd Function WPFListViewCommon Class Now that you have a collection of PropertyHeader objects you need a method that will create a GridView and a collection of GridViewColumn objects based on this PropertyHeader collection. Below is a static/Shared method that you might put into a class called WPFListViewCommon. C#public static GridView CreateGridViewColumns(  PropertyHeaders properties){  GridView gv;  GridViewColumn gvc;   // Create the GridView  gv = new GridView();  gv.AllowsColumnReorder = true;   // Create the GridView Columns  foreach (PropertyHeader item in properties)  {    gvc = new GridViewColumn();    gvc.DisplayMemberBinding = new Binding(item.PropertyName);    gvc.Header = item.HeaderText;    gvc.Width = Double.NaN;    gv.Columns.Add(gvc);  }   return gv;} VB.NETPublic Shared Function CreateGridViewColumns( _    ByVal properties As PropertyHeaders) As GridView  Dim gv As GridView  Dim gvc As GridViewColumn   ' Create the GridView  gv = New GridView()  gv.AllowsColumnReorder = True   ' Create the GridView Columns  For Each item As PropertyHeader In properties    gvc = New GridViewColumn()    gvc.DisplayMemberBinding = New Binding(item.PropertyName)    gvc.Header = item.HeaderText    gvc.Width = [Double].NaN    gv.Columns.Add(gvc)  Next   Return gvEnd Function Build the Product Screen To build the window shown in Figure 1, you might write code like the following: C#private void CollectionSample(){  Product prod = new Product();   // Setup the GridView Columns  lstData.View = WPFListViewCommon.CreateGridViewColumns(       prod.GetProperties());  lstData.DataContext = prod.GetProducts();} VB.NETPrivate Sub CollectionSample()  Dim prod As New Product()   ' Setup the GridView Columns  lstData.View = WPFListViewCommon.CreateGridViewColumns( _       prod.GetProperties())  lstData.DataContext = prod.GetProducts()End Sub The Product class contains a method called GetProperties that returns a PropertyHeaders collection. You pass this collection to the WPFListViewCommon’s CreateGridViewColumns method and it will create a GridView for the ListView. When you then feed the DataContext property of the ListView the Product collection the appropriate columns have already been created and data bound. Summary In this blog you learned how to create a ListView that acts like a DataGrid using a collection class. While it does take a little code to do this, it is an alternative to creating each GridViewColumn in XAML. This gives you a lot of flexibility. You could even read in the property names and header text from an XML file for a truly configurable ListView. NOTE: You can download the complete sample code (in both VB and C#) at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "WPF ListView as a DataGrid – Part 2" from the drop-down. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".  

    Read the article

  • OData &ndash; The easiest service I can create: now with updates

    - by Jon Dalberg
    The other day I created a simple NastyWord service exposed via OData. It was read-only and used an in-memory backing store for the words. Today I’ll modify it to use a file instead of a list and I’ll accept new nasty words by implementing IUpdatable directly. The first thing to do is enable the service to accept new entries. This is done at configuration time by adding the “WriteAppend” access rule: 1: public class NastyWords : DataService<NastyWordsDataSource> 2: { 3: // This method is called only once to initialize service-wide policies. 4: public static void InitializeService(DataServiceConfiguration config) 5: { 6: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead | EntitySetRights.WriteAppend); 7: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 8: } 9: }   Next I placed a file, NastyWords.txt, in the “App_Data” folder and added a few *choice* words to start. This required one simple change to our NastyWordDataSource.cs file: 1: public NastyWordsDataSource() 2: { 3: UpdateFromSource(); 4: } 5:   6: private void UpdateFromSource() 7: { 8: var words = File.ReadAllLines(pathToFile); 9: NastyWords = (from w in words 10: select new NastyWord { Word = w }).AsQueryable(); 11: }   Nothing too shocking here, just reading each line from the NastyWords.txt file and exposing them. Next, I implemented IUpdatable which comes with a boat-load of methods. We don’t need all of them for now since we are only concerned with allowing new values. Here are the methods we must implement, all the others throw a NotImplementedException: 1: public object CreateResource(string containerName, string fullTypeName) 2: { 3: var nastyWord = new NastyWord(); 4: pendingUpdates.Add(nastyWord); 5: return nastyWord; 6: } 7:   8: public object ResolveResource(object resource) 9: { 10: return resource; 11: } 12:   13: public void SaveChanges() 14: { 15: var intersect = (from w in pendingUpdates 16: select w.Word).Intersect(from n in NastyWords 17: select n.Word); 18:   19: if (intersect.Count() > 0) 20: throw new DataServiceException(500, "duplicate entry"); 21:   22: var lines = from w in pendingUpdates 23: select w.Word; 24:   25: File.AppendAllLines(pathToFile, 26: lines, 27: Encoding.UTF8); 28:   29: pendingUpdates.Clear(); 30:   31: UpdateFromSource(); 32: } 33:   34: public void SetValue(object targetResource, string propertyName, object propertyValue) 35: { 36: targetResource.GetType().GetProperty(propertyName).SetValue(targetResource, propertyValue, null); 37: }   I use a simple list to contain the pending updates and only commit them when the “SaveChanges” method is called. Here’s the order these methods are called in our service during an insert: CreateResource – here we just instantiate a new NastyWord and stick a reference to it in our pending updates list. SetValue – this is where the “Word” property of the NastyWord instance is set. SaveChanges – get the list of pending updates, barfing on duplicates, write them to the file and clear our pending list. ResolveResource – the newly created resource will be returned directly here since we aren’t dealing with “handles” to objects but the actual objects themselves. Not too bad, eh? I didn’t find this documented anywhere but a little bit of digging in the OData spec and use of Fiddler made it pretty easy to figure out. Here is some client code which would add a new nasty word: 1: static void Main(string[] args) 2: { 3: var svc = new ServiceReference1.NastyWordsDataSource(new Uri("http://localhost.:60921/NastyWords.svc")); 4: svc.AddToNastyWords(new ServiceReference1.NastyWord() { Word = "shat" }); 5:   6: svc.SaveChanges(); 7: }   Here’s all of the code so far for to implement the service: 1: using System; 2: using System.Collections.Generic; 3: using System.Data.Services; 4: using System.Data.Services.Common; 5: using System.Linq; 6: using System.ServiceModel.Web; 7: using System.Web; 8: using System.IO; 9: using System.Text; 10:   11: namespace ONasty 12: { 13: [DataServiceKey("Word")] 14: public class NastyWord 15: { 16: public string Word { get; set; } 17: } 18:   19: public class NastyWordsDataSource : IUpdatable 20: { 21: private List<NastyWord> pendingUpdates = new List<NastyWord>(); 22: private string pathToFile = @"path to your\App_Data\NastyWords.txt"; 23:   24: public NastyWordsDataSource() 25: { 26: UpdateFromSource(); 27: } 28:   29: private void UpdateFromSource() 30: { 31: var words = File.ReadAllLines(pathToFile); 32: NastyWords = (from w in words 33: select new NastyWord { Word = w }).AsQueryable(); 34: } 35:   36: public IQueryable<NastyWord> NastyWords { get; private set; } 37:   38: public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded) 39: { 40: throw new NotImplementedException(); 41: } 42:   43: public void ClearChanges() 44: { 45: pendingUpdates.Clear(); 46: } 47:   48: public object CreateResource(string containerName, string fullTypeName) 49: { 50: var nastyWord = new NastyWord(); 51: pendingUpdates.Add(nastyWord); 52: return nastyWord; 53: } 54:   55: public void DeleteResource(object targetResource) 56: { 57: throw new NotImplementedException(); 58: } 59:   60: public object GetResource(IQueryable query, string fullTypeName) 61: { 62: throw new NotImplementedException(); 63: } 64:   65: public object GetValue(object targetResource, string propertyName) 66: { 67: throw new NotImplementedException(); 68: } 69:   70: public void RemoveReferenceFromCollection(object targetResource, string propertyName, object resourceToBeRemoved) 71: { 72: throw new NotImplementedException(); 73: } 74:   75: public object ResetResource(object resource) 76: { 77: throw new NotImplementedException(); 78: } 79:   80: public object ResolveResource(object resource) 81: { 82: return resource; 83: } 84:   85: public void SaveChanges() 86: { 87: var intersect = (from w in pendingUpdates 88: select w.Word).Intersect(from n in NastyWords 89: select n.Word); 90:   91: if (intersect.Count() > 0) 92: throw new DataServiceException(500, "duplicate entry"); 93:   94: var lines = from w in pendingUpdates 95: select w.Word; 96:   97: File.AppendAllLines(pathToFile, 98: lines, 99: Encoding.UTF8); 100:   101: pendingUpdates.Clear(); 102:   103: UpdateFromSource(); 104: } 105:   106: public void SetReference(object targetResource, string propertyName, object propertyValue) 107: { 108: throw new NotImplementedException(); 109: } 110:   111: public void SetValue(object targetResource, string propertyName, object propertyValue) 112: { 113: targetResource.GetType().GetProperty(propertyName).SetValue(targetResource, propertyValue, null); 114: } 115: } 116:   117: public class NastyWords : DataService<NastyWordsDataSource> 118: { 119: // This method is called only once to initialize service-wide policies. 120: public static void InitializeService(DataServiceConfiguration config) 121: { 122: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead | EntitySetRights.WriteAppend); 123: config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; 124: } 125: } 126: } Next time we’ll allow removing nasty words. Enjoy!

    Read the article

  • ASP.NET MVC editor template for property

    - by Idsa
    Usually I render my forms by @Html.RenderModel, but this time I have a complex rendering logic and I render it manually. I decided to create a editor template for one property. Here is the code (copy pasted from default object editor template implementation): <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <% var modelMetadata = ViewData.ModelMetadata; %> <% if (modelMetadata.HideSurroundingHtml) { %> <%= Html.Editor(modelMetadata.PropertyName) %> <% } else { %> <% if (!String.IsNullOrEmpty(Html.Label(modelMetadata.PropertyName).ToHtmlString())) { %> <div class="editor-label"><%= Html.Label(modelMetadata.PropertyName) %></div> <% } %> <div class="editor-field"> <%= Html.Editor(modelMetadata.PropertyName) %> <%= Html.ValidationMessage(modelMetadata.PropertyName) %> </div> <% } %> And here is how I use it: @Html.EditorFor(x => x.SomeProperty, "Property") //"Property" is template above But it didn't work: labels are rendered regardless of DisplayName and editors are not rendered at all (in Watches Html.Editor(modelMetadata.PropertyName shows empty string). What am I doing wrong?

    Read the article

  • ASP.NET MVC Inheriting from ProfileBase

    - by Glen
    I have 2 related issues. I inherited from ProfileBase and I have a couple of properites as such public SomeType PropertyName { get { return (SomeType)base["PropertyName"]; } set { base["PropertyName"] = value; Save(); } } I also have a User class (UserId, UserName, Profile, LastActivityDate) that has 2 additional properties out of the profile that I retrieve in my View to show a list of Users (i.e. @Model.Profile.PropertyName). However, everytime I access a property (from my View) it seems to update the LastActivityDate in the aspnet_Users table because when I show the LastActivityDate as well as the profile properties on my screen the LastActivtyDate is out of sync with the database. Also there is a LastActivityDate property available in my profile which unfortunately is not available and is in fact set to null and throws an exception when accessing it saying the property UserName is null. So the static Create method provided by ProfileBase seems to retrieve the correct profile properties but does not set the base's UserName property even though you pass in a UserName parameter to the Create method. Is this a internal bug? I was kind of hoping if by accessing the property because the LastActivityDate is updated then I could store that value to update my LastActivityDate in my User class before it is rendered to the page. The only way I can think of doing it is: public SomeType PropertyName { get { SomeType result = (SomeType)base["PropertyName"]; OnLastActivityDateChanged(); return result; } set { base["PropertyName"] = value; } } then in my User class: ... public MyProfile() { Profile.LastActivityDateChanged += Profile_LastActivityDateChanged(); } ~MyProfile() { Profile.LastActivityDateChanged -= Profile_LastActivityDateChanged(); } ... void Profile_LastActivityDateChanged(object sender, EventArgs e) { //Run a query to get the latest LastActivityDate this.LastActivityDate = ... } It seems I have to make 1 call to retrieve the full list to my aspnet_Users table then another call for each row just to get the latest activity date. ARGGGGHHH!!! Am I going about this the wrong way! I put an ajax refresh hyperlink next to each User row and when I click it, immediately after loading the page, the value changes. Therefore my suspision is valid that calling a property via the inherited profilebase class updates the value. Is there a workaround? It is a bit miss leading when my page says User Smith has no activity for 4 days then I click my ajax refresh link (or refresh the whole page for that matter) and now it says Smith was active but it was just me meally showing the page that indirectly caused an activity read event.

    Read the article

  • Jquery: Datalink - Data linking

    - by Pickels
    I was trying out the Jquery Data linking proposal from Microsoft and noticed something strange. My objects get this extra property and I was wondering what the reason for that is. I first thought it was a mistake I made but I noticed their demo page does the same thing This is the json result of my objects: [{ "propertyName":"ProductNamese", "controlType":"Text", "jQuery1274021322131":6 }, { "propertyName":"Price", "controlType":"Number", "jQuery1274021322131":9 }, { "propertyName":"Description", "controlType":"TextArea", "jQuery1274021322131":12 } ] The property I am talking about is "jQuery1274021322131".

    Read the article

  • Implement master detail in one datagrid in wpf

    - by Archie
    Hello, I have classes as following: public class Property { public string PropertyName { get; set; } public int SumSubPropertValue; private List<SubProperty> propertyList; public void CalculateSumSubPropertValue { // implementation} } public class SubProperty { public string SubPropertyName { get; set; } public int SubPropertyValue { get; set; } } I have grouped the rows in datagrid on PropertyName . When the user clicks on PropertyName expnader the columns should display SubPropertyName and SubPropertyValue. Also SumSubPropertValue should appear in front of PropertyName in the expander header. My Datagrid is bound to a CollectionViewSource as follows: CollectionViewSource view = new CollectionViewSource(); view.Source = infoList; view.GroupDescriptions.Add(new PropertyGroupDescription("PropertyName")); Where infoList is ObservableCollection<Property>. My datagrid colmns look like <my:DataGrid.Columns> <my:DataGridTextColumn Header="SubPropertyName" Binding="{Binding SubPropertName}" Width="*"/> <my:DataGridTextColumn Header="SubPropertyValue" Binding="{Binding SubPropertyValue}" Width="*"/> </my:DataGrid.Columns> Can someone help me with it?

    Read the article

  • How to create tests for poco objects

    - by Simon G
    Hi, I'm new to mocking/testing and wanting to know what level should you go to when testing. For example in my code I have the following object: public class RuleViolation { public string ErrorMessage { get; private set; } public string PropertyName { get; private set; } public RuleViolation( string errorMessage ) { ErrorMessage = errorMessage; } public RuleViolation( string errorMessage, string propertyName ) { ErrorMessage = errorMessage; PropertyName = propertyName; } } This is a relatively simple object. So my question is: Does it need a unit test? If it does what do I test and how? Thanks

    Read the article

  • BeanUtils getPropertyOfMapBean

    - by dx-cp
    Hi, Im wondering if it is possible to get data from property which is map cotaining pairs Key-StringArray (Map) in BeanUtils library. I just simply need to access one of array elements by calling propertyName=string[0]. Current version (1.8.3) does not support indexed properties. If you look into their code you will find in class PropertyUtilsBean in method getPropertyOfMapBean: if (resolver.isIndexed(propertyName) || resolver.isMapped(propertyName)) { throw new IllegalArgumentException( "Indexed or mapped properties are not supported on" + " objects of type Map: " + propertyName); } way too bad:-( Have any of you any tip how to do it somehow differently?

    Read the article

  • C#: How to implement a smart cache

    - by Svish
    I have some places where implementing some sort of cache might be useful. For example in cases of doing resource lookups based on custom strings, finding names of properties using reflection, or to have only one PropertyChangedEventArgs per property name. A simple example of the last one: public static class Cache { private static Dictionary<string, PropertyChangedEventArgs> cache; static Cache() { cache = new Dictionary<string, PropertyChangedEventArgs>(); } public static PropertyChangedEventArgs GetPropertyChangedEventArgsa(string propertyName) { if (cache.ContainsKey(propertyName)) return cache[propertyName]; return cache[propertyName] = new PropertyChangedEventArgs(propertyName); } } But, will this work well? For example if we had a whole load of different propertyNames, that would mean we would end up with a huge cache sitting there never being garbage collected or anything. I'm imagining if what is cached are larger values and if the application is a long-running one, this might end up as kind of a problem... or what do you think? How should a good cache be implemented? Is this one good enough for most purposes? Any examples of some nice cache implementations that are not too hard to understand or way too complex to implement?

    Read the article

1 2 3 4 5 6 7 8 9 10 11  | Next Page >