dotNetCore4Delphi Examples

The following examples demonstrate how to use the dotNetCore4Delphi to produce a software by combining Delphi Source Codes with .Net Core framework and other .Net Core libraries.

How to write a simple Hello World using .Net Console

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.ObjectMgr; type (** * Delphi equivalent of the C# Console Class *) TConsole = class private class var FConsole: TCoreClrStaticObject; class function GetTitle: string; static; class procedure SetTitle(AValue: string); static; public class constructor Create; class destructor Destroy; class procedure Write(value: string); overload; class procedure WriteLine(); overload; class procedure WriteLine(value: Variant); overload; class function ReadLine(): string; class property Title: string read GetTitle write SetTitle; end; { TConsole } class constructor TConsole.Create; begin FConsole := TCoreClrStaticObject.Create('System.Console'); end; class destructor TConsole.Destroy; begin FConsole.Free; end; class function TConsole.GetTitle: string; begin Result := FConsole.GetPropertyValue('Title'); end; class function TConsole.ReadLine: string; begin Result := FConsole.InvokeMethod('ReadLine'); end; class procedure TConsole.SetTitle(AValue: string); begin FConsole.SetPropertyValue('Title', AValue); end; class procedure TConsole.Write(value: string); begin FConsole.InvokeMethod('Write', ['System.String'], [value]); end; class procedure TConsole.WriteLine(value: Variant); begin FConsole.InvokeMethod('WriteLine', ['System.Object'], [value]); end; class procedure TConsole.WriteLine; begin FConsole.InvokeMethod('WriteLine'); end; begin try TConsole.WriteLine(' Hello! Welcome to dotNetCore4Delphi '); TConsole.WriteLine('=================================================='); TConsole.WriteLine(' The program displays the string Hello World! '); TConsole.Title := 'Hello Word Title'; TConsole.WriteLine(''); TConsole.WriteLine('Hello World!'); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to Load .Net Core Assemblies

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.Intf, CNCoreClrLib.AssemblyMgr; const DONET_CORE_VER = '5.0.2'; SYSTEM_DATA_COMMON_DLL = 'C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App\'+DONET_CORE_VER+'\System.Data.Common.dll'; SYSTEM_NET_SECURITY_DLL = 'C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App\'+DONET_CORE_VER+'\System.Net.Security.dll'; SYSTEM_DATA_COMMON_ASSEMBLY_STRING = 'System.Data.Common, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'; SYSTEM_PRIVATE_DLL = 'C:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App\'+DONET_CORE_VER+'\System.Private.CoreLib.dll'; SYSTEM_RUNTIME_ASSEMBLY_STRING = 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'; procedure DisplayAssemblyTypes(AAssembly : ICoreClrAssembly); var I: Integer; m_types: TArray<ICoreClrType>; begin Writeln('Loading Types for Assembly ''{0}''', AAssembly.FullName); Writeln('-----------------------------------------------------'); m_types := AAssembly.GetTypes; // Display all the types contained in the specified assembly. for I := 0 to Length(m_types) - 1 do Writeln(m_types[I].Name); Writeln(''); Writeln(''); end; procedure LoadAssemblyFromFile; var m_assembly: ICoreClrAssembly; begin Writeln('Loading System.Data.Common.dll using Assembly File'); m_assembly := TCoreClrAssembly.LoadFrom(SYSTEM_DATA_COMMON_DLL); DisplayAssemblyTypes(m_assembly); end; //The following example loads an assembly given its fully qualified name, and //lists all the types contained in the specified assembly. procedure LoadAssemblyByAssemblyString; var m_assembly: ICoreClrAssembly; m_types: TArray<ICoreClrType>; I: Integer; begin // You must supply a valid fully qualified assembly name. m_assembly := TCoreClrAssembly.Load(SYSTEM_DATA_COMMON_ASSEMBLY_STRING); DisplayAssemblyTypes(m_assembly); end; procedure LoadAssemblyByFilePath; var m_assembly: ICoreClrAssembly; begin Writeln('Loading System.Net.Security.dll using File Path'); m_assembly := TCoreClrAssembly.LoadFile(SYSTEM_NET_SECURITY_DLL); DisplayAssemblyTypes(m_assembly); end; procedure LoadAssemblyError; var m_assembly: ICoreClrAssembly; begin Writeln('Loading Inaccessible Assembly. This should error.'); TCoreClrAssembly.LoadFile(SYSTEM_PRIVATE_DLL); end; begin try Writeln(' Hello! Welcome to dotNetCore4Delphi '); Writeln('========================================================='); Writeln('This program demonstrate how to Load .Net Core Assemblies'); LoadAssemblyFromFile; LoadAssemblyByAssemblyString; LoadAssemblyByFilePath; LoadAssemblyError; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to Create instance of a .Net Object

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.Intf, CNCoreClrLib.ObjectMgr; procedure CreateBaseObject; var baseObject: ICoreClrObject; begin baseObject := TCoreClrObject.Create(); Writeln(baseObject.GetType.FullName); Writeln(baseObject.ToString); end; procedure CreateIntegerObject; var value: Integer; clrObject: ICoreClrObject; begin value := 9878; clrObject := TCoreClrObject.Create(value); Writeln(clrObject.GetType.FullName); Writeln(clrObject.ToString); end; procedure CreateArrayObject; var clrObject: ICoreClrObject; begin clrObject := TCoreClrObject.Create(TArray<Integer>.Create(1, 2, 3, 4)); Writeln(clrObject.GetType.FullName); Writeln(clrObject.ToString); Writeln(clrObject.IsArray); Writeln(clrObject.GetArrayLength); Writeln(clrObject.getArrayElement(0)); Writeln(clrObject.getArrayElement(1)); clrObject.SetArrayElement(1, 1000); Writeln(clrObject.getArrayElement(1)); end; begin try Writeln(' Hello! Welcome to dotNetCore4Delphi '); Writeln('========================================================'); Writeln('This program demonstrate how to Create .Net Core Objects'); // Create Basic Objects CreateBaseObject; CreateIntegerObject; CreateArrayObject; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to Create static .Net Object

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.Intf, CNCoreClrLib.ObjectMgr; type //Provides constants and static methods for trigonometric, logarithmic, //and other common mathematical functions. TMath = class private class var FMath: TCoreClrStaticObject; class function GetPI: Double; static; public class constructor Create; class destructor Destroy; class function Abs(Value: Double): Double; static; class function Floor(Value: Double): Double; static; class function Ceiling(Value: Double): Double; static; class function Min(Value1, Value2: Double): Double; static; class function Max(Value1, Value2: Double): Double; static; class function Pow(x, y: Double): Double; static; class function Round(Value: Double): Double; static; class function Truncate(Value: Double): Double; static; class property PI: Double read GetPI; end; TCreateStaticObjectDemo = class public class procedure Abs; static; class procedure Floor; static; class procedure Round; static; class procedure Truncate; static; class procedure PI; static; end; { TMath } class function TMath.Abs(Value: Double): Double; begin Result := FMath.InvokeMethod('Abs', ['System.Double'], [Value]); end; class function TMath.Ceiling(Value: Double): Double; begin Result := FMath.InvokeMethod('Ceiling', ['System.Double'], [Value]); end; class constructor TMath.Create; begin FMath := TCoreClrStaticObject.Create('System.Math'); end; class destructor TMath.Destroy; begin FMath.Free; end; class function TMath.Floor(Value: Double): Double; begin Result := FMath.InvokeMethod('Floor', ['System.Double'], [Value]); end; class function TMath.GetPI: Double; begin Result := FMath.GetFieldValue('PI'); end; class function TMath.Max(Value1, Value2: Double): Double; begin Result := FMath.InvokeMethod('Max', ['System.Double', 'System.Double'], [Value1, Value2]); end; class function TMath.Min(Value1, Value2: Double): Double; begin Result := FMath.InvokeMethod('Min', ['System.Double', 'System.Double'], [Value1, Value2]); end; class function TMath.Pow(x, y: Double): Double; begin Result := FMath.InvokeMethod('Pow', ['System.Double', 'System.Double'], [x, y]); end; class function TMath.Round(Value: Double): Double; begin Result := FMath.InvokeMethod('Round', ['System.Double'], [Value]); end; class function TMath.Truncate(Value: Double): Double; begin Result := FMath.InvokeMethod('Truncate', ['System.Double'], [Value]); end; { TCreateStaticObjectDemo } //The following example uses the Abs(Double) method to //get the absolute value of a number of Double values. class procedure TCreateStaticObjectDemo.Abs; var doubles: TArray<Double>; value: Double; begin doubles := TArray<Double>.Create(1.797693134E+308, 16.354e-17, 15.098123, 0, -19.069713, -15.058e18, -1.797693134E+308); Writeln('Abs:'); for value in doubles do Writeln(FloatToStr(TMath.Abs(value))); end; //The following example illustrates the Math.Floor(Double) method and contrasts it //with the Ceiling(Double) method. class procedure TCreateStaticObjectDemo.Floor; var doubles: TArray<Double>; value: Double; begin doubles := TArray<Double>.Create(7.03, 7.64, 0.12, -0.12, -7.1, -7.6); Writeln('Floors:'); for value in doubles do Writeln(FloatToStr(TMath.Floor(value))); end; //The following example uses the Pow method to calculate the value that results from //raising 2 to a power ranging from 0 to 32. class procedure TCreateStaticObjectDemo.PI; begin Writeln(FloatToStr(TMath.PI)); end; class procedure TCreateStaticObjectDemo.Round; begin Writeln('Classic Math.Round in CSharp'); Writeln(FloatToStr(TMath.Round(4.4))); // 4 Writeln(FloatToStr(TMath.Round(4.5))); // 4 Writeln(FloatToStr(TMath.Round(4.6))); // 5 Writeln(FloatToStr(TMath.Round(5.5))); // 6 end; class procedure TCreateStaticObjectDemo.Truncate; var floatNumber: double; begin floatNumber := 32.7865; // Displays 32 Writeln(FloatToStr(TMath.Truncate(floatNumber))); floatNumber := -32.9012; // Displays -32 Writeln(FloatToStr(TMath.Truncate(floatNumber))); end; begin try Writeln(' Hello! Welcome to dotNetCore4Delphi '); Writeln('===================================================='); Writeln('This program demonstrate how to Create Static Object'); TCreateStaticObjectDemo.Abs; TCreateStaticObjectDemo.Floor; TCreateStaticObjectDemo.Round; TCreateStaticObjectDemo.Truncate; TCreateStaticObjectDemo.PI; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to Create instance of a generic Object

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.Intf, CNCoreClrLib.ObjectMgr, CoreClrTypes; type TCoreGenericObject = class(TCoreClrObject) public constructor Create(AGenericTypeName: string; AGenericTypeNames: array of string; AArguments: array of Variant); overload; constructor Create(AGenericTypeName: string; AGenericTypeNames: array of string; AArguments: array of NCObject); overload; constructor Create(AGenericTypeName: string; AGenericTypeNames: array of string; AArguments: NCObjectArray); overload; end; [TypeMappingAttribute('Project2.TList<T>', 'System.Collections.Generic.List`1')] IList<T> = Interface(ICoreClrObject) end; TList<T> = class(TCoreClrGenericObject, IList<T>) public constructor Create(); overload; constructor Create(capacity: Integer); overload; end; { TList<T> } constructor TList<T>.Create(capacity: Integer); begin Inherited Create([GetTypeInfo<T>], 'System.Collections.Generic.List`1', [GetTypeName<T>], [capacity]); end; constructor TList<T>.Create; begin Inherited Create([GetTypeInfo<T>], 'System.Collections.Generic.List`1', [GetTypeName<T>], []); end; { TCoreGenericObject } constructor TCoreGenericObject.Create(AGenericTypeName: string; AGenericTypeNames: array of string; AArguments: NCObjectArray); begin inherited Create(AGenericTypeName, AGenericTypeNames, AArguments); end; constructor TCoreGenericObject.Create(AGenericTypeName: string; AGenericTypeNames: array of string; AArguments: array of NCObject); begin inherited Create(AGenericTypeName, AGenericTypeNames, AArguments); end; constructor TCoreGenericObject.Create(AGenericTypeName: string; AGenericTypeNames: array of string; AArguments: array of Variant); begin inherited Create(AGenericTypeName, AGenericTypeNames, AArguments); end; { Generic Object Examples } procedure DisplayGenericInfo( GenericObj: TCoreClrObject); begin Writeln(GenericObj.GetType.FullName); Writeln(GenericObj.IsGeneric); Writeln(GenericObj.GetPropertyValue('Capacity')); end; procedure CreateGenericListOfInt32; var genericObject: TCoreGenericObject; begin //C# List<int> genericObject = new List<int>(10); genericObject := TCoreGenericObject.Create('System.Collections.Generic.List`1', ['System.Int32'], [10]); try DisplayGenericInfo(genericObject); finally genericObject.Free; end; end; procedure CreateGenericListOfString; var genericObject: TCoreGenericObject; begin //C# List<string> genericObject = new List<string>(); genericObject := TCoreGenericObject.Create('System.Collections.Generic.List`1', ['System.String'], nil); try DisplayGenericInfo(genericObject); finally genericObject.Free; end; end; procedure CreateGenericListObjectOfInteger; var genericObject: TList<Integer>; begin //C# List<int> genericObject = new List<int>(10); genericObject := TList<Integer>.Create(10); try DisplayGenericInfo(genericObject); finally genericObject.Free; end; end; begin try Writeln(' Hello! Welcome to dotNetCore4Delphi '); Writeln('================================================================'); Writeln('This program demonstrate how to Create .Net Core Generic Objects'); CreateGenericListOfInt32; CreateGenericListOfString; CreateGenericListObjectOfInteger; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to load external .Net Core DLL and invoke members

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.Intf, CNCoreClrLib.ObjectMgr, CNCoreClrLib.AssemblyMgr; (* Assuming you have .Net Core library project below built as Mathematics.Dll namespace Mathematics { public class Mathematics { public int Add(int a, int b) { return a + b; } public int Subtract(int a, int b) { return a - b; } public bool Equal(int a, int b) { return a == b; } } } *) //Corresponding Delphi class type of Mathematics type in the Mathematics.dll const // Assuming the .Net Core project was built and saved into C:\Temp Assembly_Path = 'C:\Temp\Mathematics.dll'; Math_TypeName = 'Mathematics.Mathematics'; type TMathematics = class(TCoreClrObject) public constructor Create; function Add(a, b: Integer): Integer; function Subtract(a, b: Integer): Integer; function Equal(a, b: Integer): Boolean; end; { TMathematics } function TMathematics.Add(a, b: Integer): Integer; begin Result := InvokeMethod('Add', ['System.Int32', 'System.Int32'], [a, b]); end; constructor TMathematics.Create; begin inherited Create(Math_TypeName); end; function TMathematics.Equal(a, b: Integer): Boolean; begin Result := InvokeMethod('Equal', ['System.Int32', 'System.Int32'], [a, b]); end; function TMathematics.Subtract(a, b: Integer): Integer; begin Result := InvokeMethod('Subtract', ['System.Int32', 'System.Int32'], [a, b]); end; var mathematics: TMathematics; begin try Writeln(' Hello! Welcome to dotNetCore4Delphi. '); Writeln('====================================================='); Writeln('This program demonstrate how to use dotNetCore4Delphi'); Writeln('to load and invoke .Net Library and Types '); Writeln(''); // Load the assembly TCoreClrAssembly.LoadFrom(Assembly_Path); // Create Mathematics Object mathematics := TMathematics.Create; try Writeln('Add(30, 50): ' + IntToStr(mathematics.Add(30, 50))); Writeln('Subtract(30, 50): ' + IntToStr(mathematics.Subtract(30, 50))); Writeln('Equal(30, 50): ' + BoolToStr(mathematics.Equal(30, 50), True)); Writeln('Equal(50, 50): ' + BoolToStr(mathematics.Equal(50, 50), True)); finally mathematics.Free; end; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to use .Net ArrayList in Delphi

Exported from Notepad++
program Project2; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, CNCoreClrLib.ObjectMgr; type (** * Delphi equivalent of the C# ArrayList Class *) TArrayList = class(TCoreClrObject) private function GetCount: Integer; function GetCapacity: Integer; function GetItem(index: Integer): Variant; procedure SetItem(Index: Integer; Value: Variant); public constructor Create; function Add(Value: Variant): Integer; property Count: Integer read GetCount; property Capacity: Integer read GetCapacity; property Item[Index: Integer]: Variant read GetItem write SetItem; default; end; { TArrayList } function TArrayList.Add(Value: Variant): Integer; begin Result := InvokeMethod('Add', ['System.Object'], [value]); end; constructor TArrayList.Create; begin inherited Create('System.Collections.ArrayList'); end; function TArrayList.GetCapacity: Integer; begin Result := GetPropertyValue('Capacity'); end; function TArrayList.GetCount: Integer; begin Result := GetPropertyValue('Count'); end; function TArrayList.GetItem(index: Integer): Variant; begin Result := GetPropertyValue('Item', index); end; procedure TArrayList.SetItem(Index: Integer; Value: Variant); begin SetPropertyValue('Item', Index, value); end; var AArrayList: TArrayList; I: Integer; begin try Writeln(' Hello! Welcome to dotNetCore4Delphi '); Writeln('=================================================='); Writeln(' This program prints out ArrayList values. '); Writeln(''); AArrayList := TArrayList.Create(); AArrayList.Add('Hello'); AArrayList.Add('World'); AArrayList.Add('!'); Writeln('Array List'); Writeln(' Count: ' + IntToStr(AArrayList.Count)); Writeln(' Capacity: ' + IntToStr(AArrayList.Capacity)); Write(' Values:'); Writeln(''); for I := 0 to AArrayList.Count - 1 do Writeln(Chr(9) + ' ' + AArrayList[I]); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to write a simple Hello World using .Net Core Console

Exported from Notepad++
program ConsoleApp; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND} CrystalNet.Console; begin try TConsole.NClass.WriteLine('Hello! Welcome to .Net Core for Delphi.'); TConsole.NClass.WriteLine('======================================'); TConsole.NClass.WriteLine('The program displays the string Hello World!'); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine('Hello World!'); TConsole.NClass.WriteLine('Press any key to exit.'); TConsole.NClass.ReadKey; except on E: Exception do Writeln(E.Message); end; end.

How to Load .Net Core Assemblies and Create .Net Core Objects

Exported from Notepad++
program CoreBridgeExample; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND} CNCoreClrLib.BridgeMgr, CrystalNet.Runtime.Intf,CNCoreClrLib.AssemblyMgr, CrystalNet.Console, CNCoreClrLib.RttiMgr; (* .Net Core Mathematics.Dll source code namespace Mathematics { public class Mathematics { public int Add(int a, int b) { return a + b; } public int Subtract(int a, int b) { return a - b; } public bool Equal(int a, int b) { return a == b; } public static int Multiply(int a, int b) { return a * b; } } } *) type //Import Mathematics.dll with dotNetCore4Delphi Import utility //This is the interface and class generated by the import utility IMathematicsClass = interface(ICoreClrClass) ['{22DBBA95-18C3-4AC7-8326-328E37544F33}'] { public } { class } function Multiply(a: Integer; b: Integer): Integer; end; [CoreTypeSignature('Mathematics.Mathematics')] IMathematics = interface(IObject) ['{32A9F9E0-5A9E-41FE-916C-09599EDAD4BD}'] { public } function Add(a: Integer; b: Integer): Integer; function Equal(a: Integer; b: Integer): Boolean; function Subtract(a: Integer; b: Integer): Integer; end; TMathematics = class(TCoreClrGenericImport<IMathematicsClass, IMathematics>) public class function Create: IMathematics; end; { TMathematics } class function TMathematics.Create: IMathematics; begin Result := inherited Create([]); end; var Mathematics : IMathematics; procedure LoadMathematicAssembly; begin // If error occurs while executing LoadFrom then // Right-Click on the file and select properties, click on the // unblock button to allow access. TCoreClrAssembly.LoadFrom('Mathematics.dll'); end; procedure CreateMathematicInstance; begin Mathematics := TMathematics.Create; end; procedure AccessMathematicsObjectMethods; begin TConsole.NClass.WriteLine('Add(30, 50): {0}', Mathematics.Add(30, 50)); TConsole.NClass.WriteLine('Subtract(30, 50): {0}', Mathematics.Subtract(30, 50)); TConsole.NClass.WriteLine('Equal(30, 50): {0}', Mathematics.Equal(30, 50)); TConsole.NClass.WriteLine('Equal(50, 50): {0}', Mathematics.Equal(50, 50)); TConsole.NClass.WriteLine('Multiply(50, 50): {0}', TMathematics.NClass.Multiply(50, 50)); //Static call end; begin TConsole.NClass.WriteLine('Hello! Welcome to .Net Core for Delphi.'); TConsole.NClass.WriteLine('======================================'); TConsole.NClass.WriteLine('This program demonstrate how to use the Core Bridge to communicate with .Net library type members'); TConsole.NClass.WriteLine; try LoadMathematicAssembly; CreateMathematicInstance; AccessMathematicsObjectMethods; except on E: Exception do TConsole.NClass.WriteLine('Exception: {0}', e.Message); end; TConsole.NClass.ReadKey; end.

