Snippset
Search by Set

Snippset Feed

Azure by Martin
...see more

Are you just starting your cloud journey or looking for ways to upgrade your knowledge in specific areas? Azure Charts is a web-based application that allows you to see what Azure consists of and how it evolves. 

thumbnail image 2 of blog post titled 
	
	
	 
	
	
	
				
		
			
				
						
							Azure Charts Visualize your cloud learning journey

References

.NET by Patrik
...see more

In C#, Task.Delay and Thread.Sleep are both used to introduce delays or pauses in the execution of your code, but they have different use cases and implications.

In summary, use Task.Delay when working with asynchronous code and you want to avoid blocking the current thread. Use Thread.Sleep when you explicitly want to block the current thread, but be cautious about using it in scenarios where responsiveness is important, such as in GUI applications. In modern C# applications, with the widespread use of async/await, Task.Delay is often the more appropriate choice.

Further Resources:

.NET by Patrik
...see more

The Thread.Sleep Method Suspends the current thread for the specified amount of time.

  • Thread.Sleep is a synchronous method that blocks the current thread for the specified amount of time.
  • It's generally used in non-async scenarios or when dealing with multi-threading where you explicitly want to pause the execution of the current thread.
  • It can introduce responsiveness issues, especially in GUI applications, as it will freeze the UI during the sleep period.

Example:

void MyMethod()
{
    // Do something before the delay
    Thread.Sleep(1000); // Sleep for 1000 milliseconds (1 second)
    // Do something after the delay
}
.NET by Patrik
...see more

The Task.Delay Method creates a task that will complete after a time delay.

  • Task.Delay is generally preferred when working with asynchronous programming using async and await.
  • It returns a Task that represents a time delay.
  • It doesn't block the calling thread. Instead, it allows the thread to be released and continue with other work while waiting for the specified time to elapse.
  • It's more suitable for scenarios where you want to introduce a delay without blocking the execution of the current method or freezing the user interface in GUI applications.

Example:

async Task MyMethod()
{
    // Do something before the delay
    await Task.Delay(1000); // Delay for 1000 milliseconds (1 second)
    // Do something after the delay
}
.NET by Patrik
...see more

In C#, you can replace multiple white spaces with a single white space using regular expressions. You can use the Regex class from the System.Text.RegularExpressions namespace to achieve this. Here's an example:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string inputString = "This   is   a    sample    string   with   multiple   spaces.";

        // Use regular expression to replace multiple white spaces with a single white space
        string result = Regex.Replace(inputString, @"\s+", " ");

        Console.WriteLine("Original string: " + inputString);
        Console.WriteLine("Modified string: " + result);
    }
}

In this example, the \s+ regular expression pattern matches one or more white spaces, and the Regex.Replace method replaces these occurrences with a single white space.

Additional Resources

EF Core by Patrik
...see more

Make EF Core update only the updated properties by turning the disconnected scenario to connected.

public void SaveBook(Book book)
{
    // Here, 'book' is the book with the changed Title.
    using(var context = new TestContext())
    {
        var dbBook = context.Books.Find(book.ID);

        // Copy book's property values to dbBook.
        context.Entry(dbBook).CurrentValues.SetValues(book);

        context.SaveChanges();
    }
}

There may be good reasons to prefer the latter method above the former.

EF Core by Patrik
...see more

Instruct EF Core to create a migration named InitialCreate:

Add-Migration InitialCreate

EF Core will create a directory called Migrations in your project, and generate some files. It's a good idea to inspect what exactly EF Core generated - and possibly amend it - but we'll skip over that for now.

EF Core by Patrik
...see more

You can remove the latest migration with the following command:

Remove-Migration
EF Core by Patrik
...see more

You can list all existing migrations as follows:

Get-Migration
EF Core by Patrik
...see more

Create a database and create your schema from the migration. This can be done via the following:

Update-Database

That's all there is to it - your application is ready to run on your new database, and you didn't need to write a single line of SQL. Note that this way of applying migrations is ideal for local development, but is less suitable for production environments - see the Applying Migrations page for more info.

.NET by Patrik
...see more

OriginalString and AbsoluteUri have different behaviors.

AbsoluteUri does escaping

Uri uri = new Uri("http://www.example.com/test.aspx?v=hello world");

Console.WriteLine(uri.OriginalString);
// http://www.example.com/test.aspx?v=hello world

Console.WriteLine(uri.AbsoluteUri);
// http://www.example.com/test.aspx?v=hello%20world  <--  different

AbsoluteUri doesn't support relative URIs

var uri = new Uri("/test.aspx?v=hello world", UriKind.Relative);

Console.WriteLine(uri.OriginalString);
// /test.aspx?v=hello world

Console.WriteLine(uri.AbsoluteUri);
// InvalidOperationException: This operation is not supported for a relative URI.
.NET by Patrik
...see more

In .NET, the System.Uri class is used to represent URIs. You can create a Uri object by passing a URI string to its constructor. The Uri class provides various properties and methods for working with different components of the URI, such as the scheme, host, path, query, and fragment.

