I am trying to access some specific variable that are only available in a child class. But the problem is that I recieve the parent of this class by parameter. Even with casting I can't seem to be able to access the members. Can it be done?
public class ENUMTranslator : ITranslate<RedisData>
{
public string Translate(RedisData message)
{
string bitMask = message.AssociatedParam.ParamDictionary["Bitmask"];
var enumerations = (EnumParams)message.AssociatedParam.EnumDictionary
}
}
The thing is that the data is not in message itself but inside AssociatedParam Which is the parent class of EnumParams.
The EnumDictionary is what I am trying to access that should be in EnumParams, but I just can't access it.
EDIT : Here is the EnumParam class.
message.AssociatedParams
is a GAPParam
public class EnumParams : GAPParam
{
#region Class Members
/// <summary>
/// Dictionary for the enums linking name with hex value
/// </summary>
private Dictionary<string, string> _enumDictionary;
#endregion // Class Members
#region Properties
/// <summary>
/// Dictionary for the enums linking name with hex value
/// </summary>
public Dictionary<string, string> EnumDictionary
{
get { return _enumDictionary; }
set { _enumDictionary = value; }
}
#endregion // Properties
#region Constructor
/// <summary>
/// Initialise the dictionaries
/// </summary>
public EnumParams()
{
_enumDictionary = new Dictionary<string, string>();
}
#endregion // Constructor
}
I cannot see it with intellisense and it would not compile either.
Well you could cast message.AssociatedParam to an EnumParams:
var enumerations = ((EnumParams)message.AssociatedParam).EnumDictionary
but if message.AssociatedParam is not castable to an EnumParams then it will fail at runtime. Some way to mitigate the risk:
should EnumDictionary be on GAPParam instead? Even if it's virtual or abstract?
should message.AssociatedParam be an EnumDictionary instead of a GAPParam?
do a check before casting to make sure message.AssociatedParam is an EnumParams - but then what do you do if its not?
Related
At the moment I'm working on funcionality that involves exporting and importing data to Xlsx file. Here's what I want to do: I want to have an attribute I can put above a property like this.
public class MyClass
{
[XlsxColumn("Column 1")]
public string myProperty1 { get; set; }
public int myProperty2 { get; set; }
}
So far I don't have problems, but then I want to "store references" to properties marked with the XlsxColumn attribute. I'm using reflection
to store properties data in List
var propsList = MyClass.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(XlsxColumn)));
I have a list with all properties marked with XlsxColumn (only myProperty1 in this example).
EDIT: The problem is I don't know how to loop over properties in MyClass, but only properties with XlsxColumn attribute (so all PropertyInfo objects stored in propsList variable), without resorting to reflection with each object saved to Xlsx file.
I'm restricted to .NET 4.0.
Thanks for your time.
MyClass.GetProperties() does not work because you have to get the type of the class to invoke the GetProperties method. Otherwise you are invoking a static method called GetProperties defined in the MyClass class.
var propsList = typeof(MyClass).GetProperties().Where(
prop => prop.IsDefined(typeof(XlsxColumnAttribute), false)).ToList();
If you just want the names (IList<string>):
var propsList = typeof(Excel).GetProperties().Where(
prop => prop.IsDefined(typeof(XlsxColumnAttribute), false))
.Select(prop=> prop.Name)
.ToList();
to use .Where you have to include System.Linq
I must say that I am not sure if this is the solution you are looking for. Because I could not quite make out what your question is. Well I have tried to provide an answer as much as I could figure out.
I went for a static class for CachingPropetyProvider but you can go for an instance class and use a dependency injection library and use it as a Singleton too. Moreover, I have written extensive comments so It is as self explanatory as possible.
Let us define MyClass. I also deliberately changed it a little bit.
public class MyClass
{
[XlsxColumn("Column 1")]
public string MyProperty1 { get; set; }
[XlsxColumn("Column 2")]
public int MyProperty2 { get; set; }
}
I also defined a MetaInfo class to hold the cached information.
public class MetaInfo {
/// <summary>
/// Immutable class for holding PropertyInfo and XlsxColumn info.
/// </summary>
/// <param name="info">PropertyInfo</param>
/// <param name="attr">XlsxColumn</param>
public MetaInfo(PropertyInfo info, XlsxColumn attr) {
PropertyInfo = info;
Attribute = attr;
}
/// <summary>
/// PropertyInfo. You may want to access the value inside the property.
/// </summary>
public PropertyInfo PropertyInfo { get; }
/// <summary>
/// Attribute. You may want to access information hold inside the attribute.
/// </summary>
public XlsxColumn Attribute { get; }
}
And lastly the main guy. This guy is responsible for providing all the data about classes
public class CachingPropProvider {
/// <summary>
/// Holds the meta information for each type.
/// </summary>
private static readonly ConcurrentDictionary<Type, List<MetaInfo>> TypeCache;
/// <summary>
/// Static constructor is guaranteed to run only once.
/// </summary>
static CachingPropProvider() {
//Initialize the cache.
TypeCache = new ConcurrentDictionary<Type, List<MetaInfo>>();
}
/// <summary>
/// Gets the MetaInfo for the given type. Since We use ConcurrentDictionary it is thread safe.
/// </summary>
/// <typeparam name="T">Type parameter</typeparam>
public static IEnumerable<MetaInfo> GetCachedStuff<T>() {
//If Type exists in the TypeCache, return the cached value
return TypeCache.GetOrAdd(typeof(T),Factory);
}
/// <summary>
/// Factory method to use to extract MetaInfo when Cache is not hit.
/// </summary>
/// <param name="type">Type to extract info from</param>
/// <returns>A list of MetaInfo. An empty List, if no property has XlsxColumn attrbiute</returns>
private static List<MetaInfo> Factory(Type #type) {
//If Type does not exist in the TypeCahce runs Extractor
//Method to extract metainfo for the given type
return #type.GetProperties().Aggregate(new List<MetaInfo>(), Extractor);
}
/// <summary>
/// Extracts MetaInfo from the given property info then saves it into the list.
/// </summary>
/// <param name="seedList">List to save metainfo into</param>
/// <param name="propertyInfo">PropertyInfo to try to extract info from</param>
/// <returns>List of MetaInfo</returns>
private static List<MetaInfo> Extractor(List<MetaInfo> seedList,PropertyInfo propertyInfo) {
//Gets Attribute
var customattribute = propertyInfo.GetCustomAttribute<XlsxColumn>();
//If custom attribute is not null, it means it is defined
if (customattribute != null)
{
//Extract then add it into seed list
seedList.Add(new MetaInfo(propertyInfo, customattribute));
}
//Return :)
return seedList;
}
}
Finally let us see how to use the solution. It is pretty straightforward actually.
//Has 2 values inside
var info = CachingPropProvider.GetCachedStuff<MyClass>();
I am using AutoMapper 4.x.
I have a couple of classes as follows:
/// <summary>
/// All service outputs need to descend from this class.
/// </summary>
public class OzCpAppServiceOutputBase : IOzCpAppServiceOutputBase
{
private readonly OzCpResultErrors _OzCpResultErrors;
public OzCpAppServiceOutputBase()
{
_OzCpResultErrors = new OzCpResultErrors();
}
public OzCpResultErrors ResultErrors
{
get { return _OzCpResultErrors; }
}
public bool ResultSuccess
{
get { return _OzCpResultErrors.Messages.Count == 0; }
}
}
/// <summary>
/// Return from the booking service when a simple booking is made.
/// </summary>
public class OzCpSimpleManualCruiseBookingOutput : OzCpAppServiceOutputBase
{
public int OzBookingId { get; set; }
}
}
public class SimpleManualCruiseBookingOutput : OzCpSimpleManualCruiseBookingOutput
{
}
My issue comes in when I call AutoMapper to translate between OzCpSimpleManualCruiseBookingOutput and SimpleManualCruiseBookingOutput is that the ResultErrors is cleared.
public SimpleManualCruiseBookingOutput SimpleManualCruiseBooking(SimpleManualCruiseBookingInput aParams)
{
OzCpSimpleManualCruiseBookingOutput result = _PlatformBookingService.SimpleManualBooking(Mapper.Map<OzCpSimpleManualCruiseBookingInput>(aParams));
//**TESTING
result.ResultErrors.AddFatalError(1, "Oh Dear!!!!");
//**As soon as I perform the mapping the ResultErrros collection loses the item I have added above
return Mapper.Map<SimpleManualCruiseBookingOutput>(result);
}
I am guessing it is because it is a read only property, but I cannot figure out how to make it transfer the collection.
Any help greatly appreciated.
EDIT
I have also tried adding the items in the collection myself so changing my mapping from:
Mapper.CreateMap<OzCpSimpleManualCruiseBookingOutput, SimpleManualCruiseBookingOutput>();
to using the after map function as follows:
Mapper.CreateMap<OzCpSimpleManualCruiseBookingOutput, SimpleManualCruiseBookingOutput>()
.AfterMap((src, dst) => dst.ResultErrors.Messages.AddRange(src.ResultErrors.Messages));
but this then results in the destination having TWO items in the list instead of 1 viz:
which are both the same entry of "Oh Dear!!!!"
SOLUTION
Using the private setter approach suggested by DavidL (and an upgrade to Automapper 4.x) meant I got the required behaviour. So this is what I ended up with:
/// <summary>
/// Defines the contract for all output DTO's to platform
/// application services.
/// </summary>
/// <seealso cref="OzCpAppServiceOutputBase" />
public interface IOzCpAppServiceOutputBase : IOutputDto
{
/// <summary>
/// Contains a list of errors should a call to an application service fail.
/// </summary>
OzCpResultErrors ResultErrors{ get; }
/// <summary>
/// When TRUE the underlying call to the application service was successful, FALSE
/// otherwise. When FALSE see ResultErrors for more information on the error condition.
/// </summary>
bool ResultSuccess { get; }
}
public class OzCpAppServiceOutputBase : IOzCpAppServiceOutputBase
{
public OzCpAppServiceOutputBase()
{
ResultErrors = new OzCpResultErrors();
}
/// <remarks>The private setter is here so that AutoMapper works.</remarks>
public OzCpResultErrors ResultErrors { get; private set; }
public bool ResultSuccess
{
get { return ResultErrors.Messages.Count == 0; }
}
}
So while needing to add a private setter "just for" AutoMapper that is a small price to pay to have this work and not use complicated mappings to deal with the issue.
With the current inheritance structure, AutoMapper will NOT be able to do what you want it to do. Since your destination structure has the same properties as your source structure, the properties are also readonly. AutoMapper will not map to readonly properties that do not have a setter declared.
You have a few options:
Make the property setter explicitly private. This answer suggests that later versions of AutoMapper support this functionality. In this case it works for 4.x.
Make the property setter internal, so that only members of this assembly can set it. Since latest versions of AutoMapper will map to private setters, they should also map to internal setters.
Make the property settable.
Downcast the object instead of mapping (you've mentioned you don't want to do this because your object structures will eventually diverge).
Shadow the property on the destination object with a public setter. Ugly and a good source of strange bugs.
public class SimpleManualCruiseBookingOutput : OzCpSimpleManualCruiseBookingOutput
{
public new OzCpResultErrors ResultErrors { get; set; }
}
Create a helper that maps your read-only properties via reflection. DO NOT DO THIS!
PropertyInfo nameProperty = aParams.GetType().GetProperty ("ResultErrors");
FieldInfo nameField = nameProperty.GetBackingField ();
nameField.SetValue (person, aParams.ResultErrors);
I have a structure:
public struct ServiceDescription
{
string serviceDescriptionText;
string serviceLogoRef;
/// <summary>
/// The position to print the service on the label.
/// </summary>
int servicePosition;
/// <summary>
/// Constructor
/// </summary>
/// <param name="serviceDescriptionText"></param>
/// <param name="serviceLogoRef"></param>
/// <param name="servicePosition"></param>
public ServiceDescription(string serviceDescriptionText, string serviceLogoRef,
int servicePosition)
{
this.serviceDescriptionText = serviceDescriptionText;
this.serviceLogoRef = serviceLogoRef;
this.servicePosition = servicePosition;
}
}
and a property:
public string pServiceDescription
{
get
{
return p_sServiceDescription;
}
// set private structure field 1
// set private structure field 2
// etc...
}
How do I set each of the private fields of the structure in the setters of my property?
It is usually a very bad idea to have mutable structs; mutable value-type semantics is not what people usually expect. You can, however, simply add a set that works like any other regular setter. It just isn't a very good idea:
public string Text
{
get { return text; }
set { text = value; } // this is a really bad idea on a struct
}
If it was me, that would be an immutable struct with private readonly fields and a constructor that sets all of them (and get-only properties), or a class - probably with automatically implemented properties, i.e.
public class ServiceDescription {
public string Text {get;set;}
//...
}
As far as I know, currently PRISM allows to pass strings, but doesn't allow to pass objects. I would like to know what are the ways of overcoming this issue.
I want to pass a list collection. The UriQuery isn't usefull in my case, what should I do in this case?
Prism 5 and 6 : The NavigationParameters class can now be used to pass object parameters during navigation, using the overloads of the RequestNavigate method of a Region or RegionManager instance.
I have my own technique.
I extract the hash code of the object and save it in a Dictionary, with the hash code as the key and the object as the value of the pair.
Then, I attach the hash code to the UriQuery.
After, I only have to get the hash code that comes from the Uri on the target view and use it to request the original object from the Dictionary.
Some example code:
Parameter repository class:
public class Parameters
{
private static Dictionary<int, object> paramList =
new Dictionary<int, object>();
public static void save(int hash, object value)
{
if (!paramList.ContainsKey(hash))
paramList.Add(hash, value);
}
public static object request(int hash)
{
return ((KeyValuePair<int, object>)paramList.
Where(x => x.Key == hash).FirstOrDefault()).Value;
}
}
The caller code:
UriQuery q = null;
Customer customer = new Customer();
q = new UriQuery();
Parameters.save(customer.GetHashCode(), customer);
q.Add("hash", customer.GetHashCode().ToString());
Uri viewUri = new Uri("MyView" + q.ToString(), UriKind.Relative);
regionManager.RequestNavigate(region, viewUri);
The target view code:
public partial class MyView : UserControl, INavigationAware
{
// some hidden code
public void OnNavigatedTo(NavigationContext navigationContext)
{
int hash = int.Parse(navigationContext.Parameters["hash"]);
Customer cust = (Customer)Parameters.request(hash);
}
}
That's it.
You can create an PRISM event with 'object' getter/setter. Rise event with your object casted or not casted to 'object' inside event (depends if event implementation 'shared' like in famous 'Infrastructure' projects) and then Navigate to Region. In ViewModel that implement Region - Subscribe() to above event, receive it and store locally and then just wait for 'OnNavigatedTo' function call. When OnNavigatedTo function called you already have the object/class/struct and can run the ViewModel.
For example - Event class:
namespace CardManagment.Infrastructure.Events
{
using Microsoft.Practices.Prism.Events;
/// <summary>
/// Event to pass 'Selected Project' in between pages
/// </summary>
public class SelectedProjectViewEvent : CompositePresentationEvent<SelectedProjectViewEvent>
{
public object SelectedPorject { get; set; }
}
}
'Calling' class
/// <summary>
/// Called when [back to project view].
/// </summary>
/// <param name="e">The e.</param>
public void OnBackToProjectView(CancelEditProjectEvent e)
{
eventAggregator.GetEvent<SelectedProjectViewEvent>().Publish(new SelectedProjectViewEvent()
{
SelectedPorject = selectedProject
});
regionManager.RequestNavigate(WellKnownRegionNames.ProjectViewRegion, new System.Uri("ProjectDetailsView", System.UriKind.Relative));
}
And this on 'Receiver' class
/// <summary>
/// Called when the implementer has been navigated to.
/// </summary>
/// <param name="navigationContext">The navigation context.</param>
public void OnNavigatedTo(NavigationContext navigationContext)
{
if (this.SelectedProject == null) // <-- If event received untill now
this.ShouldBeVisible = false;
else
this.ShouldBeVisible = true;
}
You can also check out how to pass objects if you are using an IOC and want to use constructor injection.
https://stackoverflow.com/a/20170410/1798889
How can I document the key usage in a Dictionary so that it shows in Visual studio when coding using that object?
I'm looking for something like:
/// <param name="SpecialName">That Special Name</param>
public Dictionary<string,string> bar;
So far the best attempt has been to write my own class:
public class SpecialNameDictionary : IDictionary<string, string>
{
private Dictionary<string, string> data = new Dictionary<string, string>();
/// <param name="specialName">That Special Name</param>
public string this[string specialName]
{
get
{
return data[specialName];
}
}
}
But It adds a lot of code that doesn't do anything. Additionally I must retype every Dictionary method to make it compile.
Is there a better way to achive the above?
You can define, dictionary like this:
public class SpecialNameDictionary : Dictionary<string, string>
{
/// <param name="specialName">That Special Name</param>
public new string this[string specialName]
{
get
{
return base[specialName];
}
}
}
Instead of deriving from IDictionary derive from Dictionary, and make new implementation of indexer.
Document the field like this:
/// <summary>
/// A map from the special name to the frongulator.
/// </summary>
public Dictionary<string,string> bar;
(I assume that in reality it's either not public or not a field - but the same would apply for private fields or public properties.)
You won't get IntelliSense on the indexer itself, but any usage of bar should make it reasonably clear.
Three other alternatives:
Use types which make the usage clearer (a string could be anything, but a FrongulatorSpecialName is clearer)
Make the name of the field/property itself clearer
Hide the dictionary, but add a method such as "GetFrongulatorBySpecialName"
You could inherit directly from Dictionary<> instead of IDictionary<>, that way you only need to re-implement the indexer.