How to use basic .Net core classes in Delphi

Exported from Notepad++
program BasicExample; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND} CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console, CrystalNet.Runtime.Enums,CrystalNet.IO.FileSystem,CrystalNet.IO.FileSystem.Intf; procedure MathClass; begin TConsole.NClass.WriteLine('Using Math Class Methods/Properties..'); TConsole.NClass.WriteLine('Exp(50): {0}', TMath.NClass.Exp(50)); TConsole.NClass.WriteLine('PI: {0}', TMath.NClass.PI); TConsole.NClass.WriteLine('Cos(50): {0}', TMath.NClass.Cos(50)); TConsole.NClass.WriteLine('Log(50): {0}', TMath.NClass.Log(50)); TConsole.NClass.WriteLine('Pow(50, 3): {0}', TMath.NClass.Pow(50, 3)); TConsole.NClass.WriteLine('Round(234.094833, 2): {0}', TMath.NClass.Round(234.094833, 2)); TConsole.NClass.WriteLine('Truncate(234.094833): {0}', TMath.NClass.Truncate(234.094833)); TConsole.NClass.WriteLine('Sqrt(16): {0}', TMath.NClass.Sqrt(16)); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine; end; procedure RandomClass; var m_random: IRandom; begin m_random := TRandom.Create; TConsole.NClass.WriteLine('Using Random Class Methods/Properties..'); TConsole.NClass.WriteLine('Next Value: {0}', m_random.Next); TConsole.NClass.WriteLine('NextDouble: {0}', m_random.NextDouble); TConsole.NClass.WriteLine('Next(2000): {0}', m_random.Next(2000)); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine; end; procedure GuidClass; begin TConsole.NClass.WriteLine('Using Guid Class Methods/Properties..'); TConsole.NClass.WriteLine('Empty Guid: {0}', TGuid.NClass.Empty.ToString); TConsole.NClass.WriteLine('NewGuid: {0}', TGuid.NClass.NewGuid.ToString); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine; end; procedure EnvironmentClass; begin TConsole.NClass.WriteLine('Using Environment Class Methods/Properties..'); TConsole.NClass.WriteLine('CommandLine: {0}', TEnvironment.NClass.CommandLine); TConsole.NClass.WriteLine('CurrentDirectory: {0}', TEnvironment.NClass.CurrentDirectory); TConsole.NClass.WriteLine('ExitCode: {0}', TEnvironment.NClass.ExitCode); TConsole.NClass.WriteLine('Is64BitOperatingSystem: {0}', TEnvironment.NClass.Is64BitOperatingSystem); TConsole.NClass.WriteLine('Is64BitProcess: {0}', TEnvironment.NClass.Is64BitProcess); TConsole.NClass.WriteLine('MachineName: {0}', TEnvironment.NClass.MachineName); TConsole.NClass.WriteLine('OSVersion: {0}', TEnvironment.NClass.OSVersion); TConsole.NClass.WriteLine('ProcessorCount: {0}', TEnvironment.NClass.ProcessorCount); TConsole.NClass.WriteLine('StackTrace: {0}', TEnvironment.NClass.StackTrace); TConsole.NClass.WriteLine('SystemDirectory: {0}', TEnvironment.NClass.SystemDirectory); TConsole.NClass.WriteLine('SystemPageSize: {0}', TEnvironment.NClass.SystemPageSize); TConsole.NClass.WriteLine('UserName: {0}', TEnvironment.NClass.UserName); TConsole.NClass.WriteLine('GetFolderPath: {0}', TEnvironment.NClass.GetFolderPath(TSpecialFolder.sfMyDocuments)); TConsole.NClass.WriteLine('WorkingSet: {0}', TEnvironment.NClass.WorkingSet); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine; end; procedure FileInfoClass; var m_fileInfo : IFileInfo; begin m_fileInfo := TFileInfo.Create('sqlnet.log'); TConsole.NClass.WriteLine('Using FileInfo Class Methods/Properties..'); TConsole.NClass.WriteLine('Name: {0}', m_fileInfo.Name); TConsole.NClass.WriteLine('DirectoryName: {0}', m_fileInfo.DirectoryName); TConsole.NClass.WriteLine('IsReadOnly: {0}', m_fileInfo.IsReadOnly); TConsole.NClass.WriteLine('Exists: {0}', m_fileInfo.Exists); TConsole.NClass.WriteLine('FullName: {0}', m_fileInfo.FullName); TConsole.NClass.WriteLine('Extension: {0}', m_fileInfo.Extension); TConsole.NClass.WriteLine('CreationTime: {0}', m_fileInfo.CreationTime); TConsole.NClass.WriteLine('CreationTimeUtc: {0}', m_fileInfo.CreationTimeUtc); TConsole.NClass.WriteLine('LastAccessTime: {0}', m_fileInfo.LastAccessTime); TConsole.NClass.WriteLine('LastAccessTimeUtc: {0}', m_fileInfo.LastAccessTimeUtc); TConsole.NClass.WriteLine('LastWriteTime: {0}', m_fileInfo.LastWriteTime); TConsole.NClass.WriteLine('LastWriteTimeUtc: {0}', m_fileInfo.LastWriteTimeUtc); TConsole.NClass.WriteLine('Length: {0}', m_fileInfo.Length); TConsole.NClass.WriteLine('ReadLine: {0}', m_fileInfo.OpenText.ReadToEnd); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine; end; begin TConsole.NClass.WriteLine('Hello! Welcome to .Net Core for Delphi.'); TConsole.NClass.WriteLine('======================================='); TConsole.NClass.WriteLine('This program demonstrate how to use basic .Net core classes in Delphi'); TConsole.NClass.WriteLine; try MathClass; RandomClass; GuidClass; EnvironmentClass; FileInfoClass; except on E: Exception do TConsole.NClass.WriteLine('Exception: {0}', e.Message); end; TConsole.NClass.ReadKey; end.

