What is the dotnet 6 equivalent of localizer.WithCulture? - c#

When my project was using
<TargetFramework>netcoreapp3.1</TargetFramework>
I could get the localization injected in my page constructor:
IStringLocalizer<Strings> _localizer;
public IndexModel(IStringLocalizer<Strings> localizer) {
_localizer = localizer;
}
but still retrieve an alternative language's collection of strings:
var localizer = _localizer.WithCulture(new CultureInfo(cultureCode));
var translatedStr = localizer[c.Value].ToString();
Being in the process of upgrading to:
<TargetFramework>net6.0</TargetFramework>
The _localizer.WithCulture code shows this error in VS Code:
'IStringLocalizer<Strings>' does not contain a definition for 'WithCulture' and no accessible extension method 'WithCulture' accepting a first argument of type 'IStringLocalizer<Strings>' could be found (are you missing a using directive or an assembly reference?)
What is the dotnet 6 version of this?
If I switch back to netcoreapp3.1 I can clearly see the warning:
'IStringLocalizer.WithCulture(CultureInfo)' is obsolete: 'This method is obsolete. Use `CurrentCulture` and `CurrentUICulture` instead.'
But what are the CurrentCulture and CurrentUICulture it is referring to?

Related

Getting error on AuthenticationParameters and AcquireToken

I am getting following errors:
Code:
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(redirectUrl)).Result;
Error:
An object reference is required for the non-static field, method, or property 'AuthenticationParameters.CreateFromResourceUrlAsync(Uri)' Pending email for Authorizers C:\Users\handemv\source\Workspaces\Dynamics 365\Trunk-UCI\Tools\Automation_CapGSupport\Pending Email\Pending email for Authorizers\PendingEmailCheck.cs
Code:
AuthenticationContext authContext = new AuthenticationContext(_authority, false);
AuthenticationResult result = authContext.AcquireToken(_serviceUri, clientCred);
Error:
AuthenticationContext' does not contain a definition for 'AcquireToken' and no accessible extension method 'AcquireToken' accepting a first argument of type 'AuthenticationContext' could be found (are you missing a using directive or an assembly reference?)
Can anyone help me for same?
Error : AuthenticationContext' does not contain a definition for 'AcquireToken' and no accessible extension method 'AcquireToken' accepting a first argument of type 'AuthenticationContext' could be found (are you missing a using directive or an assembly reference?)
Solution 1:
This error due to AcquireToken was removed in v3 of the Microsoft.IdentityModel.Clients.ActiveDirectory library.
To fix this downgrade the version in nuget to 2.22.302.111727 to solve this error.
Solution 2:
In V3 of ADAL.NET which appears to no longer have AcquireToken().
But it still has AcquireTokenAsync(). Note however that the parameters have slightly changed in the methods for v2 and v3.
For more details refer this thread
Error: An object reference is required for the non-static field, method, or property 'AuthenticationParameters.CreateFromResourceUrlAsync(Uri)' Pending email for Authorizers
Follow this link :https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/1410

Azure Function to Update Table Storage entity - CloudTable.Execute not found

I'm starting out using Azure and c# and I'm attempting to use Table Storage - and using an Azure Function to update entitys in the table. My code is as follows:
#r "Microsoft.WindowsAzure.Storage"
#r "Newtonsoft.Json"
using System;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
public static async Task<HttpResponseMessage> Run(HttpRequest req, CloudTable lookupTable)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string partitionKey = data.Society;
string rowKey = data.ConnectionDetails.Environment;
string newConnection = data.ConnectionDetails.Connection;
TableOperation operation = TableOperation.Retrieve<SocietyConnectionDetails>(partitionKey, rowKey);
TableResult result = lookupTable.Execute(operation);
SocietyConnectionDetails societyConnectionDetails = (SocietyConnectionDetails)result.Result;
societyConnectionDetails.Connection = newConnection;
operation = TableOperation.Replace(societyConnectionDetails);
lookupTable.Execute(operation);
}
public class SocietyConnectionDetails : TableEntity
{
public string Connection {get; set;}
}
But the errors im getting are as follows:
2020-02-25T10:33:16.956 [Error] run.csx(17,38): error CS1061: 'CloudTable' does not contain a definition for 'Execute' and no accessible extension method 'Execute' accepting a first argument of type 'CloudTable' could be found (are you missing a using directive or an assembly reference?)
2020-02-25T10:33:16.984 [Error] run.csx(22,17): error CS1061: 'CloudTable' does not contain a definition for 'Execute' and no accessible extension method 'Execute' accepting a first argument of type 'CloudTable' could be found (are you missing a using directive or an assembly reference?)
2020-02-25T10:33:17.011 [Error] run.csx(8,47): error CS0161: 'Run(HttpRequest, CloudTable)': not all code paths return a value
I can see that the issue is happening when im attempting to 'Execute' my Table Operations... this might be a relatively straight forward problem but I'm struggling to work out why this wouldn't be working...
Thanks for any help..
I can reproduce your error.
Like this:
Solution is add a function.proj file to your function.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
</ItemGroup>
</Project>
Then the error should disappear.
(If you dont do this. the compilation step will not success.)
I assume you are using the Azure Functions runtime 2, and in this case the problem is related to your references. You should reference the nuget package Microsoft.Azure.WebJobs.Extensions.Storage and ensure it is installed in your function, according to this article in Microsoft's documentation.

