Is there an alternative to JObject.TryGetValue(string role, value:out var output) in .NET Core 3.X version? - .net-core-3.1

I am migrating to .NET Core 3.X from .NETCore 2.2 and am trying to get following code to work
private static Task SetUserInformationReceived(UserInformationReceivedContext context)
{
if (context.User.TryGetValue(JwtClaimTypes.Role, value: out var roles)){
//Code comes here
}
}
But in .NET Core 3.X UserInformationReceivedContext.User is now a JsonDocument instead of JObject, rendering above code not usable. Is there any other way to get the JToken here with the specified property name?

I just found a solution for this question, and seeing there was no online solution, I'll be posting it here.
private static Task SetUserInformationReceived(UserInformationReceivedContext context){
if (context.User.RootElement.TryGetProperty(JwtClaimTypes.Role, value : out var roles)){
//Code comes here
}
}

Related

using signalR .net core client

I have set up a signalR website .net core. My function in my hub is:
public async Task Notify(int id) {
await Clients.All.InvokeAsync("Notified", id);
}
I have also tested this with the following js:
let connection = new signalR.HubConnection(myURL);
connection.on('Notified', data => {
console.log(4, data);
});
connection.start();
The js code seems to work fine and I see the log when I try connection.Invoke('Notify').
Now I have a console app that can needs to make the invoke. I am trying this in two ways and don't mind either solution:
1. A mvc controller within the signalR website that can take the id and invoke 'Notified'.
2. Use the client library Microsoft.AspNetCore.SignalR.Client in the console app.
The way 1 I have only done in classic asp.net like this:
GlobalHost.ConnectionManager.GetHubContext(hubName)
But couldn't find a way to do this in .net core.
Way 2 I have used the library and tried this so far:
var con = new HubConnectionBuilder();
con.WithUrl(myURL);
var connection = con.Build();
connection.InvokeAsync("Notify",args[0]).Wait();
This is the closest I have come to create a connection in the same way as the js code. However this code throws a null pointer when calling connection.InvokeAsync. The connection object is not null. It seems to be an internal object that is null. According to the stack trace the exception is thrown when a MoveNext() function is internally called.
Well looks like both are not currently possible. As of now I just used a forced way which is hopefully temporary.
I have created and used the following base class for hubs:
public abstract class MyHub : Hub
{
private static Dictionary<string, IHubClients> _clients = new Dictionary<string, IHubClients>();
public override Task OnConnectedAsync()
{
var c = base.OnConnectedAsync();
_clients.Remove(Name);
_clients.Add(Name, Clients);
return c;
}
public static IHubClients GetClients(string Name) {
return _clients.GetValueOrDefault(Name);
}
}
GlobalHost is gone. You need to inject IHubContext<THub> like in this sample.
This can be a bug in SignalR alpha1. Can you file an issue on https://github.com/aspnet/signalr and include a simplified repro?

Getting "main" Assembly version number

I have a solution with libraries (DLLs) which are used in 2 identical projects (one for WP7, another for WP8). In one of the libraries I have the code which determines the version of the application.
private static Version mVersion;
public static Version Version {
get {
if (mVersion == default(Version)) {
var lcAssembly = Assembly.GetExecutingAssembly();
var parts = lcAssembly.FullName.Split(',');
var lcVersionStr = parts[1].Split('=')[1];
mVersion = new Version(lcVersionStr);
}
return mVersion;
}
}
The problem is that this code returns the version number of the library itself because of this Assembly.GetExecutingAssembly() code. How to get a MAIN Assembly version and not DLL's?
That's a great question on code-sharing between WP7 and WP8.
The simplest way for you to do that would be to read the AppManfiest.xml file at run-time, get the EntryType and use that to get at the entry point Assembly instance. Here's how a sample AppManfiest.xml looks like once MSBuild did its magic on it:
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="myAssembly" EntryPointType="myNamespace.App" RuntimeVersion="4.7.50308.0">
<Deployment.Parts>
<AssemblyPart x:Name="myAssembly" Source="myAssembly.dll" />
</Deployment.Parts>
</Deployment>
And here's how you would read the file, get the attributes, then get the entry point type and finally the entry point assembly:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var appManfiest = XElement.Load("AppManifest.xaml");
var entryAssemblyName = appManfiest.Attribute("EntryPointAssembly").Value;
var entryTypeName = appManfiest.Attribute("EntryPointType").Value;
Type entryType = Type.GetType(entryTypeName + "," + entryAssemblyName);
Assembly entryAssembly = entryType.Assembly;
}
That's a simple solution and it works. However, that isn't the cleanest architectural solution. The way I'd implement this solution is to have an interface declared in the shared library, both WP7 and WP8 implement that interface and register their implementation with an IoC container.
For example, let's say you need to "DoSomething" in the shared library that's platform version specific. First you'll create have an IDoSomething interface. Let's also assume you have an IoC standing by.
public interface IDoSomething
{
}
public static class IoC
{
public static void Register<T>(T t)
{
// use some IoC container
}
public static T Get<T>()
{
// use some IoC container
}
}
In your WP7 app you'll implement the shared Interface for WP7 and register it once the WP7 starts up.
public App()
{
MainPage.IoC.Register(new MainPage.DoSomethingWP7());
}
private class DoSomethingWP7 : IDoSomething
{
}
You'll also do the same for WP8 in the WP8 app. And in your shared library you can then ask for the relevant interface regardless of its platform version specific implementation:
IDoSomething sharedInterface = IoC.Get<IDoSomething>();
I have a simpler answer. I think you are close with what you are doing. I just used your code with one modification so I can use it with the Telerik controls. Here's what I did. I located your code in my project's App class (codebehind of App.Xaml). I made one change that I think will take care of your problem:
private static Version mVersion;
public static Version Version {
get {
if (mVersion == default(Version)) {
var lcAssembly = typeof(App);
var parts = lcAssembly.FullName.Split(',');
var lcVersionStr = parts[1].Split('=')[1];
mVersion = new Version(lcVersionStr);
}
return mVersion;
}
}
Now I can get the version number by calling "App.Version".
This worked for me:
var appAssembly = Application.Current.GetType().Assembly;
var appAssemblyVersion = appAssembly.GetName().Version;
I tested with WP7.1 and WP8.0.