How to Create .Net Core Arrays

Exported from Notepad++
program ArrayExample; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND} CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console; procedure PrintArrayByTypeName; var x : Integer; oArray : IArray; begin TConsole.NClass.WriteLine; oArray := TArray.NClass.CreateInstance(TType.NCLass.GetType('System.Double'), 6); oArray.SetValue(900, 0); oArray.SetValue(800, 1); oArray.SetValue(700, 2); oArray.SetValue(600, 3); oArray.SetValue(500, 4); oArray.SetValue(400, 5); TConsole.NClass.WriteLine('Double Array'); TConsole.NClass.WriteLine(' Count: {0}', oArray.Length); TConsole.NClass.WriteLine(' Rank: {0}', oArray.Rank); TConsole.NClass.WriteLine(' Values:'); for x := 0 to oArray.Length - 1 do begin TConsole.NClass.WriteLine(Chr(9)+' {0}', oArray.GetValue(x)); end; end; procedure PrintArrayByType; var x : Integer; oArray : IArray; oType : IType; begin TConsole.NClass.WriteLine; oType := TType.NCLass.GetType('System.Double'); oArray := TArray.NClass.CreateInstance(oType, 6); oArray.SetValue(900, 0); oArray.SetValue(800, 1); oArray.SetValue(700, 2); oArray.SetValue(600, 3); oArray.SetValue(500, 4); oArray.SetValue(400, 5); TConsole.NClass.WriteLine('Double Array'); TConsole.NClass.WriteLine(' Count: {0}', oArray.Length); TConsole.NClass.WriteLine(' Rank: {0}', oArray.Rank); TConsole.NClass.WriteLine(' Values:'); for x := 0 to oArray.Length - 1 do begin TConsole.NClass.WriteLine(Chr(9)+' {0}', oArray.GetValue(x)); end; end; procedure PrintArrayByObjectType; var x : Integer; oArray : IArray; begin TConsole.NClass.WriteLine; oArray := TArray.NClass.CreateInstance(TType.NCLass.GetType('System.Object'), 6); oArray.SetValue(900, 0); oArray.SetValue(800, 1); oArray.SetValue(700, 2); oArray.SetValue(600, 3); oArray.SetValue(500, 4); oArray.SetValue(400, 5); TConsole.NClass.WriteLine('Object Array'); TConsole.NClass.WriteLine(' Count: {0}', oArray.Length); TConsole.NClass.WriteLine(' Rank: {0}', oArray.Rank); TConsole.NClass.WriteLine(' Values:'); for x := 0 to oArray.Length - 1 do begin TConsole.NClass.WriteLine(Chr(9)+' {0}', oArray.GetValue(x)); end; end; begin TConsole.NClass.WriteLine('Hello! Welcome to .Net Core for Delphi.'); TConsole.NClass.WriteLine('======================================'); TConsole.NClass.WriteLine('This program prints out Array values.'); TConsole.NClass.WriteLine; PrintArrayByTypeName; PrintArrayByType; PrintArrayByObjectType; TConsole.NClass.ReadKey; end.