HttpRequest.RouteValues property is not accessible from code but accessible from debugger

I am trying to create middleware which performs some checking for particular requests.
For example, I have such routes:
api/Test/{paramToCheck}/aaa
api/Test/bbb/ccc
and I have these requests:
http://some-host-and-port/api/Test/1234/aaa
http://some-host-and-port/api/Test/bbb/ccc
Now inside my middleware I want to check if request contains {paramToCheck} and get value of this parameter.
When I set breakpoint inside InvokeAsync I can see httpContext.Request.RouteValues property containing all needed data (Keys contains "paramToCheck" and Values contains its value).
But in code I can't access this property, I get error:
Error CS1061: 'HttpRequest' does not contain a definition for
'RouteValues' and no accessible extension method 'RouteValues'
accepting a first argument of type 'HttpRequest' could be found (are
you missing a using directive or an assembly reference?)
var value = httpContext.Request.RouteValues["paramToCheck"];
How can I access this property or how can I perform needed check?
Code:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware
(
RequestDelegate next
) => this._next = next;
public async Task InvokeAsync(HttpContext httpContext)
{
var value = httpContext.Request.RouteValues["paramToCheck"]; // error here
//... some logis with value
await this._next(httpContext);
}
}
EDIT
Middleware is inside netstandard2.1 class library and it cannot be moved to api project as it is common and should be used by several api projects.
UPDATE
Seems like currently it cannot be achieved as RouteValues propery was added in Microsoft.AspNetCore.Http.Abstractions 3.0.0 which is inside NetCoreApp 3 metapackage. And there is no possibility to install this package in netstandard 2.1 project because the latest version is 2.2.0.
Just encountered the same problem today.
This is hacky but it works
IReadOnlyDictionary<string, object>? routeValues = ((dynamic)context.Request).RouteValues as IReadOnlyDictionary<string, object>;
Using a class library, the answer for me was to upgrade to using .netcore 3.1's Microsoft.AspNetCore.App instead of Microsoft.AspNetCore.Http.Abstractions v2.2
As stated here, .net core 3 did away with all the small packages, so I replaced
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
</ItemGroup>
with
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App"/>
</ItemGroup>
and then I could access the route like so:
HttpContext.Request.RouteValues["version"];
where {version} was set in the route.
sounds like you trying to access this from a service implementation which does not have access to httpContext, am i correct in saying to have this outside of your api project.
if you do httpContext.Request.RouteValues["paramToCheck"]; in controller does it works... then to get it to work , do this in controller and pass the result to the lib.
httpContext has "binding"* to BaseController or ControllerBase... what ever its call.. basically the wiring which you are expecting is not done in your lib... so httpContext has no web context at all, there is a much better way to word this... all, but you get the just.
You can use the extension .GetRouteData() from RoutingHttpContextExtensions which will provide you a RouteData instance. This extension is part of Microsoft.AspNetCore.Routing package.
The RouteData contains a property member of type RouteValueDictionary called Values.
var routeData = httpContext.GetRouteData();
if (routeData.Values.TryGetValue("paramToCheck", out object value))
{
// ... Do some logic with the value
}
To understand a bit more about the RoutingHttpContextExtensions and RouteData check the source code at
https://github.com/dotnet/aspnetcore/tree/3.0/src/Http/Routing
Alexander Ivanov's answer:
routeValues = ((dynamic)context.Request).RouteValues as IReadOnlyDictionary<string, object>;
worked for me, thanks! It took me a little to get it working, however, as the following packages were required:
Microsoft.AspNetCore.Http.Abstractions
Microsoft.CSharp
Including this additional information in the hopes it saves someone some time.

