Cast objects of different type - casting

I have wrote a class (a snippet is below) which have some data members where i put data from the Client Side. I should send this data through Web Services where is a class which includes my data members, but has more data members that my class.
I should cast from my type into another type.
The problem is that i don't know how to access data members to take data from.
all my data are into this object "OBJ":
__XtraInvoiceInfo OBJ = new __XtraInvoiceInfo();
and , the Web Services's type is "InvoiceWithEntriesInfo"
var convertedObj = new InvoiceWithEntriesInfo()
{
invoiceNumber = OBJ.BasicInfo.InvoiceNumber --> member is not access.
| Equals
Visual Studio suggests | GetHashCode
only these methods | GetType
| ToString
invoiceDate = OBJ.BasicInfo.InvoiceDate *--> member is not accessible
firstName = OBJ.Payer.FirstName *-->> not accessible
lastName = OBJ.Payer.LastName *-->> not accessible
catem = OBJ.Payer.Catem *-->> not accessible
};
error "member is not accessible" means *--> 'object' does not contain a definition for 'InvoiceDate' and no extension method 'InvoiceDate' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
public sealed class __XtraInvoiceInfo
{
private long _payerType = -1;
public long PayerType
{
get
{
return this._payerType;
}
set
{
this._payerType = value;
if (value == Constants.NATURAL_PAYER)
{
this.Payer = new __NaturalInvoiceInfo();
}
}
}
public object Payer
{
get; set;
}
public object BasicInfo
{
get; set;
}
//-- Nested Types --
public sealed class __NaturalInvoiceInfo
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
public long Catem
{
get; set;
}
}
public sealed class __BasicInvoiceInfo
{
public long InvoiceNumber
{
get; set;
}
public DateTime? InvoiceDate
{
get; set;
}
}
}
I made properties Payer and BasicInfo because through them i take data from Client and i made a subbinding into my members like this way:
model.BindModel(xii =>
{
var bindModel = new ValidationFrameBindModel<__XtraInvoiceInfo.__BasicInvoiceInfo>();
this.BindControls(bindModel);
model.BindModel<__XtraInvoiceInfo.__BasicInvoiceInfo>((x,b) => x.BasicInfo = b, bindModel);
});
Thank you so much!!! if you have the power to answer my question.
I'm ready to say more details if it is required.

Well this is the problem:
public object Payer { get; set; }
public object BasicInfo { get; set; }
You're only declaring the properties as being of type object - why not give them more useful types? If you don't know the types, how do you know what properties will be there? Can you create abstract base class or interface which declares all the properties you want to guarantee will be there? (It's fairly hard to tell what you're trying to do, to be honest.)
If you're using C# 4 and .NET 4 you could just make them dynamic:
public dynamic Payer { get; set; }
public dynamic BasicInfo { get; set; }
Then accessing sub-properties will be bound at execution time against the actual type of object.
On a side-note, please don't prefix type names with __ - the C# specification reserves identifiers using __ for compiler-specific features. From section 2.4.2:
Identifiers containing two consecutive underscore characters (U+005F) are reserved for use by the implementation. For example, an implementation might provide extended keywords that begin with two underscores.

Related

AutoMapper's AssertConfigurationIsValid and EF navigation properties

I discovered AutoMapper's Configuration Validation feature today and it looks very promising. Using it I should be able to get rid of all our manually written unit tests for our AutoMapper profiles. We use AutoMapper to map between Entity Framework entity classes and View Model classes.
Imagine I have the following entity:
public class Article
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
[ForeignKey("TypeId")]
[InverseProperty("Article")]
public ArticleType Type { get; set; }
}
And the corresponding View Model:
public class ArticleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
}
I have left out ArticleType for brevity.
Now, in my AutoMapper profile I would have these mappings:
CreateMap<ArticleViewModel, Article>()
CreateMap<Article, ArticleViewModel>()
.ForMember(dest => dest.TypeName, options => options.MapFrom(src => src.Type.Name))
If I call AssertConfigurationIsValid on a MapperConfiguration with this profile in it AutoMapper will complain that Type is not mapped. That is true, but I do not need to map it since Entity Framework will automatically figure it out from the foreign key TypeId.
I know I can add an Ignore for Type, like below, to get rid of this error:
CreateMap<ArticleViewModel, Article>()
.ForMember(dest => dest.Type, options => options.Ignore())
But we have entities with a lot of navigation properties to other entities and having to ignore them all becomes tedious.
The other alternative I came up with is to use the source's members to validate the mapping, like this:
CreateMap<ArticleViewModel, Article>(MemberList.Source)
Is there a best practice for this?

Grouping items based on last added item in set

I have an app where I store debug information from several sources. The data is stored in a class like the following:
public class DebugMessage
{
public string ApplicationName { get; set; }
public string Details { get; set; }
public string Id { get; set; }
public DateTime OccurredOn { get; set; }
public IList<string> Tags { get; set; }
public string TextMessage { get; set; }
public MessageTypes Type { get; set; }
public IDictionary<string, string> Metadata { get; set; }
public int Count {get;set;}
public bool Same(DebugMessage other){...}
}
Now, I already have setup indexes and maps/reduce for each item I need. What I would like to do now is the following:
When ADDING a new item to the collection, If this items "looks the same" (by calling the Same method on the item and passing in the last added item in the collection), I would like to just update the last added item and do not add a new item. If the items are not the same, I would like to add it to the collection.
I guess I can do this with some kind of Map/Reduce, but I can't wrap my head around this. I'm new to Raven and don't know how to do the above (or even if that's possible).
Any directions?
You need to move your in the Same method to the map/reduce index, and group based on the values that make you consider the two things to be the same.
Alternatively, query for similar debug message, and update the result.