Here's a simple example in C#:

// Creating a Uri object
Uri uri = new Uri("https://www.example.com/path/to/resource");

// Accessing components of the URI
Console.WriteLine($"Scheme: {uri.Scheme}");
Console.WriteLine($"Host: {uri.Host}");
Console.WriteLine($"Path: {uri.AbsolutePath}");
Console.WriteLine($"Query: {uri.Query}");

This example demonstrates creating a Uri object from a URL string and accessing different components of the URI using properties like Scheme, Host, AbsolutePath, and Query.

...see more

Make Axios send cookies in its requests automatically.

You can use the withCredentials property.

axios.get(BASE_URL + '/todos', { withCredentials: true });

Also it is possible to force credentials to every Axios requests

axios.defaults.withCredentials = true

Or using credentials for some of the Axios requests as the following code

const instance = axios.create({
   withCredentials: true,
   baseURL: BASE_URL
})
instance.get('/todos')
Azure by Martin
...see more

Source app settings from key vault

Complete reference:

@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)

Alternatively:

@Microsoft.KeyVault(VaultName=myvault;SecretName=mysecret)

Source: Use Key Vault references - Azure App Service | Microsoft Learn

...see more

Arrays are ordered collections of values, and they are perhaps the most commonly used data structure in JavaScript. Elements in an array can be accessed by their index, and arrays can hold values of different data types.

let myArray = [1, 2, 3, 4, 5];
console.log(myArray[0]); // Accessing the first element

 

...see more

Objects in JavaScript are collections of key-value pairs. They are versatile and can be used to represent a wide range of data structures. Objects are often used for creating dictionaries, maps, and records.

let person = {
    name: "Maria",
    age: 28,
    city: "New York"
};
console.log(person.name); // Accessing a property

Keys are always strings (or Symbols, introduced in ES6). When you use non-string values as keys in an object, JavaScript implicitly converts them to strings.

Objects are generally used for a simple dictionary-like structure with string keys.

.NET by Patrik
...see more

The following code shows modifying of list2 does not affect list1 because list2 is a separate copy of list1.

List<string> list1 = new List<string>();
List<string> list2 = new List<string>(list1);

list2.Add("Item A");

Console.WriteLine("List1 elements:");
list1.ForEach(item => Console.WriteLine(item));

This will output list1 without any item.

List1 elements:

Explanation of copying the List

You can use the List<T> constructor with the original list as an argument to create a new list that is a separate copy of the original list. This constructor creates a new list with the same elements as the original list.

.NET by Patrik
...see more

To illustrate the issue the following code assigns list1 directly to list2.

List<string> list1 = new List<string>();
List<string> list2 = list1;

list2.Add("Item A");

Console.WriteLine("List1 elements:");
list1.ForEach(item => Console.WriteLine(item));

This will output the list1 elements and show 'Item A'.

List1 elements:
Item A

As you can see, modifying list2 also modified list1.

Explanation of direct assignment issue

When you assign one list to another using list2 = list1, you're not creating a new list. Instead, both list1 and list2 will point to the same list in memory. Any changes made to one list will be reflected in the other because they are essentially the same list.

EF Core by Patrik
...see more

In this example, you can see how you can manually manage a transaction around your database operations, providing more fine-grained control when needed. However, for most scenarios, the default behavior of wrapping SaveChanges in a transaction is sufficient.

using (var dbContext = new YourDbContext())
{
    using (var transaction = dbContext.Database.BeginTransaction())
    {
        try
        {
            // Perform your database operations here

            dbContext.SaveChanges();

            // If everything is successful, commit the transaction
            transaction.Commit();
        }
        catch (Exception ex)
        {
            // Handle exceptions and optionally roll back the transaction
            transaction.Rollback();
        }
    }
}

In this example, you can see how you can manually manage a transaction around your database operations, providing more fine-grained control when needed. However, for most scenarios, the default behavior of wrapping SaveChanges in a transaction is sufficient.

...see more
Iqra Technology, IT...

Iqra Technology is an IT Solutions and Services Company. We are a salesforce and Microsoft partner company. We aim to provide cost-effective IT services within the customer’s budget range. We scrutinize, design, and develop solutions custom-made for the business necessities. We deliver services in various domains including CRM, ERP, e-commerce, CMS, business intelligence, web development, customized applications, portals, mobile apps, & RPA technologies. We provide IT services starting from $2100 per month and 2 weeks free trial. https://iqratechnology.com/

...see more
Windows 11 Top Features You...

If you just switched to the new Windows version, here are some of the most interesting Windows 11 features that you should know about:

...see more
Tips you will listen better

Who doesn't know this? You have something on your mind and want to tell the other person how you feel and what's on your mind. However, the other person, unfortunately, does not listen properly and you do not feel understood. 

Unfortunately, most people are poor listeners. Good listeners have often undergone special training or have made listening to their profession. But what does good listening actually mean? How can you listen better and give your counterpart an appreciative feeling? In the following, I would like to show you three tips that will help you become a better listener.

...see more
Vital everyday work: tips...