How to Create and use .Net Core ArrayList

Exported from Notepad++
program ArrayList; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND} CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console; var AArrayList : IArrayList; I : Integer; begin AArrayList := TArrayList.Create; AArrayList.Add('Hello'); AArrayList.Add('World'); AArrayList.Add('!'); TConsole.NClass.WriteLine('Hello! Welcome to .Net Core for Delphi.'); TConsole.NClass.WriteLine('======================================='); TConsole.NClass.WriteLine('This program prints out ArrayList values.'); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine('Array List'); TConsole.NClass.WriteLine(' Count: {0}', AArrayList.Count); TConsole.NClass.WriteLine(' Capacity: {0}', AArrayList.Capacity); TConsole.NClass.Write(' Values:'); TConsole.NClass.WriteLine; for I := 0 to AArrayList.Count - 1 do begin TConsole.NClass.WriteLine(chr(9) + ' {0}', AArrayList.Item[I]); end; TConsole.NClass.ReadKey; end.

How to use .Net Core Collections in Delphi

Exported from Notepad++
program Collections; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND } CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console, CrystalNet.Collections.Intf, CrystalNet.Collections, CrystalNet.Collections.Specialized, CrystalNet.Collections.Specialized.Intf, CrystalNet.Collections.NonGeneric, CrystalNet.Collections.NonGeneric.Intf; var NamesArray : TArray<String>; NamesEnumerator: IIEnumerator; ArrayList: IArrayList; StringList: IStringCollection; StringDictionary: IStringDictionary; StringDictValuesEnumerator: IIEnumerator; SortedListValuesEnumerator: IIEnumerator; HashTableKeysEnumerator: IIEnumerator; AEnumerator: IIEnumerator; Stack: IStack; Queue: IQueue; BitArray: IBitArray; HashTable: IHashtable; SortedList: ISortedList; I, P: Integer; begin try //======================================================================== // Using IArrayList Interface //======================================================================== //The ArrayList interface is a dynamic array of heterogeneous objects. Note that in an array //we can store only objects of the same type. In an ArrayList, however, we can have different //type of objects; these in turn would be stored as object type only. We can have an ArrayList //object that stores integer, float, string, etc., but all these objects would only be stored as //object type. An ArrayList uses its indexes to refer to a particular object stored in its collection. //The Count property gives the total number of items stored in the ArrayList object. //The Capacity property gets or sets the number of items that the ArrayList object can contain. //Objects are added using the Add method of the ArrayList and removed using its Remove method. //An example of usage of an ArrayList is given below. ArrayList := TArrayList.Create; ArrayList.Add('Joydip'); ArrayList.Add(100); ArrayList.Add(20.5); for I := 0 to ArrayList.Count - 1 do TConsole.NClass.WriteLine(ArrayList[I]); //It is to be noted here that the initial capacity of an ArrayList is 16, which is increased once the //17th item is stored onto it. This repeated memory allocation and copying of the items can be quite //expensive in some situations. For performance reasons we can set the initial capacity of the object //of an ArrayList by using the Capacity property or an overloaded constructor of the ArrayList class. //This is shown in the example below. ArrayList := TArrayList.Create; ArrayList.Capacity := 3; ArrayList.Add('Joydip'); ArrayList.Add(100); ArrayList.Add(20.5); for I := 0 to ArrayList.Count - 1 do TConsole.NClass.WriteLine(ArrayList[I]); //======================================================================== // Using StringCollection Interface //======================================================================== //The StringCollection interface implements the IList interface and is like an ArrayList of strings. //The following code example shows how we can work with a StringCollection class. StringList := TStringCollection.Create; StringList.Add('Manashi'); StringList.Add('Joydip'); StringList.Add('Jini'); StringList.Add('Piku'); for I := 0 to StringList.Count - 1 do TConsole.NClass.WriteLine(StringList[I]); //======================================================================== // Using StringDictionary Interface //======================================================================== //Similar to the StringCollection interface we have the StringDictionary interface, //which is just a Hashtable that has its keys as strings only. Remember that a Hashtable //can contain any object type in its key. The following code shows how we can work with a //StringDictionary interface. StringDictionary := TStringDictionary.Create; StringDictionary.Add('A', 'Manashi'); StringDictionary.Add('B','Joydip'); StringDictionary.Add('C','Jini'); StringDictionary.Add('D','Piku'); StringDictValuesEnumerator := TIEnumerable.Wrap(StringDictionary.Values).GetEnumerator; while StringDictValuesEnumerator.MoveNext do TConsole.NClass.WriteLine(StringDictValuesEnumerator.Current); //======================================================================== // Using Stack Interface //======================================================================== //The Stack interface is one that provides a Last-in-First-out (LIFO) collection of items //of the System.Object type. The last added item is always at the top of the Stack and is also //the first one to be removed. The following code sample shows how we can use a Stack class for //LIFO operation on its collection of items. Stack := TStack.Create; Stack.Push('Joydip'); Stack.Push('Steve'); Stack.Push('Jini'); while (Stack.Count > 0) do TConsole.NClass.WriteLine(Stack.Pop); //The Push method is responsible for storing items in the Stack and the method Pop //removes them one at a time from the top of the Stack. //======================================================================== // Using Queue Interface //======================================================================== //Unlike the Stack interface, the Queue is a data structure that provides a First-in-First-out //collection of items of the Object type. The newly added items are stored at the end or //the rear of the Queue and items are deleted from the front of the Queue. //The following code shows how the Queue class can be used. Queue := TQueue.Create; Queue.Enqueue('Joydip'); Queue.Enqueue('Steve'); Queue.Enqueue('Jini'); while (Queue.Count > 0) do TConsole.NClass.WriteLine(Queue.Dequeue); //The Enqueue method is responsible for storing items at the rear of the Queue and the method Dequeue //removes them one at a time from the front of the Queue. //======================================================================== // Using BitArray Interface //======================================================================== //The BitArray interface can be used to store bits in an array. They can be set to true or false, //depending on the parameter supplied at the time of creating the BitArray object. //The following is an example of its usage. BitArray := TBitArray.Create(5, false); // Or BitArray := TBitArray.Create(5, true); // Similar to the other collections discussed above, the BitArray interface also contains the //Count property to get the number of items stored in this collection of bit values. //The following methods of the BitArray class allow logical bit operation. // � And // � Or // � Not // � Xor //======================================================================== // Using Hashtable Interface //======================================================================== //The Hashtable provides a faster way of storage and retrieval of items of the object type. //The Hashtable class provides support for key based searching. These keys are unique hash codes that //are unique to a specific type. The GetHashCode method of the Hashtable class returns the hash code //for an object instance. The following code snippet shows how we can use a Hashtable interface. HashTable := THashtable.Create; HashTable.Add(1, 'Joydip'); HashTable.Add(2, 'Manashi'); HashTable.Add(3, 'Jini'); HashTable.Add(4, 'Piku'); TConsole.NClass.WriteLine('The keys are:--'); HashTableKeysEnumerator := TIEnumerable.Wrap(HashTable.Keys).GetEnumerator; while HashTableKeysEnumerator.MoveNext do TConsole.NClass.WriteLine(HashTableKeysEnumerator.Current); try TConsole.NClass.WriteLine('Please enter the key to search'); p := TInt32.NClass.Parse(TConsole.NClass.ReadLine); TConsole.NClass.WriteLine(HashTable[p]); except on E: Exception do TConsole.NClass.WriteLine(E.Message); end; //To remove an item from the Hashtable interface, the Remove method is used. //The statement HashTable.Remove(3) would remove the item "Jini" from the Hashtable //object created in the above code. The code shown above can also be written as shown below //to display the contents of the Hashtable object using IDictionaryEnumerator. HashTable := THashtable.Create; HashTable.Add(1, 'Joydip'); HashTable.Add(2, 'Manashi'); HashTable.Add(3, 'Jini'); HashTable.Add(4, 'Piku'); TConsole.NClass.WriteLine('The keysare:--'); AEnumerator := TIEnumerable.Wrap(HashTable.Keys).GetEnumerator; while AEnumerator.MoveNext do TConsole.NClass.WriteLine(HashTable[p]); //======================================================================== // Using SortedList Interface //======================================================================== //The SortedList interface allows items of the Object type to be placed in the //collection using key value pairs and, at the same time, supports sorting. //The following code shows how we can use a SortedList. SortedList := TSortedList.Create; SortedList.Add(1, 'Manashi'); SortedList.Add(3, 'Joydip'); SortedList.Add(2, 'Jini'); SortedList.Add(4, 'Piku'); TConsole.NClass.WriteLine('Displaying thenames'); SortedListValuesEnumerator:= TIEnumerable.Wrap(SortedList.Values).GetEnumerator; while SortedListValuesEnumerator.MoveNext do TConsole.NClass.WriteLine(SortedListValuesEnumerator.Current); //The output of the above code is: // Manashi // Jini // Joydip // Piku //The same code can be written using IDictionaryEnumerator to display all the items of the //SortedList object, as shown below. SortedList := TSortedList.Create; SortedList.Add(1, 'Manashi'); SortedList.Add(3, 'Joydip'); SortedList.Add(2, 'Jini'); SortedList.Add(4, 'Piku'); TConsole.NClass.WriteLine('Displaying thenames'); AEnumerator := TIEnumerable.Wrap(SortedList.Values).GetEnumerator; while AEnumerator.MoveNext do TConsole.NClass.WriteLine(AEnumerator.Current); TConsole.NClass.ReadKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to use .Net Core Generic List in Delphi