EF6 Code First: How can I centralize content for separate sections of my site?

I want to store all our site's content in one central Content table but relate it to each section of the site. Something like:
Content (for the actual content byte[] and basic info all sections use)
ResearchArticleContent (basically has the related ContentId from the content table and extra cols for info specific to ResearchArticles)
ResearchArticle
ExecutiveContent (basically has the related ContentID from Content table and extra cols for specific data for Executives)
Executive
...and so on.
I'm having trouble understanding the whole code first approach as it pertains to ForeignKeys and InverseProperties. That's the real issue.
So, say I have these two classes as an example:
public class Content
{
[Key]
public int ContentId { get; set; }
public int ContentType { get; set; }
public byte[] ContentBytes { get; set; }
public DateTime AddedDate { get; set; }
[**`InverseProperty or ForeignKey???`**("ResearchArticleContent")]
public virtual ResearchArticleContent ResearchArticleContent { get; set; }
}
and:
public class ResearchArticleContent
{
[Key]
public int ResearchArticleContentId { get; set; }
[ForeignKey("ContentId")]
public virtual Content Content {get;set;}
public int ResearchArticleId { get; set; }
[ForeignKey("ResearchArticleId")]
public virtual ResearchArticle RelatedArticle { get; set; }
}
Where do I put the ForeignKeys / InverseProperties to relate these correctly. Because ideally, I will have Executivecontent, ResearchArticlecontent and so on for each section of the site. (I am following the precedent already laid out in a Data-First prj that I am mimicking so this is the way I have do this, fyi.)
Entity framework requires a type identifier field when you store compound objects in a single table; however, you can get around this pretty easily using views. To use views, create a single content table and a > base < class. Do not apply the TableAttribute data annotation to the base class. All other data annotations are fine.
public class ContentBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContentId { get; set; }
public string Content { get; set; }
...
}
Then, you can create derived classes that more closely represent the content and apply the TableAttribute data annotation to those. For example,
[Table("ResearchArticleView")]
public class ResearchArticle : ContentBase
{
...you can add more properties here that are included in the view...
...and not necessarily the underlying table, like from a joined table...
...or just use the class as is, so that you have a better name...
}
To use this, set up a view called ResearchArticleView that includes the columns in the base class, as well as any computed or joined columns you want, then add a DbSet to your context that represents the view.
I recommend having content tables for each type of content and then use the method I've described for derived types for each content type. For example, create a base for research articles and a base for execute content. Because, when your database gets big and full of content, having one monolithic content table may cause you backup and optimization issues.

Getting an Internal Link with Glass.Mapper

I've got an Internal Link set up in Sitecore, and I'm trying to map the field using Glass.Mapper, but it just keeps coming back empty, and I'm not sure what I'm doing wrong.
The template in Sitecore is pretty simple:
The Source of the link is set to a folder that only allows content based on the 'System' template to be created.
In my code, I have an object set up:
namespace Playground.GlassObjects
{
public partial class Status
{
public virtual string Description { get; set; }
public virtual string StatusCode { get; set; }
public virtual Glass.Mapper.Sc.Fields.Link System { get; set; }
}
}
Which is being used basically like this:
public void DoStuff(Sitecore.Data.Items.Item item)
{
var status = item.GlassCast<Status>();
this.DoOtherStuff(status);
}
What I'm running into is glassObj.Description, and glassObj.StatusCode are being wired up exactly like I want/expect, but glassObj.System is not.
Can anyone tell me what I'm doing wrong here? I'm at a loss right now, with all the magic that's going on behind the scenes.
The Glass.Mapper.Sc.Fields.Link class is designed to work with the General Link field. The internal link field stores values as paths e.g /sitecore/content/home/events. This means it isn't compatible with the Link class.
Instead you should map it to another class you have created.
public partial class Status
{
public virtual string Description { get; set; }
public virtual string StatusCode { get; set; }
public virtual MySystem System { get; set; }
}
public class MySystem{
public virtual string Url { get; set; }
public virtual string MyField { get; set; }
}
Fast forward to 2022 Internal Link field seems to be working with Glassmapper without any extra effort. All you have to do is add Internal Link case to GlassGenerator.tt file on the project where you will generate the template.
This will ensure your model will have Link field like this:
[SitecoreField(FieldId = "{D2CF138A-0A1C-4766-B250-F56E9458B624}")]
Link InternalLinkField{ get; set; }
It will have some info populated and most of the other properties will be null. The ones that will help you are:
Url (full path to the internal link item)
TargetId (ID of the internal link item)
Here are the available properties:
There is an alternative to that, you can get the link from fields like this:
yourGlassItem.Item.Fields["InternalLinkFieldName"]
You will get the entire Internal link Item. You can use Value or InheritedValue property to get the path of the linked item.

Need to Seriazlize List<object>, but FXCop complains "Do not expose generic lists"

I have an object that I need to serialize. The object contains several properties, including a List. FXCop is complaining that I should not expose generic lists, and I get that, however, due to the fact that I can't specify an interface based property on an object that I want serialized I'm not sure where to turn next.
Any thoughts?
BTW, I'm using XMLSerialization, but that's not a requirement.
I took FxCop's suggestion and wrapped my list in a Collection. This blew some of my code out of the water, but a after a few adjustments I was up and running again.
Here's some code showing before and after:
Before:
public class PersistentDataView
{
public string Title { get; set; }
private List<object> Inputs { get; set;}
}
After:
public class PersistentDataView
{
private List<object> _inputs;
public string Title { get; set; }
public Collection<object> Inputs
{
get
{
if (_inputs == null)
_inputs = new List<object>();
//Wrap the private field into a collection.
return new Collection<object>(_inputs);
}
}
}