Is there any way that could help me select specific data from table in Microsoft.AspNetCore.Datasync.EFCore - wpf

Am learning about data sync from API to WPF app. Got a demo from https://github.com/Azure/azure-mobile-apps/tree/main/samples. But I got into a problem that all the data inside the tables are collected on the call but I need to select specific data using Id. Tried a query etc all came to nothing. Please guide me
Thank you
PatientsController.cs
[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
public PatientsController(AppDbContext context)
: base(new EntityTableRepository<Patients>(context))
{
}
}
AppDbContext.cs
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Patients> Patients => Set<Patients>();
}

Try to use the following code:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Patients> Patients {get;set;}
}
controller:
[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
private readonly AppDbContext _context;
public PatientsController(AppDbContext context)
: base(new EntityTableRepository<Patients>(context))
{
_context=context;
}
public async Task<IActionResult> Index(int id){
var Patients=_context.Patients.FindAsync(id);
return View(Patients);
}
}

If you just need to get a record by Id, you use the URL https://mysite/tables/myTable/id - no search required - it will go directly to the entity you want.
If you need to limit what a user can see, you will need to implement an access control provider (which is an implementation of IAccessControlProvider). This provides three methods to limit what a user can see and do model updates for ensuring the write operations store the right thing. You can read more here: https://learn.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/howto/server/dotnet-core#configure-access-permissions
If it's something else, you'll need to be a little more specific. I hang out in the issues and discussions of the azure/azure-mobile-apps repo, so feel free to file a question there.

Related

How can I access HttpContext Header values in Static class

I am programming an ASP.NET Core 5.0 Web API.
I have a CurrentUser class like this. I want to access the header info anywhere in the project by using CurrentUser.Id. How can I do that? (or where can I initialize httpContext variable?)
public class CurrentUser
{
private static HttpContext _context;
private static UserDto _myUserObj;
public static void Initialize(AuthorizationFilterContext context)
{
_context = context.HttpContext;
_myUserObj = context.HttpContext.Request.Headers["User"] as UserDto;
}
public static int Id()
{
return _myUserObj.Id
}
}
I found some solutions. But I think its not best practice solutions. (There must be another and better way..)
MySolutions is that:
I am building a custom Attribute and i am adding it every API Controller like this:
[MyCustomAttribute]
public class UserController : ControllerBase{
//blablabla
}
After this : I am setting my CurrentUser.Initilaze() method in this Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute: Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//fortest
var userObj = context.HttpContext.Request.Headers["User"];//working
var userObj2 = JsonSerializer.Deserialize<UserDto>(userObj, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});//working
CurrentUser.Initialize(context);//working
var testResult = CurrentUser.Test();//working
}
}
So I can use CurrentUser static class everywhere in N-Layerd project and I am accessing UserId or another variables..
But i am saying again, I think its not best solution. Because I have to add [MyCustomAttribute] to all Controllers. There must be a better solition.

Trying to set up a Dapper-based Data Access Layer. ABP.Dapper documentation is confusing and incomplete

I'm trying to set up a simple DAL that will return a List of typed objects. Pretty standard data repository stuff. I downloaded all of ABP's code from GitHub, built the DLLs for Abp.Dapper and Abp.EntityFrameworkCore and started following the instructions on this page:
https://aspnetboilerplate.com/Pages/Documents/Dapper-Integration
But I can't even get past step one of this. This code doesn't compile because it doesn't know what SampleApplicationModule is. But there's no guidance in these instructions as to what that is supposed to be.
How am I supposed to use Abp's libraries? I'm lost. Can someone please let me know the minimum number of things I need to do in order to wire up my database to Abp's library and query for a List of typed objects?
Code from Abp's Dapper Integration documentation:
[DependsOn(
typeof(AbpEntityFrameworkCoreModule),
typeof(AbpDapperModule)
)]
public class MyModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(SampleApplicationModule).GetAssembly());
}
}
if you are confused what to write for SampleApplicationModule use the below code
Module Registration
[DependsOn(
typeof(AbpEntityFrameworkModule),
typeof(AbpKernelModule),
typeof(AbpDapperModule)
)]
public class SampleApplicationModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
Usage
public class SomeDomainService : ITransientDependency
{
private readonly IDapperRepository<Animal> _animalDapperRepository;
private readonly IRepository<Animal> _animalRepository;
private readonly IDapperRepository<Person> _personDapperRepository;
private readonly IRepository<Person> _personRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public SomeDomainService(
IUnitOfWorkManager unitOfWorkManager,
IRepository<Person> personRepository,
IRepository<Animal> animalRepository,
IDapperRepository<Person> personDapperRepository,
IDapperRepository<Animal> animalDapperRepository)
{
_unitOfWorkManager = unitOfWorkManager;
_personRepository = personRepository;
_animalRepository = animalRepository;
_personDapperRepository = personDapperRepository;
_animalDapperRepository = animalDapperRepository;
}
public void DoSomeStuff()
{
using (IUnitOfWorkCompleteHandle uow = _unitOfWorkManager.Begin())
{
_personRepository.Insert(new Person("Oğuzhan"));
_personRepository.Insert(new Person("Bread"));
_animalRepository.Insert(new Animal("Bird"));
_animalRepository.Insert(new Animal("Cat"));
_unitOfWorkManager.Current.SaveChanges();
Animal animal = _animalRepository.FirstOrDefault(x => x.Name == "Bird");
Person person = _personDapperRepository.Get(1);
int personCount = _personDapperRepository.Count(x => x.Name == "Oğuzhan");
List<Animal> persons = _animalDapperRepository.GetList(x => x.Name.StartsWith("O")).ToList();
uow.Complete();
}
}
}
See the related post for AbpDapper
https://github.com/aspnetboilerplate/aspnetboilerplate/pull/1854#issuecomment-284511423
PS: Abp.Dapper integration is implemented by the community.

