Snippset
Filter by Set

Snipps

JavaScript by Benjamin
...see more
 

In JavaScript, functions cannot directly return multiple values. To achieve this, you can return an array or an object containing the values. Returning an object allows for more readable and maintainable code by assigning names to each value. The ES6 syntax { firstName, lastName } simplifies this by directly returning the values as an object with named properties. In React's useState, this approach is useful when returning multiple pieces of state from a custom hook, making the returned state properties easily accessible via object destructuring.

Read more at Returning Multiple Values from a Function (javascripttutorial.net)

JavaScript by Benjamin
...see more

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.

...see more

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

React by Patrik
...see more

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.

 

React by Patrik
...see more

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

EF Core by Marlon
...see more

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

.NET by Jerry
...see more

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# by Gregory
...see more

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# by Jarvis
...see more

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)

C# by Myles
...see more

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."
.NET by Roman
...see more

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.
  • The ?. 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.
C# by Shawn
...see more

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
  1. We use LINQ extension methods 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).
  2. Finally, we use ToList() to convert the filtered enumerable to a List<string>.
C# by Nélio
...see more

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);
C# by Nélio
...see more

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

EF Core by Jarvis
...see more

In EF Core, joining a subquery with two columns (INNER JOIN table) can be achieved using LINQ syntax. Below is an example of how to do this:

var query = from user in context.Users
            join post in context.Posts
            on new { UserId = user.Id, IsPublished = true }
            equals new { post.UserId, IsPublished = true }
            select new
            {
                user.Username,
                post.Title
            };

In this example

  • The LINQ query joins the Users and Posts tables on two columns (UserId and a condition IsPublished) using the equals keyword.
  • In a LINQ join operation, you need to match corresponding columns or properties from the joined tables/entities. In the case of UserId = user.Id, you are matching the UserId column from the Post entity with the Id column from the User entity.

Additional reading at EF Core Join Query - TekTutorialsHub

...see more

To join a subquery (INNER JOIN table) in EF Core, you can use the Join method along with LINQ expressions. Below is a example code snippet:

var query = from order in context.Orders
            join orderItem in context.OrderItems
            on order.OrderId equals orderItem.OrderId
            where order.CustomerName == "John Doe"
            select new
            {
                order.OrderId,
                order.CustomerName,
                orderItem.ProductName,
                orderItem.Price
            };

