Discord.net issues creating, adding and removing roles - c#

so I'm working on a mute and unmute command and what I want it to do is find if there is a role called "Muted" in the server if there is then give the user that role if there isn't then create the role with the necessary permissions. I've tried messing with bot permissions, role permissions, and hierarchy and it just doesn't do anything. There is no error given to me via Console nor is there an error generated in the text, it just simply seems to do nothing no matter what I try, can anyone see what I'm doing wrong? I created a pre-existing role called "Muted" and even with the role pre-applied it didn't add it. It also doesn't work while trying to remove the role if I manually added it to the user. This is what I've got:
[Command("mute")]
[Remarks("Mutes A User")]
[RequireUserPermission(GuildPermission.MuteMembers)]
public async Task Mute(SocketGuildUser user)
{
var UserCheck = Context.Guild.GetUser(Context.User.Id);
if (!UserCheck.GuildPermissions.MuteMembers)
{
await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
{
Color = Color.LightOrange,
Title = "You dont have Permission!",
Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command",
Author = new EmbedAuthorBuilder()
{
Name = Context.Message.Author.ToString(),
IconUrl = Context.Message.Author.GetAvatarUrl(),
Url = Context.Message.GetJumpUrl()
}
}.Build());
}
else
{
await Context.Guild.GetUser(user.Id).ModifyAsync(x => x.Mute = true);
var muteRole = await GetMuteRole(user.Guild);
if (!user.Roles.Any(r => r.Id == muteRole.Id))
await user.AddRoleAsync(muteRole);//.ConfigureAwait(false);
}
}
[Command("unmute")]
[Remarks("Unmutes A User")]
[RequireUserPermission(GuildPermission.MuteMembers)]
public async Task Unmute(SocketGuildUser user)
{
var UserCheck = Context.Guild.GetUser(Context.User.Id);
if (!UserCheck.GuildPermissions.MuteMembers)
{
await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
{
Color = Color.LightOrange,
Title = "You dont have Permission!",
Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command",
Author = new EmbedAuthorBuilder()
{
Name = Context.Message.Author.ToString(),
IconUrl = Context.Message.Author.GetAvatarUrl(),
Url = Context.Message.GetJumpUrl()
}
}.Build());
}
else
{
await Context.Guild.GetUser(user.Id).ModifyAsync(x => x.Mute = false).ConfigureAwait(false);
try { await user.ModifyAsync(x => x.Mute = false);/*.ConfigureAwait(false); */} catch { ReplyAsync("no"); }
try { await user.RemoveRoleAsync(await GetMuteRole(user.Guild));/*.ConfigureAwait(false); */} catch { ReplyAsync("No lmao"); }
}
}
public async Task<IRole> GetMuteRole(IGuild guild)
{
const string defaultMuteRoleName = "Muted";
var muteRoleName = "Muted";
var muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName);
if (muteRole == null)
{
try
{
muteRole = await guild.CreateRoleAsync(muteRoleName, GuildPermissions.None, Color.Default, false, false);//.ConfigureAwait(false);
}
catch
{
muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName) ?? await guild.CreateRoleAsync(defaultMuteRoleName, GuildPermissions.None, Color.Default, false, false);//.ConfigureAwait(false);
}
}
foreach (var toOverwrite in (await guild.GetTextChannelsAsync()))
{
try
{
if (!toOverwrite.PermissionOverwrites.Any(x => x.TargetId == muteRole.Id && x.TargetType == PermissionTarget.Role))
{
await toOverwrite.AddPermissionOverwriteAsync(muteRole, denyOverwrite);//.ConfigureAwait(false);
await Task.Delay(200);//.ConfigureAwait(false);
}
}
catch
{
}
}
return muteRole;
}
If anyone can help me that would be great, cheers!

Related

Identifier missing on GameCenter Firebase Auth

I have implemented auth in PlayGames for Android. When users sign in, their usernames show up under "Identifier" in the fireBase console.
In GameCenter, it does not:
public void AuthenticateToGameCenter(Action onAuthenticationComplete = null)
{
Social.localUser.Authenticate(success =>
{
Debug.Log("Game Center Initialization Complete - Result: " + success);
if (onAuthenticationComplete != null)
onAuthenticationComplete();
});
}
public Task SignInWithGameCenterAsync()
{
var credentialTask = Firebase.Auth.GameCenterAuthProvider.GetCredentialAsync();
var continueTask = credentialTask.ContinueWithOnMainThread((Task<Credential> task) =>
{
if (!task.IsCompleted)
return null;
if (task.Exception != null)
Debug.Log("GC Credential Task - Exception: " + task.Exception.Message);
var credential = task.Result;
Debug.Log($"credential { task.Result}");
var loginTask = auth.SignInWithCredentialAsync(credential);
return loginTask.ContinueWithOnMainThread(handleLoginResult);
});
return continueTask;
}
private void GameCenterLogin()
{
// first initialize, then sign in
var signinAsync = new Action(() => SignInWithGameCenterAsync());
AuthenticateToGameCenter(signinAsync);
}
Am I authing wrong?