A large proportion of German employees suffer from recurring chronic back pain, which, according to medical experts, is mainly caused by immobile sitting in everyday working life.

In the following, you will find out what a vital workday can do for your health. First, however, you should start at the basis of your every day (work) life.

...see more
Foods that cool you from...

Do you not know where to go with you because of the heat? Rescue is at hand! According to traditional Chinese medicine, these foods provide a large portion of cooling.

The fan has given up the ghost, your feet are boiling, and you don't know if that thing on your neck is a head or a hotplate? We feel you! We can't offer you a nice igloo in the Arctic at the moment, but at least the heat buildup in your body can be solved with smart decisions when eating.

...see more
Save Money On Food

Doesn’t it make sense then to try to save as much of your hard-earned money as possible? The less you spend, the more you have.

Here are some money tips you can use to save big on many of your expenses.

...see more
Cultivate a Growth Mindset

Vasily Alekseyev was tricked into lifting 500 pounds over his head.

Until 1970, many weightlifters had only come close to cracking that psychological barrier.

So when his trainers told him that the bar was loaded with slightly less than 500 pounds, a weight he’d lifted before, he threw it up like a matchstick.

Only they had lied—he’d actually lifted 500.5 pounds. Over the next seven years, he continued to smash records, topping out at 564 before retiring.

Because seeing is believing, many others started lifting 500+ soon after.

Remember Roger Bannister? Until 1954, everyone believed a human couldn't run a mile in under four minutes. Then Roger did it, and his record stood for only 46 days. In the next 50 years, more than a thousand runners beat the four-minute mile.

What changed? Only a belief in what’s possible.

...see more
These 7 things make you...

A few everyday things make us look immediately unattractive to our counterpart - at least, that's what science says.

Do you get too little sleep and are often in a bad mood? Then watch out! These and other everyday things that seem supposedly "normal" to us have a negative impact on your attractiveness. Scientists have found out which behaviors don't go down well and cast a bad light on us:

...see more
Walking barefoot...

Walking barefoot is the natural way for humans to walk why it's worthwhile to go barefoot more often.

For thousands of years, our ancestors stomped around barefoot. Only recently have people started to squeeze into socks and shoes with rubber soles, completely isolating themselves from the earth's surface - yet walking with bare feet brings so many health benefits. Because walking barefoot...

...see more
Lack of time at work? 5...

Too many tasks and too little time is a permanent condition for you? Do you feel stressed and are unproductive? Poor time management is often to blame. With these 5 tips, you'll finally get the hang of it.

Everyone has 24 hours in a day, yet some people seem to use them better than others. Those who cultivate poor time management struggle to complete their tasks. The consequences: Constant stress and declining productivity. These tips (from Focus Online) show you how good time management works and bring peace back into your workday.

...see more
Reasons why singletasking...

Our society places great value on multitasking. So, too, are our work environments designed for multitasking: Now more than ever, we use computers and networks that offer instant messaging, email, and other "productive" tools. We are constantly jumping back and forth between them.

Multitasking includes three different types:

Performing two or more tasks simultaneously.

Switching back and forth between tasks.

Performing a series of tasks in rapid succession.

While this way of working seems normal to many people, multitasking is a disadvantage. If we use single-tasking instead and consciously approach each project "task-by-task," we can be very productive.

The fastest way to get many things done is to do one thing at a time.

...see more
Four Misconceptions About...

At least two liters a day should be. You should definitely drink before sports ... There are plenty of myths about drinking. But which ones are really true?

...see more
6 simple methods for a more...

Many of us find it difficult to follow through on all work tasks and figure out how to continue to be as productive as possible after an extended period of physical and social isolation. With a little mindfulness, planning ahead, and acknowledging what's actually going well, it's possible to jumpstart productivity with new strategies. These six simple methods will help you be more productive in your workday:

...see more
What happens when you drink...

This is what happens when you drink water in the morning on an empty stomach.

These 7 things happen when you drink water after waking up on an empty stomach, from weight loss to visibly healthier hair.

We hear again and again that sufficient liquid is important for our body. But what happens when water is drunk directly after getting up? We'll tell you:

...see more
Careers of the Future You...

How would the world look like 5, 10, or 15 years from now? Well, indeed, no one can predict.

Monitoring the changing pattern of technological usage & growth can help understand how the professional world may change in the future.

A career you may want to pursue, or a career you already have may shape up to be quite a boom in years to come.

In this blog, we shall shed some light on in-demand careers which we believe shall grow in years to come.

...see more
Score with authenticity in...

In the job interview, it is important to score points with professional competence and personality. In recent years, soft skills have become increasingly important compared to pure hard skills. Companies are looking for a "team fit" rather than a pure "skill fit. The problem with personality traits is that, in comparison to hard skills, they cannot be proven with a certificate. Companies are therefore not only looking for personalities. They are looking for personalities that are as authentic as possible. Here I explain how you can present yourself as authentically as possible.

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
  • Application Insights
  • 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 Storage Account
  • 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 Cmdlets
  • 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 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