DNN DAL 2 Transactions Accross multiple Repositories - dotnetnuke

I have the following application design
Entities (Models)
Customer
Order
Repositories - Wrapper Around the DNN DAL2 Repository for CRUD
CustomerRepo
OrderRepo
How to implement Transaction support accross multiple repositories
for e.g
using(IDataContext ctx = DataContext.Instance()) {
ctx.BeginTransaction();
CustomerRepo.Create(customer);
order.CustomerID = customer.ID;
OrderRepo.Create(Order);
ctx.CommitTransaction();
}
CustomerRepo Example.
class CustomerRepo
{
public Customer Create(Customer customer) {
using(IDataContext ctx = DataContext.Instance())
{
var repo = ctx.GetRepository<Customer>();
repo.Insert(customer);
}
return customer;
}
}

Related

How to save app data after restart of an app - flutter?

I was wondering how to make my app save data after restart? (The user can delete task and add new task to list, as well as check the box that the task is done. I want the app to save this data so when the user exists the app it will display all the tasks that he left the app with)
I was reading on google for few hours now, I got to
[1]: https://flutter.dev/docs/cookbook/persistence/reading-writing-files
This link as someone recommended on a similar post. But after reading it through I am a bit confused about where to start with my app.
Including some of my code and if you could help me I would really appreciate it as after hours of reading and watching tutorials I am still quite unsure where to start or which way of doing this is best.
My main.dart is this
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) =>
TaskData(), //changing builder: to create: fixed the errors i been having
child: MaterialApp(
home: TasksScreen(),
),
);
}
}
class TaskData extends ChangeNotifier {
List<Task> _tasks = [
Task(name: "Sample task 1"),
Task(name: "Sample task 2"),
Task(name: "Sample task 3"),
];
UnmodifiableListView<Task> get tasks {
return UnmodifiableListView(_tasks);
}
int get taskCount {
return _tasks.length;
}
void addTask(String newTaskTitle) {
final task = Task(name: newTaskTitle);
_tasks.add(task);
notifyListeners();
}
void updateTask(Task task) {
task.toggleDone();
notifyListeners();
}
void deleteTask(Task task) {
_tasks.remove(task);
notifyListeners();
}
Thank you so much!
The basic method is using the device local storage.
1 - Add the shared_preferences in your pubspec.yaml
2 - Create a class to write and read data :
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class StoreData {
StoreData._privateConstructor();
static final StoreData instance = StoreData._privateConstructor();
Future<void> saveString(String key, String value) async {
try{
SharedPreferences pref = await SharedPreferences.getInstance();
final encodedValue = base64.encode(utf8.encode(value));
pref.setString(key, encodedValue);
} catch (e){
print('saveString ${e.toString()}');
}
}
Future<String> getString(String key) async {
SharedPreferences pref = await SharedPreferences.getInstance();
final value = pref.getString(key) == null ? '' : pref.getString(key);
if (value.length > 0) {
final decodedValue = utf8.decode(base64.decode(value));
return decodedValue.toString();
}
return '';
}
Future<bool> remove(String key) async {
SharedPreferences pref = await SharedPreferences.getInstance();
return pref.remove(key);
}
}
3 Use :
Save Data:
StoreData.instance.saveString('name', 'sergio');
Retrieve Data:
final String storedName = await StoreData.instance.getString('name');
print('The name is $storedName');
We have many other methods, like use a SQlite, NoSql or a Database in back-end, but the local storage is the most basic case
What you need is a database or a document based data storage. You can store data in a local sqlite db, using sqflite plugin. Or you can store in a JSON asset file.
You can also use a server or cloud service. Firebase is pretty well integrated with flutter, but AWS and Azure are also great.
You can write the data in a text file in the asset, but that would very complicated.

Creating new Role (by code) during the Tenant creation process from UI (ABP.IO)

I am trying to add the creation of roles while I create a new Tenant from the UI on ABP.IO Framework version 4.
From ABP.IO documentation, I found that by using the existing class SaasDataSeedContributor I can "seed" some datas while I am creating a new Tenant.
My issue is that from this class, I do not have permission to use IIdentityRoleAppService.CreateAsync method (Given policy has not granted).
So I tried to go through an AppService and use IdentityRoleManager or even IIdentityRoleRepository,but it is not possible to create IdentityRole object as the constructor is inaccessible due to his protection level.
Any thought about it? Is there any another way to do action while creating a tenant appart using SaasDataSeedContributor. Or maybe I am doing something wrong here.
Thanks for your help
Try this.
public class AppRolesDataSeedContributor : IDataSeedContributor, ITransientDependency
{
private readonly IGuidGenerator _guidGenerator;
private readonly IdentityRoleManager _identityRoleManager;
public AppRolesDataSeedContributor(IGuidGenerator guidGenerator, IdentityRoleManager identityRoleManager)
{
_guidGenerator = guidGenerator;
_identityRoleManager = identityRoleManager;
}
public async Task SeedAsync(DataSeedContext context)
{
if (context.TenantId.HasValue)
{
// try this for a single known role
var role = await _identityRoleManager.FindByNameAsync("new_role");
if (role == null)
{
var identityResult = await _identityRoleManager.CreateAsync(
new IdentityRole(_guidGenerator.Create(), "new_role", context.TenantId.Value));
}
// or this (not tested) for multiple roles
/*
var newRoles = new[] { "role1", "role2" };
var identityRoles = from r
in _identityRoleManager.Roles
where r.TenantId == context.TenantId.Value
select r.Name;
var except = newRoles.Except(identityRoles.ToList());
foreach (var name in except)
{
var identityResult = await _identityRoleManager.CreateAsync(
new IdentityRole(_guidGenerator.Create(), name, context.TenantId.Value));
}
*/
}
}
}

About load supported cultures from DB in .NET CORE

I have a Language entity with all supported languages in my db, each language has a culture string attribute. I want to load supported cultures from DB.
In my service initializer I have it:
public void ConfigureServices(IServiceCollection services)
{
// ... previous configuration not shown
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-GB"),
new CultureInfo("en-US"),
new CultureInfo("en"),
new CultureInfo("fr-FR"),
new CultureInfo("fr"),
};
opts.DefaultRequestCulture = new RequestCulture("en-GB");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
}
How I can access my DB context inside it?
There is any other better way to do it?
I don't think there's an out of the box solution for this.
However, you can implement your own middleware that achieves this by using ASP.Net's RequestLocalizationMiddleware:
public class CustomRequestLocalizationMiddleware
{
private readonly RequestDelegate next;
private readonly ILoggerFactory loggerFactory;
public CustomRequestLocalizationMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
this.next = next;
this.loggerFactory = loggerFactory;
}
public async Task Invoke(HttpContext context /* You can inject services here, such as DbContext or IDbConnection*/)
{
// You can search your database for your supported and/or default languages here
// This query will execute for all requests, so consider using caching
var cultures = await Task.FromResult(new[] { "en" });
var defaultCulture = await Task.FromResult("en");
// You can configure the options here as you would do by calling services.Configure<RequestLocalizationOptions>()
var options = new RequestLocalizationOptions()
.AddSupportedCultures(cultures)
.AddSupportedUICultures(cultures)
.SetDefaultCulture(defaultCulture);
// Finally, we instantiate ASP.Net's default RequestLocalizationMiddleware and call it
var defaultImplementation = new RequestLocalizationMiddleware(next, Options.Create(options), loggerFactory);
await defaultImplementation.Invoke(context);
}
}
Then, we inject the required services and use the custom middleware in Startup.cs or Program.cs as follows:
services.AddLocalization()
/* ... */
app.UseMiddleware<CustomRequestLocalizationMiddleware>()
Do not call app.UseRequestLocalization(), because this would call ASP.Net's RequestLocalizationMiddleware again with the default options, and override the culture that has been resolved previously.

