Thursday, December 31, 2020

Gem in C# - Span

System.Span<T> is a value type representing a continuous memory region for a collection of value type objects. It works like an array of value type <T>. Span<T> is a ref struct. Ref struct can only exist in stack and can't be the fields. Span can be used to access heap, stack, and unmanaged memory.

  • Supports type check by compiler
  • Boundary check at runtime
  • Indexer and Enumerator

Why should developers care?

  • Avoid overhead of allocation
  • Avoid overhead of memory copy
  • Avoid overhead of garbage collection 

What real-world problems can Span<T> solve?

  • Iterating a collection of value types (simple types, struct, enum), such as byte[], involves memory copy because value type by default is pass-by-value.
  • String.Substring could be used to carve out just the piece that’s interesting to them, but that’s a relatively expensive operation, involving a string allocation,  memory copy, and garbage collection. 
  • Coding with raw pointer is dangerous because it has no strong-type and boundary-check in runtime.  
  • Same logic has to be implemented for different memories, such as heap, stack, and native code (unmanaged memory, interop).

Final words

Microsoft Search Engine Bing is written in .NET Core. The performance of Bing has improved by 34% after using Span<T>.

Span<T> is one of the gems in C#.

Enjoy!

Best Features for C# Language (2.0-9.0)

 C# 2.0 language: 

Generics, nullable types, anonymous methods etc.

C# 3.0 language: 

LINQ, extension methods, lambda expressions, var (implicit types), get/set shortcuts etc.

C# 4.0 language: 

dynamic (late binding), optional arguments, covariance and contravariance in collections etc. 

C# 5.0 language: 

async/await, Caller Info

C# 6.0 language: 

string interpolation, dictionary initializer, nameof, using static

c# 7.0 Language

Span, ref struct, in, out, 

C# 8.0 Language

Async Streaming, Patterns, indices and range

C# 9.0 Language

        record, Covariant return types, Lambda discard parameters



Sunday, December 27, 2020

Yadex Release v1.1 Published on GitHub




Yadex Retirement
 is an asset management desktop application to help you reach the goal of F.I.R.(E.) — Financial Independence, Retire (Early.)

     https://github.com/tonyjy/YadexRetirement 

  • Track your assets performance
  • Categorize your assets
  • Summarize your assets
  • Evaluate your retirement goal

Yadex Retirement runs on Windows only.

  • Asset total tracking year over year.
  • Asset details tracking year over year.
  • Asset add, update, and duplicate.

To run the executable, please unzip Yadex_v1.1.0_win10-x64_EXE.zip and run Yadex.Retirement.exe

     Yadex_v1.1.0_win10-x64_EXE.zip

Author: Tony Jiang

Released Date: 12/26/2020



Wednesday, November 25, 2020

"Student PC" Over $1,300

I am proud that my son built his first PC successfully. It was a great achievement for a 15-year-old planning, researching, learning, and building a PC all by himself. Well, I admit this new PC is way much more powerful than a "Student PC". It belongs to the different category "Gaming PC". However, it is worth every penny seeing the big smile in my son's face.

Here are the main parts: 

1. CPU - AMD Ryzen 7 3700X Matisse 3.6GHz 8-Core AM4 Boxed Processor with Wraith Prism Cooler $279.00

2. Graphics Card - MSI GeForce GTX 1660 Ti VENTUS XS OC Graphics Card $292.00

3. Motherboard - MSI B550-A Pro AMD AM4 ATX Motherboard $139.99

4. Case - COOLMAST MASTERBOX NR600 MT TG ATX $69.99

5. PSU - PowerSpec 650W Gold FULL ATX $99.99

6. RAM - G.Skill Ripjaws V 32GB (2 x 16GB) DDR4-3200 PC4-25600 CL16 Dual Channel Desktop Memory Kit F4-3200C16D-32G $116.99

7. SSD - Inland Premium 1TB SSD 3D NAND M.2 2280 PCIe NVMe 3.0 x4 Internal Solid State Drive $109.99

8. Accessories such as keyboard, mouse, case fans, webcam, speaker, and WIFI card are not listed. 

Tuesday, October 27, 2020

