RingDotNetfor Ring

The .NET class library

A tour of the base class library as seen from Ring — dates, text, files, regex, compression, networking, cryptography, XML, JSON, data tables, reflection and big numbers. Every program on this page is a real sample and the output is real.

What is wrapped#

Every namespace below has generated classes, loaded on demand with using { "Name" }.

AreaNamespaces
CoreSystem, System.Globalization, System.Numerics, System.Reflection, System.Runtime.InteropServices, System.Runtime.Loader, System.ComponentModel, System.Resources
TextSystem.Text, System.Text.RegularExpressions, System.Text.Json, System.Text.Json.Nodes, System.Text.Encodings.Web, System.Text.Unicode
Files and streamsSystem.IO, System.IO.Compression, System.IO.Pipes, System.IO.MemoryMappedFiles, System.Formats.Tar
CollectionsSystem.Collections, .Generic, .Specialized, .Concurrent, .ObjectModel
NetworkingSystem.Net, .Http, .Http.Json, .Http.Headers, .Sockets, .NetworkInformation, .Mail, .WebSockets, .Security, .Mime
SecuritySystem.Security.Cryptography, .X509Certificates, System.Security.Claims, System.Security.Principal
XML and dataSystem.Xml, .Linq, .XPath, .Schema, .Serialization, .Xsl, System.Data, .Common, .SqlTypes, System.Runtime.Serialization, System.ComponentModel.DataAnnotations
Expressions and transactionsSystem.Linq.Expressions (the expression class is ExpressionsExpression), System.Transactions
Processes and threadsSystem.Diagnostics, System.Threading, System.Threading.Tasks, System.Timers
GraphicsSystem.Drawing, .Drawing2D, .Imaging, .Text, .Printing
UISystem.Windows.Forms, WPF — see Windows Forms and WPF
Web and dataASP.NET Core, Entity Framework Core — see ASP.NET Core and Entity Framework

Other namespaces and any DLL: Your own assemblies.

Note

tools/dotnettools/auditcoverage.ring compares the public types of the installed .NET framework with the generated classes. Enums need no class (they are texts), delegates are callbacks (a delegate type has a class only when extension methods extend it), ref structs cannot be objects and obsolete types are left out on purpose. Every other public type of the namespaces of the manifest has a class: the tool lists any that does not, so you can see what is not wrapped yet.

Dates, strings, conversions, math#

DateTime, TimeSpan, Convert, Math, String helpers, Guid, Random, Environment:

samples/UsingDotNet/introduction/test08_system.ring
samples/UsingDotNet/introduction/test08_system.ring
# Dates and times, strings, conversions and math from the .NET class library
load "dotnet.ring"

using { "System" }

# Dates and times
oNow = new DateTime(2024,12,25).AddHours(18.5)
? "Christmas 2024 : " + oNow.Format("dddd, dd MMMM yyyy HH:mm")
? "Plus 10 days   : " + oNow.AddDays(10).Format("yyyy-MM-dd")
? "Day of week    : " + oNow.DayOfWeek
oSpan = new TimeSpan().FromMinutes(135)
? "135 minutes    : " + oSpan.ToString() + " (" + oSpan.TotalHours + " hours)"

# Strings, conversions, math
oStr = new String()
? oStr.Join([ :separator = " | ", :value = ["Ring","loves",".NET"] ])
? "Base64         : " + new Convert().ToBase64String("Hello Ring")
? "Hex of 255     : " + new Convert().Format([ :value = 255, :toBase = 16 ])
? "2 ^ 20         : " + new Math().Pow(2,20)

# Uri, Guid, Version, Environment
oUri = new Uri("https://ring-lang.github.io:8443/docs/index.html?lang=en")
? "Host / Port    : " + oUri.Host + " / " + oUri.Port
? "Path / Query   : " + oUri.AbsolutePath + " / " + oUri.Query
? "Guid length    : " + len(new Guid().NewGuid().ToString())
? "Version        : " + new Version("1.28.3").Minor
? "Processors > 0 : " + (new Environment().ProcessorCount > 0)

# out parameters return a list
aParsed = new Int32().TryParse("123")
? "TryParse       : " + aParsed[1] + " -> " + aParsed[2]
aParsed = new Int32().TryParse("12x")
? "TryParse bad   : " + aParsed[1]
Output
Christmas 2024 : Wednesday, 25 December 2024 18:30
Plus 10 days   : 2025-01-04
Day of week    : Wednesday
135 minutes    : 02:15:00 (2.25 hours)
Ring | loves | .NET
Base64         : SGVsbG8gUmluZw==
Hex of 255     : ff
2 ^ 20         : 1048576
Host / Port    : ring-lang.github.io / 8443
Path / Query   : /docs/index.html / ?lang=en
Guid length    : 36
Version        : 28
Processors > 0 : 1
TryParse       : 1 -> 123
TryParse bad   : 0

