Migrating one code from dotnet core to dotenet framewrok 4.8 - migration

This is dotnet core 3.0 code segment. Due to some limitation i have to use dotnet framework 4.8. Can someone help migrating this code to dotnet framework 4.8.
return Value switch
{
BigInteger _ => Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value),
Length),
long l => Type.Format(l, Length),
_ => Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length)
};

Related

How to load .NET 6 project in a .NET 6 console application

I am attempting to load a .NET 6 project (SDK Style) in a .NET 6 console application. My entire project is fairly simple - it actually attempts to load its own .csproj file when it runs from the default output folder:
using Microsoft.Build.Evaluation;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}
I am using the following nuget packages:
Microsoft.Build (17.2.0)
Microsoft.Build.Utilities.Core (17.2.0)
When I run the code, I get the following exception:
Microsoft.Build.Exceptions.InvalidProjectFileException: 'The SDK 'Microsoft.NET.Sdk' specified could not be found. C:\Users\vchel\source\repos\ProjLoading\ProjLoading\ProjLoading.csproj'
This exception was originally thrown at this call stack:
Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(string, Microsoft.Build.Shared.IElementLocation, string, object[])
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(string, Microsoft.Build.Construction.ProjectImportElement, out System.Collections.Generic.List<Microsoft.Build.Construction.ProjectRootElement>, out Microsoft.Build.BackEnd.SdkResolution.SdkResult, bool)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImports(string, Microsoft.Build.Construction.ProjectImportElement, out Microsoft.Build.BackEnd.SdkResolution.SdkResult)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.EvaluateImportElement(string, Microsoft.Build.Construction.ProjectImportElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.PerformDepthFirstPass(Microsoft.Build.Construction.ProjectRootElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.Evaluate()
Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.Project(string, System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext, Microsoft.Build.FileSystem.IDirectoryCacheFactory)
...
[Call Stack Truncated]
I am building/running this console application from Visual Studio 2022 (17.2.2).
How can I solve this problem?
I don't understand why, but I ran across this solution and it has solved the problem:
https://blog.rsuter.com/missing-sdk-when-using-the-microsoft-build-package-in-net-core/
In case the link dies in the future, my full project now sets the environment variable MSBUILD_EXE_PATH to the latest version of msbuild as shown in the following code:
using Microsoft.Build.Evaluation;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var startInfo = new ProcessStartInfo("dotnet", "--list-sdks")
{
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
process.WaitForExit(1000);
var output = process.StandardOutput.ReadToEnd();
var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
.OfType<Match>()
.Select(m => System.IO.Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll"));
var sdkPath = sdkPaths.Last();
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath);
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}

How to Evaluate JavaScript code from .NetCore

I need to evaluate Javascript code from .netcore 2.1 project
string vRule = "var input = arguments[0]; if (!input) return \"\"; if(input.length != 7) return \"a fixed string length of 7 is required\"; else return \"\"";
string spResponse = "sdfsd23";
string errorText =
_jscriptEval.EvalToString(new List<object>
{
"var args = new Array('" + spResponse +
"');\r\n validateRule(args);\r\n function validateRule(arguments){" + vRule +
"}\r\n"
});
You can use Jint. Jint implements the ECMA 5.1 spec and can be use from any .NET implementation (Xamarin, .NET Framework, .NET Core). Just use the NuGet package and has no dependencies to other stuff - it’s a single .dll and you are done!
Just transform your javascript code into a function and run it like this (this is just an example, not your implementation):
var engine = new Engine()
.Execute("function MyFunction(a, b) { return a + b; }")
;
engine.Invoke("MyFunction", 1, 2); // -> 3
You have more explanations and examples on https://github.com/sebastienros/jint

Migrate CRUD Plugin from Play 1.2.4 to 2.5.x : views compilation errors

i'm new on Playframework and i need to migrate the CRUD Plugin from Play-1.2.4 to a module on Play-2.5.x. I'm facing some strange problems with the views. For example the form.scala.html component have the following errors :
app\views\tags\crud\form.scala.html:28: not found: type fieldName
app\views\tags\crud\form.scala.html:28: variable fieldsHandler of type Array[String] does not take type parameters.
app\views\tags\crud\form.scala.html:31: not found: value field
Here is a piece of code of the form file :
#(fields: List[String], obj: Object, typ: controllers.CRUD.ObjectType)(body: Html)
#import scala.Predef; var currentObject: Object = null; var currentType: controllers.CRUD.ObjectType = null; var fieldsHandler = new Array[String](10);
#for(fieldName <- fields) {
var am : String = "";
var field = #currentType.getField(fieldName);
#if(field == null){
throw new play.exceptions.TagInternalException("Field not found -> " + #fieldName)
}
#if(field.typ == "text") {
#tags.crud.textField(fieldName, currentObject[fieldName])
}
#if(field.typ == "password") {
#tags.crud.passwordField(fieldName, currentObject[fieldName])
}
#if(field.typ == "binary"){
#tags.crud.fileField(fieldName, currentObject[fieldName], currentObject.id )
}
}
--> 80% of the compile errors are related to variable recognition !
A piece from build.sbt file:
scalaVersion := "2.11.7"
lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean, SbtTwirl)
fork in run := true
Any idea ? Your help will be appreciated. Thanks.
I understood that the principle of the crud plugin is in contradiction with the new logic of compiling scala templates. So I started on a new generic implementation of crud.
Thank you

