Asp.Net Boilerplate...How to search in existing tables? - async-await

I want to apply queries on Boilerplate default tables in database. But boilerplate uses async methods. How to search in database by Boilerplate framework.

Could you elaborate your question?
I'm not sure what do you want to achieve.
If you uses IRepository you can use both synchronous and asynchronous methods by default.
If you're using asynchronous query and expecting immediate result you can use
If you have to wait for query results you can use Result property of Task. e.g.
var valueImWaitingFor = _repository.GetAllListAsync().Result;
Edit:
Assuming that you want to update user under login you can use provided UserManager class.
var user = loginResult.User; // get your user object
user.Name = "New name"; // edit property
// use one of 3 proposed solutions.
var updatedUser = _userManager.Update(user);
var updatedUser1 = _userManager.UpdateAsync(user).ConfigureAwait(false);
var updatedUser2 = AsyncHelper.RunSync(()=>_userManager.UpdateAsync(user));
Even if you don't use UserManager you can run async call similar way using second and third option.

If you want to use async methods as sync methods then there's a helper class in ABP.
var records = AsyncHelper.RunSync(() => _repository.GetAllListAsync());

Related

ReactiveUI - ReactiveCommand to get more data for objects in ReactiveList

Currently I am learning ReactiveUI and I am not sure how to approach this problem. What I want to achieve is once a reactive list has been loaded (in this case I am using a command to load it from a local store) I want to be able to trigger that each of the items in the reactive list then go off and fetch data from an api endpoint and update the view model.
What I currently have to load and create the view models using this logic:
LoadSavedLocations = ReactiveCommand.CreateAsyncTask(async o => {
var savedLocations = await _savedLocationService.GetUserSavedLocations();
return savedLocations;
});
LoadSavedLocations.Subscribe(savedLocations =>
{
foreach (var savedZone in savedLocations)
{
Zones.Add(new ZoneDetailViewModel() {
ZoneId = savedZone.ZoneId,
SavedName = savedZone.SavedName,
});
}
});
I want to then be able to have a command that I can kick off (one first load of the screen and then when the user prompts for an update - pull for reload).
There are two ways I think I can do this but struggling with the approach and the code to achieve this.
Option 1
A command which loops through the items in the ReactiveList fetches data from the Api and then updates that viewmodel something along the lines of
UpdateZones = ReactiveCommand.CreateAsyncTask(async o =>
{
foreach (var zone in Zones)
{
// Fetch
// Await
// Update view model
}
return null;
});
With this I am confused around what the return type of the command would be just a new object()? Is there a better way than just looping like this?
Option 2
On the view model ZoneDetailViewModel have a command called FetchExtraData which will then return the data from the API and I can subscribe to that command in the view model and populate the extra properties. With this approach how does the parent viewmodel trigger all the items in the ReactiveList to fire their commands.
For both approaches I don't know how to get each of the items in the ReactiveList to do logic which involves going to an Api and update.

In Meteor, where do I model my business rules?