Files, regular expressions and compression#

File, Directory, Path, StreamReader/StreamWriter, MemoryStream, Regex, GZipStream:

samples/UsingDotNet/introduction/test09_io_regex.ring
samples/UsingDotNet/introduction/test09_io_regex.ring
# Text files, compression and regular expressions
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.IO.Compression"
	"System.Text.RegularExpressions"
}

oPath = new Path()
oFile = new File()
cDir = oPath.Combine([oPath.GetTempPath(),"ringdotnet_demo"])
new Directory().CreateDirectory(cDir)

# Text files
cLog = oPath.Combine([cDir,"log.txt"])
oWriter = new StreamWriter(cLog)
oWriter.WriteLine("2024-05-17 ERROR disk full")
oWriter.WriteLine("2024-05-18 INFO backup done")
oWriter.WriteLine("2024-06-01 ERROR network down")
oWriter.Close()
? "Lines in file : " + len(oFile.ReadAllLines(cLog).toList())
? "File size     : " + new FileInfo(cLog).Length + " bytes"

# Regular expressions: find the errors and their month
oRegex = new Regex("(?<month>\d{4}-\d{2})-\d{2} ERROR (?<what>.+)")
oMatches = oRegex.Matches(oFile.ReadAllText(cLog))
? "Errors found  : " + oMatches.Count
for nLoop = 0 to oMatches.Count - 1
	oMatch = oMatches.Item(nLoop)
	? "  " + oMatch.Groups.Item("month").Value + " -> " + trim(oMatch.Groups.Item("what").Value)
next
? "Cleaned       : " + new Regex("\s+").Replace([ :input = "too    many   spaces", :replacement = " " ])

# Compression
oPacked = new MemoryStream()
oGzip = new GZipStream(oPacked,"Compress")
cData = copy("Ring and .NET ",200)
oGzip.Write(cData,0,len(cData))
oGzip.Close()
? "GZip          : " + len(cData) + " -> " + len(oPacked.ToArray()) + " bytes"

cZip = oPath.Combine([oPath.GetTempPath(),"ringdotnet_demo.zip"])
if oFile.Exists(cZip) oFile.Delete(cZip) ok
new ZipFile().CreateFromDirectory([ :sourceDirectoryName = cDir, :destinationArchiveFileName = cZip ])
? "Zip created   : " + new FileInfo(cZip).Length + " bytes"

new Directory().Delete([ :path = cDir, :recursive = True ])
oFile.Delete(cZip)
Output
Lines in file : 3
File size     : 88 bytes
Errors found  : 2
  2024-05 -> disk full

  2024-06 -> network down

Cleaned       : too many spaces
GZip          : 2800 -> 57 bytes
Zip created   : 184 bytes

Networking#

Uri, IPAddress, Dns, HttpClient, WebUtility, Encoding — a program that does not need the internet to run:

samples/UsingDotNet/introduction/test12_network.ring
samples/UsingDotNet/introduction/test12_network.ring
# HTTP: a small web server and a web client in one program
load "dotnet.ring"

using {
	"System"
	"System.Text"
	"System.Net"
	"System.Net.Http"
	"System.Threading.Tasks"
}

# A tiny web server and client in one Ring program: .NET runs the requests on its thread pool,
# Ring waits for the tasks and answers
cPrefix = "http://localhost:" + (20000 + random(20000)) + "/"
oServer = new HttpListener()
oServer.Prefixes.Add(cPrefix)
oServer.Start()
? "Listening on " + cPrefix

oWaiting = oServer.GetContextAsync()
oClient = new HttpClient()
oRequest = oClient.GetStringAsync(cPrefix + "greet?name=Ring")

oWaiting.Wait(NULL)
oContext = oWaiting.Result
? "Request        : " + oContext.Request.HttpMethod + " " + oContext.Request.Url.PathAndQuery
cReply = "Hello " + oContext.Request.QueryString.Item("name") + ", this is .NET speaking Ring!"
cBytes = new UTF8Encoding().GetBytes(cReply)
oContext.Response.OutputStream.Write(cBytes,0,len(cBytes))
oContext.Response.Close(NULL)

oRequest.Wait(NULL)
? "Response       : " + oRequest.Result
oServer.Stop()

