using a factory to create new objects in ValueInjecter - valueinjecter

When using the format...
var customerInput = Mapper.Map<CustomerInput>(customer);
A CustomerInput is created using Activator.CreateInstance. I would think there should be a way to use a factory to create these objects. So we would like to...
var customerInput = Mapper.Map<ICustomerInput>(customer);
...where we could use a factory to map ICustomerInput to a "new" CustomerInput.
Is there a way to do this with ValueInjecter?

you can use the "additional parameters" feature for this:
var customer = Mapper.Map<Customer>(foo, new Customer { ... });
you can use this parameter in AddMap like this:
Mapper.AddMap<Foo, Customer>((src, tag) =>
{
var res = (Customer)tag;
res.InjectFrom(src);
res.A = src.B + src.C;
...
return res;
});

Related

web api - list all data types on a class

I'm trying to list all the data types on a class and after give the information to a client
i know that i have to use the GetType. So here is what i have at the moment
var variables = typeof(MockClass).GetType()
.Select(field => field.Name) //error: 'Type' does not contain a definition for select
.ToList();
I'm trying to enter inside the class, use a query to select all the variables name and try to get their data type.. Any ideas?
Try this
var type = typeof(MockClass);
var nestedTypes = new List<Type>();
var typeNames = new List<string>();
var propertiesNames = new List<string>();
foreach(var p in type.GetProperties())
{
var t = p.PropertyType;
nestedTypes.Add(t);
typeNames.Add(t.Name);
propertiesNames.Add(p.Name);
}

Linq in C# using IEnumerable

Appearently, I got an error if using the following code. It said:
Cannot implicity converrt type System.Linq.IQueryable<AnonymousType> to System.Collection.Generic.IEnumerable.
Please advise how I can fix this?
public IEnumerable<Session> GetAllListDetailConsumer(string refId)
{
ObjectQuery<Session> sessions = db.Sessions;
ObjectQuery<SessionsList> sessionsLists = db.SessionsList;
var query =
from s in sessions
join sList in sessionsLists on s.ReferralListID equals sList.ReferralListID
where s.ReferralListID == new Guid(refId)
select new SessionConsumerList
{
ReferralListID = s.ReferralListID,
SessionServerId = s.SessionServerID,
ApplicationID = s.ApplicationID,
// ...
ConsumerID = sList.ConsumerID,
ConsumerFirstName = sList.ConsumerFirstName,
ConsumerFamilyName = sList.ConsumerFamilyName,
// ...
};
return query.ToList();
}
You are selecting using select new, which would create an anonymous type, you need to project to class Session in your query like.
select new Session
{
....
But remember if your Session class is a representing a table in your database/data context, then you can't project to that class, instead you may have to create a temporary class and project the selection to that class.
EDIT (Since the question now has been edited)
Now you are selecting new SessionConsumerList and you are returning IEnumerable<Session>, you need to modify method signature to return IEnumerable<SessionConsumerList>
Why not separate the creation of the SessionConsumerList in another method? Makes the code a lot cleaner. Like this:
public static SessionConsumerList CreateSessionConsumerList(
Session s,
SessionsList sList)
{
return new SessionConsumerList
{
ReferralListID = s.ReferralListID,
SessionServerId = s.SessionServerID,
ApplicationID = s.ApplicationID,
// ...
ConsumerID = sList.ConsumerID,
ConsumerFirstName = sList.ConsumerFirstName,
ConsumerFamilyName = sList.ConsumerFamilyName,
// ...
};
}
And then:
var query =
from s in sessions
join sList in sessionsLists on s.ReferralListID equals sList.ReferralListID
where s.ReferralListID == new Guid(refId)
select CreateSessionConsumerList(s, sList);

Backbone.js + MVC3. Nested collection doesn't get populated

I have a backbone collection on the client.
Model of the collection has some properties along with another collection
When I do fetch() my action method on the server returns some data, collection gets populated, all the properties too, except that nested collection.
What could be the reason?
var Job = Backbone.Model.extend();
var Jobs = Backbone.Collection.extend({model: Job})
var Foo = Backbone.Model.extend({
initialize:function(){
this.jobs = new Jobs();
}})
var FooCollection = Backbone.Collection.extend({model: Foo})
var fooCol = new FooCollection()
fooCol.fetch();
fooCol.first().get('name') // => returns name
fooCol.first().jobs.toJSON() // returns nothing
// although this will
fooCol.first().get('jobs') //it will return an array
So somehow nested Backbone collection becomes just a regular property (Array)
OK - with your extra information, I can give you an answer.
First - "get" doesn't get a property off of the model. It gets a property off of the model's attributes property. So, the attributes probably look like:
{
name: 'blah',
jobs: [{name: 'job1'}, {name: 'job2'}]
}
Backbone doesn't automagically transform arrays into collections and models, and simply setting this.jobs isn't going to work. What you need to do is a little more complex.
var Foo = Backbone.Model.extend({
initialize:function(){
this.jobs = new Jobs(this.attributes.jobs));
}
});
This will set your 'jobs' property to a new jobs object with the data that was sent over for the jobs. But, alas, it won't automatically fire events on the Jobs collection, nor will it allow you to use helpers like this.get('jobs').each(fn); - you'll only be able to use it as Foo.jobs.each(fn).
In order for you to use the attribute as an actual collection, you'll have to do a lot more complicated things.
var Foo = Backbone.Model.extend({
initialize:function(){
this.createJobs(this.attributes.jobs);
},
toJSON: function () {
var json = Backbone.Model.prototype.toJSON.apply(this);
json.jobs = this.get('jobs').toJSON();
return json;
},
set: function (key, val) {
var attributes;
if(!_.isObject(key)) {
attributes = {}; attributes[key] = val;
} else {
attributes = key;
}
safeAttributes = _.omit(attributes, 'jobs');
Backbone.Model.prototype.set.call(this, safeAttributes);
if(attributes.jobs) { this.get('jobs').reset(attributes.jobs); }
},
clear: function () {
if(this.get('jobs') && this.get('jobs').destroy) {
this.get('jobs').off();
this.get('jobs').destroy();
}
Backbone.Model.prototype.clear.apply(this);
this.createJobs();
},
createJobs: function (jobsArray) {
var jobsCollection = new Jobs(jobsArray);
jobsCollection.on('change', function () {this.trigger('change'); }, this);
this.set('jobs', jobsCollection);
}
});
Note that this is completely untested, but hopefully it shows some of the way you'd do this.