Beginner question : I've worked through the Try Meteor tutorial. I've got fields in my HTML doc, backed by helper functions that reference collections, and BOOM --> the fields are updated when the data changes in the DB.
With the "Hide completed" checkbox, I've also seen data-binding to a session variable. The state of the checkbox is stored in the Session object by an event handler and BOOM --> the list view is updated "automatically" by its helper when this value changes. It seems a little odd to be assigning to a session object in a single page application.
Through all this, my js assigns nothing in global scope, I've created no objects, and I've mostly seen just pipeline code, getting values from one spot to another. The little conditional logic is sprayed about wherever it is needed.
THE QUESTION... Now I want to construct a model of my business data in javascript, modelling my business rules, and then bind html fields to this model. For example, I want to model a user, giving it an isVeryBusy property, and a rule that sets isVeryBusy=true if noTasks > 5. I want the property and the rule to be isolated in a "pure" business object, away from helpers, events, and the meteor user object. I want these business objects available everywhere, so I could make a restriction, say, to not assign tasks to users who are very busy, enforced on the server. I might also want a display rule to only display the first 100 chars of other peoples tasks if a user isVeryBusy. Where is the right place to create this user object, and how do I bind to it from my HTML?
You can (and probably should) use any package which allows you to attach a Schema to your models.
Have a look at:
https://github.com/aldeed/meteor-collection2
https://github.com/aldeed/meteor-simple-schema
By using a schema you can define fields, which are calculated based on other fields, see the autoValue property: https://github.com/aldeed/meteor-collection2#autovalue
Then you can do something like this:
// Schema definition of User
{
...,
isVeryBusy: {
type: Boolean,
autoValue: function() {
return this.tasks.length > 5;
}
},
...
}
For all your basic questions, I can strongly recommend to read the DiscoverMeteor Book (https://www.discovermeteor.com/). You can read it in like 1-2 days and it will explain all those basic questions in a really comprehensible way.
Best Regards,
There is a very good package to implement the solution you are looking for. It is created by David Burles and it's called "meteor-collection-helper". Here it the atmosphere link:
You should check the link to see the examples presented there but according to the description you could implement some of the functionality you mentioned like this:
// Define the collections
Clients = new Mongo.Collection('clients');
Tasks = new Mongo.Collection('tasks');
// Define the Clients collection helpers
Clients.helpers({
isVeryBusy: function(){
return this.tasks.length > 5;
}
});
// Now we can call it either on the client or on the server
if (Meteor.isClient){
var client = Clients.findOne({_id: 123});
if ( client.isVeryBusy() ) runSomeCode();
}
// Of course you can use them inside a Meteor Method.
Meteor.methods({
addTaskToClient: function(id, task){
var client = Clients.findOne({_id: id});
if (!client.isVeryBusy()){
task._client = id;
Tasks.insert(task, function(err, _id){
Clients.update({_id: client._id}, { $addToSet: { tasks: _id } });
});
}
}
});
// You can also refer to other collections inside the helpers
Tasks.helpers({
client: function(){
return Clients.findOne({_id: this._client});
}
});
You can see that inside the helper the context is the document transformed with all the methods you provided. Since Collections are ussually available to both the client and the server, you can access this functionality everywhere.
I hope this helps.

Many update statements in one Transaction in Entity Framework

I need to update more than one update statements, but all should work on automicity i.e update all or none.
on internet and in someother SO Questions i have found how to use Transaction but i didnt' find any of them saying to update mulitple statements in one transaction.
See below three updates statements, currently there not running under transaction
/// this are my update calls.
var report = reportRepository.Update(reportModel);
var book = bookRepository.Update(bookModel);
var mobile = mobileRepository.Update(mobileModel);
// each Update method for all repository will looks like
public returnModel Update(someModel model)
{
// assign values from model to entity
Context.ObjectStateManager.ChangeObjectState(entity,System.Data.EntityState.Modified)
Context.SaveChanges();
}
You could wrap the updates in a TransactionScope:
using (TransactionScope transaction = new TransactionScope())
{
var report = reportRepository.Update(reportModel);
var book = bookRepository.Update(bookModel);
var mobile = mobileRepository.Update(mobileModel);
...
transaction.Complete();
}
As Darin mentioned use a transaction scope or my preferred method is to have your repositories belong to an IUnitOfWork interface. Calling update simply sets the state to modified and the SaveChanges happens OUTSIDE of your repository to save all changes at once.
This should happen automatically inside of one transaction.
So you call all your Updates and then unitOfWork.SaveChanges where your custom unit of work class contains a reference to your context and implements a method defines in IUnitOfWork called Save()
Basically you need to manage it through TransactionScope Class and using this you can set up multiple update to a Model and then use Transaction.Complete to save your stuff in one transaction.
Please check Updating multiple objects in single transaction in entity framework for more details.

Intercepting context.SaveChanges() in MVC 3 so that I can modify and use a custom sql query instead

I am working on an MVC3 project whose model is designed using Code First approach. I am using EF4 for ORM and have a need where I need two thing -
1. Intercept the context.SaveChages method
2.Do my own custom update query for one specific entity type only.
I got the first part working by overriding the SaveChanges() method like -
public override int SaveChanges()
{
var modifiedItems = this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Modified && e.Entity is myEntityName);
foreach (var item in modifiedItems)
{
//ToDo: Write UPDATE Sql Query here
}
return base.SaveChanges();
}
How can I write my update query?
Thanks!
This is not possible. You can only map custom stored procedures to be used instead of CUD operations (only with EDMX) generated by EF but still you will have single stored procedure call per each operation and entity instance.

How do you re-use select statements with Entity Framework?

Given the following query:
var query = from item in context.Users // Users if of type TblUser
select new User() // User is the domain class model
{
ID = item.Username,
Username = item.Username
};
How can I re-use the select part of the statement in other queries? I.e.
var query = from item in context.Jobs // Jobs if of type TblJob
select new Job() // Job is the domain class model
{
ID = item.JobId,
User = ReuseAboveSelectStatement(item.User);
};
I tried just using a mapper method:
public User MapUser(TblUser item)
{
return item == null ? null : new User()
{
ID = item.UserId,
Username = item.Username
};
}
With:
var query = from item in context.Users // Users if of type TblUser
select MapUser(item);
But if I do this, then the framework throws an error such as:
LINQ to Entities does not recognize
the method 'MapUser(TblUser)' method,
and this method cannot be translated
into a store expression.
You can't use regular function calls in a query definition like that. LINQ needs expression trees, it can't analyze compiled functions and magically translate that to SQL. Read this for a more elaborate explanation
The techniques used in the cited article are incorporated in linqkit (factoring out predicates) and might be of help, though I'm not sure you can use the same technique for managing projections, which is what you seem to want.
The more fundamental question you should ask yourself here IMHO is whether you really need this extra mapping layer? It seems like you're implementing something that EF is already perfectly capable of doing for you...
Try making your MapUser method static.

Resources