# URL and address helpers
? "UrlEncode      : " + new WebUtility().UrlEncode("ring & .net = fun")
? "Loopback       : " + new IPAddress().Loopback.ToString()
? "Host name set  : " + (len(new Dns().GetHostName()) > 0)
Output
Listening on http://localhost:24995/
Request        : GET /greet?name=Ring
Response       : Hello Ring, this is .NET speaking Ring!
UrlEncode      : ring+%26+.net+%3D+fun
Loopback       : 127.0.0.1
Host name set  : 1
Tip

For HTTP requests use HttpClient. Methods that return a Task give you an object: call Wait() and read its property Result. A complete example is the self test of samples/UsingDotNet/applications/WebApi.

Cryptography and globalization#

Hashes (SHA256, MD5), HMAC, random bytes, AES, culture-aware formatting:

samples/UsingDotNet/introduction/test13_security.ring
samples/UsingDotNet/introduction/test13_security.ring
# Hashes, HMAC and AES encryption
load "dotnet.ring"

using {
	"System"
	"System.Globalization"
	"System.Security.Cryptography"
	"System.Diagnostics"
}

# Hashes and HMAC
oConvert = new Convert()
? "SHA256(abc)    : " + lower(oConvert.ToHexString(new SHA256().HashData("abc")))
? "MD5(abc)       : " + lower(oConvert.ToHexString(new MD5().HashData("abc")))
oHmac = new HMACSHA256().@New([ :key = "secret key" ])
? "HMAC           : " + left(lower(oConvert.ToHexString(oHmac.ComputeHash("message"))),32) + "..."

# AES encryption round trip
oAes = new Aes().Create(NULL)
oAes.GenerateKey()
oAes.GenerateIV()
cText = "Ring talks to .NET crypto"
cCipher = oAes.CreateEncryptor(NULL).TransformFinalBlock(cText,0,len(cText))
? "AES            : " + len(cText) + " bytes -> " + len(cCipher) + " bytes encrypted"
? "Decrypted      : " + oAes.CreateDecryptor(NULL).TransformFinalBlock(cCipher,0,len(cCipher))

# Cultures
oUS = new CultureInfo("en-US")
oDate = new DateTime(2024,7,4)
? "US date        : " + oDate.Format([ :format = "D", :provider = oUS ])
? "German date    : " + oDate.Format([ :format = "D", :provider = new CultureInfo("de-DE") ])
? "Title case     : " + oUS.TextInfo.ToTitleCase("ring meets dot net")

# Start a process and read its output
oInfo = new ProcessStartInfo()
if iswindows()
	oInfo {
		FileName = "cmd"
		Arguments = "/c ver"
	}
else
	oInfo.FileName = "uname"
ok
oInfo {
	RedirectStandardOutput = True
	UseShellExecute = False
	CreateNoWindow = True
}
oProcess = new Process().Start([ :startInfo = oInfo ])
? "Process says   : " + trim(oProcess.StandardOutput.ReadToEnd())
oProcess.WaitForExit(NULL)
Output
SHA256(abc)    : ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
MD5(abc)       : 900150983cd24fb0d6963f7d28e17f72
HMAC           : c431e4857a6b817f9eeaab86b00f78e2...
AES            : 25 bytes -> 32 bytes encrypted
Decrypted      : Ring talks to .NET crypto
US date        : Thursday, July 4, 2024
German date    : Donnerstag, 4. Juli 2024
Title case     : Ring Meets Dot Net
Process says   : 

Microsoft Windows [Version 10.0.26200.9974]

XML, JSON and data tables#

XmlDocument, XPath, System.Text.Json, DataTable and DataView — no database needed:

samples/UsingDotNet/introduction/test14_xml_json_data.ring
samples/UsingDotNet/introduction/test14_xml_json_data.ring
# XML with XPath, JSON and data tables
load "dotnet.ring"

using {
	"System.Xml"
	"System.Text.Json"
	"System.Data"
}

# XML with XPath
oDoc = new XmlDocument()
oDoc.LoadXml("<shop><item price='3.5'>apple</item><item price='1.2'>fig</item><item price='9'>melon</item></shop>")
oItems = oDoc.SelectNodes("//item[@price > 2]")
? "Items over 2    : " + oItems.Count
for nLoop = 0 to oItems.Count - 1
	oItem = oItems.Item(nLoop)
	? "  " + oItem.InnerText + " costs " + oItem.GetAttribute("price")
next

# JSON: serialize Ring lists, read documents
oJson = new JsonSerializer()
? "Serialize       : " + oJson.Serialize([1,"two",[3,4]])
oDocument = new JsonDocument().Parse('{"user":"ring","langs":["ring","c","lua"],"stars":123}')
oRoot = oDocument.RootElement
? "user / stars    : " + oRoot.GetProperty("user").GetString() + " / " + oRoot.GetProperty("stars").GetInt32()
? "languages       : " + oRoot.GetProperty("langs").GetArrayLength()

