How to make the autocomplete handler work in Discord.Net? - discord

I'm sorry if it sound a bit newbie, but i'm stuck trying to get working the AutocompleteHandler.
Following the documentation, i tried to create a very basic autocomplete system :
public class ExampleAutocompleteHandler : AutocompleteHandler
{
public override async Task<AutocompletionResult> GenerateSuggestionsAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter, IServiceProvider services)
{
// Create a collection with suggestions for autocomplete
IEnumerable<AutocompleteResult> results = new[]
{
new AutocompleteResult("Name1", "value111"),
new AutocompleteResult("Name2", "value2")
};
// max - 25 suggestions at a time (API limit)
return AutocompletionResult.FromSuccess(results.Take(25));
}
}
In the module :
public class ItemModule : InteractionModuleBase
{
// you need to add `Autocomplete` attribute before parameter to add autocompletion to it
[SlashCommand("command_name", "command_description")]
public async Task ExampleCommand([Summary("parameter_name"), Autocomplete(typeof(ExampleAutocompleteHandler))] string parameterWithAutocompletion)
=> await RespondAsync($"Your choice: {parameterWithAutocompletion}");
}
I tried to register the handler as a Singleton, but nothing worked. It doesnt display the list when i type the commands.
I appreciate some help. Thanks in advance!

Indeed the documentation is currently missing this.
Just like Slash Commands, you need to handle the Autocompletion event and forward it to your interaction service.
On your discord client, handle the event
_client.AutocompleteExecuted += async (SocketAutocompleteInteraction arg) => {
var context = new Discord.Interactions.InteractionContext(_client, arg, arg.Channel);
await _interactionService.ExecuteCommandAsync(context,services: _serviceProvider);
};

Related

Adding a claim using a custom endpoint with AddLocalApiAuthentication

I'm attempting to employ a custom endpoint that adds a specific claim based on a parameter passed to LocalApiController.
I'm following help at:
http://docs.identityserver.io/en/latest/topics/add_apis.html
I configured startup.cs:
services.AddLocalApiAuthentication(principal =>
{
principal.Identities.First().AddClaim(new Claim("additional_claim", "additional_value"));
return Task.FromResult(principal);
});
and my receiving controller:
[Route("localApi")]
[Authorize(LocalApi.PolicyName)]
public class LocalApiController : ControllerBase
{
public IActionResult Get()
{
var claims = from c in User.Claims select new { c.Type, c.Value };
return new JsonResult(claims);
}
}
[Authorize(LocalApi.PolicyName)] works and fires the helper configured in startup.cs which logically fires before the controllers get method.
I don't see how I can pass the controller's {id} parameter to the helper method (that will become the value of the claim I'm to add, replacing the "additional_value" constant).
Any suggestions?

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

CefSharp: Injecting custom CSS File using a custom scheme

I'm using CefSharp (47) to render a webpage from a host that I have no control over, and I want to make some additional CSS tweaks to those provided by the host.
Reading up on various topics across GitHub (https://github.com/cefsharp/CefSharp/blob/cefsharp/47/CefSharp.Example/CefSharpSchemeHandlerFactory.cs), and here (CefSharp custom SchemeHandler), I wrote a custom scheme handler accordingly:
public class CustomSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "custom";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
Console.WriteLine(request.Url);
if (schemeName.ToLower() == SchemeName.ToLower())
{
// Do some stuff
}
return null;
}
}
I attempt to bind it in my application in the following manner:
CefSettings settings = new CefSettings();
settings.CachePath = browserCachePath;
settings.RegisterScheme(new CefCustomScheme()
{
SchemeName = CustomSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomSchemeHandlerFactory()
});
Cef.Initialize(settings);
The application then browses to the appropriate website, and uses the 'LoadingStateChanged' event to then fire off some JavaScript to inject the CSS file I want to load:
string linkText = "<link rel=\u0022stylesheet\u0022 type=\u0022text/css\u0022 href=\u0022custom://custom.css\u0022>";
var jsFunctionText = string.Format("(function() {{ $('head').append('{0}'); return true;}}) ();", linkText);
var injectionTask = await _myBrowser.GetMainFrame().EvaluateScriptAsync(jsFunctionText, null);
...which succeeds.
But my custom resource handler 'Create' event is never fired.
I can only presume that the handler isn't being registered properly, so I'd appreciate any advice/help in getting this working properly!
Thanks!

Nancy testing GetModel<T> throws KeyNotFoundException