Exported from Notepad++
program GenericList; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND } CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console; var Dinosaurs: IList<string>; I: Integer; begin try Dinosaurs := TList<string>.Create(); TConsole.NClass.WriteLine('Capacity: {0}', Dinosaurs.Capacity); Dinosaurs.Add('Tyrannosaurus'); Dinosaurs.Add('Amargasaurus'); Dinosaurs.Add('Mamenchisaurus'); Dinosaurs.Add('Deinonychus'); Dinosaurs.Add('Compsognathus'); TConsole.NClass.WriteLine(); for I := 0 to Dinosaurs.Count - 1 do TConsole.NClass.WriteLine(Dinosaurs[I]); TConsole.NClass.WriteLine('Capacity: {0}', Dinosaurs.Capacity); TConsole.NClass.WriteLine('Count: {0}', Dinosaurs.Count); TConsole.NClass.WriteLine('Contains(''Deinonychus''): {0}', Dinosaurs.Contains('Deinonychus')); TConsole.NClass.WriteLine('Insert(2, ''Compsognathus'')'); Dinosaurs.Insert(2, 'Compsognathus'); TConsole.NClass.WriteLine(); for I := 0 to Dinosaurs.Count - 1 do TConsole.NClass.WriteLine(Dinosaurs[I]); // Shows accessing the list using the Item property. TConsole.NClass.WriteLine('dinosaurs[3]: {0}', Dinosaurs[3]); TConsole.NClass.WriteLine('Remove(''Compsognathus'')'); Dinosaurs.Remove('Compsognathus'); TConsole.NClass.WriteLine(); for I := 0 to Dinosaurs.Count - 1 do TConsole.NClass.WriteLine(Dinosaurs[I]); Dinosaurs.TrimExcess(); TConsole.NClass.WriteLine('TrimExcess()'); TConsole.NClass.WriteLine('Capacity: {0}', Dinosaurs.Capacity); TConsole.NClass.WriteLine('Count: {0}', Dinosaurs.Count); Dinosaurs.Clear(); TConsole.NClass.WriteLine('Clear()'); TConsole.NClass.WriteLine('Capacity: {0}', Dinosaurs.Capacity); TConsole.NClass.WriteLine('Count: {0}', Dinosaurs.Count); TConsole.NClass.ReadKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to use .Net Core Dictionary in Delphi

