How to especify a current key-node in xamarin with firebase? - database

I’m working with Xamarin and FireBase, I have the next problem:
I have Users in my database and each one has a list of items. I need to retrieve the list of items of the current user, and the problem is that I don’t know how to replace the key of each user in the tree, (I just hard-wrote it). This is the snippet :
var products = (await client.Child("Users").Child("-MXf6T19md1UOTVvHWRU").Child("Items")
.OnceAsync<Item>())
.Select(f => new Item
{ . . .
Here is a picture of the database tree.
How do I replace the Child("-MXf6T19md1UOTVvHWRU") by the current branch where I’m at?, taking into account that I have to access another Child next to that. Of course I have access to the Username value that is stored in preferences.
I would appreciate some enlightenment, thanks in advance.

I need to retrieve the list of items of the current user, and the problem is that I don’t know how to replace the key of each user in the tree, (I just hard-wrote it).
You could use the code below to get all the items first and then get the specific item.
public async Task<List<User>> GetAllUsers()
{
return (await firebase
.Child("Users")
.OnceAsync<User>()).Select(item => new User
{
Name = item.Object.Name,
UserId = item.Object.UserId,
}).ToList();
}
public async Task<User> GetUser(int userId)
{
var allUsers = await GetAllUsers();
await firebase
.Child("Users")
.OnceAsync<User>();
return allUsers.Where(a => a.UserId == userId).FirstOrDefault();
}
Model:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
}
You could download the similar source code from the GitHub.
https://github.com/susairajs/Xamarin-Firebase-RealtimeDatabase

Related

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));
}
*/
}
}
}

VisualForce Page to render list of selected contacts

Here is a scenario , I am stuck in.
//edited post to elaborate more details.
Requirement: I need to email bulk of selected contacts. When there is no email to selected contacts, we are required to populate the name of contacts on UI who do not have the email. I am able to accomplish first part of requirement but stuck on displaying contact names on visual force page .
List button : BulkEmailTest which calls firstVF visual force page.
firstVF code:
<apex:page standardController="Contact" extensions="FirstController" recordSetVar="listRecs"
action="{!send}">
Emails are being sent!
window.history.back();
</apex:page>
FirstController code: for simplified code, I have edited snippet for contacts with email as our priority is only related to contacts with no email.
public with sharing class FirstController
{
public List noEmail {get;set;}
public Contact contact;
public List allcontact {get; set;}
Id test;
public Contact getAllContact() {
return contact;
}
ApexPages.StandardSetController setCon;
ApexPages.StandardController setCon1;
public static Boolean err{get;set;}
public FirstController(ApexPages.StandardController controller)
{
setCon1 = controller;
}
public FirstController(ApexPages.StandardSetController controller)
{
setCon = controller;
}
public PageReference cancel()
{
return null;
}
public FirstController()
{
}
public PageReference send()
{
noEmail = new List();
set ids = new set();
for(Integer i=0;i<setCon.getSelected().size();i++){
ids.add(setCon.getSelected()[i].id);
}
if(ids.size() == 0){
err = true;
return null;
}
List allcontact = [select Email, Name, firstName , LastName from Contact where Id IN :ids];
for(Contact current : allcontact)
{
system.debug(current);
if (current.Email!= null)
{
PageReference pdf = Page.pdfTest;
pdf.getParameters().put('id',(String)current.id);
system.debug('id is :'+current.id);
pdf.setRedirect(true);
return pdf;
}
else //No email
{
system.debug('in else current'+current );
noEmail.add(current);
// noEmail.add(current);
system.debug('in else noemail'+noEmail );
}//e
}
if(noEmail.size()>0 ) {
PageReference pdf1 = Page.NoEmailVF;
pdf1.getParameters().put('Name', String.valueOf(noEmail));
system.debug('pring noEmail' +noEmail);
pdf1.setRedirect(false);
return pdf1;
}
return null;
}
}
NoEmailVF visual force page code
<apex:page controller="FirstController">
Emails are not sent to below contacts :
Name
<apex:repeat var="cx" value="{!allcontact}" rendered="true">
{!cx.name}
Please note that emails are not sent to selected Donors only when
they did not make any donation for that year or if they do not have email address listed.
If you still wish to retrieve donations made in this year, then you may use "Hard Copy" button listed on the Donor record to have the data printed.
.
It doesn't look like your apex:commandButton has any action. If it doesn't have an action prop, no contact is being made with your Apex code. So no oncomplete should fire.
Also, when you want to refresh some data after completing some Apex call, you can use reRender prop. Put your dynamic data in an apex:outputPanel (docs), give the apex:outputPanel an id and pass that id to the reRender of your button.
See apex:commandButton docs

How to post array as form data in Angular Typescript

