Let's say I have the following mappings. Is there a way to reuse the ForMember so that I don't have duplicate code?
I have 2 objects (A, ARequest) that needs to map to the same object (B)
this.CreateMap<A, B>()
.ForMember(dest => dest.test1, opts => opts.MapFrom(src => src.test1))
.ForMember(dest => dest.test2, opts => opts.MapFrom(src => src.test2))
this.CreateMap<ARequest, B>()
.ForMember(dest => dest.test1, opts => opts.MapFrom(src => src.test1))
.ForMember(dest => dest.test2, opts => opts.MapFrom(src => src.test2))
Related
When I try to map a POCO to UserPrincipal(AD) I have a problem that Mapper needs a default constructor with 0 parm. I'm using autmapper.
The error is "UserPrincipal needs to have a constructor with 0 args or only optional args."
How can I fix this?
Below my code.
public bool Add(User user)
{
try
{
var userPrincePrincipal = _mapper.Map<UserPrincipal>(user,opt=>opt.ConstructServicesUsing(c=> new PrincipalContext(ContextType.Domain, Environment.UserDomainName)));
userPrincePrincipal.Save();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return false;
}
return true;
}
public UserMapper()
{
CreateMap<User, UserPrincipal>()
.ForMember(dest => dest.GivenName, act => act.MapFrom(src => src.Name))
.ForMember(dest => dest.AccountExpirationDate, act => act.MapFrom(src => src.AccountExpirationData))
.ForMember(dest => dest.EmailAddress, act => act.MapFrom(src => src.EmailAddress))
.ForMember(dest => dest.MiddleName, act => act.MapFrom(src => src.MiddleName))
.ForMember(dest => dest.EmployeeId, act => act.MapFrom(src => src.EmployeeId))
.ForMember(dest => dest.VoiceTelephoneNumber, act => act.MapFrom(src => src.VoiceTelephoneNumber))
.ForMember(dest => dest.UserPrincipalName, act => act.MapFrom(src => src.UserPrincipalName))
.ForMember(dest => dest.Description, act => act.MapFrom(src => src.Description))
.ForMember(dest => dest.AccountLockoutTime, act => act.MapFrom(src => src.AccountLockoutTime))
.ForMember(dest => dest.AllowReversiblePasswordEncryption, act => act.MapFrom(src => src.AllowReversiblePasswordEncryption))
.ForMember(dest => dest.Description, act => act.MapFrom(src => src.Description))
.ForMember(dest => dest.Enabled, act => act.MapFrom(src => src.Enabled))
.ForMember(dest => dest.BadLogonCount, act => act.MapFrom(src => src.BadLogonCount))
.ForMember(dest => dest.DisplayName, act => act.MapFrom(src => src.DisplayName))
.ForMember(dest => dest.Name, act => act.MapFrom(src => src.Name))
.ForMember(dest => dest.HomeDirectory, act => act.MapFrom(src => src.HomeDirectory))
.ForMember(dest => dest.HomeDrive, act => act.MapFrom(src => src.HomeDrive))
.ForMember(dest => dest.SamAccountName, act => act.MapFrom(src => src.SamAccountName))
.ForMember(dest => dest.Sid, act => act.MapFrom(src => src.Sid))
.ForMember(dest => dest.UserCannotChangePassword, act => act.MapFrom(src => src.Sid))
.ForMember(dest => dest.SmartcardLogonRequired, act => act.MapFrom(src => src.SmartCardLogonRequired))
.ForMember(dest => dest.ScriptPath, act => act.MapFrom(src => src.ScriptPath))
.ForMember(dest => dest.PasswordNeverExpires, act => act.MapFrom(src => src.Company))
.ForMember(dest => dest.PasswordNotRequired, act => act.MapFrom(src => src.PasswordNotRequired))
.ForMember(dest => dest.PermittedLogonTimes, act => act.MapFrom(src => src))
.ForMember(dest => dest.BadLogonCount, act => act.MapFrom(src => src.BadLogonCount))
.ForMember(dest => dest.LastLogon, act => act.MapFrom(src => src.LastLogon))
.ForMember(dest => dest.LastBadPasswordAttempt, act => act.MapFrom(src => src.LastBadPasswordAttempt))
.ForMember(dest => dest.LastPasswordSet, act => act.MapFrom(src => src.LastPasswordSet))
.ForMember(dest => dest.LastBadPasswordAttempt, act => act.MapFrom(src => src.LastBadPasswordAttempt))
.ForMember(dest => dest.DelegationPermitted, act => act.MapFrom(src => src.DelegationPermitted))
.ForMember(dest => dest.Surname, act => act.MapFrom(src => src.Surname));
I am creating a web application using the REST Countries API (link given)
https://restcountries.com/.
The API gives json with the property borders, which is an array of strings giving the cca3 of the bordering countries. I would like to get the names of the countries too and so am making another request for that data. So far this is what I have come up with. But, the json returned from the first request is never changed. I don't know what is going on, if anybody could advice?
const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', (req, res, next) => {
const code = req.params.code
fetch(`${dataAPI}/alpha/${code}?fields=borders`)
.then(response => response.json())
.then(json => fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`))
.then(response => response.json())
.then(bordersJson => {
fetch(`${dataAPI}/alpha/${code}`)
.then(response => response.json())
.then(data => {
data.borders = bordersJson
res.send(data)
}).catch(err => next(err))
}).catch(err => next(err))
})
Async/await is a better approach for this case.
const dataAPI = 'https://restcountries.com/v3.1/'
router.get('/country/:code', async (req, res, next) => {
try {
const code = req.params.code;
const borderJSON = await fetch(`${dataAPI}/alpha/${code}?fields=borders`).then(response => response.json());
// response: {"borders":["BGD","BTN","MMR","CHN","NPL","PAK"]}
const codes = borderJSON.borders.join(',');
const cca3 = await fetch(`${dataAPI}/alpha?codes=${codes}&fields=cca3,name`)).then(response => response.json());
// [{"name":{...},"cca3":"BGD"},{"name":{...},"cca3":"PAK"}]
res.send(cca3);
} catch (err) {
next(err);
}
});
The reason the borders property was not replaced was that the API endpoint used returns an array with one object, not the object itself. Also, I found that finding the borders separately was unnecessary.
Final Solution
router.get('/country/:code', (req, res, next) => {
const code = req.params.code
fetch(`${dataAPI}/alpha/${code}`)
.then(response => response.json())
.then(json => {
json = json[0]
fetch(`${dataAPI}/alpha?codes=${json.borders.join()}&fields=cca3,name`)
.then(response => response.json())
.then(bordersJSON => {
json.borders = bordersJSON
res.send(json)
}).catch(err => next(err))
}).catch(err => next(err))
})
Code below retrieves the JSON data without any problems.
app.get('/startgame', (req, res) => {
res.send('Welcome To The Start Of The Game')
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/deck_count=1")
.then(res => res.json())
.then(json => console.log(json))
})
Code below returns undefined when I do console.log(json). The only difference between these two blocks of code are the squiggly brackets on the bottom block of code. I would like to know why exactly is this happening. My understanding is that they should both produce the same result.
app.get('/startgame', (req, res) => {
res.send('Welcome To The Start Of The Game')
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1")
.then((res) => {res.json()})
.then((json) => {console.log(json)})
})
The reason is that this syntax:
() => foo()
Is short for:
() => { return foo(); }
On this line in your code:
.then((res) => { res.json() })
you are no longer returning the result of res.json(). You need to explicitly use return when you use curly braces:
.then((res) => { return res.json(); })
Which is equivalent to:
.then((res) => res.json())
I am deploying this code on cloud functions, getting Cannot modify a WriteBatch that has been committed, I have tried committing after getting every collection but it's not a right way and is inconsistent, could not spot the error after trying several hours. Also the code run on first time after cold start , this post has same problem Batch write to firebase cloud firestore , where to create
a new batch for each set of writes.
in this code .
var batch = db.batch();
db.collection("myposts")
.doc(post_id)
.collection("fun")
.get()
.then(snapshot => {
return snapshot.forEach(doc => {
batch.delete(doc.ref);
});
})
.then(
db
.collection("relations_new")
.where("uid", "==", uid)
.get()
.then(snapshot => {
return snapshot.forEach(doc => {
batch.delete(doc.ref);
});
})
)
.then(
db
.collection("relation")
.where("uid", "==", uid)
.get()
.then(snapshot => {
return snapshot.forEach(doc => {
batch.delete(doc.ref);
});
})
.catch(err => {
console.log(err);
})
)
.then(
db
.collection("posts")
.doc(post_id)
.get()
.then(snap => {
return batch.delete(snap.ref);
})
.then(batch.commit())
)
.catch(err => {
console.log(err);
});`
Make sure to return promises from your then functions, and to ultimately return a promise from your cloud function. ESLint is a great tool for catching these kinds of errors.
let batch = db.batch();
return db.collection("myposts").doc(post_id)
.collection("fun").get()
.then(snapshot => {
snapshot.forEach(doc => {
batch.delete(doc.ref);
});
return null;
})
.then(() => {
return db.collection("relations_new")
.where("uid", "==", uid)
.get();
})
.then(snapshot => {
snapshot.forEach(doc => {
batch.delete(doc.ref);
});
return null;
})
.then(() => {
return db.collection("relation")
.where("uid", "==", uid)
.get();
})
.then(snapshot => {
snapshot.forEach(doc => {
batch.delete(doc.ref);
});
return null;
})
.then(() => {
return db.collection("posts").doc(post_id).get();
})
.then(snap => {
batch.delete(snap.ref);
return null;
})
.then(() => {
return batch.commit();
})
.then(() => {
console.log("Success");
return null;
})
.catch(err => {
console.log(err);
});
I am using node.js. I have this function which uses promises to introduce delay between performing certain actions.
function do_consecutive_action() {
Promise.resolve()
.then(() => do_X() )
.then(() => Delay(1000))
.then(() => do_Y())
.then(() => Delay(1000))
.then(() => do_X())
.then(() => Delay(1000))
.then(() => do_Y())
;
}
What I want to do is to have this set of actions repeat itself forever. How can this be done in node.js?
//make following actions repeat forever
do_X()
Delay(1000)
do_Y()
Delay(1000)
EDIT: I started a bounty for answers that use a repeating queue to solve the problem.
Just use recursion
function do_consecutive_action() {
Promise.resolve()
.then(() => do_X() )
.then(() => Delay(1000))
.then(() => do_Y())
.then(() => Delay(1000))
.then(() => do_consecutive_action())
// You will also want to include a catch handler if an error happens
.catch((err) => { ... });
}
function cb(func) {
try {
func();
}
catch (e) {
do_consecutive_action();
}
}
function do_consecutive_action() {
Promise.resolve()
.then(() => cb(do_X))
.then(() => Delay(1000))
.then(() => cb(do_Y))
.then(() => Delay(1000))
.then(() => do_consecutive_action())
// You will also want to include a catch handler if an error happens
.catch((err) => { ... });
}