ServiceCollection does not contain a definition from "AddLogging"

I'm currently trying to create a Logger so I can inject it in Unit Tests. I'm following https://stackoverflow.com/a/43425633/1057052, and it used to work! I then moved the project and reestablished the dependencies, and now I'm getting
'ServiceCollection' does not contain a definition for 'AddLogging' and
no accessible extension method 'AddLogging' accepting a first argument
of type 'ServiceCollection' could be found (are you missing a using
directive or an assembly reference?)
There must be something silly I'm missing. Currently under ASP.NET Core 2.2, and I believe I have assigned the correct dependencies.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection?view=aspnetcore-2.2
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.loggingservicecollectionextensions.addlogging?view=aspnetcore-2.2
I've been reinstalling for the past hour our so! Can't nail what the problem is
Here's the code:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Planificacion.UnitTest.Config
{
public class LoggerTestConfig
{
private LoggerTestConfig()
{
}
// https://stackoverflow.com/a/43425633/1057052
public static ILogger<T> GetLoggerConfig<T>() where T : class
{
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
var factory = serviceProvider.GetService<ILoggerFactory>();
return factory.CreateLogger<T>();
}
}
}
The image highlights that the dependency injection dll is referenced, but desired LoggingServiceCollectionExtensions.AddLogging Method as shown in the links provided, indicates
Namespace: Microsoft.Extensions.DependencyInjection
Assembly: Microsoft.Extensions.Logging.dll <----NOTE THIS
Which is not referenced as shown in the image.
Add a reference to the Microsoft.Extensions.Logging.dll assembly stated above.

Missing extension methods in HtmlHelper using NHaml

I discovered NHaml some days ago and it's a great project.
When I try to use MVC2 Html helpers like Html.LabelFor(), Html.TextBoxFor(); the views won't compile.
Example:
error CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'LabelFor' and no extension method 'LabelFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
0185: textWriter.Write(" ");
0185: textWriter.Write(Convert.ToString(Html.LabelFor(model => model.Username)));
0187: textWriter.WriteLine();
error CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
0194: textWriter.Write(" ");
0194: textWriter.Write(Convert.ToString(Html.TextBoxFor(model => model.Username)));
0196: textWriter.WriteLine();
I tried to add assemblies and namespaces in the nhaml's Web.config section but it doesn't change anything.
I'm using :
System.Web.Mvc 2.0
.NET Framework 3.5 SP1
Nhaml 1.5.0.2 from git trunk (and tried other builds)
My NHaml configuration is:
<nhaml autoRecompile="true" templateCompiler="CSharp3" encodeHtml="false" useTabs="false" indentSize="2">
It looks like you have an assembly reference problem.
You are probably referencing the MVC 1.0 assemblies, instead of 2.0 assemblies?
The problem is the view class contains a non-generic HtmlHelper. Or some new extension methods requires the ViewData.Model's type.
To correct this problem, change the property and instantiation in NHaml.Web.Mvc/NHamlMvcView.cs.
//public HtmlHelper Html { get; protected set; } // line 42
public HtmlHelper<TModel> Html { get; protected set; }
//Html = new HtmlHelper( viewContext, this ); // line 37
Html = new HtmlHelper<TModel>( viewContext, this );
Rebuild and use :)
As far as I can see the new MVC helpers are not supported, actually only a limited amount of HtmlHelpers are namely LinkExtensions. As a wild guess, you can possibly try to adding the LabelExtensions to the setup of the NHaml viewengine in the NHaml.Web.Mvc/NHamlMvcViewEngine.cs file (since you do have the source) and check if that works.
private void InitializeTemplateEngine()
{
// snip
_templateEngine.Options.AddReference( typeof( LabelExtensions ).Assembly.Location ); // Line 50
}

Categories