Discord: Change region using .NET library? - c#

I'm currently trying to prevent lags on my Discord server using a bot checking the latency, and switching to another region if it does happen. I saw a couple of bots in js doing that, I'd like to know if there's something in Discord.NET able to do it. Of course, I've been parsing Google for hours to find a way.
Thanks

You can call ModifyAsync on an instance of your SocketGuild and set the RegionId property to your desired new region.
//I'm doing this as a command, but the logic can be implemented wherever you decide.
[Command("region")]
[Remarks("Let's pretend my module has access to a singleton instance of random")]
public async Task ChangeRegion()
{
//Get a collection of all available voice regions
//Exclude the region we are currently in
var voiceRegions = Context.Client.VoiceRegions.Where(r => !r.Id.Equals(Context.Guild.VoiceRegionId));
//Select a random new region
var newRegion = voiceRegions(random.Next(voiceRegions.Count));
//Update the RegionId property for the guild.
await Context.Guild.ModifyAsync(prop => prop.RegionId = newRegion.Id)
await ReplyAsync($"Region updated to {newRegion.Name}: {newRegion.Id}");
}

Related

What is the proper way of using the Windows.Media.Miracast namespace?

I am looking into screen casting through Miracast in an application but am unsure of how to use the Windows.Media.Miracast namespace. Limited information exists on the internet due to the short age of the Windows 10 1903 update that the namespace comes as a part of.
The only thing I've found so far is this documentation.
My question is does anybody know what the proper way of using this namespace is? Any examples or resources found online would be a great help.
Cheers.
These three sample projects demonstrate various MiraCast source apis that can be used from UWP applications. Not sure about outside UWP.
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BasicMediaCasting
https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/AdvancedCasting
https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/Projection
I'm personally using code like the following, on Windows IoT Core, to cast my whole screen
Scan for devices:
miraDeviceWatcher = DeviceInformation.CreateWatcher(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
miraHandlerAdded = new TypedEventHandler<DeviceWatcher, DeviceInformation>(async (watcher, deviceInfo) =>
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Add each discovered device to our listbox
CastingDevice addedDevice = await CastingDevice.FromIdAsync(deviceInfo.Id);
var disp = new CastingDisplay(addedDevice); //my viewmodel
MiraDevices.Add(disp); //ObservableCollection
});
});
miraDeviceWatcher.Added += miraHandlerAdded;
Connect to selected device:
public async Task StartCasting(CastingDisplay castee)
{
//When a device is selected, first thing we do is stop the watcher so it's search doesn't conflict with streaming
if (miraDeviceWatcher.Status != DeviceWatcherStatus.Stopped)
{
miraDeviceWatcher.Stop();
}
//Create a new casting connection to the device that's been selected
connection = castee.Device.CreateCastingConnection();
//Register for events
connection.ErrorOccurred += Connection_ErrorOccurred;
connection.StateChanged += Connection_StateChangedAsync;
var image = new Windows.UI.Xaml.Controls.Image();
await connection.RequestStartCastingAsync(image.GetAsCastingSource());
}
This Image is just used as a casting source. Once the connection is made, my whole screen is broadcast. The behavior is not documented. Hopefully it won't get 'fixed' in a future update.

How to retrieve channel users list with agora.io Unity SDK

I'm using Agora.io Unity SDK to implement a video chat feature in a game. But I don't know how to retrieve the list of users currently present in the channel. Does someone have an idea how to do so ?
There is no script to query the list of users in the channel. You will have to keep track of that yourself. It pretty simple.
Within the script where you initialize the Agora engine, create a list
static List<uint> remoteStreams = new List<uint>();
and then whenever you initialized the engine be sure to include the call back to listen for any remote user that joins the stream.
mRtcEngine.OnUserJoined += (uint uid, int elapsed) => {
string userJoinedMessage = string.Format("onUserJoined with uid {0}", uid);
Debug.Log(userJoinedMessage);
remoteStreams.Add(uid); // add remote stream id to list of users
};
Once the user has joined the channel, the callback above is called for every existing user in the channel and then again whenever a new person joins.

"Object reference not set to an instance of an object" exception when assigning EF property to variable