The expression on order.OrderId equals orderItem.OrderId is used to specify the join condition between two tables/entities (Orders and OrderItems  based on their related columns OrderId.

Additional Reading at EF Core Inner Join (csharptutorial.net)

...see more

This code sample show how to insert an entity Element without updating related entities.

_dbContext.Entry<Element>(element).State = EntityState.Added;

// Set the state of the Category navigation property of 'element' to Unchanged
_dbContext.Entry<Category>(element.Category).State = EntityState.Unchanged;

// Detach all roles associated with the 'element' from the DbContext
element.Roles.ToList().ForEach(r => _dbContext.Entry<Role>(r).State = EntityState.Detached);

// Mark the Roles collection of 'element' as not modified to prevent updating roles
_dbContext.Entry<Element>(element).Collection(r => r.Roles).IsModified = false;

await _dbContext.SaveChangesAsync();
  • The element's associated Category object to Unchanged in the _dbContext. This indicates that the Category object is not modified and should not be updated in the database.
  • For each Role, it sets the state to Detached. Detaching an entity means it is no longer tracked by the EF Core context for changes.
  • The IsModified property of the Roles collection in the element is explicitly set to false. This indicates to EF Core that the Roles collection has not been modified and should not be updated in the database.
EF Core by Jarvis
...see more

To inspect the SQL generated by your LINQ query, you can convert the LINQ query to a SQL string using the ToQueryString() method.

// Example LINQ query
var query = from o in context.Orders;

// Convert LINQ query to SQL string
string sqlQuery = query.ToQueryString();
Console.WriteLine(sqlQuery);

This code snippet demonstrates how to generate and inspect the SQL query string using LINQ in C# useful for debugging and optimization purposes.

...see more

To group in EF Core using LINQ query syntax, use the group by clause followed by the grouping key and aggregate functions as needed. For example, to group a collection of items by a property called "Category" and count the items in each group:

var groupedData = from item in dbContext.Items
                  group item by item.Category into grouped
                  select new { Category = grouped.Key, Count = grouped.Count() };
Add to Set
  • .NET
  • .NET 6.0 Migration
  • 5 Best websites to read books online free with no downloads
  • 5 surprising things that men find unattractive
  • 5 Ways To Take Control of Overthinking
  • 6 simple methods for a more productive workday
  • 6 Ways To Stop Stressing About Things You Can't Control
  • Add React to ASP.NET Core
  • Adding reCAPTCHA to a .NET Core Web Site
  • Admin Accounts
  • Adobe Acrobat
  • Afraid of the new job? 7 positive tips against negative feelings
  • Agile
  • AKS and Kubernetes Commands (kubectl)
  • API Lifecycle Management
  • arc42
  • Article Writing Tools
  • Atlassian
  • Azure API Management
  • Azure App Registration
  • Azure Application Gateway
  • Azure Arc
  • Azure Arc Commands
  • Azure Architectures
  • Azure Bastion
  • Azure Bicep
  • Azure CLI Commands
  • Azure Cloud Products
  • Azure Cognitive Services
  • Azure Container Apps
  • Azure Cosmos DB
  • Azure Cosmos DB Commands
  • Azure Costs
  • Azure Daily
  • Azure Daily 2022
  • Azure Daily 2023
  • Azure Data Factory
  • Azure Database for MySQL
  • Azure Databricks
  • Azure Diagram Samples
  • Azure Durable Functions
  • Azure Firewall
  • Azure Functions
  • Azure Kubernetes Service (AKS)
  • Azure Landing Zone
  • Azure Log Analytics
  • Azure Logic Apps
  • Azure Maps
  • Azure Monitor
  • Azure News
  • Azure PowerShell Cmdlets
  • Azure PowerShell Login
  • Azure Private Link
  • Azure Purview
  • Azure Redis Cache
  • Azure Security Groups
  • Azure Sentinel
  • Azure Service Bus
  • Azure Service Bus Questions (FAQ)
  • Azure Services Abstract
  • Azure SQL
  • Azure Tips and Tricks
  • Backlog Items
  • BASH Programming
  • Best LinkedIn Tips (Demo Test)
  • Best Practices for RESTful API
  • Bing Maps
  • Birthday Gift Ideas for Wife
  • Birthday Poems
  • Black Backgrounds and Wallpapers
  • Bootstrap Templates
  • Brave New World
  • Brian Tracy Quotes
  • Build Websites Resources
  • C# Development Issues
  • C# Programming Guide
  • Caching
  • Caching Patterns
  • Camping Trip Checklist
  • Canary Deployment
  • Careers of the Future You Should Know About
  • Cheap Vacation Ideas
  • Cloud Computing
  • Cloud Migration Methods
  • Cloud Native Applications
  • Cloud Service Models
  • Cloudflare
  • Code Snippets
  • Compelling Reasons Why Money Can’t Buy Happiness
  • Conditional Access
  • Configurations for Application Insights
  • Create a Routine
  • Create sitemap.xml in ASP.NET Core
  • Creative Writing: Exercises for creative texts
  • CSS Selectors Cheat Sheet
  • Cultivate a Growth Mindset
  • Cultivate a Growth Mindset by Stealing From Silicon Valley
  • Custom Script Extension for Windows
  • Daily Scrum (Meeting)
  • Dalai Lama Quotes
  • DataGridView
  • Decision Trees
  • Deployments in Azure
  • Dev Box
  • Development Flows
  • Docker
  • Don’t End a Meeting Without Doing These 3 Things
  • Drink More Water: This is How it Works
  • Dropdown Filter
  • Earl Nightingale Quotes
  • Easy Steps Towards Energy Efficiency
  • EF Core
  • Elon Musk
  • Elon Musk Companies
  • Employment
  • English
  • Escape Double Quotes in C#
  • Escaping characters in C#
  • Executing Raw SQL Queries using Entity Framework Core
  • Factors to Consider While Selecting the Best Earthmoving System
  • Feng Shui 101: How to Harmonize Your Home in the New Year
  • Flying Machines
  • Foods against cravings
  • Foods that cool you from the inside
  • Four Misconceptions About Drinking
  • Fox News
  • Free APIs
  • Funny Life Quotes
  • Generate Faces
  • Generate Random Numbers in C#
  • Genius Money Hacks for Massive Savings
  • GitHub
  • GitHub Concepts
  • Green Careers Set to Grow in the Next Decade
  • Habits Of Highly Stressed People and how to avoid them
  • Happy Birthday Wishes & Quotes
  • Helm Overview
  • How to Clean Floors – Tips & Tricks
  • How to invest during the 2021 pandemic
  • How To Make Money From Real Estate
  • How To Stop Drinking Coffee
  • Image for Websites
  • Inspirational Quotes
  • Iqra Technology, IT Services provider Company
  • Jobs Of 2050
  • jQuery
  • jQuery plugins
  • JSON for Linking Data (JSON-LD)
  • Json to C# Converters
  • Karen Lamb Quotes
  • Kubernetes Objects
  • Kubernetes Tools
  • Kusto Query Language
  • Lack of time at work? 5 simple tricks to help you avoid stress
  • Lambda (C#)
  • Last Minute Travel Tips
  • Last-Minute-Reisetipps
  • Latest Robotics
  • Leadership
  • List Of Hobbies And Interests
  • Logitech BRIO Webcam
  • Management
  • Mark Twain Quotes
  • Markdown
  • Meet Sophia
  • Message-Oriented Architecture
  • Microservices
  • Microsoft Authenticator App
  • Microsoft Power Automate
  • Microsoft SQL Server
  • Microsoft Teams
  • Mobile UI Frameworks
  • Motivation
  • Multilingual Applications
  • NBC News
  • NuGet
  • Objectives and Key Results (OKR)
  • Objectives and Key Results (OKR) Samples
  • OKR Software
  • Online JSON Viewer and Parser
  • Outlook Automation
  • PCMag
  • Phases of any relationship
  • Playwright
  • Popular cars per decade
  • Popular Quotes
  • PowerShell
  • PowerShell Array Guide
  • PowerShell Coding Samples
  • PowerToys
  • Prism
  • Pros & Cons Of Alternative Energy
  • Quill Rich Text Editor
  • Quotes
  • RACI Matrix
  • Razor Syntax
  • Reasons why singletasking is better than multitasking
  • Regular Expression (RegEx)
  • Resize Images in C#
  • RESTful APIs
  • Rich Text Editors
  • Rob Siltanen Quotes
  • Robots
  • Run sudo commands
  • Salesforce Offshore Support Services Provider
  • Salesforce Offshore Support Services Providers
  • Sample Data
  • Save Money On Food
  • Score with authenticity in the job interview
  • Security
  • Semantic Versioning
  • Serialization using Thread Synchronization
  • Service Worker
  • Snipps
  • Speak and Presentation
  • SQL References
  • SQL Server Full-Text Search
  • Successful
  • Surface Lineup 2021
  • Surface Lineup 2021 Videos
  • SVG Online Editors
  • Team Manifesto
  • Technologies
  • Technology Abbreviations
  • Technology Glossary
  • TechSpot
  • That is why you should drink cucumber water every day
  • The Cache Tag Helper in ASP.NET Core
  • The Verge
  • Theodore Roosevelt Quotes
  • These 7 things make you unattractive
  • Things Successful People Do That Others Don’t
  • Things to Consider for a Great Birthday Party
  • Things to Consider When Designing A Website
  • Thoughts
  • TinyMCE Image Options
  • TinyMCE Toolbar Options
  • Tips for a Joyful Life
  • Tips for fewer emails at work
  • Tips for Making Better Decisions
  • Tips for Managing the Stress of Working at Home
  • Tips for Writing that Great Blog Post
  • Tips On Giving Flowers As Gifts
  • Tips you will listen better
  • Top Fitness Tips
  • Top Healthy Tips
  • Top Money Tips
  • Top Ten Jobs
  • Track Authenticated Users in Application Insights
  • Unicode Characters
  • Visual Studio 2022
  • Vital everyday work: tips for healthy work
  • Walking barefoot strengthens your immune system
  • Walt Disney Quotes
  • Ways for Kids to Make Money
  • Web Design Trends & Ideas
  • Web Icons
  • Web Scraping
  • Webhooks
  • Website Feature Development
  • What are my options for investing money?
  • What happens when you drink water in the morning
  • What Is Stressful About Working at Home
  • What To Eat For Lunch
  • Windows 11 Top Features You Should Know
  • Winston Churchill Quotes
  • XPath
  • You'll burn out your team with these 5 leadership mistakes
  • ZDNet
 
Sets