Spring Boot JPA: How to avoid creating multiple repositories for identical databases?

My spring boot mvc project interacts with a database via a repository interface, which works nicely using Spring boot default configurations:
spring:
datasource:
url: jdbc:mysql://localhost/some_schema
username:
...
#Configuration
#EnableJpaRepositories(basePackages = {"my.path.to.repository"})
public class Application extends WebMvcConfigurerAdapter {
....
Now depending on some runtime condition, I need to interact with an identical second database (same schema) in a separate location. The solutions I found all point to creating a separate repository package per datasource.
Since the databases are identical, however, is there an elegant way to avoid duplicating the repository package for each added datasource?
You can accomplish this with a Spring AbstractRoutingDataSource.
Roughly:
public class ChooseOneDataSource extends AbstractRoutingDataSource {
#Override
protected Object determineCurrentLookupKey() {
if (***some runtime condition***) {
return "dataSource1";
} else {
return "dataSource2";
}
}
}
And in your conguration:
#Bean
#ConfigurationProperties(prefix = "dataSource1")
DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
#Bean
#ConfigurationProperties(prefix = "dataSource2")
DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
#Bean
DataSource dataSource() {
AbstractRoutingDataSource dataSource = new ChooseOneDataSource();
Map<Object,Object> resolvedDataSources = new HashMap<>();
resolvedDataSource.put("dataSource1", dataSource1());
resolvedDataSource.put("dataSource2", dataSource2());
dataSource.setDefaultTargetDataSource(dataSource1()); // << default
dataSource.setTargetDataSources(resolvedDataSources);
return dataSource;
}
For more info/examples:
http://fizzylogic.nl/2016/01/24/Make-your-Spring-boot-application-multi-tenant-aware-in-2-steps/
https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

How to Consume Secured Web Api from C# MVC and AngularJS

How to Consume Secured Web Api from other application C# MVC and AngularJS .
[Authorize(Users = "Steve,Mike")]
public class EmployeeController : ApiController
{
MyDB db = new MyDB();
public IEnumerable<EmployeeViewModel> GetAllEmployee()
{
return db.Employee.Select(item => new EmployeeViewModel { EmpID = item.EmpID, Name = item.Name, Region = item.Region }).ToList();
}
}
The following code I can get without Secure WebApi from AngularJS
var ft = searchText.toLowerCase();
$http.get('/api/Employee/GetAllEmployee').success(function (largeLoad) {
data = largeLoad.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data, page, pageSize);
});
Your help is highly appreciated...
what kind of Secured Web Api do you want to consume?
you may think about oAuth

Resources