Turn Off Pooling in ADO.NET

Have you ever wondered how not to use connection pool provided in ADO.NET?

By default, when a connection is first opened using ADO.NET, a connection pool is created based on an exact matching algorithm that associates the pool with the connection string in the connection. Each connection pool is associated with a distinct connection string. 

Thanks EF and ADO.NET for making our lives easier. But sometime we want to take the control.

There are cases that you don't want long running database session (for example, a few hours) to avoid memory leak, database resource constraints, or performance issues in database. Disabling connection pooling can help. If you do want to have a connection closed after connecting to database, you need to set the Pooling flag to false by adding the flag to connection string. 

Just simply append "Pooling=false;" to the connection string. 

That Is Easy.

Sunday, August 09, 2020

Pros & Cons of Serverless Computing

Serverless computing, Function as a Service (FaaS) application model, offers a number of advantages over traditional cloud-based or server-centric infrastructure. For many developers, serverless architectures offer greater scalability, more flexibility, and quicker time to release, all at a reduced cost. With serverless architectures, developers do not need to worry about purchasing, provisioning, and managing backend servers. 

Although 'serverless' computing does actually take place on servers, developers never have to deal with the servers. They are managed by the vendor. This can reduce the investment necessary in DevOps, which lowers expenses, and it also frees up developers to create and expand their applications without being constrained by server capacity.

As in a 'pay-as-you-go' phone plan, developers are only charged for what they use. Code only runs when backend functions are needed by the serverless application, and the code automatically scales up as needed. In contrast, in a traditional 'server-full' architecture, developers have to project in advance how much server capacity they will need and then purchase that capacity, whether they end up using it or not.

Quick deployments (update, patch, fix) and updates are possible. Developers can very quickly upload bits of code and release a new product. They can upload code all at once or one function at a time, since the application is not a single monolithic stack but rather a collection of functions provisioned by the vendor. This also makes it possible to quickly update, patch, fix, or add new features to an application. It is not necessary to make changes to the whole application; instead, developers can update the application one function at a time.

Serverless computing's concerns include Debugging, Security, Versioning, Multi-tenancy, Not for long-running processes (cost),  'boot up'/'cold start' time, and vendor lock-in (AWS Lamda, Azure Function, Google Cloud Functions, or Openshift Function).

AWS Lambda natively supports JavaScript, Java, Python, Go, C#, F#, PowerShell, and Ruby code.

Azure Functions has runtimes for JavaScript, Java, Python, C#, F#, and PowerShell (preview). Azure lacks Go and Ruby—otherwise, the language options are very similar.

AWS Lambda has a straightforward programming model. A function receives a JSON object as input and may return another JSON as output. The event type defines the schema of those objects, which are documented and defined in language SDKs.

Azure Functions has a more sophisticated model based on triggers and bindings. A trigger is an event that the function listens to. The function may have any number of input and output bindings to pull and/or push extra data at the time of processing. 

AWS Lambda always reserves a separate instance for a single execution. Each execution has its exclusive pool of memory and CPU cycles. Therefore, the performance is entirely predictable and stable.

Azure Functions allocates multiple concurrent executions to the same virtual node. If one execution is idle waiting for a response from the network, other executions may use resources which would otherwise be wasted. 

Advantages of containers
• Control and Flexibility
• Vendor-agnostic
• Easier migration path
• Portability

Advantages of serverless
• Zero administration
• Pay-per-execution
• Zero cost for idle time
• Auto-scaling
• Faster time-to-market
• Microservice nature: Clear codebase separation
• Significantly reduced administration and maintenance burden

Containers are great if you need the flexibility to install and use software with specific version requirements. With containers, you can choose the underlying operating system and have full control of the installed programming language and runtime version.

Saturday, July 25, 2020

Why gRPC Not Replacing REST (Web API)?













Google's gRPC is actually a new take on an old approach known as RPC, or Remote Procedure Call, which has come a long way to stand out among Messaging, Queuing, COM, CORBA, SOAP, REST, and GraphQL in Microservice world.

Performance

