To see all the services on your system, use the Get-Service
cmdlet:
Get-Service
This outputs a list showing:
This command helps you get an overview of all services and their current state.
PowerShell is a powerful tool for managing system services, offering flexibility and control through straightforward commands. This guide covers the essentials of listing, searching, and managing services.
You often need administrative privileges to manage services. Running PowerShell as an administrator ensures you have the necessary permissions to start, stop, or modify services.
The article outlines seven free tools to wipe hard drives securely. These are:
You can find further details here.
How to disable Perfwatson2.exe from Visual Studio (March 8, 2017)
To stop PerfWatson2.exe, a background process in Visual Studio that tracks performance issues, go to Help > Privacy > Privacy Settings and opt out of the Visual Studio Experience Improvement Program. In earlier Visual Studio versions, select Send Feedback > Settings and uncheck participation. Alternatively, use the registry path HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VSCommon\...
and set OptIn
to 0 to disable it permanently.
JavaScript functions are reusable blocks of code that perform specific tasks. Defined using the function keyword or as arrow functions, they can accept parameters and return values. Functions enhance code organization, modularity, and reusability, allowing developers to execute the same logic multiple times throughout a program with ease.
Problem Statement: Extracting extended file properties, such as the Media Created Date, is necessary for certain applications. Utilizing the Microsoft.WindowsAPICodePack.Shell namespace facilitates this task efficiently.
Approach: Utilize the ShellObject class from the WindowsAPICodePack.Shell namespace to access extended file properties. Specifically, retrieve the Media Created Date using the System.Media.DateEncoded property.
using Microsoft.WindowsAPICodePack.Shell;
ShellObject shell = ShellObject.FromParsingName(path);
var mediaCreatedDate = shell.Properties.System.Media.DateEncoded;
Explanation: This code utilizes the ShellObject class to access extended file properties. It fetches the Media Created Date of a file specified by its path using the System.Media.DateEncoded property, providing crucial metadata for various applications.
Further resources
useContext
is a React Hook that lets you read and subscribe to context from your component. React Context is a way to manage state globally.
The useNavigate
hook from React Router returns a function that lets you navigate programmatically, for example in an effect:
import { useNavigate } from "react-router-dom";
function useLogoutTimer() {
const userIsInactive = useFakeInactiveUser();
const navigate = useNavigate();
useEffect(() => {
if (userIsInactive) {
fake.logout();
navigate("/session-timed-out");
}
}, [userIsInactive]);
}
Button click
import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
<Button onClick={() => navigate('../user', { replace: true })}>Register</Button>
Reference
To only update one field, we can simply change the update method to the following:
Person person = new Person {Id=4, Lastname="Miller"};
dbContext.Attach(person);
dbContext.Entry(person).Property(p => p.Lastname).IsModified = true;
dbContext.SaveChanges();
The above function first constructs the object with the specified Id
and updated Lastname
, and then appends the object; it then explicitly marks the Lastname
property as modified.
The generated UPDATE statement now looks like this
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (8ms) [Parameters=[@p1='?' (DbType = Int32), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
UPDATE `Persons` SET `Lastname` = @p0
WHERE `Id` = @p1;
SELECT ROW_COUNT();
As shown in the EFCore log, only the Lastname
field is updated.
This approach can slightly improve performance because the SQL statement is smaller and the query execution on the database server can be faster.
See also the discussion at Stack Overflow How to update not every fields of an object using Entity Framework and EntityState.Modified
Logging is an essential part of application development for debugging, monitoring, and understanding the flow of execution, especially in complex systems. When logging in a C# method with parameters that need validation, it's crucial to follow best practices to ensure clear and useful log messages. Below is a sample demonstrating how to log and validate parameters in a C# method:
public bool ValidateAndProcessData(string data)
{
// Log the start of the method
_logger.LogInformation("ValidateAndProcessData method started");
// Validate input data
if (string.IsNullOrEmpty(data))
{
_logger.LogError("Input data is null or empty");
throw new ArgumentException("Input data cannot be null or empty", nameof(data));
}
try
{
// Process data
_logger.LogInformation("Processing data: {data}", data);
// Simulating processing time
System.Threading.Thread.Sleep(1000);
_logger.LogInformation("Data processed successfully");
return true;
}
catch (Exception ex)
{
// Log any exceptions that occur during processing
_logger.LogError(ex, "Error processing data: {data}", data);
throw; // Re-throw the exception for higher-level handling
}
finally
{
// Log the end of the method
_logger.LogInformation("ValidateAndProcessData method completed");
}
}
By following this sample, you ensure that your method logs relevant information about parameter validation and method execution, making it easier to debug and monitor your application's behavior.
C# is a strongly-typed language. It means we must declare the type of a variable that indicates the kind of values it is going to store, such as integer, float, decimal, text,
Additional reading at Data types in C# (tutorialsteacher.com)
C# includes specialized classes that store series of values or objects are called collections.
There are two types of collections available in C#: non-generic collections and generic collections.
The System.Collections
namespace contains the non-generic collection types and System.Collections.Generic
namespace includes generic collection types.
Additional reading at C# Generic & Non-generic Collections (tutorialsteacher.com)
In C#, a string is a series of characters that is used to represent text. It can be a character, a word or a long passage surrounded with the double quotes ". The following are string literals.
// String Literal Examples
"S"
"String"
"This is a string."
In a console apps, there is often a need to obtain user input from the console while ensuring that the input is not empty or only whitespace characters.
In this sample, we define a method GetUserInput
that takes an optional message parameter. It continuously prompts the user until a non-empty, non-whitespace input is provided.
static string GetUserInput(string message = "Please enter some input:")
{
string input;
do
{
Console.WriteLine(message);
input = Console.ReadLine()?.Trim();
} while (string.IsNullOrWhiteSpace(input));
return input;
}
Explanation:
message
parameter allows customizing input prompt message.Console.ReadLine()?.Trim()
reads user input and trims leading/trailing whitespace.?.
operator is used for null-conditional access, ensuring that Console.ReadLine()
doesn't throw a null reference exception if the input is null.do-while
loop ensures user input is not empty or whitespace.To filter out nullable strings and obtain only non-null strings, you can use LINQ Where
method along with a null check. Here's an example:
IEnumerable<string?> nullableStrings //
List<string> nonNullStringsList = nullableStrings
.Where(s => s != null) // Filter out null values
.Select(s => s!) // Convert nullable strings to non-nullable
.ToList(); // Convert IEnumerable to List
Where
to filter out null values and Select
to convert nullable strings to non-nullable strings (string!
indicates a non-nullable reference type in C# 8.0 and later).ToList()
to convert the filtered enumerable to a List<string>
.The JsonSerializer.Serialize
converts the value of a specified type into a JSON string.
using System.Text.Json;
var user = new User("Krish Jackon", "female", new MyDate(1985, 03, 30));
var json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
The JsonSerializer.Deserialize
parses the text representing a single JSON value into an instance of a specified type.
using System.Text.Json;
string json = @"{""Name"":""Krish Jackon"", ""Gender"":""female"",
""DateOfBirth"":{""year"":1985,""month"":03,""day"":30}}";
var user = JsonSerializer.Deserialize<User>(json);
Resources to deserialize to dynamic object