EF Core Migrations is a feature that helps manage database schema changes. It allows developers to easily create, update, and rollback database migrations using a code-first approach, ensuring that your database schema stays in sync with your application models.
This set outlines how to construct a filter for the User Object Filter and Group Object Filter attributes in an LDAP configuration.
(&(objectClass=user)(cn=Mark*))
This means: search for all entries that have objectClass=user AND cn that start with the word 'Mark'.
A C# method can be called with invalid arguments, this may cause an ArgumentException.
ArgumentException indicates that a method was called with an invalid argument. This can help improve program quality.
ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. The ParamName property identifies the invalid argument.
When using the ArgumentNullException constructor, you can pass a string literal indicating the null argument.
The time service in Windows can be reset to a default state by running the following inside an elevated Command Prompt (CMD):
net stop w32time
w32tm /unregister
w32tm /register
net start w32time
To verify the time server, follow these steps:
timedate.cpl
time.windows.com
)Scrum is an empirical process control framework.
Empirical means to runs experiments to improve the product.
Meetings in Scrum
Additional meetings
In EF Core you can select specific columns from a database table using the Select()
method with an anonymous type. This allows you to specify only the necessary columns, improving performance by reducing unnecessary data retrieval. Here's a sample code snippet:
var query = dbContext.TableName
.Where(condition)
.Select(x => new
{
x.ColumnName1,
x.ColumnName2,
// Add more columns as needed
})
.ToList();
This technique is beneficial for optimizing data retrieval in Entity Framework queries. For more details, refer to the following websites.
You can use the following code snippets to get a class's public methods using reflection. The class name is provided as typeName
.
MethodInfo[] methodInfos = typeof(Class).GetMethods();
Variant with filter using BindingFlags
MethodInfo[] methodInfos = Type.GetType(typeName)
.GetMethods(BindingFlags.Public | BindingFlags.Instance);
You can use this code to get only the methods decorated with a custom attribute.
MethodInfo[] methodInfos = assembly.GetTypes()
.SelectMany(t => t.GetMethods())
.Where(m => m.GetCustomAttributes(typeof(CustomAttribute), false).Length > 0)
.ToArray();
Here’s an example of how to invoke a private method using reflection in .NET:
MyClass myClass = new MyClass();
Type classType = myClass.GetType();
MethodInfo methodInfo = classType.GetMethod("MethodName",
BindingFlags.Instance | BindingFlags.NonPublic);
// Make an invocation:
var result = await (dynamic)methodInfo.Invoke(myClass, null);
TanStack Query is a data-fetching library for React applications. It simplifies communication with APIs by abstracting complex logic into simple queries. With TanStack Query, you can define queries using plain JavaScript objects, leverage caching and automatic refetching, handle pagination, and easily manage loading and error states. It enhances productivity and improves the data-fetching experience in React projects.
To use useState, you must first import it from the React library. Then you can call the useState function with an initial value for your state variable. This will return an array with two elements: the current value of the state variable and a function that you can use to update that value.
For example, let's say you want to create a counter that increments each time a button is clicked. You could use useState to create a state variable for the count like this:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
In this example, we're using the useState hook to create a state variable called count
, which is initially set to 0. We're also defining a function called handleClick
that updates the count variable by calling the setCount
function with the new value of count + 1
. Finally, we're rendering the current value of count
in a paragraph tag, along with a button that calls the handleClick
function when clicked.
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.
Sometimes, we want to change an HTML5 input’s placeholder color with CSS.
To change an HTML5 input’s placeholder color with CSS, we use the ::placeholder
selector.
For instance, to set the input placeholder’s color to #909 we write:
::placeholder {
color: #909;
}
Updating data using EF Core is straightforward. Retrieve the entity, modify its properties, and call `SaveChanges()`. EF Core automatically generates the appropriate SQL statements to update the corresponding record in the database, making data updates a breeze.
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
HTTP response status codes indicate whether a specific HTTP request has been successfully completed.
The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.
The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is, no side effect), whereas successive identical POST requests may have additional effects, akin to placing an order several times.
It is possible to use PUT without a body like
PUT /example HTTP/1.0
Content-Type: text/plain
Content-Length: 0
A sample would be the github starring API, which uses PUT with an empty body to turn on a star and DELETE to turn off a star.
You can get private property like so:
Class class = new Class();
var privateProperty = class.GetType().GetProperty("privateProperty", BindingFlags.Instance | BindingFlags.NonPublic);
int propertyValue = (int) privateProperty.GetValue(class);
var privateField = class.GetType().GetField("privateField", BindingFlags.Instance | BindingFlags.NonPublic);
int fieldValue = (int) privateField.GetValue(class);
Entity Framework Core 5 is the first EF version to support filtering in Include
.
Supported operations are Where
, OrderBy
(Descending)/ThenBy
(Descending), Skip
, Take
Some usage example
context.Customers
.Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.OrderDetails)
.Include(c => c.Orders).ThenInclude(o => o.Customer)
Only one filter is allowed per navigation, so for cases where the same navigation needs to be included multiple times (e.g. multiple ThenInclude on the same navigation) apply the filter only once, or apply exactly the same filter for that navigation.
In the example below, we have a list of numbers. The ForEach method is called on the list and a lambda expression num => Console.WriteLine(num) is passed as the argument. This lambda expression takes each element num from the list and prints it using Console.WriteLine. The lambda acts as the action to be performed on each element in the list.
var numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.ForEach(num => Console.WriteLine(num));
The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
Spread operator doing concat
let arrayOne = [1, 2, 3];
let arraryTwo = [4, 5];
arrayCombined = [...arrayOne,...arrayTwo];
Add item using spread operator
let arrayOne = [1, 2, 3];
arrayNew = [...arrayOne, 3];
Inline functions allow you to write code for event handling directly in JSX. See the example below:
import React from "react";
const App = () => {
return (
<button onClick={() => alert("Hello!")}>Say Hello</button>
);
};
export default App;
Another common use case for event handlers is passing a parameter to a function in React so it can be used later. For example:
import React from "react";
const App = () => {
const sayHello = (name) => {alert(`Hello, ${name}!`);
};
return (
<button onClick={() => {sayHello("John");}}>Say Hello</button>
);
};
export default App;
React hooks are functions that let you use state and other React features in functional components. They provide an easier way to manage component state, handle side effects, and access lifecycle methods. Hooks like useState and useEffect help you write cleaner and more reusable code, making React development easier and more intuitive.
This is an elementary guide to Git for beginners. Git is a version-control system for tracking changes in files associated with projects of different types. It is primarily used for source-code management in software development, but it can be used to keep track of changes in any set of files.
Without a version control system, you probably used to frequently save copies of your work-in-progress in zip files. But when you feel that your work is a mess and you need to get back to a previous version of some files, how to deal with mixed changes in files? It’s a real pain to do that. Git and other version control systems like SVN are a great solution.
React Router is a popular routing library for building single-page web applications with React, a JavaScript library for building user interfaces. Routing in web applications is the process of determining which components or views to display based on the URL or user navigation. React Router provides a way to handle routing in React applications by allowing you to map different URLs to specific components, enabling the creation of multi-page experiences within a single-page application (SPA).
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
R452b ist ein nichtozonabbauendes, Hydrofluorolefine (HFOs)-basiertes Kältemittel
Eine zukunftssichere und nachhaltige Investition ist heute nur noch mit natürlichen Kältemitteln, die bereits seit mehr als hundert Jahren erfolgreich eingesetzt werden, möglich.
Systeme mit natürlichen Stoffen mit niedrigem Treibhauspotential, wie Kohlenwasserstoffe, Kohlendioxid oder Ammoniak, können sowohl die Einträge von TFA deutlich verringert als auch das Klima geschützt werden.
Auf europäischer Ebene gibt es Bestrebungen HFO-Kältemittel aufgrund ihrer starken Umweltschädigung schnellstmöglich zu verbieten!
R 410A gehört zu den synthetischen Kältemitteln, die in Kälte- und Klimaanlagen und Wärmepumpen verwendet werden.
R 410A ist zwar nicht ozonschädlich, jedoch mit einem GWP (Global Warming Potential)-Wert von 2088 ein Treibhausgas.
Natürliche Kältemittel
Kältemittel | Toxizität | Brenbarkeit | |
R-290 Propan | 3 | Gering | Hoch |
R-717 Ammoniak | 0 | Hoch toxisch | Gering |
R-1270 Propen | 3 | Gering | Hoch |
R-744 CO2 | 1 | Gering | Nicht brennbar |
Synthetische, in der Luft stabile Kältemittel
Kältemittel | GWP | Toxizität | Brenbarkeit |
R32 | 675 | Gering | Gering |
R-407 C | 1770 | Gering | Nicht brennbar |
R-410 A/C | 2090 | Gering | Nicht brennbar |
R-452 B | 698 | Gering | Gering |
R-454 A/C | 466 | Gering | Gering |
Generell wird zwischen natürlichen und synthetischen Kältemitteln unterschieden. Zu den natürlichen Kältemitteln zählt man z. B. Kohlenwasserstoffe, Kohlenstoffdioxid, Ammoniak, Wasser und Luft – also Stoffe, die es so in der Natur gibt. Natürliche Kältemittel haben demnach auch geringe Auswirkungen auf die Umwelt.
Synthetische Kältemittel dagegen werden künstlich hergestellt. Sie werden chemisch auch als halogenierte Kohlenwasserstoffe bezeichnet und eignen sich ebenfalls hervorragend für den Einsatz in Klimaanlagen und Wärmepumpen.
Alle Kältemittel haben ihre Berechtigung, denn jedes Kältemittel hat andere Merkmale und Eigenschaften. Manche eignen sich für den Heizbetrieb besonders gut, andere eignen sich vor allem zum Kühlen. Die Wahl des Kältemittels bestimmt den Energieverbrauch, die Aufstellmöglichkeiten und die Kosten der jeweiligen Anlage.
Opteon™ XL20 (R-454C) ist ein leicht entflammbares Kältemittel mit einem Erderwärmungspotenzial (GWP) von weniger als 150.
Für viele Haustechnikprodukte wie z.B. lokale Kompakt-Klimageräte gilt bereits ein gesetzlich vorgeschriebener maximaler GWP-Wert von 150 (super low GWP). R454C unterschreitet diesen Grenzwert. Mit einem GWP von 148 hat R454C ein ca. 14-fach geringeres Treibhauspotential als das bisher übliche Kältemittel R410A.
Weitere Informationen
C# expression operators are fundamental tools for performing computations and evaluating conditions in code.
By understanding and utilizing these operators, you gain powerful tools to perform calculations, make decisions, and control the behavior of your C# programs.
C# Lambda expression operator (=>) is a shorthand syntax for defining anonymous functions. It allows you to write compact and inline functions without the need to declare a separate method. Lambdas are commonly used in LINQ queries, event handlers, and functional programming. They improve code readability, enable concise operations on collections, and provide a flexible way to work with data and delegates.
In lambda expressions, the lambda operator =>
separates the input parameters on the left side from the lambda body on the right side.
Here's an example that calculates the square of each number in a list:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> squaredNumbers = numbers.Select(x => x * x).ToList();
// squaredNumbers will be [1, 4, 9, 16, 25]
In this code, we have a list of numbers. Using the Select
method and a Lambda expression x => x * x
, we square each number in the list. The Lambda expression takes an input x
and returns its square x * x
. Finally, we have a new list squaredNumbers
containing the squared values of the original numbers. Lambda expressions are versatile and enable concise operations on collections, making code more expressive and readable.
If you use the same query in multiple places, consider adding a wrapper hook to keep your code clean:
function useAllBooks() {
return useQuery("books", getAllBooks)
}
function Component1() {
const {...} = useAllBooks()
return (...)
}
function Component2() {
const {...} = useAllBooks()
return (...)
}
This useArticleQuery
hook is designed to handle data fetching for articles based on the provided articleId
using the TanStack Query useQuery
function.
export const useArticleQuery = (articleId) => {
return useQuery({
queryKey: ["articles", articleId],
queryFn: () => getArticles(articleId)
});
};
The code snippet defines a custom hook called useArticleQuery
using the export
keyword, indicating it can be imported and used in other modules.
Inside the hook, the useQuery
function is called with an object as its argument. The object has two properties:
queryKey
: It is an array containing two elements: "articles" and articleId
. This array is used as a key to identify the query.
queryFn
: It is a function that gets executed to fetch the articles based on the given articleId
. The specific implementation of getArticles
is not shown in the provided code snippet.
The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.
Syntax: {cond ? <A /> : <B />}
means “if cond
, render <A />
, otherwise <B />
”.
Sample
{itemCollapsed ? (
<CommandItem title='Expand' />
) : (
<CommandItem title='Collapse' />
)}
In React it often comes up when you want to render some JSX when the condition is true, or render nothing otherwise.
Syntax: {cond && <A />}
means “if cond
, render <A />
, otherwise nothing”.
Sample
{article.content.length > 0 && (
<ArticleContent content={article.content} slug={article.slug} />
)
To align content like buttons to the right you can use CSS flexible box layout.
<div class='align-right'>
<button>Cancel</button>
<button type='submit'>Create</button>
</div>
The CSS to align the buttons on the right uses two properties.
.align-right {
display: flex;
justify-content: flex-end;
}
References
To do a case-sensitive search in EF Core you can use an explicit collation in a query like
var customers = context.Customers
.Where(c => EF.Functions.Collate(c.Name, "SQL_Latin1_General_CP1_CS_AS") == "John")
.ToList();
Note: EF Core does not support operators on in-memory collections other than simple Contains with primitive values.
References
Resources
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
Example
Using a callback, you could call the calculator function (myCalculator) with a callback (myCallback), and let the calculator function run the callback after the calculation is finished:
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
In the example above, myDisplayer is a called a callback function.
It is passed to myCalculator() as an argument.
Note
When you pass a function as an argument, remember not to use parenthesis.
Right: myCalculator(5, 5, myDisplayer);
Wrong: myCalculator(5, 5, myDisplayer());
What's the best way to get the data of a promise response of a useQuery() dependant query?
Option 1: you can check if data is available via isSuccess
:
const { isSuccess, data } = useQuery(
['articles', articleId],
getArticleById,
)
if (isSuccess) {
return data.map(...) // <-- data is guaranteed to be defined
}
Option 2: you can simply check if data exists, or use optional chaining:
const { isSuccess, data } = useQuery(
['articles', articleId],
getArticleById,
)
return data?.map(...) ?? null // <-- make sure to handle fallback with ??
You can assign a new value to clear or reset a useRef in your React app. For example, if you have a useRef called myRef, you can reset it by setting it to null or any other value you want. Here's an example:
import React, { useRef } from 'react';
function MyComponent() {
const myRef = useRef(null);
function handleClick() {
myRef.current = null; // reset the ref
}
return (
<div>
<button onClick={handleClick}>Reset Ref</button>
</div>
);
}
In this example, we create a useRef called myRef and initialize it to null. Then, we define a handleClick function that sets myRef.current to null when the button is clicked. This effectively resets the ref.
Note: Resetting a ref may not always be necessary or desirable, and you should only do it if it makes sense for your specific use case.
Question: How can I check if a string is empty?
Option 1: Check using ""
if (str === "") {
}
Note: to know if it's an empty string use === instead of ==. This is because === will only return true if the values on both sides are of the same type, in this case a string. for example: (false == ""
) will return true, and (false === ""
) will return false.
Option 2: Check length of string
if (!str || str.trim().length === 0) {
}
In this Snipp we show how to create a loading spinner component in React JS using pure CSS.
1. Create the React component to display the spinner
// Spinner.jsx
import React from "react";
import "./spinner.css";
export default function Spinner() {
return (
<div className='container'>
<div className='loader'></div>
</div>
);
}
2. Add CSS styles for loading spinner animation
/* spinner.css */
.container {
display: grid;
justify-content: center;
align-items: center;
}
.loader {
border: 3px solid #f3f3f3;
border-top: 3px solid #3498db;
border-radius: 50%;
width: 25px;
height: 25px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
Additional Resources:
Question: How do you convert a nullable bool? to a bool in C#?
Solution:
You can use the null-coalescing operator: x ?? something
, where something
is a boolean value you want to use if x
is null
.
Example:
bool? nullBool = null;
bool convertedBool = nullBool ?? false; // convertedBool will be false
The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.
Question: For me, if I invalidate the query, only the last page gets refetched and rendered. I want to fetch all of the pages
Solution: queryCache.clear()
does the trick for me
Additional resources:
Sometimes is helpful to know the scroll height of the window. Let's look at an example.
Suppose we have a component with two elements: a navigator and a main component.
import React from 'react';
import Nav from './Nav';
import Main from './Main';
export default const Page = () => {
return (
<div className = 'Page'>
<Nav/>
<Main/>
</div>
);
}
Let's suppose that Page.js
is a flex-box, Nav.js
is a sticky element, and Main.js
has a position: absolute
element inside of it.
If the element with absolute position is larger than the size of main, the sticky navigator will not work as expected (it won't stick).
We'll need to resize the Main.js
component and make it as big as the scroll height of the window. To do so, we need to read scrollHeight
property.
import React, { useEffect, useState } from 'react';
export default const Main = () => {
const [height, setHeight] = useState(0);
useEffect( () => { setHeight(document.documentElement.scrollHeight) });
return (
<div className = 'Main' style = {{height: `${height}px`}}>
<div className = 'Absolute'>This is an absolute positioned element.</div>
</div>
);
}
Now the main component will expand and the sticky element will work as expected.
Azure Key Vault is a cloud-based secrets store for holding app secrets, including configuration values like passwords and connection strings that must always remain secure. It keeps secrets in a single central location and provides secure access, permissions control, and access logging.
Use Azure Key Vault to store secrets like Passwords, Shared Access Signature (SAS) tokens, Application Programming Interface (API) keys, and Personal Access Tokens (PAT).
The definition of the CSS class
.rotate{
width:80px;
height:80px;
animation: rotation infinite 3s linear;
}
Here we added an animation property with a value rotation infinite 3s linear, which is.
rotation
: this is the name of the animation.infinite
: the animation should play infinitely.3s
: animation duration.linear
: play the animation at the same speed from start to end.Source: How to rotate an image continuously in CSS | Reactgo