asp.net identity authentication for simple registration -- asp.net mvc

I am about to start a project that needs custom identity authetication and authorization.
For authentication I am asking this question.
I need to know how can I create ExampleDBContext class that extends from DBContext class? and what settings I need to do in Startup.Auth.cs to make it work. And for registration, what should be the name of the registration table and what should be its columns? and what other tables and their columns need to be there?
There is so much info related to identity authentication but nothing actually useful. thanks
I'm not sure but I think you want something like this:
ExampleDbContext.cs
public class ExampleDbContext : IdentityDbContext<User>, IExampleDbContext
{
public ExampleDbContext()
: base("yourConnectionStringName", throwIfV1Schema: false)
{
}
public static ExampleDbContext Create()
{
return new ExampleDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
}
void IDisposable.Dispose()
{
this.Dispose();
}
}
You can use the code first method to generate the tables. That means that you can customize your User model the way you want. Here is the example of
User.cs
public class User : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
In the Users you can see that I've added some custom fields (FirstName LastName) and if you use the code first you can generate the custom Users table and use it for authentication. No need to add anything in Startup.Auth.cs you just need to setup dependency injection correctly.

Bind data from WCF Ria Services to data grid Entity Framework Code First

I've created simple POCO class like this :
public class Entity
{
public int Id { get; set; }
public bool IsActive { get; set; }
}
And this is my EF DbContext :
public class SampleContext:DbContext
{
public DbSet<Entity> Entities { get; set; }
}
I defined sample logic layer like this :
public class EntityTask : IEntityTask
{
#region Implementation of IEntityTask
public IEnumerable<Entity> GetAll()
{
var contex = new SampleContext();
return contex.Entities.ToList();
}
#endregion
}
public interface IEntityTask
{
IEnumerable<Entity> GetAll();
}
This is DomainService class that defined in server project :
[EnableClientAccess()]
public class CrudService : DomainService
{
private readonly IEntityTask _entityTask;
public CrudService(IEntityTask entityTask)
{
_entityTask = entityTask;
}
public IQueryable<Entity> GetAll ()
{
return _entityTask.GetAll().AsQueryable();
}
}
After these steps I don't know how to bind data to DataGrid in silverlight project.
I've checked many links on the web but many of them use wizard to bind data to datagrid.
How do I bind entities to DataGrid ?
Start marking your entity with the KeyAttribute (probably on the Id property) then
you must indicate to msbuild how to create the proxy counterpart of your service (named the DomainContext): in your silverlight project under properties tab
select your "server side" project and build the solution.
Client side a proxy will be generated, check it by looking in the client project (be sure to press "Show all files in Solution Explorer" and look for something similar to the image below
Under the Generated_Code hidden folder you'll find your DomainContext.
From now on it should be pretty straightforward to load and bind your data. Look at the excellent blog posts series by Brad Abrams here, you'll find everything you need.

MEF Importing ViewModel that needs data, to View for Silverlight

I'm not sure the best way to get this accomplished. Here's my view:
public partial class MyPage : Page
{
[Import]
public MyVM ViewModel
{
get { return DataContext as MyVM ; }
set { DataContext = value; }
}
public String EventName { get; set; }
public MyPage()
{
InitializeComponent();
CompositionInitializer.SatisfyImports(this);
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{ }
}
And my VM:
[Export]
public class MyVM : ViewModelBase
{
public MyVM ()
{
}
}
This works great. However, I need to get data from either the viewmodel that has my string, or the URL. Either way, I'm not sure the best way to get the string to MyVW using MEF.
I thought ok I'll use Messaging from MVVMLight, but the MyVM class isn't instantiated yet to receive the broadcast from the other ViewModel. So then I thought well, I'll try this:
[Export]
public class MyVM : ViewModelBase
{
public MyVM ([Import("hello")]string hello)
{
}
}
and then put this in the view:
[Export("hello")]
public String MyHello { get; set; }
but that gave me an error. Cannot call SatisfyImports on a object of type 'Form A' because it is marked with one or more ExportAttributes.
So what's the best way to accomplish this?
To share data between views I usually inject a SharedData object into my ViewModels.
[Import(RequiredCreationPolicy = CreationPolicy.Shared)]
public ISharedData SharedData { get; set; }
I'm also using the Caliburn Micro framework so I'm not passing data around via the URL querystring. By convention CM will parse out URL parameters and inject them into properties on your VM but I'm not sure if this functionality only applies to Windows Phone development.
from here
Examine the Page’s QueryString. Look
for properties on the VM that match
the QueryString parameters and inject
them, performing the necessary type
coercion.
When you say you want to possibly pass data from the view to the vm, that should happen through databinding.

Resources