Login
A chronicle of the thoughts, learning experiences, ideas and actions of a tech junkie, .NET, JS and Mobile dev, aspiring entrepreneur, devout Christian and travel enthusiast.
As a .NET developer, you have access to a vast ecosystem of open-source libraries and frameworks that can help you accelerate your development process, enhance the functionality of your applications, and streamline your workflow. One of the key tools in the .NET ecosystem is NuGet, a package manager that allows you to easily discover, install, and manage third-party libraries in your .NET projects. In this blog post, we will explore some of the popular NuGet packages for .NET development that can greatly improve your productivity and efficiency.
Newtonsoft.Json Json.NET, also known as Newtonsoft.Json, is a widely used and versatile JSON (JavaScript Object Notation) library for .NET. It provides powerful JSON processing capabilities, including serializing .NET objects to JSON and deserializing JSON to .NET objects, as well as manipulating and querying JSON data. Json.NET supports a variety of JSON standards and has extensive features, such as support for LINQ-to-JSON, custom converters, and schema validation. It is widely used in many .NET applications for handling JSON data and has become the de facto standard for JSON serialization and deserialization in the .NET ecosystem.
EntityFramework Core Entity Framework Core (EF Core) is a modern, lightweight, and cross-platform object-relational mapping (ORM) framework for .NET that enables developers to work with databases using .NET objects. EF Core is a complete rewrite of the original Entity Framework (EF) and is designed to be more modular, performant, and compatible with different database providers. EF Core provides a higher-level abstraction for interacting with databases, allowing you to model your database schema using .NET classes and work with data using familiar object-oriented programming (OOP) concepts. EF Core supports various database providers, such as SQL Server, MySQL, PostgreSQL, and SQLite, and offers features such as automatic code generation, caching, and query optimization. EF Core simplifies database access and enables you to write more maintainable and scalable data access code in your .NET applications.
AutoMapper Automapper is a popular object-object mapping library for .NET that simplifies the process of mapping one object to another. It allows you to define mapping configurations between objects with different structures and automatically maps properties based on conventions or explicit mappings. AutoMapper eliminates the need for writing repetitive and error-prone mapping code, making object mapping in .NET applications more efficient and readable. It also supports advanced mapping scenarios, such as flattening, nesting, and customization, and can greatly reduce the amount of boilerplate code required for object mapping tasks.
Serilog Serilog is a flexible and extensible logging library for .NET that provides a powerful and expressive way to log events and messages in your applications. It supports various log sinks, such as console, file, database, and third-party services, and allows you to configure logging behavior using a fluent and code-first configuration API. Serilog also supports advanced features, such as structured logging, event filtering, and custom log message templates, making it a powerful tool for logging and diagnostics in .NET applications. With its rich ecosystem of extensions and integrations, Serilog is widely used in many .NET applications for logging and tracing purposes.
Microsoft.Extensions.DependencyInjection Microsoft.Extensions.DependencyInjection is a lightweight and extensible dependency injection (DI) container for .NET that provides a simple and flexible way to manage object dependencies in your applications. DI is a design pattern that promotes loosely coupled and testable code by allowing objects to request their dependencies instead of creating them directly. Microsoft.Extensions.DependencyInjection allows you to define service registrations and resolve dependencies using a fluent and expressive
Before we dig into the technical, permit me to reminisce a little. My reason for starting this website and the associated blog was to share my learning experiences and thoughts. If there is anything I have learnt along my software development journey, it is that when you are dealing with mature technologies and frameworks, most questions have been asked, most bugs have been reported and fixes or workarounds have been detailed and a thousand and one blog posts and articles would have been written about every minutia.
That has been my experience working with C#, JavaScript and Angular, but on some rare occasion, you find yourself trying to accomplish some arcane task, do research and not find much to go on.
A situation quite like that is what led to this post. While working on the dimmer module on the Ngx Semantic project, I found that I needed to instantiate a defined component, set its inputs and then retrieve the generated HTML to manually insert into the DOM at my convenience. I was able to find a solution which is what I'd detail below.
Let's define a sample component that takes one input. This would be the component that we need to programmatically instantiate and render.
import {Component, Input} from '@angular/core';
@Component({
selector: 'app-sample',
template: `<div>Hello world. {{input}}</div>`
})
export class SampleComponent {
@Input() input: string;
}
NOTE: if you are running Angular 10 and above you do not need to add the SampleComponent
to the entry components of your module.
With that done, in the component or directive where you need to manually render the sample component, you would need to inject a number of dependencies via the constructor as shown:
import {ApplicationRef, ComponentFactoryResolver, ApplicationRef} from '@angular/core';
...
constructor(private factoryResolver: ComponentFactoryResolver, private injector: Injector,
private applicationRef: ApplicationRef) {
}
Let's define a function to actually do the manual component rendering. The function would be renderComponent()
. I would add comments in the function implementation detailed below to explain each step:
private renderComponent() {
// generate a factory that would help in creating our component
const factory = this.factoryResolver.resolveComponentFactory(SampleComponent);
// create an instance of the sample component
const component = factory.create(this.injector);
// since we need to modify inputs on the component, we extract the instance and make our changes
component.instance.input = 'John';
// we attach the component instance to the angular application reference
// this step is necessary as it allows for our components view to be dirty-checked
this.applicationRef.attachView(component.hostView);
// the step we have been building to
// we pull the rendered node from the components host view
const renderedHtml = (component.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
}
The content in the renderedHtml
variable is the HTML representation of the component with the provided inputs. For the example above, the HTML would look something like:
<div>Hello World. John</div>
That's about it, I stumbled onto a solution for a very niche problem and shared as I think it may be useful to someone else.
Till next time, happy coding.
Cheers!
As you build a mobile app, you may want to save small bits of user data and/or preferences usually as a key-value pair. For a while, there was no Xamarin cross-platform way of getting that done, so platform-specific code had to be written. With the introduction of Xamarin Essentials, a number of commonly accessed functionality has been made cross-platform. In this guide, we'll walk through persisting some user data in a Xamarin Forms application. NOTE: If you want to save sensitive data, use Secure Storage instead.
Using your favourite editor, create a Xamarin Forms project. I am using JetBrains Rider as my IDE and naming my project xamarin-forms
.
To make use of the Xamarin Essentials library, it has to be installed in the PCL/NET Standard project as well as any platform-specific projects. For my own IDE, this is the view:
After the installation is complete, if there is an Android target project then we need to update the MainActivity.cs
file (or any other Activity file that is the launch target) with the following:
...
base.OnCreate(savedInstanceState);
// add the line below to your file
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
...
For this example, I want to save the current Date and Time in the user's preferences when I call a method. The logic for my method is shown below:
using Xamarin.Essentials;
...
public void SaveToPreferences()
{
Preferences.Set("app_CurrentDate", DateTime.UtcNow);
}
In this case, we saved a DateTime
type to the preferences but the library has overloads to support a number of primitives including bool
, double
, int
, float
, long
and string
.
To retrieve the data I persisted, I would add in a method to get the date I saved. The method is shown below:
protected DateTime ReadSavedPreference()
{
var date = Preferences.Get("app_CurrentDate", DateTime.MinValue);
return date;
}
The more astute of you would have noticed the DateTime.MinValue
values provided to the Get
method. That is the default
that the method returns if the provided key does not exist. For our example, if we have not saved a value to the app_CurrentDate
key, then the default .NET minimum DateTime
value (1/01/0001 0:00:00 AM) would be returned.
If at any point we no longer need the data tied to a certain key, we can remove the data. In the context of the data, we have saved in the previous examples. if we were to create a method to remove the date we saved, the method implementation should look like :
public void RemoveSavedDate()
{
Preferences.Remove("app_CurrentDate");
}
If we want to remove all saved app preferences, the Xamarin Essentials library provides us with a handy method to accomplish that as well.
Preferences.Clear();
Till the next one,
Cheers
About 2 years ago, I took a hiatus from writing .NET code to focus on NodeJS as I needed it for work. I worked with Express, and MongoDB and over the course of working and learning I developed a fondness for some tools and libraries as they just made my life easy and saved me time. Fast forward a few months and I am back to writing dot net code again (though it is dot net core now) I realise that quite a number of those libraries have no dot net equivalent and that is what set me down this trip.
The first library from the JavaScript world that I missed was shortid. It is a simple package that generates unique strings from seven to fourteen characters long and those can be used for just about anything. I used them as my _id
fields in my mongo collections instead of the mongoid
format that MongoDB assigns by default. It helped make them human-readable at least for me. I got back to writing web apps with ASP.NET Core and was itching for a way to generate short ids that I could use to uniquely identify objects in my database and use in a URL as well. When I discussed this with other dot net devs their response was to use Guid
's and while that would have met my requirement for uniqueness, I just didn't like seeing a Guid
in my URI. My grand solution was to write a dot net analogue called (you won't believe the amount of creativity this took) shortid. Writing it and posting the source code online allowed for me to gain valuable feedback and insights about handling thread safety and memory management when dealing with a lot of strings.
The second library I realized I missed was dotenv which is a library that helps load environment variables from .env
files. When I started working with ASP.NET Core, I tried handling configuration data using the baked in appsettings.json
files but those had the glaring limitation of having you place potentially sensitive information in plain text. .env
files allow for the files to just reside locally and not be checked into source control. I looked around and did not see any library that allowed for that to be done on ASP.NET Core and so ... (you guessed it) I wrote one. I called it dotenv.net. I made a few changes to the way the dot net port works to make sure it familiar to the target audience. Building this and having it open source helped me learn how to handle ideas from other developers in the form of issues or pull requests, know when a change recommended is in line with the goals and spirit of the project.
Recently, I really wanted to see a summary if the details of the calls my ASP.NET Core Web API was receiving and I realised the dot net ecosystem doesn't have something like morgan
which exists for NodeJS. I set out to write a port called Logly
which is out and on nuget. Writing a piece on that as well, that should be out in a few days.
The purpose for writing all of this and telling these stories is to encourage someone somewhere to do something. Do not feel like you cannot. If you identify an issue or a need in your environment, step up and take responsibility and this goes for more than just programming,
Cheers people,
Till the next one.
It’s been a while I posted an excerpt from Quora. This one really resonated with me and I felt I should share. It was written as a response by Gary Wisnieski.
First, it’s important to differentiate software architecture from simply best practices. A good software engineer may be excellent at coding, excellent and detailed in their approach, and have a great deal of insight into the problem, but still, may not be a good architect.
At a minimum, a good architect should have the following skills:
An architect is excellent at problem decomposition. Problem decomposition is the skill necessary to see a problem at virtually any level and break it down into the steps and pieces necessary to implement it. A good software architect can take a statement like “Our Air Traffic Control systems are inadequate and we need a better design” and knows the questions to ask to begin to decompose the problem into achievable components, to decompose those component goals into achievable sub-projects, and decompose those sub-projects into achievable programming tasks. A good architect can do these things at any level or scale from envisioning a billion line software project to understanding the best way to implement an algorithm to cope with unreliable links. The scale is irrelevant because the process is always the same.
An architect understands interfaces. Interfaces, whether in the form of protocols, function libraries, class interfaces, or schemas are the primary tool needed to manage the complexity of projects when there are independent contractors and implementers. By knowing the process of defining crisp, unambiguous interfaces that are logically complete, an architect can empower many people to build pieces of systems that connect easily to achieve a larger goal.
An architect understands that complexity is the enemy, and has a mastery of the programming tools and paradigms necessary to reduce complexity in all components, to reduce the complexity of interfaces, and assure minimal or no redundancy of implementation of function. They can quickly recognize algorithms and implementations which are too specific or too generic, and guide those developing to create components which perform just the right function. Often, the tools of managing complexity are things such as data hiding, object-oriented programming, self-validating systems, and comprehensive testing plans for standard interfaces. But, a good architect is not dogmatic about tools and technologies because they have a comprehensive academic understanding of the underpinnings and reasons why data hiding works, and why certain languages support good design principles and others do not.
An architect is a good communicator, a good and prolific writer, and documentor, and is good at speaking the language of programming as well as the common language of those who are stakeholders in the system’s design. Along with good communication, a good architect can give concrete reasons for programming practices rather than opinions, and offers insight to their team rather than argument. They strongly favor and seek out the user’s opinion of suitability to that of their own or the programmers involved in the project.
A good architect is a good leader and is excellent at gaining the respect of all the technical people they work with. Usually, this means that they have a high level of skill, have worked in multiple languages, and have been an architect before, or have demonstrated their ability to create systems designs which have remained flexible in the face of change.
Many definitions include an array of buzzwords, emphasizing methodologies like data-driven design, agile programming, specific languages, platforms, and toolkits. These things are current labels for various techniques whose basis needs to be well understood, not accepted because they are currently in vogue. So, in many ways, the chief skills of an architect are experience, intelligence, willingness to work hard and take a hands-on role, good intuition, and the ability to break down problems using logic so that as industry buzzwords come and go, their designs remain useful and relevant.
My definition above intentionally does not include project management, scheduling, and management skills. The architect’s role is to create good systems, not to solve team problems or budgets. In fact, it is best if those with budgets and team issues are simply stakeholders who help define one of the constraints the architect must deal with, just as if it were part of their design problem.