I'm getting an "Object reference not set to an instance of an object" exception when I'm trying to assign one of the property of my EF object model to a variable but can't figure out why as the EF object definitely contains data and is accessible in the Immediate Window.
I call the following code to get data from a specific organization:
var organizationModelFromDb = this.DbContext.Organizations.
SingleOrDefault(o => o.OrganizationId ==
organizationEditViewModel.Organization.OrganizationId);
This definitely returns data as I can see data displayed when expanding the tooltip when hovering my mouse over the organizationModelFromDb object. I can also access the data when I type:
organizationModelFromDb.MembershipType
in the Immediate Window but when I try to assign this property from my object model as such:
var membershipType = organizationModelFromDb.MembershipType;
I get the mentioned exception.
Everything within this Controller's method is working as expected but I was in the process of introducing new functionality but I'm stuck with this problem.
Any idea what may be happening. I'm pretty sure I'm assigning EF data to variables using the same technique all over the place in my project but for whatever reason it just won't work in this method.
What am I missing?
UPDATE-1:
This is not a duplicate question. The referenced article deal with the fact that object may actually be null and how best handle each scenario but as explained my object is not actually null. Data is being returned and it is available via the immediate window and the tooltip.
Update-2
This is the data I get when I'm calling "organizationModelFromDb" from the immediate window:
{System.Data.Entity.DynamicProxies.
OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB
71945EF111ADF7AE5EAEB3AD073A15D5A3}
AdditionalDetails:
{System.Data.Entity.DynamicProxies.OrganizationAddition_
05739F8DE2F5D549B3A7FC852AC32ED9C002953ED41AAA7751B12289E23D8A6C}
AutoImport: false
Members: Count = 1
MembershipType: Full
OrganizationId: "4be433d5-48a9-4891-a008-c70fe4cfoie3"
OrganizationName: "My Company"
StatusType: Approved
Website: ""
_entityWrapper: {System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships<System.Data.Entity.DynamicProxies.OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB71945EF111ADF7AE5EAEB3AD073A15D5A3>}
As you can see, there is data in the object.
But as mentioned, when I call this line of code:
var membershipType = organizationModelFromDb.MembershipType;
in my code, I get the exception with the following StackTrace:
"System.NullReferenceException: Object reference not set to an instance of an object.
at Mywebsite.Controllers.OrganizationsController.d__8.MoveNext() in C:\Work\MyWebsite\Controllers\OrganizationsController.cs:line 349"
Hope this helps resolving my problem.
Update-3
I've removed the code originally provided in this update to keep things tidy rather than providing yet another update but the code below is the full code contained in my controller but note that I've removed unnecessary code for readability sake:
var organizationModelFromDb = await this.DbContext.Organizations
.FirstOrDefaultAsync<OrganizationModel>(o => o.OrganizationId ==
organizationEditViewModel.Organization.OrganizationId);
if (ReferenceEquals(organizationModelFromDb, null))
return HttpNotFound();
organizationModelFromDb.StatusType = StatusType.Approved;
var memberModelsFromDb =
this.DbContext.Members.Where(
m => m.OrganizationId ==
organizationEditViewModel.Organization.OrganizationId).ToList();
if (memberModelsFromDb.Count > 0)
{
foreach (var memberModel in memberModelsFromDb.ToList())
{
var user = new ApplicationUser
{
UserName = memberModel.Email,
Email = memberModel.Email,
UserType = UserType.IsMember
};
var password = RandomPassword.Generate();
var result = await this.UserManager.CreateAsync(user, password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, JoiffRoles.IsMember);
try
{
var membershipType = organizationModelFromDb.MembershipType;
}
catch (Exception e)
{
Console.WriteLine(e);
}
string code = await this.UserManager.
GenerateEmailConfirmationTokenAsync(user.Id);
string codeHtmlVersion = HttpUtility.UrlEncode(code);
new Thread(async () =>
{
await CustomEmailService.
SendConfirm(this, Request, user, codeHtmlVersion);
}).Start();
}
}
}
Now as you can see, there's nothing special about this code. I'm checking if an organization exists, then I'm getting all the members for that organization and then I'm looping through each member and creating a user and adding roles to the database. Once created successfully, it sends an email to the newly created user with credential information.
Now the weird part, the exception "Object reference not set to an instance of an object" occurs with the above code but somehow, it doesn't occur if I comment either section of code:
1) Remove everything above the try/catch but leave the email section below the try catch:
var password = RandomPassword.Generate();
var result = await this.UserManager.CreateAsync(user, password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, JoiffRoles.IsMember);
…
}
2) Remove the email section
new Thread(async () =>
{
await CustomEmailService.SendConfirm(this,
Request, user, codeHtmlVersion);
}).Start();
I know this sounds ridiculous, I've gone through it over and over again and if I leave the code as is, I get this error when trying to set the variable to the OrganizationFromDb.MembershipType. If I remove either of the section mentioned above, everything works as expected.
As #CamiloTerevinto mentioned, I do believe it is related to something that hasn't been fully fetched and is only partially built but how are either section affecting this?
Any suggestions?
I haven't got to the bottom as to why this is happening nor why does it work when removing snippets of codes as mentioned in my updates but I'm pretty sure it is indeed related to what #CamiloTerevinto previously mentioned regarding the EF entity being only partially built/queried.
I can only assume that displaying data in the Immediate window and/or via the tooltip behaves differently than using it at run-time when assigned to a variable.
Anyway, rather than trying to fixed and/or figure out why removing these snippets of codes did the trick, I thought I'd try a different approach.
Since my organization details were only required to be pulled once there was no need for it to be within the members loop, so
I decided to assign the MembershipType variable outside the Members
loop
and this appeared to have done the trick.
I wonder if it is related to EF's lazy loading or something similar where it is trying to fetch the organization's EF entity details when requested within a loop that's also fetching details about another object. I'm not sure to be honest.
Would love someone to highlight and explain the actual reason.
I hope this help.