I'm trying to test that the model returned from my Nancy application is as expected. I have followed the docs here but whenever I call the GetModel<T> extension method it throws a KeyNotFoundException.
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
I know what the error means but I'm failing to see why it's being thrown.
Here's my module
public class SanityModule : NancyModule
{
public SanityModule()
{
Get["sanity-check"] = _ => Negotiate.WithModel(new SanityViewModel { Id = 1 })
.WithStatusCode(HttpStatusCode.OK);
}
}
my view model
public class SanityViewModel
{
public int Id { get; set; }
}
and here's my test
[TestFixture]
public class SanityModuleTests
{
[Test]
public void Sanity_Check()
{
// Arrange
var browser = new Browser(with =>
{
with.Module<SanityModule>();
with.ViewFactory<TestingViewFactory>();
});
// Act
var result = browser.Get("/sanity-check", with =>
{
with.HttpRequest();
with.Header("accept", "application/json");
});
var model = result.GetModel<SanityViewModel>();
// Asset
model.Id.ShouldBeEquivalentTo(1);
}
}
Debugging this test shows that the module is hit and completes just fine. Running the application shows that the response is as expected.
Can anyone shed some light on this?
Thanks to the lovely guys, albertjan and the.fringe.ninja, in the Nancy Jabbr room we've got an explanation as to what's going on here.
TL;DR It makes sense for this to not work but the error message should be more descriptive. There is a workaround below.
The issue here is that I am requesting the response as application/json whilst using TestingViewFactory.
Let's take a look at the implementation of GetModel<T>();
public static TType GetModel<TType>(this BrowserResponse response)
{
return (TType)response.Context.Items[TestingViewContextKeys.VIEWMODEL];
}
This is simply grabbing the view model from the NancyContext and casting it to your type. This is where the error is thrown, as there is no view model in NancyContext. This is because the view model is added to NancyContext in the RenderView method of TestingViewFactory.
public Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext)
{
// Intercept and store interesting stuff
viewLocationContext.Context.Items[TestingViewContextKeys.VIEWMODEL] = model;
viewLocationContext.Context.Items[TestingViewContextKeys.VIEWNAME] = viewName;
viewLocationContext.Context.Items[TestingViewContextKeys.MODULENAME] = viewLocationContext.ModuleName;
viewLocationContext.Context.Items[TestingViewContextKeys.MODULEPATH] = viewLocationContext.ModulePath;
return this.decoratedViewFactory.RenderView(viewName, model, viewLocationContext);
}
My test is requesting json so RenderView will not be called. This means you can only use GetModel<T> if you use a html request.
Workaround
My application is an api so I do not have any views so changing the line
with.Header("accept", "application/json");
to
with.Header("accept", "text/html");
will throw a ViewNotFoundException. To avoid this I need to implement my own IViewFactory. (this comes from the.fringe.ninja)
public class TestViewFactory : IViewFactory
{
#region IViewFactory Members
public Nancy.Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext)
{
viewLocationContext.Context.Items[Fixtures.SystemUnderTest.ViewModelKey] = model;
return new HtmlResponse();
}
#endregion
}
Then it is simply a case of updating
with.ViewFactory<TestingViewFactory>();
to
with.ViewFactory<TestViewFactory>();
Now GetModel<T> should work without needing a view.

Exception thrown when using TaskSourceCompletion in Silverlight 5

I'm trying to wrap the Event Async Programming model used in RIA Services in a Task.
I have followed the standard way of using a TaskCompletionSource and implemented the following extension method:
public static Task<IEnumerable<T>> LoadAsync<T>(this DomainContext source, EntityQuery<T> query) where T : Entity
{
TaskCompletionSource<IEnumerable<T>> taskCompletionSource = new TaskCompletionSource<IEnumerable<T>>();
source.Load(
query,
loadOperation =>
{
if (loadOperation.HasError && !loadOperation.IsErrorHandled)
{
taskCompletionSource.TrySetException(loadOperation.Error);
loadOperation.MarkErrorAsHandled();
}
else if (loadOperation.IsCanceled)
{
taskCompletionSource.TrySetCanceled();
}
else
{
taskCompletionSource.TrySetResult(loadOperation.Entities);
}
},
null);
return taskCompletionSource.Task;
}
I then use this in the following way:
var task = _context.LoadAsync(_context.GetPlayersQuery());
task.Start();
task.Result;
The problem though is that I get an InvalidOperationException stating that "Start may not be called on a promise-style task". I have tried not starting the task, but then the loadOperation callback never fires.
Can anyone see what I am doing wrong here?
Thanks in advance
Problem is solved. Under the hood the DomainContext.Load() method is already operating in an asynchronous manner. There must have been some conflict with trying to wrap an already asynchronous method in a task.
However, even if I still follow the EAP correctly with the code below, I still get the InvalidOperationException of 'start cannot be called on a promise-style task'
public static Task<IEnumerable<T>> LoadAsync<T>(this DomainContext source, EntityQuery<T> query) where T : Entity
{
TaskCompletionSource<IEnumerable<T>> taskCompletionSource = new TaskCompletionSource<IEnumerable<T>>();
var loadOperation = source.Load(query);
loadOperation.Completed += (obj, args) =>
{
if (loadOperation.HasError && !loadOperation.IsErrorHandled)
{
taskCompletionSource.TrySetException(loadOperation.Error);
loadOperation.MarkErrorAsHandled();
}
else if (loadOperation.IsCanceled)
{
taskCompletionSource.TrySetCanceled();
}
else
{
taskCompletionSource.TrySetResult(loadOperation.Entities);
}
};
return taskCompletionSource.Task;
}
Try this instead
var result = await _context.LoadAsync(_context.GetPlayersQuery());
Try using
task.ContinuewWith(Action<Task<T>> continuation)
That worked for me, as I too got that exception when using task.Start

Resources