react-native .toLocaleString() not working on android

Updated 2022: With hermes enabled you should be good now.
I'm using .toLocaleString() on react-native for my number output. All work on IOS but seems not working on Android. This is normal or? Do I need to use a function for the decimal?
rather than using a polyfill or an external dependency, change the JSC your android app builds with. For the newer versions of react-native add or override the following line in app/build.gradle
def jscFlavor = 'org.webkit:android-jsc-intl:+'
On newer versions of RN >0.62 you can change the JSC (JavaScriptCore) build variant to support/include ICU i18n library and necessary data allowing to use e.g. Date.toLocaleString and String.localeCompare
Replace this line in your android/app/build.gradle file
def jscFlavor = 'org.webkit:android-jsc:+'
with this line
def jscFlavor = 'org.webkit:android-jsc-intl:+'
Clean build and react-native run android
Note
This variant is about 6MiB larger per architecture than default.
So, expect your APK size to increase by about 4MB for each APK architecture build if using def enableSeparateBuildPerCPUArchitecture = true and a more bigger APK if separate build per architecture is disabled
You can use
number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
This is an issue with Javascript core used to run react native in Android and not with react native itself. To overcome this, you'll have to integrate latest javascript core into your android build or upgrade react native to 0.59.
The details are documented in JSC Android Buildscripts repo.
Now for people who would like to do the locale string formatting without needing to integrate the entire javascript core, Javascript has Internationalization API which lets you format numbers to language sensitive format. Documentation available at MDN
This API is not available in android and needs to be polyfilled using Intl
In your project root, install the Intl library
yarn add intl
And then in your project's index file (index.js) add the following code at the top of the file:
if(Platform.OS === 'android') { // only android needs polyfill
require('intl'); // import intl object
require('intl/locale-data/jsonp/en-IN'); // load the required locale details
}
After doing the above two steps, you can now get locale string anywhere in your project using
new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(10000000);
In case you need to format number for another locale code, all the locale code details are available under the intl/locale-data/jsonp/ directory. Simply require the ones you need in your index.js file.
The reason for this is very old version of JavaScriptCore used by react-native. iOS embeds own version which is why it is working fine there.
Issue still exists (some reading about where it's heading https://github.com/facebook/react-native/issues/19737)
And more info about this from Airbnb devs
https://medium.com/airbnb-engineering/react-native-at-airbnb-the-technology-dafd0b43838 (search for "JavaScriptCore inconsistencies")
(value) => {
if (typeof value === 'number') {
const [currency, cents] = (value / 100).toFixed(2).toString().split('.');
return `${currency.replace(/\B(?=(\d{3})+(?!\d))/g, '.')},${cents}`;
}
return '0,00';
}
it's more recent and lightweight, please check
First install:
yarn add #formatjs/intl-getcanonicallocales #formatjs/intl-locale #formatjs/intl-pluralrules #formatjs/intl-numberformat
Check if need polyfill
import {shouldPolyfill} from '#formatjs/intl-numberformat/should-polyfill'
if (shouldPolyfill()) {
require('#formatjs/intl-getcanonicallocales/polyfill');
require('#formatjs/intl-locale/polyfill');
require('#formatjs/intl-pluralrules/polyfill');
require('#formatjs/intl-numberformat/polyfill');
require('#formatjs/intl-numberformat/locale-data/en-US');
}
see source: https://formatjs.io/docs/polyfills/intl-numberformat/
A very easy and straight forward way is to use a polyfill:
First it needs to be installed:
npm i number-to-locale-string-polyfill
This has to be added in your code, best just outside the class/function where you want to use .toLocaleString().
require('number-to-locale-string-polyfill');
I solved this using a custom function
function numberToMoney(amount, simbol = '$', decimalCount = 2, decimal
= ".", thousands = ",") {
decimalCount = Math.abs(decimalCount)
decimalCount = isNaN(decimalCount) ? 2 : decimalCount
const negativeSign = amount < 0 ? "-" : ""
const i = parseInt(amount = Math.abs(Number(amount) ||
0).toFixed(decimalCount)).toString()
const j = (i.length > 3) ? i.length % 3 : 0
return simbol + negativeSign + (j ? i.substr(0, j) + thousands : '') +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ?
decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "")
};
No need to install extra packages
Displaying currency values in React Native A zero dependencies solution:
const parseCurr = (value) =>
Platform.OS === 'android'
? '$' + price.toFixed(2)
: price.toLocaleString('en-US', { style: 'currency', currency:'USD' });
parseCurr(25.75) // => $25.75
A real life example (money values are multiplied by 100 for better cents precision) and converting the value to Brazilian Reais (R$)
export const getBRPrice = (price: number) => {
const parsedPrice =
( price / 100 ).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
return Platform.OS === 'android'
? `R$${ ( price / 100 ).toFixed(2) }`
: parsedPrice;
};
// getBRPrice(450) => R$4,50
Solution: 1
Go to your android/app/build.gradle
Replace this line def jscFlavor = 'org.webkit:android-jsc:+'
with this
def jscFlavor = 'org.webkit:android-jsc-intl:+'
Stop the metro and rebuild your app.
Solution: 2
Otherwise, you can use this package https://www.npmjs.com/package/luxon
import import {DateTime} from 'luxon';
const date = DateTime.fromISO(new Date().toISOString());
const formatted = date.toLocaleString(DateTime.DATETIME_MED);
console.log(formatted);
Merging some responses from this thread, you can use this code where it is possible to customize the formatted response
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ',',
decimalSeparator: '.',
symbol: '$'
}
const currencyFormatter = (value, options) => {
if (typeof value !== 'number') value = 0.0
options = { ...defaultOptions, ...options }
value = value.toFixed(options.significantDigits)
const [currency, decimal] = value.split('.')
return `${options.symbol} ${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
options.thousandsSeparator
)}${options.decimalSeparator}${decimal}`
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
This will remove commas after decimal point
If you need two digits after the decimal and always want to round down
you can use below code.
Math.floor(1233.31231231 * 100) / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
To round differently check out this resource
If these solutions don't work for you... In my case, I was using React Native with the expo web simulator and wanted to format minutes with 2 characters ie. 00, 01, ... 10, 11, etc. My solution was to check if minutes contained one character, if so, prepend a "0".
... + (date.getMinutes().toString().length == 1 ? "0" : "") + date.getMinutes().toString()

Calling a Metro based Security Token Service from an Axis2 STS Client

I want to call a Security Token Service which was created and deployed using Metro 2.2 framework from an Axis 2 STS Client. I'm trying to do the same but getting issues like the one below: -
java.lang.RuntimeException:Incorrect inclusion value: -1
I went deep into the source code and saw that in SecureConversationTokenBuilder class code is wriiten something like this:-
String inclusionValue = attribute.getAttributeValue().trim();
conversationToken.setInclusion(SP11Constants.getInclusionFromAttributeValue(inclusionValue));
then I went into the SP11Constants.getInclusionFromAttributeValue(inclusionValue) and saw the following piece of code:-
public static int getInclusionFromAttributeValue(String value ) {
if (INCLUDE_ALWAYS.equals(value)) {
return SPConstants.INCLUDE_TOEKN_ALWAYS;
} else if (INCLUDE_ALWAYS_TO_RECIPIENT.equals(value)) {
return SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT;
} else if (INCLUDE_NEVER.equals(value)) {
return SPConstants.INCLUDE_TOKEN_NEVER;
} else if (INCLUDE_ONCE.equals(value)) {
return SPConstants.INCLUDE_TOKEN_ONCE;
} else {
return -1;
}
}
as INCLUDE_ALWAYS = "http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always" which is not equal to what is defined by metro in policy.xml like
http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Always
Therefore the above code always return -1 and in turn throws a runtime exception as below:-
public void setInclusion(int inclusion) {
if(SPConstants.INCLUDE_TOEKN_ALWAYS == inclusion ||
SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == inclusion ||
SPConstants.INCLUDE_TOEKN_ALWAYS_TO_INITIATOR == inclusion ||
SPConstants.INCLUDE_TOKEN_NEVER == inclusion ||
SPConstants.INCLUDE_TOKEN_ONCE == inclusion ) {
this.inclusion = inclusion;
} else {
//TODO replace this with a proper (WSSPolicyException) exception
throw new RuntimeException("Incorrect inclusion value: " + inclusion);
}
}
Just wanted to know whether it is possible to get token from Security Token Service (STS) created in Metro Framework invoked from an Axis2 based STS Client.Please advise as I'm stuck in between.
Thanks in advance.