Data synchronization (validation) between two clients

I have a webshop built on ASP.NET Boilerplate (Angular frontend and MSSQL database).
The webshop contains items and I want to keep an inventory of these items.
Every time an order is created the inventory is updated. So basically I have a database with Webshops, Items and Orders.
I have repositories and managers for these objects.
All works fine, but the issue occurs when two clients at the same time load the webshop.
Client1 opens webpage:
Webshop1
Item1: "10 items available"
Item2: "8 items available"
Client2 opens webpage at the same time:
Webshop1
Item1: "10 items available"
Item2: "8 items available"
The first one that buys all the available items, should be able to create an order and the second one should get an error.
When an order is created, the backend checks if there are enough items available.
But when the webshop is loaded BEFORE the order of the first client is created, the second client does not know the updated inventory and will be able to create the order as well.
Meaning 20 items of Item1 can be sold!
How do I "sync" the data between the two sessions in the backend? It seems somehow the data is cached in the backend when loading the webshop.
CreateOrder function
public async Task<CreateOrderResponseDto> Create(CreateOrderDto input, long? userId)
{
input.OrderItems.ForEach(async o =>
{
if (!(await _salesItemManager.ReserveStock(o.SalesItemId, o.Quantity)).IsSuccess)
{
throw CodeException.ToAbpValidationException("OrderItem", "OrderItemCreate");
}
});
var salesPage = await _salesPageManager.Get(input.SalesPageId, false);
if (salesPage.GetState() != StatePage.Published)
{
throw CodeException.ToAbpValidationException("Order", "PageNotAvailable");
}
if (salesPage.CommentsRequired.HasValue && salesPage.CommentsRequired.Value)
{
if (string.IsNullOrWhiteSpace(input.Description))
{
throw CodeException.ToAbpValidationException("Order", "CommentsRequired");
}
}
var order = new Order
{
Address = input.Address,
City = input.City,
LastName = input.LastName,
Name = input.Name,
PostalCode = input.PostalCode,
Email = input.Email,
PhoneNumber = input.PhoneNumber,
Description = input.Description,
SalesPage = salesPage
};
try
{
order.Price = await _salesItemManager.GetPriceByOrders(input.OrderItems);
order = await _orderRepository.InsertAsync(order);
input.OrderItems.ForEach(async o =>
{
var orderItem = new OrderItem();
orderItem.SalesItemId = o.SalesItemId;
orderItem.OrderId = order.Id;
orderItem.Quantity = o.Quantity;
await _orderItemRepository.InsertAsync(orderItem);
});
if (input.SelectedSalesPageOptionId.HasValue)
{
order.SalesOption = await _salesPageManager.GetOption(input.SelectedSalesPageOptionId.Value);
}
}
catch (Exception e)
{
throw CodeException.ToAbpValidationException("OrderItem", "OrderItemCreate");
}
if (userId.HasValue && salesPage.User.Id == userId.Value)
{
var payment = await _paymentManager.CreateManualPayment(order, input.IsPaid);
order.Payment = payment;
return new CreateOrderResponseDto() { IsSuccess = true, PaymentUrl = string.Empty, OrderId = order.Id.ToString() };
}
else
{
var payment = await _paymentManager.CreatePayment(order);
order.Payment = payment;
return new CreateOrderResponseDto() { IsSuccess = true, PaymentUrl = payment.PaymentUrl, OrderId = order.Id.ToString() };
}
}
ReserveStock function
public async Task<GeneralDto> ReserveStock(Guid itemId, int quantity)
{
var salesItem = await _salesItemRepository.GetAsync(itemId);
if (salesItem == null || salesItem.Stock == null || salesItem.ReservedStock == null)
return new GeneralDto() { IsSuccess = false };
if (salesItem.Stock < quantity)
{
return new GeneralDto() { IsSuccess = false };
}
salesItem.Stock -= quantity;
salesItem.ReservedStock += quantity;
try
{
await _salesItemRepository.UpdateAsync(salesItem);
}
catch (Exception e)
{
throw CodeException.ToAbpValidationException("SalesItem", "SalesItemUpdate");
}
return new GeneralDto() { IsSuccess = true };
}
The problem is not that the data is cached.
The problem is that your ReserveStock checks are async tasks that are not awaited by the caller:
input.OrderItems.ForEach(async o =>
{
if (!(await _salesItemManager.ReserveStock(o.SalesItemId, o.Quantity)).IsSuccess)
{
throw CodeException.ToAbpValidationException("OrderItem", "OrderItemCreate");
}
});
Assign your async ReserveStock checks to an array of tasks that is awaited by the caller:
var reserveStockChecks = input.OrderItems.Select(async o =>
{
if (!(await _salesItemManager.ReserveStock(o.SalesItemId, o.Quantity)).IsSuccess)
{
throw CodeException.ToAbpValidationException("OrderItem", "OrderItemCreate");
}
}).ToArray();
await Task.WhenAll(reserveStockChecks);