Exported from Notepad++
program GenericDictionary; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND } CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console; var OpenWith: IDictionary<string,string>; OpenWithEnumerator: IDictionary_Enumerator<string,string>; ValueCollection: IDictionary_ValueCollection<string,string>; ValueCollEnumerator: IValueCollection_Enumerator<string,string>; keyCollection: IDictionary_KeyCollection<string,string>; keyCollEnumerator: IKeyCollection_Enumerator<string,string>; Value: string; begin try // Create a new dictionary of strings, with string keys. OpenWith := TDictionary<string,string>.Create(); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. OpenWith.Add('txt', 'notepad.exe'); OpenWith.Add('bmp', 'paint.exe'); OpenWith.Add('dib', 'paint.exe'); OpenWith.Add('rtf', 'wordpad.exe'); // The Add method throws an exception if the new key is // already in the dictionary. try OpenWith.Add('txt', 'winword.exe'); except //(ArgumentException) TConsole.NClass.WriteLine('An element with Key = ''txt'' already exists.'); end; // The Item property is another name for the indexer, so you // can omit its name when accessing elements. TConsole.NClass.WriteLine('For key = ''rtf'', value = {0}.', OpenWith['rtf']); // The indexer can be used to change the value associated // with a key. OpenWith['rtf'] := 'winword.exe'; TConsole.NClass.WriteLine('For key = ''rtf'', value = {0}.', OpenWith['rtf']); // If a key does not exist, setting the indexer for that key // adds a new key/value pair. OpenWith['doc'] := 'winword.exe'; // The indexer throws an exception if the requested key is // not in the dictionary. try TConsole.NClass.WriteLine('For key = ''tif'', value = {0}.', OpenWith['tif']); except //(KeyNotFoundException) TConsole.NClass.WriteLine('Key = ''tif'' is not found.'); end; // When a program often has to try keys that turn out not to // be in the dictionary, TryGetValue can be a more efficient // way to retrieve values. if (OpenWith.TryGetValue('tif', Value)) then TConsole.NClass.WriteLine('For key = ''tif'', value = {0}.', Value) else TConsole.NClass.WriteLine('Key = ''tif'' is not found.'); // ContainsKey can be used to test keys before inserting them. if (not OpenWith.ContainsKey('ht')) then begin OpenWith.Add('ht', 'hypertrm.exe'); TConsole.NClass.WriteLine('Value added for key = ''ht'': {0}', OpenWith['ht']); end; // When you use when loop to enumerate dictionary elements from GetEnumerator, // the elements are retrieved as KeyValuePair objects. TConsole.NClass.WriteLine(); OpenWithEnumerator := OpenWith.GetEnumerator; while OpenWithEnumerator.MoveNext do TConsole.NClass.WriteLine('Key = {0}, Value = {1}', OpenWithEnumerator.Current.Key, OpenWithEnumerator.Current.Value); // To get the values alone, use the Values property. ValueCollection := OpenWith.Values; ValueCollEnumerator := ValueCollection.GetEnumerator; // The elements of the ValueCollection are strongly typed // with the type that was specified for dictionary values. TConsole.NClass.WriteLine(); while ValueCollEnumerator.MoveNext do TConsole.NClass.WriteLine('Value = {0}', ValueCollEnumerator.Current); // To get the keys alone, use the Keys property. keyCollection := OpenWith.Keys; keyCollEnumerator := keyCollection.GetEnumerator; // The elements of the KeyCollection are strongly typed // with the type that was specified for dictionary keys. TConsole.NClass.WriteLine(); while keyCollEnumerator.MoveNext do TConsole.NClass.WriteLine('Key = {0}', keyCollEnumerator.Current); // Use the Remove method to remove a key/value pair. TConsole.NClass.WriteLine('Remove(''doc'')'); OpenWith.Remove('doc'); if (not OpenWith.ContainsKey('doc')) then TConsole.NClass.WriteLine('Key ''doc'' is not found.'); TConsole.NClass.ReadKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.

