ProgrammingPro #68: .NET SafeHandle Strategies, Python's Tiobe Milestone, and Rust-Python Interoperability Course
Bite-sized actionable content, practical tutorials, and resources for programmers.
Welcome to this week’s edition of ProgrammingPro!
In today’s Expert Insight, we bring you an excerpt from the recently published book, Effective .NET Memory Management, which demonstrates how to leverage SafeHandle to manage unmanaged resources effectively for application stability.
News Highlights: Python reaches a record 18.04% in Tiobe's August 2024 index; GitHub Models debuts a sandbox for experimenting with AI from Meta, Mistral, and Microsoft; JetBrains' 2024.2 update makes its new UI default, adding GPT-4o support; and Stack Overflow's 2024 survey shows PostgreSQL gaining over MySQL, with little migration from C/C++ to Rust.
My top 5 picks from today’s learning resources:
Open Access Book | Data structures and algorithms in Python📖
Convert Your Native Project to Kotlin Multiplatform — Developer’s Guide📲
Architectural Retrospectives - The Key to Getting Better at Architecting🏗️
But there’s more, so dive right in.
Stay Awesome!
Divya Anne Selvaraj
Editor-in-Chief
PS: This month’s survey is now live! Do take the oppotunity to give us your feedback on ProgrammingPro, request specific learning resources, and get your one Packt Credit for the month.
🗞️News and Analysis🔎
Python scores its highest rating in Tiobe index: Python reached a record high of 18.04% in Tiobe's August 2024 programming language popularity index. Read to learn about the current rankings and trends in programming language popularity.
Ahead-of-time class loading proposal would speed Java startups: The proposal aims to maintain Java's dynamism while reducing startup costs, without needing changes to application code or command-line launch processes.
White House is recommending that use of open source AI models not be restricted: An NTIA report promotes ongoing risk-benefit monitoring and open development to enhance transparency and trust in AI technologies.
GitHub Models is a new playground for experimenting with AI models: This new sandbox environment allows developers to experiment with AI models from various providers including Meta, Mistral, and Microsoft.
JetBrains’ new UI is now default across all IDEs in 2024.2 update: The update also enhances the AI Assistant with smarter features like GPT-4o support and AI-assisted version control. Read to learn about more enhancements.
Npm overflowing with Tea spam, spills out from 70% of all new packages: The Tea protocol is designed to financially reward open source contributors. Read to learn how this initiative has inadvertently created security concerns.
Little sign of migration from C or C++ to Rust in latest dev survey – but PostgreSQL is winning against MySQL: The 2024 Stack Overflow developer survey also shows notable growth in the JavaScript tool Bun and ChatGPT usage.
🎓Tutorials and Learning Resources💡
Sponsored: Learn Million Dollar AI Strategies & Tools in just 3 hours. Join free Workshop
Python
Open Access Book | Data structures and algorithms in Python: Explains algorithms and data structures, offers coding tips, and provides a collection of resources for popular LeetCode problems, starting with the Grind 75 list.
For more Python resources go to PythonPro
C# and .NET
The best new features in C# 13: Key features include expanded params collections, a new Lock API for better thread synchronization, and support for ref local variables in asynchronous methods. Read to learn how to utilize the features.
General Structure of a C# Program: Explains how a C# program can consist of multiple files, each potentially containing several namespaces. Read to learn how to organize components effectively within namespaces to develop a functioning app.
🎥Introduction to .NET Aspire with Azure Container Apps: .NET Aspire is a stack designed for building and deploying distributed applications, including through Azure Container Apps. Read to learn how to use .NET Aspire solutions.
C and C++
Enum Class Improvements for C++17, C++20 and C++23: Showcases how these developments improve code safety, readability, and maintainability. Read to learn about the key updates to enum class functionalities across recent C++ standards.
The difference between undefined behavior and ill-formed C++ programs: Undefined behavior occurs during runtime while ill-formed programs violate C++ language rules during compilation. Read to improve the reliability of your programs.
C is Turing complete: Discusses the debate over whether C's abstract machine, described as a large finite state machine, can support unbounded I/O operations as required by Turing's model to be considered Turing complete.
Java
💼Case Study | Netflix Adopts Virtual Threads - A Case Study on Performance and Pitfalls: Underscores the importance of careful integration and testing of virtual threads in complex systems to prevent performance pitfalls.
🎓Tutorial | Common I/O Tasks in Modern Java: Discusses reading and writing files, handling data from the web, and managing directory and ZIP file operations. Read to learn efficient and modern techniques for handling I/O operations in Java.
🎓Tutorial | 5 Java JUnit 5 Features I Wish I Knew Earlier: Discusses Temporary Directory Support, Parallel Test Execution, Tag Expressions, Conditional Test Execution, and Test Class Ordering. Read to learn how to leverage these features.
JavaScript and TypeScript
11 reasons the new JavaScript isn’t like the old JavaScript: JavaScript has evolved dramatically from its initial vision. Read to learn how its capabilities and applications have expanded far beyond simple web scripting.
💼Case Study | How Google handles JavaScript throughout the indexing process: Debunks myths about Google's rendering of JavaScript-heavy sites. Read to learn about practical strategies for optimizing web pages.
🎓Tutorial | What the heck are reverse mapped types?: Discusses how to allow inferring function type parameters from values and setting constraints. Read to learn how to leverage reverse mapped types to create more type-safe code.
Go
Is the Go Programming Language Worth Using on Your Next Project?: Discusses the Go programming language, focusing on its syntax, types, and concurrency features. Read to learn about Go's unique features.
📑Book Chapter | Gist of Go - Wait groups: Wait groups synchronize goroutines by incrementing and decrementing a counter to signal when goroutines complete. Read to enhance your understanding of synchronization.
Rust
🏫Open Access Course | Rust-Python interoperability: A course designed for those familiar with Rust and Python but new to interoperability. Read to learn through a structured curriculum with exercises and solutions.
💼Case Study | Hard Mode Rust: Explores developing a Rust application under strict constraints, avoiding dynamic memory allocation and using only minimal APIs. Read to learn how to build applications through manual memory handling.
Swift
Swift Navigation - Powerful navigation tools for all Swift platforms: Introduces an open-source library that enhances state management and navigation across Apple (SwiftUI, UIKit, AppKit) and non-Apple (Windows, Linux, Wasm) platforms.
App design - 5 benefits of using system components: Emphasizes that while custom elements may be appealing, system components offer significant advantages. Read to learn how using them can improve user experience.
PHP
🎓Tutorial | Leveraging Laravel's built in driver functionality: Demonstrates creating custom drivers for stock data sources, such as Google and Apple. Read to learn how to switch between different implementations effortlessly.
SQL
Accelerate PostgreSQL migrations to Google Cloud - move terabytes of data with Database Migration Service: Highlights challenges in large migrations and offers solutions to enhance speed by using parallel initial loads and more.
Ruby
🎓Tutorial | You should use the Ruby on Rails logger block syntax: Discusses using block syntax in Ruby on Rails logging to reduce unnecessary object allocations and CPU usage. Read to learn how to implement this efficient technique.
Kotlin
🎓Tutorial | Convert Your Native Project to Kotlin Multiplatform — Developer’s Guide: Covers technical decisions, challenges, and recommendations for preparing repositories, modularizing shared code, and ensuring Kotlin code is Swift-friendly.
🌟Best Practices and Advice🚀
Q&A - 10 emerging technologies to watch in 2024: Forrester's 2024 list of emerging technologies highlights a shift from generative to agentic AI, which are AI agents capable of executing specific actions.
Code is “drowning in security debt” says Veracode – and AI is both problem and solution: The Veracode State of Software Security 2024 report reveals that 63% of applications have flaws in first-party code and 70% in third-party code.
How to maximize your ROI for AI in software development: Discusses maximizing ROI in software development by integrating AI across various stages of the development lifecycle beyond just automating coding.
Architectural Retrospectives - The Key to Getting Better at Architecting: Discusses the importance of architectural retrospectives in refining the processes used to make critical decisions in software development.
Take the Survey, Get a Packt Credit!
🧠 Expert Insight 📚
Here’s an excerpt from “Chapter 7: Low-Level Programming” in the book, Effective .NET Memory Management by Trevoir Williams, published in July 2024.
Handling unmanaged resources with the SafeHandle class
Going back to earlier concepts, we can think of unmanaged resources as resources that are provisioned outside the GC’s watchful gaze. This can include recounting earlier sections of the book: file handles, network connections, and
memory allocated outside the .NET runtime. They pose the ever-present risk of resource leaks and application instability.
The SafeHandle class provides a reliable and secure way to handle unmanaged resources. It is an abstract class in the System.Runtime.InteropServices namespace that provides ways to ensure that resources are correctly released, even in the presence of exceptions or improper use. It allows us to ensure the following:
Automatic resource release: Ensures that the resource is released when the handle is no longer needed, preventing resource leaks
Reliability: Works correctly with the GC, ensuring that resources are released safely
Security: Minimizes security risks by preventing handle recycling and invalid handle usage
Ease of use: Provides a simple way to manage the life cycle of unmanaged resources, reducing the need for complex error-handling code
The SafeHandle class provides methods and properties to interact with unmanaged resources. We will attempt to create a file using the kernel32.dll library in the code snippet that follows. Notice how we can verify the validity of the fileHandle and wrap the native file stream resource in a scoped operation:
// Import the CreateFile function from kernel32.dll
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
// Create a file handle
SafeFileHandle fileHandle = CreateFile(
"example.txt",
GENERIC_READ,
0,
IntPtr.Zero,
OPEN_EXISTING,
0,
IntPtr.Zero);
if (!fileHandle.IsInvalid)
{
using (FileStream fs = new FileStream(fileHandle,
FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fs))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}
else
{
Console.WriteLine("Failed to open file.");
}
The CreateFile function from kernel32.dll is declared using P/Invoke. It returns a SafeFileHandle instead of an IntPtr. The SafeFileHandle is used to create a FileStream, which is then used to read the file contents. When the SafeFileHandle and FileStream objects are disposed of, the unmanaged file handle is released automatically, ensuring that there are no resource leaks.
Since the SafeHandle class is abstract, extending its functionality for custom operations through standard inheritance is possible. When you inherit from SafeHandle, you must override the IsInvalid and ReleaseHandle() members:
[DllImport("SomeUnmanagedLibrary.dll")]
static extern SafeExampleHandle GetExampleHandle();
SafeExampleHandle handle = GetExampleHandle();
if (!handle.IsInvalid)
{
// Use the handle
Console.WriteLine("Handle acquired and valid.");
// The handle will be released when it goes out of scope and is
// disposed
}
else
{
Console.WriteLine("Failed to acquire handle.");
}
public class SafeExampleHandle : SafeHandle
{
// Constructor
public SafeExampleHandle() : base(IntPtr.Zero, true) { }
// Override IsInvalid
public override bool IsInvalid
{
get { return this.handle == IntPtr.Zero; }
}
// Override ReleaseHandle
protected override bool ReleaseHandle()
{
// Perform necessary cleanup of the handle
// For example, if the handle was allocated using Marshal.
AllocHGlobal:
Marshal.FreeHGlobal(this.handle);
return true;
}
}
A public parameter-less constructor must always be present. It should call the base constructor with a value representing an invalid handle value and a boolean value indicating whether the SafeHandle owns the native handle or not. In this case, the constructor initializes the base with IntPtr.Zero and a flag indicating that the handle is owned by the SafeHandle instance. We also override the IsInvalid property with custom logic to determine whether the handle is invalid. The ReleaseHandle method override performs the necessary cleanup, which, in this case, consists of freeing the memory allocated with Marshal.AllocHGlobal.
Effective .NET Memory Management was published in July 2024. Packt library subscribers can continue reading the entire book for free or you can buy the book here!
🛠️ Useful Tools ⚒️
Semantic Kernel’s Agent Framework: An SDK that integrates LLMs with C#, Python, and Java to enable developers to build AI agents for specialized tasks and interactions.
RagBuilder: an open-source toolkit that streamlines optimizing Retrieval-Augmented Generation setups with hyperparameter tuning and templates for quick, optimal configuration.
Blip: a real-time incident management platform that minimizes downtime with automated alerts and efficient tracking to enhance productivity and customer satisfaction.
That’s all for today.
We have an entire range of newsletters with focused content for tech pros. Subscribe to the ones you find the most useful here. Complete ProgrammingPro archives can be found here. Complete PythonPro archives are here.
If your company is interested in reaching an audience of developers, software engineers, and tech decision makers, you may want to advertise with us.
If you have any feedback, take the survey, or leave a comment below.