JINT - Unable to "console.log"

I am new to JINT, and trying to just do some basic tests to kind of learn the ropes. My first attempt was to just store some javascript in my database, load it, and execute it in a unit test. So that looks essentially like this....
[Fact]
public void can_use_jint_engine() {
using (var database = DocumentStore()) {
using (var session = database.OpenSession()) {
var source = session.Load<Statistic>("statistics/1");
// join the list of strings into a single script
var script = String.Join("\n", source.Scripting);
// this will create the script
// console.log("this is a test from jint.");
//
var engine = new Jint.Engine();
// attempt to execute the script
engine.Execute(script);
}
}
}
And it doesn't work, I get this error, which makes absolutely no sense to me, and I cannot find any documentation on.
Jint.Runtime.JavaScriptExceptionconsole is not defined at
Jint.Engine.Execute(Program program) at
Jint.Engine.Execute(String source) at
SampleProject.Installers.Instanced.__testing_installer.can_use_jint_engine()
in _testing_installer.cs: line 318
Can anyone assist in shedding some light on this? I'm pretty confused at this point.
With JavaScript there are three entities - we care about. The host (browser, your application etc), the engine (JINT in this case) and the script ("console.log(...)") in this case.
JavaScript defines a bunch of functions and object as part of the language, but console is not one of them. By convention, browsers define a console object that can be used in the manner you describe. However, since your app is not a browser (and JINT does not do this by itself), there's no console object defined in your namespace (globals).
What you need to do is add a console object that will be accessible in JINT. You can find how to do this in the docs, but here's a simple example of how to add a log function to the engine so it can be used from the JS code (example taken from github).
var engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine))
;
engine.Execute(#"
function hello() {
log('Hello World');
};
hello();
");

How to get Virtual Machine name using VMWare API?

I'm using the Vestris.VMWareLib API to remotely control my VMs on an ESX 5.0 server. I use the VMWareVirtualMachine.Open method to power on my virtual images. My code is written in C#. The problem is that you need to know the path to the datastore before you can power on the image - I'd like to be able to power it on knowing the VM name only. Is there a way to do this? I've included my current code below.
Thanks, John
using Vestris.VMWareLib;
//Works if VM name is in the path but what if it isn't?
List<VMWareVirtualMachine> vitualMachines = esxServer.RegisteredVirtualMachines.ToList();
VMWareVirtualMachine virtualMachine = vitualMachines.Where(vm => vm.PathName.Contains(vmName)).First();
VMWareVirtualMachine virtualMachine = esxServer.Open(vmName);
There's a method called VMWareVirtualMachine.GetProperty() which can be used to obtain the VM name but I don't know how to use it. Any suggestions or ideas how I can do this?
Thanks,
John
There's been a commit to VMWareTasks that adds the property "Name" to the VMWareVirtualMachine class, it is taken from the "displayName" property in the vmx file. The property is not in VMWareTasks 1.7 so as of right now, you will need to pull the source and build it yourself.
Use it to iterate the registered guests, checking this variable and then power on the appropriate one.
using Vestris.VMWareLib;
private void powerOnVm(string vmName)
{
using (VMWareVirtualHost esxServer = new VMWareVirtualHost())
{
esxServer.ConnectToVMWareVIServer("yourHost", "yourUser", "yourPassword");
using (VMWareVirtualMachine virtualMachine = esxServer.RegisteredVirtualMachines.FirstOrDefault(vm => vm.Name == vmName))
{
if (virtualMachine != null && !virtualMachine.IsRunning)
virtualMachine.PowerOn();
}
}
}
I just tested the above and it worked fine.

Categories