how to replace code that uses now obsolete System.Data.OracleClient namespace classes?

I've made a "generic" program that converts data from a db to another. It uses configuration files to define the conversion. It uses code like this:
static DbProviderFactory _srcProvFactory;
static DbProviderFactory _trgtProvFactory;
public static bool DoConversions()
{
try
{
if (!InitConfig())
return false;
_srcProvFactory = DbProviderFactories.GetFactory(GetConnectionClassTypeByDatabaseType(Preferences.SourceDatabaseType));
_trgtProvFactory = DbProviderFactories.GetFactory(GetConnectionClassTypeByDatabaseType(Preferences.TargetDatabaseType));
using (DbConnection srcCnctn = _srcProvFactory.CreateConnection(),
trgtCnctn = _trgtProvFactory.CreateConnection())
{
srcCnctn.ConnectionString = Preferences.SourceConnectionString;
srcCnctn.Open();
trgtCnctn.ConnectionString = Preferences.TargetConnectionString;
trgtCnctn.Open();
//DO STUFF
}
}
}
Above GetConnectionClassTypeByDatabaseType-method return strings like "System.Data.OracleClient" depending on config file.
The DO STUFF part calls methods like one below (there's many of these) to find out database table column properties from schema. This is needed cause Oracle, SQL server etc. handle these differently.
public static int GetColumnMaxStringLength(DbProviderFactory provFactory, DataRow schemaTableRow)
{
if (provFactory is OracleClientFactory)
{
return Convert.ToInt32(schemaTableRow["LENGTH"]);
}
else if // OTHER OPTIONS
...
throw new Exception(string.Format("Unsupported DbProviderFactory -type: {0}", provFactory.GetType().ToString()));
}
So how this is supposed to be fixed now when the build says these classes are obsolete? This was supposed to be kind of text book solution when I did this (Pro C# 2008 and the
.NET 3.5 Platform). Now I'm baffled.
Thanks in advance & Best Regards - Matti
ODP.NET or any of the other 3rd party ADO.NET driver providers:
ref: Comparison of 3rd Party Oracle .NET Providers

Is it possible to extend web matrix with plugins?

The new Webmatrix is a cool and free development environment. Does it have any extension points to add new functionality?
With Webmatrix 2.0 Beta and later there is an extensibility framework in place for adding "Extensions." The API is quite simple at present but it appears you can create any arbitrary managed code and include in your constructor where you inherit the Microsoft.WebMatrix.Extensibility.IExtension interface.
Here's a snippet to get you started based on my simple Extension:
[Export(typeof(IExtension))]
public class UmbracoExtension : IExtension
{
public IEnumerable<IDashboardItem> DashboardItems
{
get { return null; }
}
public string Name
{
get { return "Extension"; }
}
public string Version
{
get { return "1.0"; }
}
private IRibbonGroup _ribbonGroup;
private IWebMatrixHost _webMatrixHost;
private List<IRibbonItem> _ribbonItems;
public IEnumerable<IRibbonItem> RibbonItems
{
...
}
[Import(typeof(IWebMatrixHost))]
private IWebMatrixHost WebMatrixHost
{
...
}
-Paul
WebMatrix does not support any extensibility (such as plugins) in version 1.0.
The feature I miss most with WebMatrix 2.0 is not being able to toggle commenting of lines of code but it sure is maturing as an outstanding CMS.
Clinton: You can actually comment and uncomment lines using Ctrl-K-C and Ctrl-K-U keyboard shortcuts.
Others: For more information on extensibility: http://extensions.webmatrix.com/documentation

Can Resharper (or Visual Studio) collapse a method call (replace the call with the contents of that method/constant)?

I've inherited a web application written in ASP.NET that has an incomplete implementation of a localization scheme (not using resource files). Here's a micro version:
public class Useful
{
public void DoSomething()
{
return Localizations.Do_Something_Message_vx7Hds8i;
}
}
public class Localizations
{
public const string Do_Something_Message_vx7Hds8i = "Some text!";
}
In almost all cases, these localized strings aren't even used in more than one place. I'd like to factor out this annoying localization layer before properly localizing the app.
The end result I want is just:
public class Useful
{
public void DoSomething()
{
return "Some text!";
}
}
This is proving tediously slow and I have over 1000 in this app.
What would be awesome would be a one-click way of selecting the reference and have it automatically suck in the string contents. I'm using Visual Studio 2008 and ReSharper 5.1.
Does anyone know if there's a way to accomplish this? It seems like there should be a proper name for what I'm trying to do (anti-modularization?) but I'm a little stumped where to start.
The default key command in Resharper is Ctrl+Alt+N for inline refactoring.

Resources