PHAssetChangeRequest Cocoa error -1

I need to save downloaded video to gallery on iPhone, but getting error:
The operation couldnt be completed. (Cocoa error -1/)
Tried also to do this through webClient.DownloadDataAsync(), getting same error. Here is my listing:
public async Task<string> DownloadFile(string fileUri)
{
var tcs = new TaskCompletionSource<string>();
string fileName = fileUri.Split('/').Last();
var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string videoFileName = System.IO.Path.Combine(documentsDirectory, fileName);
var webClient = new WebClient();
webClient.DownloadFileCompleted += (s, e) =>
{
var authStatus = await PHPhotoLibrary.RequestAuthorizationAsync();
if(authStatus == PHAuthorizationStatus.Authorized){
var fetchOptions = new PHFetchOptions();
var collections = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
collection = collections.firstObject as PHAssetCollection;
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
var assetCreationRequest = PHAssetChangeRequest.FromVideo(NSUrl.FromFileName(videoFileName));
var assetPlaceholder = assetCreationRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { assetPlaceholder });
}, delegate (bool status, NSError error) {
if (status)
{
Console.Write("Video added");
tcs.SetResult("success");
}
});
}
try
{
webClient.DownloadFileAsync(new Uri(fileUri), videoFileName);
}
catch (Exception e)
{
tcs.SetException(e);
}
return await tcs.Task;
}
Any help would be appreciated. Thanks.
(Cocoa error -1/)
Are you sure that you actually have valid data/mp4 from your download?
Are you using SSL (https), otherwise have you applied for an ATS exception in your info.plist?
Check the phone/simulator console output for errors concerning ATS
Note: I typically use NSUrlSession directly to avoid the HttpClient wrapper...
Example using NSUrlSession task:
var videoURL = NSUrl.FromString(urlString);
var videoPath = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0];
NSUrlSession.SharedSession.CreateDownloadTask(videoURL, (location, response, createTaskError) =>
{
if (location != null && createTaskError == null)
{
var destinationURL = videoPath.Append(response?.SuggestedFilename ?? videoURL.LastPathComponent, false);
// If file exists, it is already downloaded, but for debugging, delete it...
if (NSFileManager.DefaultManager.FileExists(destinationURL.Path)) NSFileManager.DefaultManager.Remove(destinationURL, out var deleteError);
NSFileManager.DefaultManager.Move(location, destinationURL, out var moveError);
if (moveError == null)
{
PHPhotoLibrary.RequestAuthorization((status) =>
{
if (status.HasFlag(PHAuthorizationStatus.Authorized))
{
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
PHAssetChangeRequest.FromVideo(destinationURL);
}, (complete, requestError) =>
{
if (!complete && requestError != null)
Console.WriteLine(requestError);
});
}
});
}
else
Console.WriteLine(moveError);
}
else
Console.WriteLine(createTaskError);
}).Resume();
Note: To confirm your code, try using a known valid secure URL source:
https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4 via “Video For Everybody” Test Page

GetClaimsAsync(user) throws Sequence contains more than one matching element