django multiple model in dictionary json

I want to pass to create a json output with a dictionary with multiple models, like this:
results = {}
results["game_info_db"] = db.gameInfo.objects.get(name='name')
results["dlc_list_db"] = db.gameAddon.objects.filter(game__name='name')
What i tried is serialize (serializers.serialize) all dicts entrys and after this i dumps (simplejson.dumps) all the dict... but it doesn't seems to be correct ...
any sugestion ?
You could pass in the values of the models and convert it to a list:
results = {}
results["game_info_db"] = list(db.gameInfo.objects.get(name='name').values())
results["dlc_list_db"] = list(db.gameAddon.objects.filter(game__name='name').values())
return HttpResponse(json.dumps(results), mimetype='application/javascript')
The data will appear as objects on the javascript side. Assuming you have a name column, you can access the attributes like the following:
$.getJSON("/ajax/", function(data) {
var dlcs = data.dlc_list_db;
for (i = 0; i < dlcs.length; i++) {
var dlc = dlcs[i];
alert(dlc.name);
}
});

How to make IQueryable<out T> work with a reqular IQueryable?

I am using Linq2SQL and working with a legacy system. The system was built in .Net but without a datalayer so I am transcoding it so that it will have one. I have a linq query that looks like this...
var data = from p in db.tblPeoples
orderby p.strLastName,p.strFirstName
select new
{
guidPersonId = p.guidPersonId,
strFirstName = p.strFirstName,
strLastName = p.strLastName,
strRank = p.tblCodesRank.strDescription,
strPhone = p.strPhone,
strEmail = p.strEmail,
strOffice = p.tblOrganization.strAcronym,
RolesList = p.tblRoles
};
and when I check the signature of the var it is an IQueryable and I have no idea what that is. In my datalayer I have this returning as an IQueryable, but when I try to use the datalayer version and then do a .where on the returned dataset to search on it, I get errors that I Cannot convert lambda expresstion to type 'string' because it is not a delegate type.
What should I do about this? I am trying to create code reuse and use my datalayer version that is already written. the data layer version looks like this:
public static IQueryable RetrieveAllPeople()
{
var data = from p in db.tblPeoples
orderby p.strLastName, p.strFirstName
select new
{
guidPersonId = p.guidPersonId,
strFirstName = p.strFirstName,
strLastName = p.strLastName,
strRank = p.tblCodesRank.strDescription,
strPhone = p.strPhone,
strEmail = p.strEmail,
strOffice = p.tblOrganization.strAcronym,
RolesList = p.tblRoles
};
return data;
}
Your return type should be IQueryable<T>, which is not the same as IQueryable.
To do so, you need to create a class to fill in your select instead of using an anonymous one like you do.

Resources