gRPC is roughly 7 times faster than REST when receiving data & roughly 10 times faster than REST when sending data for this specific payload. This is mainly due to the tight packing of the Protocol Buffers and the use of HTTP/2 by gRPC. Protobuf is about 3x faster than Jackson and 1.33x faster than DSL-JSON for integer encoding. gRPC uses HTTP/2, it can multiplex multiple RPCs on the same TCP connection. gRPC supports bidirectional streaming. Therefore, gRPC has low latency and high throughput.

For in-depth analysis of gRPC vs REST, please visit https://medium.com/@EmperorRXF/evaluating-performance-of-rest-vs-grpc-1b8bdf0b22da

Interoperability 

gRPC's IDL (Interface Description Language) provides a simpler and more direct way of defining remote procedures than OpenAPI's approach of using URL paths, their parameters, and the HTTP methods that are used with them. It is a cross-platform/multi-language framework. 

Stability

In addition to gRPC is language-neutral, platform-neutral, and extensible, gRPC mitigates Microservice and Distributed Communication pitfalls. gRPC IDL is more stable than REST over time. REST or OpenAPI use HTTP verbs (GET, PUT, POST) and payload (usually JSON). 

.NET Integration

Speaking of .NET, gRPC is very easy to integrate with ASP.NET Core. Please refer C# 8 new feature Async Streming. However all things are shiny. Some .NET data types are not supported. The tooling is behind Web APIs in Visual Studio and Postman. For the UI facing (JavaScript in browser, not nodejs), the services have to be built in Web APIs.

In the end, I have to come to the conclusion – gRPC might be a success in performance critical Microservices but it will not replace REST/Web APIs. 

We will see.

Sunday, July 19, 2020

How to Add SignalR in ASP.NET Core?

SignalR provides an API for creating server-to-client remote procedure calls (RPC). The clients can be JavaScript, .NET, or Java functions. Here are some of the main benefits to use SignalR as push architecture for real time applications.
  1. Handles connection management automatically.
  2. automatically chooses the best transport method that is within the capabilities of the server and client. (WebSocket, Server Sent Event, and Long Poll)
  3. Sends messages to all connected clients simultaneously. For example, a chat room.
  4. Sends messages to specific clients or groups of clients.
  5. Scales to handle increasing traffic.
It's very easy to set up an ASP.NET Core project with SignalR support in Visual Studio 2019 with Web Development tools. Hereunder are the key steps to enable SignalR in a web project with a browser client.

The SignalR server library is included in the ASP.NET Core 3.1 shared framework. The JavaScript client library isn't automatically included in the project. 

In Solution Explorer, right-click  wwwroot/js/ folder, and select Add Client-Side Library. If you don't see it in the context menu, please check if you have VS extension Microsoft Library Manager. 


Only select signalr.js and signalr.min.js.

              

After this you can create JS client now. Here is an example of JS client.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

For more details to use SignalR in ASP.NET Core 3.1, please refer to the link below.



Saturday, July 11, 2020

What is C# 8 Async Stream?

Asynchronous stream is a new feature introduced in .NET Standard 2.1 or C# 8. It is based on interface – IAsyncEnumerable<T>. It can be used with async/awaitThe main benefit with Async Stream is that the it can shorten the response time and reduce the usage of computing resource. The client (or the consumer) will get the a "stream" of items asynchronously, therefore act on each one item as soon as it is produced. 

Here is an example in my GitHub:

Tuesday, July 07, 2020

What's New in C# 8?

One Minute Answer: 

C# 8 was released in September 2019. It has come with a lot of good features.
  • Default Interface Methods
  • Property Pattern
  • Type Pattern
  • Tuple Pattern
  • Using declaration
  • Null-coalescing assignment
  • Indices and ranges *
  • Nullable reference types *
  • Asynchronous streams *

Add On Answer: 

  • C# 8 is fully supported in .NET Core 3.0 and .NET Standard 2.1
  • C# 8 is partially supported in .NET Frameworks 4.8 (*). But it will be fully supported in the up coming .NET 5.
  • C# 8 compiler exists Visual Studio 2019 v16.3 and above





Be A Developer That Uses AI

Developers will not be replaced by AI, they'll be replaced by developers that use AI. Generative AI tools are revolutionizing the way de...