I have a .NET Core 2.0 Web API. I am using Jwt authentication on it.
Whenever the application reaches this line, an exception is thrown:
var userClaims = await _userManager.GetClaimsAsync(user);
The exception is:
System.InvalidOperationException: Sequence contains more than one matching element
What is weird is that this wasn't happening before, it started happening when I upgraded to .NET Core 2.0 from 1.1.
The Seed method for the database is below:
public async Task Seed()
{
var adminUserJ = await _userManager.FindByNameAsync("Ciwan");
var regularUser = await _userManager.FindByNameAsync("John");
if (adminUserJ == null)
{
if (!await _roleManager.RoleExistsAsync("Admin"))
{
var role = new IdentityRole("Admin");
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = "IsAdmin", ClaimValue = "True" });
await _roleManager.CreateAsync(role);
}
adminUserJ = new BbUser
{
UserName = "Ciwan",
Email = "ck83s9#gmail.com"
};
var userResult = await _userManager.CreateAsync(adminUserJ, "Welcome123");
var roleResult = await _userManager.AddToRoleAsync(adminUserJ, "Admin");
var claimResult = await _userManager.AddClaimAsync(adminUserJ, new Claim("Points", "10"));
if (!userResult.Succeeded || !roleResult.Succeeded || !claimResult.Succeeded)
{
throw new InvalidOperationException("Failed to build user and roles");
}
}
if (regularUser == null)
{
if (!await _roleManager.RoleExistsAsync("Regular"))
{
var role = new IdentityRole("Regular");
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = "IsRegular", ClaimValue = "True" });
await _roleManager.CreateAsync(role);
}
regularUser = new BbUser
{
UserName = "John",
Email = "j.watson#world.com"
};
var userResult = await _userManager.CreateAsync(regularUser, "BigWow321");
var roleResult = await _userManager.AddToRoleAsync(regularUser, "Regular");
var claimResult = await _userManager.AddClaimAsync(regularUser, new Claim("Points", "10"));
if (!userResult.Succeeded || !roleResult.Succeeded || !claimResult.Succeeded)
{
throw new InvalidOperationException("Failed to build user and roles");
}
}
_context.AddRange(GetListOfArtists(adminUserJ.Id, regularUser.Id));
await _context.SaveChangesAsync();
}
I can't see anything wrong. I tried looking at the AspNetUserClaims table in the database, but all seems OK. I have 2 claims in there, one for each user.
This error happens when I attempt to log in a user, so the request arrives here:
[HttpPost("auth/token")]
public async Task<IActionResult> CreateToken([FromBody] CredentialsDto credentials)
{
try
{
var user = await _userManager.FindByNameAsync(credentials.Username);
if (user != null)
{
if (IsUserPasswordValid(credentials, user))
{
var claims = await GetClaimsAsync(user);
var token = CreateNewJwtToken(claims);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
return BadRequest("Failed to generate token!");
}
private async Task<IEnumerable<Claim>> GetClaimsAsync(BbUser user)
{
var userClaims = await _userManager.GetClaimsAsync(user);
return new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}.Union(userClaims);
}

Dynamic change Microsoft BOT Framework Form's Field Step: hiding and showing the confirmation

I'm new to MS BOT Framework.
I changed MS github MultiDialogsBot.sln , I added a HotelsQuery property to init Form's Field value at HotelsDialog.cs,
public class HotelsDialog : IDialog<object>
{
public HotelsQuery _HotelsQuery { get; set; }
public HotelsDialog()
{
_HotelsQuery = new HotelsQuery{
Destination = "Taiwan",
CheckIn = new DateTime(2017,10,29),
Nights = 3
};
}
public async Task StartAsync(IDialogContext context)
{
await context.PostAsync("Welcome to the Hotels finder!");
var hotelsFormDialog = FormDialog.FromForm(this.BuildHotelsForm, FormOptions.PromptInStart);
context.Call(hotelsFormDialog, this.ResumeAfterHotelsFormDialog);
}
public IForm<HotelsQuery> BuildHotelsForm()
{
OnCompletionAsyncDelegate<HotelsQuery> processHotelsSearch = async (context, state) =>
{
await context.PostAsync($"Ok. Searching for Hotels in {state.Destination} from {state.CheckIn.ToString("MM/dd")} to {state.CheckIn.AddDays(state.Nights).ToString("MM/dd")}...");
};
var destField = new FieldReflector<HotelsQuery>(nameof(HotelsQuery.Destination))
.SetActive((state) =>
{
//depend on _HotelsQuery's values
bool isActive = string.IsNullOrWhiteSpace(_HotelsQuery.Destination);
if (!isActive) state.Destination = _HotelsQuery.Destination;
return isActive;
});
var checkInField = new FieldReflector<HotelsQuery>(nameof(HotelsQuery.CheckIn))
.SetActive((state) =>
{
//depend on _HotelsQuery's values
bool isActive = _HotelsQuery.CheckIn == DateTime.MinValue;
if (!isActive) state.CheckIn = _HotelsQuery.CheckIn;
return isActive;
});
var nightsField = new FieldReflector<HotelsQuery>(nameof(HotelsQuery.Nights))
.SetActive((state) =>
{
//depend on _HotelsQuery's values
bool isActive = _HotelsQuery.Nights == 0;
if (!isActive) state.Nights = _HotelsQuery.Nights;
return isActive;
});
var form = new FormBuilder<HotelsQuery>()
.Field(destField)
.Message("Looking for hotels in {Destination}...")
.Field(checkInField)
.Message("Check in {CheckIn}...")
.Field(nightsField)
.Message("Nights : {Nights}...")
.Confirm("Is this your selection?\n {*}", state =>
{
//clean all fields for showing fields in confirmation
_HotelsQuery.Destination = string.Empty;
_HotelsQuery.CheckIn = DateTime.MinValue;
_HotelsQuery.Nights = 0;
return true;
}, new List<string>())
.Message("Thanks you ...")
.OnCompletion(processHotelsSearch)
.Build();
return form;
}
public async Task ResumeAfterHotelsFormDialog(IDialogContext context, IAwaitable<HotelsQuery> result)
{
try
{
var searchQuery = await result;
var hotels = await this.GetHotelsAsync(searchQuery);
await context.PostAsync($"I found in total {hotels.Count()} hotels for your dates:");
var resultMessage = context.MakeMessage();
resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel;
resultMessage.Attachments = new List<Attachment>();
foreach (var hotel in hotels)
{
HeroCard heroCard = new HeroCard()
{
Title = hotel.Name,
Subtitle = $"{hotel.Rating} starts. {hotel.NumberOfReviews} reviews. From ${hotel.PriceStarting} per night.",
Images = new List<CardImage>()
{
new CardImage() { Url = hotel.Image }
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "More details",
Type = ActionTypes.OpenUrl,
Value = $"https://www.bing.com/search?q=hotels+in+" + HttpUtility.UrlEncode(hotel.Location)
}
}
};
resultMessage.Attachments.Add(heroCard.ToAttachment());
}
await context.PostAsync(resultMessage);
}
catch (FormCanceledException ex)
{
string reply;
if (ex.InnerException == null)
{
reply = "You have canceled the operation. Quitting from the HotelsDialog";
}
else
{
reply = $"Oops! Something went wrong :( Technical Details: {ex.InnerException.Message}";
}
await context.PostAsync(reply);
}
finally
{
context.Done<object>(null);
}
}
private async Task<IEnumerable<Hotel>> GetHotelsAsync(HotelsQuery searchQuery)
{
var hotels = new List<Hotel>();
// Filling the hotels results manually just for demo purposes
for (int i = 1; i <= 5; i++)
{
var random = new Random(i);
Hotel hotel = new Hotel()
{
Name = $"{searchQuery.Destination} Hotel {i}",
Location = searchQuery.Destination,
Rating = random.Next(1, 5),
NumberOfReviews = random.Next(0, 5000),
PriceStarting = random.Next(80, 450),
Image = $"https://placeholdit.imgix.net/~text?txtsize=35&txt=Hotel+{i}&w=500&h=260"
};
hotels.Add(hotel);
}
hotels.Sort((h1, h2) => h1.PriceStarting.CompareTo(h2.PriceStarting));
return hotels;
}
}
I have trouble after the confirmation shows. When a user answers yes, BOT will ask CheckIn's prompt.
Why does it not go to the OnCompletion event?
Thanks for your help.
You are clearing out the values in the .Confirm
Try something like this:
var form = new FormBuilder<HotelsQuery>()
.Field(destField)
.Message("Looking for hotels in {Destination}...")
.Field(checkInField)
.Message("Check in {CheckIn}...")
.Field(nightsField)
.Message("Nights : {Nights}...")
.Confirm("Is this your selection?\n {*}", state =>
{
if (_HotelsQuery.Destination == string.Empty ||
_HotelsQuery.CheckIn == DateTime.MinValue ||
_HotelsQuery.Nights == 0)
return false;
return true;
}, new List<string>())
.Message("Thanks you ...")
.OnCompletion(processHotelsSearch)
.Build();

Categories