How to Create and use .Net Core StringBuilder in Delphi

Exported from Notepad++
program StringBuilder; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND } CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Console; var AStringBuilder : IStringBuilder; begin AStringBuilder := TStringBuilder.Create; AStringBuilder.Append('Hello'); AStringBuilder.Append('World'); AStringBuilder.Append('!'); TConsole.NClass.WriteLine('Hello! Welcome to .Net Core for Delphi.'); TConsole.NClass.WriteLine('======================================='); TConsole.NClass.WriteLine('This program prints out StringBuilder values.'); TConsole.NClass.WriteLine; TConsole.NClass.WriteLine('AStringBuilder'); TConsole.NClass.WriteLine(' Count: {0}', AStringBuilder.Length); TConsole.NClass.WriteLine(' Capacity: {0}', AStringBuilder.Capacity); TConsole.NClass.WriteLine(' Values: {0}', AStringBuilder.ToString(0, AStringBuilder.Length - 1)); TConsole.NClass.ReadKey; end.

How to encrypt and decrypt sample data using the .Net Core RijndaelManaged

Exported from Notepad++
program RijndaelSecurity; {$APPTYPE CONSOLE} {$R *.res} uses {$IF CompilerVersion > 22} System.SysUtils, {$ELSE} SysUtils, {$IFEND } CrystalNet.Security.Cryptography.Algorithms, CrystalNet.Security.Cryptography.Algorithms.Intf, CrystalNet.Security.Cryptography.Primitives.Intf, CrystalNet.Security.Cryptography.Primitives, CrystalNet.Runtime.Intf, CrystalNet.Runtime, CrystalNet.Security.Cryptography.Primitives.Enums; function EncryptStringToBytes(plainText: string; Key, IV: TArray<Byte>): TArray<Byte>; var rijAlg: IRijndaelManaged; encryptor: IICryptoTransform; msEncrypt: IMemoryStream; csEncrypt: ICryptoStream; swEncrypt: IStreamWriter; begin // Check arguments. if plainText.Length <= 0 then raise Exception.Create('plainText argument is empty'); if (Key = nil) or (Length(Key) <= 0) then raise Exception.Create('Key argument is empty or nil'); if (IV = nil) or (Length(IV) <= 0) then raise Exception.Create('IV argument is empty or nil'); // Create an RijndaelManaged object with the specified key and IV. rijAlg := TRijndaelManaged.Create; rijAlg.Key := Key; rijAlg.IV := IV; // Create a decrytor to perform the stream transform. encryptor := rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for encryption. msEncrypt := TMemoryStream.Create; csEncrypt := TCryptoStream.Create(msEncrypt, encryptor, TCryptoStreamMode.csmWrite); swEncrypt := TStreamWriter.Create(csEncrypt); //Write all data to the stream. swEncrypt.Write(plainText); swEncrypt.Close; // Return the encrypted bytes from the memory stream. result := msEncrypt.ToArray; msEncrypt.Close; csEncrypt.Close; swEncrypt.Close; end; function DecryptStringFromBytes(cipherText, Key, IV: TArray<Byte>): string; var rijAlg: IRijndaelManaged; decryptor: IICryptoTransform; msDecrypt: IMemoryStream; csDecrypt: ICryptoStream; srDecrypt: IStreamReader; begin // Check arguments. if (cipherText = nil) or (Length(cipherText) <= 0) then raise Exception.Create('cipherText argument is empty or nil'); if (Key = nil) or (Length(Key) <= 0) then raise Exception.Create('Key argument is empty or nil'); if (IV = nil) or (Length(IV) <= 0) then raise Exception.Create('IV argument is empty or nil'); // Create an RijndaelManaged object // with the specified key and IV. rijAlg := TRijndaelManaged.Create; rijAlg.Key := Key; rijAlg.IV := IV; // Create a decrytor to perform the stream transform. decryptor := rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for decryption. msDecrypt := TMemoryStream.Create(cipherText); csDecrypt := TCryptoStream.Create(msDecrypt, decryptor, csmRead); srDecrypt := TStreamReader.Create(csDecrypt); // Read the decrypted bytes from the decrypting stream and place them in a string. result := srDecrypt.ReadToEnd; msDecrypt.Close; csDecrypt.Close; srDecrypt.Close; end; var key: Char; original, roundtrip: string; myRijndael: IRijndaelManaged; encrypted: TArray<Byte>; begin try original := 'Here is some data to encrypt!'; // Create a new instance of the RijndaelManaged // class. This generates a new key and initialization // vector (IV). myRijndael := TRijndaelManaged.Create; myRijndael.GenerateKey; myRijndael.GenerateIV; // Encrypt the string to an array of bytes. encrypted := EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV); // Decrypt the bytes to a string. roundtrip := DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV); //Display the original data and the decrypted data. Writeln('Original: ', original); Writeln('Round Trip: ', roundtrip); Writeln('Press any key to continue.....'); Readln(key); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.