I am working in Angular 8 and is using web.api in .net core 2.2
I have a form including some "regular" inputs, a file and multi selectable checkboxes.
The problem is the multi selectable checkboxes, that I turn into an array of numbers. Before I post the data to the server, I Convert my FormGroup into FormData and add the file manually and also the array of ints from the multiselectable checkboxes:
data.append('locationsSecondaryIds',
new Blob( [ JSON.stringify(this.profilePersonalData.locationsSecondaryIds)], { type : 'application/json' } ) );
if (this.file) {
data.append('document', this.file, this.file.name);
}
locationsSecondaryIds is a number[].
I have also tried leaving out the Blob and just send it as [1,1], but when the server gets to the server it can't convert it to a List
Any good suggestions?
Thanks very much in advance :-)
I had the same scenario and here is how I did.
My component.ts File in Angular:
const formData = new FormData();
formData.append('Parameter1', "Some String Value");
formData.append('Parameter2', this.currentUserId.toString());
for (const index in this.arrayValues)
{
// instead of passing this.arrayValues.toString() iterate for each item and append it to form.
formData.append(`ArrayValue[${index}]`,this.arrayValues[index].toString());
}
for (const file of this.importedFiles)
{
formData.append('Files', file);
}
Now post it to asp.net core web api and it should work.
My server side C# Class:
public class SomeClass
{
public string Parameter1 { get; set; }
public int Parameter2 { get; set; }
public string[] ArrayValue { get; set; }
public IFormFile[] Files { get; set; }
}
Note: Make sure to decorate your parameter with [FromForm]in your action method.
Asp.Net Core Web Api Controller action method:
public async Task<IActionResult> SomeMethod([FromForm] SomeClass someClass)
{
...
}
You can try this for picking multiple checkbox values and appending it in a form data.
On submit button:
let subs = [];
subs = this.skillForm.value.subjects; // here subject refers to multi select dropdown
let subString = subs.toString(); // you can let the values to be int as per your DB
//column
let fd = new FormData();
fd.append('values',subString);
The answer from fingers10 worked for me. For my code, I had to add an array of objects, to do this I used his answer with the following code.
for (const index in voteData.feedMessageTags) {
// instead of passing this.arrayValues.toString() iterate for each item and append it to form.
formData.append(`feedMessageTags[${index}].key`, voteData.feedMessageTags[index].key);
formData.append(`feedMessageTags[${index}].value`, voteData.feedMessageTags[index].value);
}

Blazor with AzureAD Auth, Context.Identity.User.Name is null

Only authenticated users can access the application as expected. I need to be able to track users via signalr. For example, if I run a ChatHub type of service, I'd like people to be able to chat using their AzureAD username which should be set automatically and not let people set their own usernames.
The hub always shows Context.Identity.User.Name is null.
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.AddTransient<HubConnectionBuilder>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub<App>(selector: "app");
endpoints.MapFallbackToPage("/_Host");
endpoints.MapHub<SomeHub>("/SomeHub");
});
Any idea if here is a way to preserve identity information and pass to SignalR?
Inspect your JWT token and check its claims. You can past it on http://jwt.ms/ to decode it. Then, look for the claims that are being returned that references the user name (in my case it is preferred_username).
Then you can change the default mapping of the Identity.Name using this code:
services.Configure<OpenIdConnectOptions>(AzureADDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters.NameClaimType = "<claim_name_that_returns_username>";
});
My workaround at the moment will be to just pass the username when the connection is created to the hub.
In codebehind (SomePage.razor.cs)
public class SomePageBase : ComponentBase
{
[Inject]
private HubConnectionBuilder _hubConnectionBuilder { get; set; }
[Inject]
private AuthenticationStateProvider authProvider { get; set; }
protected async override Task OnInitializedAsync()
{
var user = (await authProvider.GetAuthenticationStateAsync()).User.Identity.Name;
// in Component Initialization code
var connection = _hubConnectionBuilder // the injected one from above.
.WithUrl("https://localhost:44331/SomeHub")
.Build(); // Build the HubConnection
await connection.StartAsync();
var stringResult =
await connection.InvokeAsync<string>("HubMethodName", user);
}
}

How to list all users along with user profile from ASP.NET Membership?

Right now I'm working with silverlight project and I'm stuck on how to list all of users and user profile together.
Now I'm using this method to get all user via WCF
public IEnumerable<MembershipServiceUser> GetAllUsers()
{
return Membership.GetAllUsers().Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
public void FromMembershipUser(MembershipUser user)
{
this.Comment = user.Comment;
this.CreationDate = user.CreationDate;
this.Email = user.Email;
this.IsApproved = user.IsApproved;
this.UserName = user.UserName;
}
I can get all user from those code above but I don't know how extactly to get user profile
eg. Firstname , Lastname , etc..
You can create a new instance of ProfileBase and access the profile fields with the method GetPropertyValue("propertyName"), where propertyName is the name of your custom registration data.
var profile = ProfileBase.Create(user.UserName);
this.CustomProperty = profile.GetPropertyValue("customPropertyName");
I'm not 100% sure about the syntax, I come from a vb environment and haven't written any c# in a while.
ProfileInfoCollection profiles = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
foreach (ProfileInfo pi in profiles)
{
ProfileCommon p = Profile.GetProfile(pi.UserName);
countries.Add(p.Country);
}

Resources