# DataTable with SQL-like filtering and sorting
oTable = new DataTable()
oTable.Columns.Add([ :columnName = "Product", :type = "System.String" ])
oTable.Columns.Add([ :columnName = "Qty", :type = "System.Int32" ])
oTable {
	Rows.Add(["pens",120])
	Rows.Add(["paper",15])
	Rows.Add(["ink",60])
}
? "Total quantity  : " + oTable.Compute("SUM(Qty)","")
oView = oTable.DefaultView
oView.Sort = "Qty DESC"
? "Biggest stock   : " + oView.Item(0).Item("Product")
? "Low stock rows  : " + len(oTable.Select([ :filterExpression = "Qty < 100" ]).toList())
Output
Items over 2    : 2
  apple costs 3.5
  melon costs 9
Serialize       : [1,"two",[3,4]]
user / stars    : ring / 123
languages       : 3
Total quantity  : 195
Biggest stock   : pens
Low stock rows  : 2

Reflection and big numbers#

Type, Assembly, MethodInfo, BigInteger, Complex:

samples/UsingDotNet/introduction/test15_reflection_numbers.ring
samples/UsingDotNet/introduction/test15_reflection_numbers.ring
# Big numbers, reflection, encoders and concurrent collections
load "dotnet.ring"

using {
	"System"
	"System.Reflection"
	"System.Numerics"
	"System.Text.Encodings.Web"
	"System.Collections.Concurrent"
	"System.Runtime.InteropServices"
}

# Big integers: factorial of 40
oBig = new BigInteger()
nFactorial = oBig.Parse("1")
for nLoop = 2 to 40
	nFactorial = oBig.Multiply(nFactorial,nLoop)
next
? "40!            : " + nFactorial.ToString()
? "2^200          : " + oBig.Pow(2,200).ToString()
oZ = new Complex().@New([ :real = 3, :imaginary = 4 ])
? "|3+4i|         : " + oZ.Magnitude

# Reflection: explore a type
oMath = new Type().GetType([ :typeName = "System.Math" ])
aNames = []
aMethods = oMath.GetMethods(NULL).toList()
for oMethod in aMethods
	if find(aNames,oMethod.Name) = 0 aNames + oMethod.Name ok
next
? "Math methods   : " + len(aNames) + " names, e.g. " + aNames[1] + ", " + aNames[2] + ", " + aNames[3]
oAsm = new Assembly().@Load("System.Linq")
? "Assembly       : " + oAsm.GetName(NULL).Name + " " + oAsm.GetName(NULL).Version.ToString()

# Environment and encoders
? "OS             : " + new RuntimeInformation().OSDescription
? "HTML encoded   : " + new HtmlEncoder().Default.Encode("<script>alert('x')</script>")
oQueue = new ConcurrentStringQueue()
oQueue.Enqueue("first")  oQueue.Enqueue("second")
? "Concurrent     : " + oQueue.TryDequeue()[2] + ", left " + oQueue.Count
Output
40!            : 815915283247897734345611269596115894272000000000
2^200          : 1606938044258990275541962092341162602522202993782792835301376
|3+4i|         : 5
Math methods   : 47 names, e.g. Acos, Acosh, Asin
Assembly       : System.Linq 9.0.0.0
OS             : Microsoft Windows 10.0.26200
HTML encoded   : &lt;script&gt;alert(&#x27;x&#x27;)&lt;/script&gt;
Concurrent     : first, left 1

Processes and threads#

Ring
using {
	"System.Diagnostics"
	"System.Threading.Tasks"
}

oInfo = new ProcessStartInfo() {
	FileName = "cmd"
	Arguments = "/c ver"
	RedirectStandardOutput = True
	UseShellExecute = False
	CreateNoWindow = True
}
oProcess = new Process().Start([ :startInfo = oInfo ])
? trim(oProcess.StandardOutput.ReadToEnd())
oProcess.WaitForExit(NULL)

oTask = new Task().Delay(30)                    # a Task: wait for it on the Ring thread
oTask.Wait(NULL)
? oTask.IsCompleted

oResult = new Task().FromResult("done")
? oResult.Result                                 # the Result of a Task<T>
Note

Ring code runs on the Ring thread only. A callback invoked from a pool thread prints a message on stderr instead. Use tasks for pure .NET work (HTTP, files, hashing), then Wait() for them on the Ring thread.

A bigger example#

samples/UsingDotNet/introduction/test16_forms_app.ring and demo_todo.ring combine collections, files, JSON and a form. For complete programs see Applications.

Where to go next#

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.