Lanyon A Simple Blogger template

Free tutorials, courses, generative tools, and projects built with Javascript, PHP, Python, ML, AI,.Net, C#, Microsoft, Youtube, Github Code Download and more.

March 2023

Archive for March 2023

Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course


Curriculum for the course Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course

Learn how to build a dashboard that generates RegEx using the OpenAI API and a low code tool called Retool. The dashboard allows users to input a string, write a description of the desired RegEx, and generate the code to transform the string accordingly. 💻 You can find the iframe code here: https://github.com/kubowania/regex-openai ✏️ This course was created by @AniaKubow . 🏗 Retool provided a grant to make this course possible. Learn more about Retool: https://retool.com ⭐️ Contents ⭐️ (0:00) Introduction (2:36) Writing our own regex code (5:06) Creating the header element (8:11) Creating the text area (11:35) How to create a custom code editor (16:32) Creating the new button (19:08) Setting up the sidebar (20:58) Configuring the open api api (22:51) The body of the example example (24:58) Setting up the code 🎉 Thanks to our Champion and Sponsor supporters: 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Erdeniz Unvan 👾 Justin Hual 👾 Agustín Kussrow 👾 Otis Morgan -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news

Watch Online Full Course: Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course


Click Here to watch on Youtube: Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course


This video is first published on youtube via freecodecamp. If Video does not appear here, you can watch this on Youtube always.


Udemy Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course courses free download, Plurasight Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course courses free download, Linda Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course courses free download, Coursera Use ChatGPT to Build a RegEx Generator – OpenAI API Low Code Course course download free, Brad Hussey udemy course free, free programming full course download, full course with project files, Download full project free, College major project download, CS major project idea, EC major project idea, clone projects download free

Design a Cloud Book Reading Application - Software Architect Mock Interview

Are you ready to Ace your next Software Architect job interview?

In this video, Keith Galley conducts a mock full-length real-world coding technical interview with Kylie Ying for a software engineering role. They discuss how to use object-oriented programming and dynamic programming to solve questions and get the job you want.

Technical interviews are challenging for software engineers as they require working on solutions, optimizing them, and writing code or pseudo code on the spot. The purpose of these interviews is to assess problem-solving abilities, understanding of data structures and algorithms, coding level, and coding ability. In this mock interview, Keith Galley will ask Kylie Ying questions similar to those in a real software engineering interview. The interview questions for Software Engineer job in a Product or Service company would cover below topics in details.

Design a Cloud Book Reading Application - Software Architect Mock Interview
Design a Cloud Book Reading Application - Software Architect Mock Interview

Understanding the reasoning behind technical interviews

  • Technical interviews help interviewers evaluate candidates' problem-solving skills, ability to understand problems deeply, and optimize solutions.
  • These interviews also assess candidates' knowledge of data structures and algorithms as well as their coding proficiency.

Introduction to the mock interview

  • Keith Galley will conduct a mock interview with Kylie Ying.
  • The questions asked will resemble those in real software engineering interviews.
  • The specific question is unknown to Kylie Ying beforehand.

Designing an online Cloud reading application

The problem scenario involves designing a book system for an online Cloud reading application. The requirements include:

  • Users should have a library of books that they can add or remove from.
  • Users can set a book from their library as active.
  • The reading application should remember the last page the user read in a given book.
  • The reading application should display one page of text at a time in the active book.

Object-oriented design for the book system

To implement the book system, two classes are suggested:

  1. Book class:
    • Attributes: title, content (pages), last page
    • Methods: display page, turn

Introduction to Indexing Content

  • The speaker discusses the use of a mono-spaced font for indexing content.
  • Characters per page are determined and used to index into the content.
  • Turning the page triggers a function call.

Granularity and Function Customization

  • The granularity of turning pages is discussed.
  • The advantage of having a customizable function is highlighted.

Multiple Users Sharing Books

  • Consideration is given to multiple users sharing books in the system.
  • Customization may be specific to each user, while books and content are shared among all users.

Storing Books in a Database Table

  • Books can be stored in a database table, such as SQL.
  • Each book can have an ID, title, and content stored in the table.
  • Customization are per user, while books and content remain common.

Handling Duplicate Entries in the Table

  • When adding to the collection, check if the title and content already exist in the table.
  • If they do, return the existing book instead of creating a duplicate entry.

Designing an Algorithm for Detecting Plagiarism

  • The task is to design an algorithm that detects the two most likely books with plagiarism.
  • Plagiarism is defined as having the longest shared common section of text.
  • The length of the shared section should be determined.

Understanding Sub strings and Consecutive Characters

  • Sub strings are explained using examples.
  • Consecutive characters are not necessary for a sub string, as long as the characters appear in order.

Class Breakdown

  • Suggests further breakdown of classes to improve the solution.
  • Proposes a separate display class to handle font sizes, characters per page, etc.

Critique on ID Structure

  • Comments on the structure of IDs and suggests adding more details for robustness.
  • Mentions the idea of retroactively grabbing an ID based on title or book contents.

Feedback on IDS and Book Identification

  • Suggests using title and author as a better solution for book identification.
  • Acknowledges the challenge of not having access to a proper library system.

Breaking Down Components

  • Suggests breaking down components into separate classes, such as user-specific book classes.

Positive Feedback on Algorithm Solution Approach

  • Commends the candidate for explaining their thoughts and considering pros and cons during algorithm solution.
  • Appreciates the iterative approach in finding a more optimal solution.

Dynamic Programming Solution Discussion

  • Highlights the challenge in formulating a dynamic programming solution.
  • Mentions potential improvements regarding tenses and punctuation matching.

Positive Feedback on Dynamic Programming Solution

  • Praises the candidate for running with the dynamic programming solution once given a starting point.
  • Recognizes the optimal nature of the longest common subsequence or substring approach.

Reflection on Interview Performance

  • Reflects on the challenging nature of the problem and areas for improvement.
  • Discusses the importance of rebound

Design a Cloud Book Reading Application - Software Architect Mock Interview

Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod


Curriculum for the course Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod

Use Flutter 3.7 to build a Twitter clone in this full course. We will cover various features such as signing up and signing in with email and password, tweeting text, images, and links, identifying and storing hashtags, displaying tweets, liking tweets, retweeting, commenting/replying, following users, searching for users, displaying followers, following, and recent tweets, editing user profiles, showing tweets with specific hashtags, and a premium feature called "Twitter Blue". Additionally, we will also be implementing a notifications tab that will show notifications when someone replies to you, follows you, likes your tweet or retweets. By the end of this tutorial, you'll have a fully-functional Twitter clone that you can further customize and improve upon. Tech Used - Flutter, Appwrite Authentication, Database, Storage, Realtime, Queries, Indexes, Riverpod. Prerequisites: Flutter & Dart Basics ✏️ Course developed by @RivaanRanawat 💻 Source Code - https://github.com/RivaanRanawat/flutter_twitter_clone 📌 Discord Server (Join the Community) - https://discord.gg/Q8Rx8YWFVF ADB Command - adb reverse tcp:3000 tcp:3000 📄 Resources: Assets - https://github.com/RivaanRanawat/flutter_twitter_clone/tree/master/assets/svgs Asset Constants File - https://github.com/RivaanRanawat/flutter_twitter_clone/blob/master/lib/constants/assets_constants.dart Pallete (Colours File) - https://github.com/RivaanRanawat/flutter_twitter_clone/blob/master/lib/theme/pallete.dart Theme File - https://github.com/RivaanRanawat/flutter_twitter_clone/blob/master/lib/theme/app_theme.dart Appwrite Docs - https://appwrite.io/docs ⭐️ Contents ⭐️ (0:00:00) Introduction (0:02:07) Appwrite & Docker Installation (0:05:31) Important Appwrite Commands (0:07:14) Appwrite Setup for Android & iOS (0:09:32) Setting up Flutter Project (0:17:59) Architectural & Folder Pattern (0:24:37) Login UI (0:49:53) Signup UI (0:55:23) Signing Up User with Appwrite Auth (1:16:37) Providing the Class / Dependency Injection (1:25:03) Signing Up User contd. (Auth Controller) (1:49:11) Login User with Appwrite Auth (1:54:12) Adding Proper Navigation (1:57:22) Persisting Auth State (2:06:37) Saving User Data to Appwrite Database (2:33:03) FIXING Android Related Problems (2:34:31) Solving Appwrite unauthorized_scope Problem (2:36:27) Home Screen UI (2:44:43) Create Tweet Screen UI (2:58:16) FIXING User Data Storage & Retrieval Bug (3:00:43) Create Tweet Screen UI contd. (3:08:23) Picking Multiple Images & Displaying in Carousel (3:17:48) Storing Tweets to Appwrite Database & Appwrite Storage (4:01:46) Displaying Tweets (4:38:07) Displaying New Tweets LIVE with Appwrite Realtime (5:01:04) Like Button Animation (5:04:53) Liking Tweet (5:16:38) Retweeting / Resharing Tweet (Realtime) (5:40:52) Replying to other user’s Tweets (6:18:06) Searching Users (6:37:21) Displaying User Profiles (7:04:39) Editing User Own Profile (7:31:57) Updating User Profile Data Realtime (7:41:30) Following Other users (7:52:54) Sending Notifications when User Likes (8:10:07) FIXING Like Bug (8:10:58) Displaying & Sending Notifications (8:38:47) Displaying Posts By Hashtags (8:48:57) Side Drawer UI & Navigation to Current User Profile (8:54:11) TWITTER BLUE (8:59:23) Logging Out with Appwrite Auth (9:02:27) Conclusion 🎉 Thanks to our Champion and Sponsor supporters: 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Erdeniz Unvan 👾 Justin Hual 👾 Agustín Kussrow 👾 Otis Morgan -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news

Watch Online Full Course: Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod


Click Here to watch on Youtube: Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod


This video is first published on youtube via freecodecamp. If Video does not appear here, you can watch this on Youtube always.


Udemy Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod courses free download, Plurasight Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod courses free download, Linda Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod courses free download, Coursera Flutter App Development Course – Build a Twitter Clone with Appwrite and Riverpod course download free, Brad Hussey udemy course free, free programming full course download, full course with project files, Download full project free, College major project download, CS major project idea, EC major project idea, clone projects download free

React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP


Curriculum for the course React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP

Learn how to build a 3D animation in React, using technologies such as WebGi (powered by Three.js) and GSAP. First, we will learn how to find 3D models and display them on your website using WebGi. Then, we'll use React and GSAP to make a 3D animation of that model. Next we'll learn how to optimize 3D animations in React for mobile devices. Finally, we'll build this website for production and upload. ✏️ Course created by @CodewithSloba 🔗 Final website: https://sloba-3d-animation-iphone.netlify.app/ 🔗 Starter project: https://github.com/bobangajicsm/iphone-3d-website-starter 🔗 For full source code check https://patreon.com/CodewithSloba 🔗 Webgi SDK https://webgi.xyz/docs/index.html 🔗 3D model credit Reaper3D: https://sketchfab.com/3d-models/iphone-13-pro-max-4f92b60d824a42c89bbf1833374c4f73 🔗 Upload to https://www.netlify.com/ ⭐️ Chapters ⭐️ ⌨️ (0:00:00) Intro ⌨️ (0:01:27) Project setup ⌨️ (0:07:12) Building website navigation ⌨️ (0:15:02) Building jumbotron ⌨️ (0:21:42) Building sound section ⌨️ (0:29:27) Building display section ⌨️ (0:33:27) How to find and load 3D models ⌨️ (0:36:55) Building WebGi viewer component ⌨️ (0:53:17) Animating 3D model with GSAP scroll animation ⌨️ (1:13:42) Implementing 3D model preview mode ⌨️ (1:32:27) Optimizing 3D animation for mobile phones ⌨️ (1:43:31) Building production-ready website and uploading ⌨️ (1:45:07) Outro 🎉 Thanks to our Champion and Sponsor supporters: 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Erdeniz Unvan 👾 Justin Hual 👾 Agustín Kussrow 👾 Otis Morgan -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news

Watch Online Full Course: React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP


Click Here to watch on Youtube: React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP


This video is first published on youtube via freecodecamp. If Video does not appear here, you can watch this on Youtube always.


Udemy React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP courses free download, Plurasight React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP courses free download, Linda React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP courses free download, Coursera React 3D Animation Website Tutorial with ThreeJS (WebGi) & GSAP course download free, Brad Hussey udemy course free, free programming full course download, full course with project files, Download full project free, College major project download, CS major project idea, EC major project idea, clone projects download free

Discover .NET 7 SDK Containers – Support for Authentication and Cross-architecture Builds

Back in August we announced support for building container images directly from the .NET CLI. Now, for the release of the .NET 7.0.200 SDK, we’ve expanded on that support to enable pushing to authenticated registries, targeting cross-architecture container images, and made it easier than ever to support rootless containers. We’ve also invested in making it easier to get started with the new container tooling. In this post we’ll talk about all of these features, new to version 0.3.2 of the Microsoft.Net.Build.Containers package, as well as the roadmap for the future of .NET SDK container support.

If you’re eager to get started, you can skip ahead.

What’s all this again?

Before we dig deep into the changes in this version, it may be helpful to review where we stand today. In .NET 7.0.100, the .NET SDK gained the ability to create container images via the dotnet publish command. The tools to do this do a bunch of inference based on the properties of your project and its outputs, and then create the same image that a simple Dockerfile would create. It can take a few as three commands to create a new application and publish it as an image:

dotnet new webapi
dotnet add package Microsoft.Net.Sdk.Containers
dotnet publish -c Release -r linux-x64 --no-self-contained -p PublishProfile=DefaultContainer

These three commands

  • Create a new C# webapi project
  • Add the container support package to the project
  • Publish the project targeting the linux-x64 RuntimeIdentifier, using the mcr.microsoft.com/dotnet/aspnet:7.0 image as the base image, to a local Docker daemon

The intent of the tools are to reduce the concept count required to build containers and make it easier to get your code to the cloud.

If you’d like to learn more in general about containers and their benefits, there is a Learn module that I can recommend that goes into detail.

Registry Authentication

If you’ve worked with Docker before, you know that in order to use your images in production you typically have to push them to a remote registry of some kind. There are many different registries available, but they all share one thing in common – they require you to authenticate in order to push an image to them. In our initial release, we didn’t support authenticating to remote registries, but in this release we’ve integrated support for the same Docker authentication protocol that all container tooling relies on – config.json and the ecosystem of Docker credential helpers. Our tooling uses the superb ValleySoft.DockerCredsProvider library to seamlessly interact with your existing Docker credentials configuration, ensuring that pushing via the .NET SDK behaves exactly the same as via docker push. (As an aside, Matt has many helpful container-related libraries available on his GitHub page – I blanket recommend them all for working with containers and registries!) Let’s take a look at what it takes to push to GitHub Container Registry. For these next steps, I’m going to use my GitHub username (baronfel) and one of my demo apps (sdk-container-demo) as examples.

Authenticate to the registry

To authenticate to GitHub Container Registry you’ll need a GitHub Personal Access Token with the read:packages and write:packages permissions. First, login to GitHub Package Registry via the Docker CLI:

# Assume you have a GitHub Personal Access Token saved to the GITHUB_PACKAGE_PAT environment variable
echo $GITHUB_PACKAGE_PAT | docker login -n ghcr.io -u baronfel --password-stdin

Publish the app as a container image

Then, publish your application as a container image to that registry using the following command. Note that the ContainerImageName property requires using the GitHub user name or organization name as a kind of “namespace” for the generated container image:

dotnet publish -c Release --os linux --arch x64 \
    -p PublishProfile=DefaultContainer \
    -p ContainerRegistry=ghcr.io \
    -p ContainerImageName=baronfel/sdk-container-demo

For me, this is a lot to type out, so I like to save the parameters to a ‘Publish Profile’. You can read more about Publish Profiles at the Learn docs, but I think of them as a snippet of a project that I can reuse and refer to by name. To create a Publish Profile, I created a new file called github.pubxml in a Properties/PublishProfiles subdirectory of my project, and added the following contents:

<Project>
    <PropertyGroup>
        <ContainerRegistry>ghcr.io</ContainerRegistry>
        <ContainerImageName>baronfel/sdk-container-demo</ContainerImageName>
        <WebPublishMethod>Container</WebPublishMethod>
    </PropertyGroup>
</Project>

Now, I can publish with the following shorter command instead of the longer one from before:

dotnet publish -c Release --os linux --arch x64 -p PublishProfile=github

Much more readable! If you want to see a worked example, there is a repository that we’ve set up available at baronfel/sdk-container-demo. This repository shows GitHub actions workflows pushing to many of the most popular container registries – if you see one that you use missing from the list, please send a PR!

Authentication in Docker is a bit detailed, so if you’d like to read more on it we’ve got detailed documentation about it at Authenticating to container registries in our repository.

As of this release we are not aware of any incompatibilities with the major container registries. I want to take the time to shout out Norm Johanson from the AWS .NET SDK team, as well as his coworkers at the AWS Elastic Container Registry team, who took the time to contribute fixes for the way we handle the AWS ECR – without them it would have taken much longer! If you do encounter issues with registry communications please let us know by opening an issue at the GitHub repo!

Cross-architecture containers

It’s become very common for containers to be built for different platforms – while the default for Linux containers is x64, the rise of arm64 compute resources in cloud providers means that targeting that architecture is a requirement for container tooling. What this ends up looking like to the end user is a kind of container image called a manifest list – a container reference that brings together different platforms of the same image under a single name and tag. Microsoft-authored container images like mcr.microsoft.com/dotnet/runtime:7.0 are actually these manifest lists, built with support for multiple Linux and Windows architectures and versions. With this release of our container support package, we now use the RuntimeIdentifier passed to the publish command to help determine which specific platform should be used for your application when you use a manifest list as your base image. In concrete terms, this means that you can target runtimes other than linux-x64 in your publish command and the command will work, as long as your base image supports that runtime. For example, let’s build a version of an application that targets arm64 Linux:

dotnet publish -c Release -r linux -a arm64 -p PublishProfile=DefaultContainer

That’s all it takes to target your application for a different platform! If you choose a runtime identifier that your base image doesn’t support, we’ll tell you the ones it does support so you can update your commands.

And as always, all of this logic is completely customizable – if you specify a ContainerBaseImage that is very specific and points to only a single image – let’s say mcr.microsoft.com/dotnet/runtime:7.0-bullseye-slim-amd64 – then none of this code runs at all. You get exactly what you asked for.

Improved support for rootless containers

It’s more common than ever for containers to support running in a ‘rootless’ mode – one in which the container doesn’t need additional permissions to execute. Typically this means that the container doesn’t bind to ports below 1024, which require root access, and the application doesn’t attempt to write to the container file system. You can read about rootless containers for .NET in more detail in the Secure your .NET cloud apps with rootless Linux Containers blog post.

In previous versions of the SDK Container tooling we had logic that would attempt to enforce binding to specific ports on your behalf. That logic interfered with support for rootless containers, so we’ve removed it in this version. Instead, if the base image you’ve chosen to use defines any necessary ports we support those. As always you can define your own ports via the ContainerPort MSBuild Item in your project file or publish profile.

With this change, container images produced via the .NET SDK are completely compliant with rootless execution.

Easier ‘getting started’ path

For Web SDK projects, it’s easier than ever to start building containers. Simply add the <EnableSdkContainerSupport>true</EnableSdkContainerSupport> property to your project file and the .NET SDK will automatically include the necessary package reference to the tooling. The tooling that ships with the 7.0.200 .NET SDK is version 0.3.2, but you can change this at any time by setting the SdkContainerSupportPackageVersion to another version.

If you are using Visual Studio, the publish dialogs will automatically detect and add this property for you if you choose to use the .NET SDK to publish your containers, so you just need to check in that change.

For other project types, you’ll still need to add the PackageReference to Microsoft.Net.Build.Containers manually for now, but we are working on smoothing out the experience here in the future.

Roadmap for the future

Our roadmap for the next release is centered around fit and finish items – primarily moving the container capability completely into the .NET SDK and focusing on localization and error messages (especially from the Visual Studio experience). These mark the end of what I consider the ‘first phase’ of the containerization effort.

Moving the containerization capability directly into the .NET SDK means two things to us:

  • that it’s available to all project types out of the box with no additional PackageReferences or properties required, and
  • that updates to it ship on a consistent cadence, with the rest of the SDK

We hope to complete this work for the 7.0.300 release of the .NET SDK.

We also are investing in error messages for the various failure modes that can occur in the application. Currently, network errors with registries result in horrible stacktraces – we’d like to clean those up for presentation. We’d also like to do more precondition checking to fail fast with actionable errors, for instance in the case where you’re pushing to a local Docker daemon but the daemon isn’t yet started. We also want to take extra care to make sure that the Visual Studio experience receives the same fidelity of errors as the CLI experience. Because the Visual Studio implementation of the tooling is powered by a .NET 7 CLI application, it’s easy for us to emit errors in a form that Visual Studio can’t translate to the error pane. We’ll fix those and ensure uniform error reporting between the CLI and Visual Studio so that all of our users get the same level of actionable error reporting.

During this time we’re also investing in more integrations with partner teams, like the Docker tooling for Visual Studio and Visual Studio Code, the Oryx++ project, and the Azure Developer CLI. We’ll make changes required for those tools to successfully integrate with us, and as a result you should start to see these experiences ‘light up’ automatically. Things like F5-debugging in Visual Studio/Visual Studio Code should just work. Running azd up should be seamless. Our aim is to make this tooling a natural fit for your existing workflows. If you use other tools, please let us know so we can reach out to the authors for integrations!

After the 7.0.300 time frame, there are a number of areas we could explore. Image Indexes and authoring manifest lists in a single gesture might make it easier to autho the kinds of images that Microsoft ships for the runtime and ASP.NET Core each month. Improving our support for using local Dockerfiles as a base image would make it easier to commit to our tools without running into the limitations of a VM-less image creation model. Investing in better support for Windows Containers might make it easier for users investing in Windows to get their code onto cloud resources. We need your help to prioritize the work! Please let us know what you’d like to see by interacting with the issues and discussions on our repo.

Wrapping up

The 0.3.2 release of the .NET SDK Container tooling brings a host of new features like registry authentication, support for cross-architecture image builds, and support for rootless containers. The tooling is easier than ever to get started with, and is will continue to be invested into to improve the user experience.

I encourage you to take the tooling for a spin and create your own container images! Make sure to check out the docs to learn how to Containerize an app with dotnet publish. When you do, please reach out on the repo to let us know of any problems or features that you’d like to add. Happy building!

The post Discover .NET 7 SDK Containers – Support for Authentication and Cross-architecture Builds appeared first on .NET Blog.



Create a portfolio website without installing any tools

Create, customize, and deploy your own portfolio website in minutes without installing any tools. All you need is a GitHub account and a few minutes to get started. We will use GitHub Codespaces and Blazor to build the website and Azure Static Web Apps or GitHub Pages to deploy it.

GitHub Codespaces

Now, with GitHub Codespaces you can create your own portfolio website in minutes without any extra tools or lengthy environment setup! All you need is a GitHub account.

Follow these instructions to create your free GitHub account.

GitHub Codespaces is a development environment that is hosted in the cloud. This means that you can get started coding right away in your browser – we set everything up for you ahead of time! You do not need to worry about setting up the right coding editor or tools.

.NET Blazor Portfolio Site with GitHub Codespaces

With the .NET Blazor Portfolio Site project template, all you need to do is launch your Codespace then follow the README instructions to customize your website. The goal is to give you a template you can immediately utilize to create your own website through GitHub Codespaces.

This template shows you how to build your website using Blazor. Blazor is a UI Framework that lets you build frontend web applications with C#. The template is in the education/codespaces-project-template-dotnet on GitHub!

  • Who is this for? Anyone looking to create a portfolio site, learn web development, or test out Codespaces.
  • How much experience do you need? Zero. You decide how much you want to customize based on your experience, and time available.
  • Tools needed: None. No need to install anything! All you need is a GitHub account and web browser.
  • Prerequisites: None. This template includes your development environment and deployable web app for you to create your own site.

Get Started with the .NET Portfolio Website Template

  1. Go to the template

  2. Click Use this template then Create a new repository

    Use this template button

  3. Create a copy of the repository in your GitHub account. You can keep the repository name the same or change it if you would like.

  4. At the top of the README, click on the Open in GitHub Codespaces button

    Open in a Codespace

  5. The Codespace may take a few minutes to set up. Upon setup completion, you will be in a GitHub Codespace! Notice that it has the same layout as VS Code.

    Setting up Codespace

  6. Follow the README instructions to run your website. Use the swa start command.

  7. From here, you can continue to follow the instructions in the README to customize your portfolio website and deploy it!

When you’re finished, your site will look something like this!

Finished Blazor WASM portfolio site

Continue Learning

Want to learn more about building with C# and .NET? Check out the following resources.

The post Create a portfolio website without installing any tools appeared first on .NET Blog.



source https://devblogs.microsoft.com/dotnet/codespaces-template-blazor-portfolio-website/

Discover .NET 7 SDK Containers – Support for Authentication and Cross-architecture Builds

Back in August we announced support for building container images directly from the .NET CLI. Now, for the release of the .NET 7.0.200 SDK, we’ve expanded on that support to enable pushing to authenticated registries, targeting cross-architecture container images, and made it easier than ever to support rootless containers. We’ve also invested in making it easier to get started with the new container tooling. In this post we’ll talk about all of these features, new to version 0.3.2 of the Microsoft.Net.Build.Containers package, as well as the roadmap for the future of .NET SDK container support.

If you’re eager to get started, you can skip ahead.

What’s all this again?

Before we dig deep into the changes in this version, it may be helpful to review where we stand today. In .NET 7.0.100, the .NET SDK gained the ability to create container images via the dotnet publish command. The tools to do this do a bunch of inference based on the properties of your project and its outputs, and then create the same image that a simple Dockerfile would create. It can take a few as three commands to create a new application and publish it as an image:

dotnet new webapi
dotnet add package Microsoft.Net.Sdk.Containers
dotnet publish -c Release -r linux-x64 --no-self-contained -p PublishProfile=DefaultContainer

These three commands

  • Create a new C# webapi project
  • Add the container support package to the project
  • Publish the project targeting the linux-x64 RuntimeIdentifier, using the mcr.microsoft.com/dotnet/aspnet:7.0 image as the base image, to a local Docker daemon

The intent of the tools are to reduce the concept count required to build containers and make it easier to get your code to the cloud.

If you’d like to learn more in general about containers and their benefits, there is a Learn module that I can recommend that goes into detail.

Registry Authentication

If you’ve worked with Docker before, you know that in order to use your images in production you typically have to push them to a remote registry of some kind. There are many different registries available, but they all share one thing in common – they require you to authenticate in order to push an image to them. In our initial release, we didn’t support authenticating to remote registries, but in this release we’ve integrated support for the same Docker authentication protocol that all container tooling relies on – config.json and the ecosystem of Docker credential helpers. Our tooling uses the superb ValleySoft.DockerCredsProvider library to seamlessly interact with your existing Docker credentials configuration, ensuring that pushing via the .NET SDK behaves exactly the same as via docker push. (As an aside, Matt has many helpful container-related libraries available on his GitHub page – I blanket recommend them all for working with containers and registries!) Let’s take a look at what it takes to push to GitHub Container Registry. For these next steps, I’m going to use my GitHub username (baronfel) and one of my demo apps (sdk-container-demo) as examples.

Authenticate to the registry

To authenticate to GitHub Container Registry you’ll need a GitHub Personal Access Token with the read:packages and write:packages permissions. First, login to GitHub Package Registry via the Docker CLI:

# Assume you have a GitHub Personal Access Token saved to the GITHUB_PACKAGE_PAT environment variable
echo $GITHUB_PACKAGE_PAT | docker login -n ghcr.io -u baronfel --password-stdin

Publish the app as a container image

Then, publish your application as a container image to that registry using the following command. Note that the ContainerImageName property requires using the GitHub user name or organization name as a kind of “namespace” for the generated container image:

dotnet publish -c Release --os linux --arch x64 \
    -p PublishProfile=DefaultContainer \
    -p ContainerRegistry=ghcr.io \
    -p ContainerImageName=baronfel/sdk-container-demo

For me, this is a lot to type out, so I like to save the parameters to a ‘Publish Profile’. You can read more about Publish Profiles at the Learn docs, but I think of them as a snippet of a project that I can reuse and refer to by name. To create a Publish Profile, I created a new file called github.pubxml in a Properties/PublishProfiles subdirectory of my project, and added the following contents:

<Project>
    <PropertyGroup>
        <ContainerRegistry>ghcr.io</ContainerRegistry>
        <ContainerImageName>baronfel/sdk-container-demo</ContainerImageName>
        <WebPublishMethod>Container</WebPublishMethod>
    </PropertyGroup>
</Project>

Now, I can publish with the following shorter command instead of the longer one from before:

dotnet publish -c Release --os linux --arch x64 -p PublishProfile=github

Much more readable! If you want to see a worked example, there is a repository that we’ve set up available at baronfel/sdk-container-demo. This repository shows GitHub actions workflows pushing to many of the most popular container registries – if you see one that you use missing from the list, please send a PR!

Authentication in Docker is a bit detailed, so if you’d like to read more on it we’ve got detailed documentation about it at Authenticating to container registries in our repository.

As of this release we are not aware of any incompatibilities with the major container registries. I want to take the time to shout out Norm Johanson from the AWS .NET SDK team, as well as his coworkers at the AWS Elastic Container Registry team, who took the time to contribute fixes for the way we handle the AWS ECR – without them it would have taken much longer! If you do encounter issues with registry communications please let us know by opening an issue at the GitHub repo!

Cross-architecture containers

It’s become very common for containers to be built for different platforms – while the default for Linux containers is x64, the rise of arm64 compute resources in cloud providers means that targeting that architecture is a requirement for container tooling. What this ends up looking like to the end user is a kind of container image called a manifest list – a container reference that brings together different platforms of the same image under a single name and tag. Microsoft-authored container images like mcr.microsoft.com/dotnet/runtime:7.0 are actually these manifest lists, built with support for multiple Linux and Windows architectures and versions. With this release of our container support package, we now use the RuntimeIdentifier passed to the publish command to help determine which specific platform should be used for your application when you use a manifest list as your base image. In concrete terms, this means that you can target runtimes other than linux-x64 in your publish command and the command will work, as long as your base image supports that runtime. For example, let’s build a version of an application that targets arm64 Linux:

dotnet publish -c Release -r linux -a arm64 -p PublishProfile=DefaultContainer

That’s all it takes to target your application for a different platform! If you choose a runtime identifier that your base image doesn’t support, we’ll tell you the ones it does support so you can update your commands.

And as always, all of this logic is completely customizable – if you specify a ContainerBaseImage that is very specific and points to only a single image – let’s say mcr.microsoft.com/dotnet/runtime:7.0-bullseye-slim-amd64 – then none of this code runs at all. You get exactly what you asked for.

Improved support for rootless containers

It’s more common than ever for containers to support running in a ‘rootless’ mode – one in which the container doesn’t need additional permissions to execute. Typically this means that the container doesn’t bind to ports below 1024, which require root access, and the application doesn’t attempt to write to the container file system. You can read about rootless containers for .NET in more detail in the Secure your .NET cloud apps with rootless Linux Containers blog post.

In previous versions of the SDK Container tooling we had logic that would attempt to enforce binding to specific ports on your behalf. That logic interfered with support for rootless containers, so we’ve removed it in this version. Instead, if the base image you’ve chosen to use defines any necessary ports we support those. As always you can define your own ports via the ContainerPort MSBuild Item in your project file or publish profile.

With this change, container images produced via the .NET SDK are completely compliant with rootless execution.

Easier ‘getting started’ path

For Web SDK projects, it’s easier than ever to start building containers. Simply add the <EnableSdkContainerSupport>true</EnableSdkContainerSupport> property to your project file and the .NET SDK will automatically include the necessary package reference to the tooling. The tooling that ships with the 7.0.200 .NET SDK is version 0.3.2, but you can change this at any time by setting the SdkContainerSupportPackageVersion to another version.

If you are using Visual Studio, the publish dialogs will automatically detect and add this property for you if you choose to use the .NET SDK to publish your containers, so you just need to check in that change.

For other project types, you’ll still need to add the PackageReference to Microsoft.Net.Build.Containers manually for now, but we are working on smoothing out the experience here in the future.

Roadmap for the future

Our roadmap for the next release is centered around fit and finish items – primarily moving the container capability completely into the .NET SDK and focusing on localization and error messages (especially from the Visual Studio experience). These mark the end of what I consider the ‘first phase’ of the containerization effort.

Moving the containerization capability directly into the .NET SDK means two things to us:

  • that it’s available to all project types out of the box with no additional PackageReferences or properties required, and
  • that updates to it ship on a consistent cadence, with the rest of the SDK

We hope to complete this work for the 7.0.300 release of the .NET SDK.

We also are investing in error messages for the various failure modes that can occur in the application. Currently, network errors with registries result in horrible stacktraces – we’d like to clean those up for presentation. We’d also like to do more precondition checking to fail fast with actionable errors, for instance in the case where you’re pushing to a local Docker daemon but the daemon isn’t yet started. We also want to take extra care to make sure that the Visual Studio experience receives the same fidelity of errors as the CLI experience. Because the Visual Studio implementation of the tooling is powered by a .NET 7 CLI application, it’s easy for us to emit errors in a form that Visual Studio can’t translate to the error pane. We’ll fix those and ensure uniform error reporting between the CLI and Visual Studio so that all of our users get the same level of actionable error reporting.

During this time we’re also investing in more integrations with partner teams, like the Docker tooling for Visual Studio and Visual Studio Code, the Oryx++ project, and the Azure Developer CLI. We’ll make changes required for those tools to successfully integrate with us, and as a result you should start to see these experiences ‘light up’ automatically. Things like F5-debugging in Visual Studio/Visual Studio Code should just work. Running azd up should be seamless. Our aim is to make this tooling a natural fit for your existing workflows. If you use other tools, please let us know so we can reach out to the authors for integrations!

After the 7.0.300 time frame, there are a number of areas we could explore. Image Indexes and authoring manifest lists in a single gesture might make it easier to autho the kinds of images that Microsoft ships for the runtime and ASP.NET Core each month. Improving our support for using local Dockerfiles as a base image would make it easier to commit to our tools without running into the limitations of a VM-less image creation model. Investing in better support for Windows Containers might make it easier for users investing in Windows to get their code onto cloud resources. We need your help to prioritize the work! Please let us know what you’d like to see by interacting with the issues and discussions on our repo.

Wrapping up

The 0.3.2 release of the .NET SDK Container tooling brings a host of new features like registry authentication, support for cross-architecture image builds, and support for rootless containers. The tooling is easier than ever to get started with, and is will continue to be invested into to improve the user experience.

I encourage you to take the tooling for a spin and create your own container images! Make sure to check out the docs to learn how to Containerize an app with dotnet publish. When you do, please reach out on the repo to let us know of any problems or features that you’d like to add. Happy building!

The post Discover .NET 7 SDK Containers – Support for Authentication and Cross-architecture Builds appeared first on .NET Blog.



source https://devblogs.microsoft.com/dotnet/updates-to-container-support-in-the-dotnet-sdk/

Learn Vite – Frontend Build Tool Course


Curriculum for the course Learn Vite – Frontend Build Tool Course

Learn how to use Vite, a build tool and development server designed specifically for modern web development. This course covers various topics, including creating a static server, using templates, integrating Tailwind, using environment variables, deploying to GitHub, Netlify, and Vercel, and configuring Vite. It also discusses the features of Vite, including hot module replacement and static asset handling. ✏️ Course created by @KhattakDev YouTube: https://youtube.com/khattakdev Twitter: https://twitter.com/khattakdev Instagram: https://www.instagram.com/khattakdev ⭐️ Contents ⭐️ ⌨️ (0:00:00) Start ⌨️ (0:00:22) Learning Objectives ⌨️ (0:01:29) Introduction ⌨️ (0:02:50) What makes it fast? ⌨️ (0:04:49) Creating Static Server ⌨️ (0:17:29) Using Templates ⌨️ (0:24:39) Tailwind Integration ⌨️ (0:32:30) Env Variables ⌨️ (0:40:58) Deployments ⌨️ (1:00:22) Configurations ⌨️ (1:30:35) Wrap Up 🎉 Thanks to our Champion and Sponsor supporters: 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Erdeniz Unvan 👾 Justin Hual 👾 Agustín Kussrow 👾 Otis Morgan -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news

Watch Online Full Course: Learn Vite – Frontend Build Tool Course


Click Here to watch on Youtube: Learn Vite – Frontend Build Tool Course


This video is first published on youtube via freecodecamp. If Video does not appear here, you can watch this on Youtube always.


Udemy Learn Vite – Frontend Build Tool Course courses free download, Plurasight Learn Vite – Frontend Build Tool Course courses free download, Linda Learn Vite – Frontend Build Tool Course courses free download, Coursera Learn Vite – Frontend Build Tool Course course download free, Brad Hussey udemy course free, free programming full course download, full course with project files, Download full project free, College major project download, CS major project idea, EC major project idea, clone projects download free

Django Project – Code a CRM App Tutorial


Curriculum for the course Django Project – Code a CRM App Tutorial

Learn how to build a CRM (Customer Relationship Management) App with Django, Python, and MySQL. The app will use MySQL for the database. We'll be able to Register, Log In, Log Out, Add Records, View Records, Update Records, and Delete Records. ✏️ Course created by John Elder. Check out his channel: https://www.youtube.com/@Codemycom 💻 Github Code: https://github.com/flatplanet/Django-CRM 🔗 MySQL Download: https://dev.mysql.com/downloads/installer/ ⭐️ Contents ⭐️ 0:00:00 Introduction 0:01:50 Installation and App Setup 0:06:45 MYSQL Configuration 0:13:18 Version Control Git and Github.com 0:18:14 Build Out The Basic App 0:28:46 Login Users 0:47:32 Logout Users 0:51:45 Register Users 1:15:00 Database Model 1:25:48 View Records On Website 1:31:01 Bootstrap Table 1:38:23 Individual Records 1:48:41 Bootstrap Card 1:56:51 Delete Record 2:01:05 Add New Records 2:12:10 Update Records 2:20:06 Push Code To Github 2:20:54 Conclusion 🎉 Thanks to our Champion and Sponsor supporters: 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Erdeniz Unvan 👾 Justin Hual 👾 Agustín Kussrow 👾 Otis Morgan -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news

Watch Online Full Course: Django Project – Code a CRM App Tutorial


Click Here to watch on Youtube: Django Project – Code a CRM App Tutorial


This video is first published on youtube via freecodecamp. If Video does not appear here, you can watch this on Youtube always.


Udemy Django Project – Code a CRM App Tutorial courses free download, Plurasight Django Project – Code a CRM App Tutorial courses free download, Linda Django Project – Code a CRM App Tutorial courses free download, Coursera Django Project – Code a CRM App Tutorial course download free, Brad Hussey udemy course free, free programming full course download, full course with project files, Download full project free, College major project download, CS major project idea, EC major project idea, clone projects download free

File and Folder dialogs in .NET MAUI with CommunityToolkit

Note: This is a guest blog post by Vladislav Antonyuk, who is a senior software engineer at DataArt and a core contributor of the .NET MAUI Community Toolkit.

Interacting with files and folders is a routine task for countless applications, yet it often involves writing tedious platform-specific code.

The good news is that the new CommunityToolkit.Maui version 5.0 now contains the enhanced versions of FolderPicker and FileSaver classes which provide an easy way to select target folders and save files to the filesystem across all the .NET MAUI platforms.

FileSaver

By using FileSaver, your application can offer users a convenient dialog that allows them to choose a destination folder. With only a few lines of code, you can then save any file type, including documents, images, videos, and more.

Here’s an example of how you can use FileSaver in C#:

using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Community Toolkit!"));
var fileSaveResult = await FileSaver.Default.SaveAsync("sample.txt", stream, cancellationToken);
if (fileSaveResult.IsSuccessful)
{
    await Toast.Make($"File is saved: {fileSaveResult.FilePath}").Show(cancellationToken);
}
else
{
    await Toast.Make($"File is not saved, {fileSaveResult.Exception.Message}").Show(cancellationToken);
}

This code opens a filesystem dialog, that allows the user to choose the target file location, creates a new file called “sample.txt” and writes a stream with the text “Hello from the Community Toolkit!” to it. Users can also change the file name to suit their needs.

FileSaver Dialog on Windows

FileSaver catches all exceptions and returns the operation result. However, if you would like to handle only specific exceptions like the user cancels the operation, you can wrap code in a try/catch and call the EnsureSuccess method:

using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Community Toolkit!"));
try
{
    var fileSaverResult = await FileSaver.SaveAsync("initial-path", "sample.txt", stream, cancellationToken);
    fileSaverResult.EnsureSuccess();

    await Toast.Make($"File is saved: {fileSaverResult.FilePath}").Show(cancellationToken);
}
catch (Exception ex)
{
    await Toast.Make($"File is not saved, {ex.Message}").Show(cancellationToken);
}

A more complete example of using FileSaver is in my MauiPaint sample application. This is how it works on macOS:

Note: Android Developers should provide permission to work with file storage.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

FolderPicker

FolderPicker is another powerful capability that can be found as part of CommunityToolkit.Maui which allows users to select folders in the filesystem using a UI dialog. With FolderPicker developers can easily get information about the selected folder such as its name and path.

Here’s an example of how FolderPicker can be used in C#:

var folderPickerResult = await folderPicker.PickAsync(cancellationToken);
if (folderPickerResult.IsSuccessful)
{
    await Toast.Make($"Folder picked: Name - {folderPickerResult.Folder.Name}, Path - {folderPickerResult.Folder.Path}", ToastDuration.Long).Show(cancellationToken);
}
else
{
    await Toast.Make($"Folder is not picked, {folderPickerResult.Exception.Message}").Show(cancellationToken);
}

This code prompts the user to select a folder, and the result of the operation will be stored in the “folderPickerResult” variable.

FolderPicker Dialog on Windows

Again, it’s a good idea to wrap in a try/catch in case you prefer to use the EnsureSuccess method:

try
{
    var folderPickerResult = await FolderPicker.Default.PickAsync("initial-path", cancellationToken);
    folderPickerResult.EnsureSuccess();
    await Toast.Make($"Folder picked: Name - {folderPickerResult.Folder.Name}, Path - {folderPickerResult.Folder.Path}", ToastDuration.Long).Show(cancellationToken);
}
catch (Exception ex)
{
    await Toast.Make($"Folder is not picked, {ex.Message}").Show(cancellationToken);
}

Note: Android Developers should provide permission to work with file storage.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Summary

FileSaver and FolderPicker are two powerful new tools that can be found as part of the CommunityToolkit.Maui library. They make it easy for developers to collaborate with the filesystem to manage the files and folders. As usual, further information about these two APIs can be found in the documentation.

If you’re a developer working with C# and .NET MAUI, give them a try today and see how they can help get better integration with the OS filesystem.

Finally, be sure to check out the full release notes for version 5.0 for even more great resources for .NET MAUI developers.

The post File and Folder dialogs in .NET MAUI with CommunityToolkit appeared first on .NET Blog.



source https://devblogs.microsoft.com/dotnet/file-and-folder-dialogs-communitytoolkit/

Generate images with AI using Stable Diffusion, C#, and ONNX Runtime

Stable Diffusion is an AI model used to generate images based on text prompts. Using ONNX Runtime you can quickly get started generating AI images locally using your preferred .NET technologies like C# and Visual Studio!

What is ONNX Runtime?

The Open Neural Network Exchange (ONNX) is an open source format to represent AI models. The ONNX Runtime (ORT) is a runtime for ONNX models which provides an interface for accelerating the consumption / inferencing of machine learning models, integrating with hardware-specific libraries, and sharing models across programming languages and frameworks like PyTorch, Tensorflow / Keras, scikit-learn, ML.NET, and others.

That means you can:

  1. Train a model in one of the many popular machine learning frameworks that support ONNX conversion.
  2. Convert your model into ONNX format.
  3. Load and consume the ONNX model in a different framework or language than the one the model was originally trained with like C#.

To learn more, visit the ONNX and ONNX Runtime websites.

What is Stable Diffusion?

Stable Diffusion is an AI model that can generate images based on a text prompt.

Image showing input and outputs of Stable Diffusion model

How does Stable Diffusion work?

Although the theory and innovations behind Stable Diffusion can be complex, it’s made up of relatively few components.

The main components in Stable Diffusion are:

  • Text encoder – Encodes text to embeddings. The sample referenced in this post uses a combination of ONNX Runtime Extensions implementation of the OpenAI’s Contrastive Language-Image Pre-Training (CLIP) and ONNX models.
  • Variable Autoencoder (VAE) – Encodes and decodes images to embeddings.
  • U-Net – Neural network architecture typically used for the task of image segmentation.
  • Scheduler – Computes denoised image embeddings. The sample referenced in this post uses a C# implementation of the Linear Multistep (LMS) Discrete Scheduler.

For more details on Stable Diffusion, see the original paper High-Resolution Image Synthesis with Latent Diffusion Models.

Image showing high-level process of Stable Diffusion model

At a high level, the process for generating images using Stable Diffusion consists of 3 steps:

  1. Encoding text prompt and random noise into text and image embeddings.
  2. Use a U-Net neural network and scheduler to reduce noise (denoise) in the image.
  3. Decoding the denoised image.

Generate text and image embeddings

The first step in using Stable Diffusion to generate AI images is to:

  1. Generate an image sample and embeddings with random noise.
  2. Use the ONNX Runtime Extensions CLIP text tokenizer and CLIP embedding ONNX model to convert the user prompt into text embeddings.

Embeddings are a numerical representation of information such as text, images, audio, etc. This numerical representation contains semantic meaning. In the case of Stable Diffusion, the text and images are encoded into an embedding space that can be understood by the U-Net neural network as part of the denoising process.

OpenAI’s CLIP text tokenizer is written in Python. Instead of reimplementing it in C#, ONNX Runtime has created a cross-platform implementation using ONNX Runtime Extensions. ONNX Runtime Extensions is a library that extends the capability of the ONNX models and inference with ONNX Runtime by providing common pre and post-processing operators for vision, text, and NLP models.

Note that for training, you’ll also need to use the VAE to encode the images you use during training. The sample referenced in this post is inferencing only, so using the VAE is not required.

This code sample shows the general process of tokenizing and encoding the input text prompt. Some code has been ommitted for brevity.

var prompt = "a fireplace in an old cabin in the woods";
//...
var textTokenized = TextProcessing.TokenizeText(prompt);
var textPromptEmbeddings = TextProcessing.TextEncoder(textTokenized).ToArray();

Denoise image loop

The image and text embeddings are the initial input for the U-Net model. The U-Net model then reduces the noise (denoises) in the image using the text prompt as a conditional.

Using a scheduler algorithm, the output from the U-Net model is then used to compute new image embeddings. These new image embeddings are then used as the new input for the U-Net model.

This denoising process is repeated for N number of steps.

This code sample shows the general process that takes place when the text and image embeddings are run through the U-Net and denoised by the scheduler. Some code has been ommitted for brevity.

//...
var scheduler = new LMSDiscreteScheduler();
//...
var timesteps = scheduler.SetTimesteps(numInferenceSteps);
//...
var seed = new Random().Next();
var latents = GenerateLatentSample(batchSize, height, width, seed, scheduler.InitNoiseSigma);
//...
var unetSession = new InferenceSession(modelPath, options);
var input = new List<NamedOnnxValue>();
//...
for (int t = 0; t < timesteps.Length; t++)
{
    //...
    var latentModelInput = TensorHelper.Duplicate(latents.ToArray(), new[] { 2, 4, height / 8, width / 8 });
    //...
    latentModelInput = scheduler.ScaleInput(latentModelInput, timesteps[t]);
    //...
    input = CreateUnetModelInput(textEmbeddings, latentModelInput, timesteps[t]);
    var output = unetSession.Run(input);
    //...
    noisePred = performGuidance(noisePred, noisePredText, guidanceScale);
    //...
    latents = scheduler.Step(noisePred, timesteps[t], latents);
}

Decode denoised image

After the loop to denoise the image completes, the VAE is used to decode the final image embeddings back into an image.

This code sample shows the general process of using the VAE to decode the final denoised output into an image. Some code has been ommitted for brevity.

var decoderInput = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor("latent_sample", latents) };
var imageResultTensor = VaeDecoder.Decoder(decoderInput);
var image = VaeDecoder.ConvertToImage(imageResultTensor);

Get started generating images using AI

Now that you have a general idea of how Stable Diffusion works, it’s time to unleash your creativity!

To get started using AI to generate your own images inside your .NET applications, check out the Inference Stable Diffusion with C# and ONNX Runtime tutorial and corresponding GitHub repository.

The post Generate images with AI using Stable Diffusion, C#, and ONNX Runtime appeared first on .NET Blog.



source https://devblogs.microsoft.com/dotnet/generate-ai-images-stable-diffusion-csharp-onnx-runtime/

Introducing the Reliable Web App Pattern for .NET

The first step of your application’s cloud journey often times is the most difficult. It’s not uncommon to find you need to scale a legacy application to meet increased business demand, but do so with minimal investments in code changes and infrastructure.

Moving the application to the cloud is a great way to achieve scale and resiliency to support increased business demand, but how do you take that first step with your existing application to get it ready? How can you feel more confident about the cloud journey before you get started?

The reliable web app pattern (RWA) is here to help you on your cloud journey.

The Reliable Web App Pattern

The RWA is a set of best practices built on the Azure Well-Architected Framework that helps developers successfully migrate to the cloud and set a foundation for future modernization in Azure.

The reliable web app pattern provides guidance on several business and technical objectives with focus on low-cost, high-value wins. It provides guidance on security, reliability design patterns, operational excellence, cost-optimized environments, and more.

A diagram showing all of the pillars included in the reliable web app pattern

In other words, the RWA gives you prescriptive guidance to get your app ready to successfully run in Azure with as little code changes to your existing app as possible.

To help you understand and use the RWA pattern, we’ve created a comprehensive collection of materials that describe it in full. You can review the documentation. A production-quality, and ready-to-deploy web application’s source code. And videos that help explain everything.

But what we’d like to cover in this article are some low-cost code changes you can make to your app today that will prepare your application for its cloud journey.

Building for resiliency

Ensuring your application can recover from errors is critical when working in a distributed system like the cloud. You need to anticipate transient faults that can occur when your application tries to connect to a service or network resource.

Faults can include the momentary loss of network connectivity, the temporary unavailability of a network service, or timeouts that occur when a service is busy.

Anticipating and properly handling these transient faults can improve the stablilty and the resiliency of your application.

Two relatively easy to implement patterns that do just that are the Retry and Circuit-breaker patterns.

Retry pattern

The retry pattern is a technique for handling temporary interruptions in the service your code is trying to call. You expect these interuptions, or transient faults, to resolve themselves in a few seconds.

The retry pattern handles transient faults by resending failed requests to the service. You can configure the amount of time between retries and how many times to attempt before throwing an exception.

The Azure SDKs

Most Azure services and their client SDKs have a built-in retry mechanism. You should use this mechanism to expedite the retry pattern implementation. (For more info, see the Azure service retry guidance).

Here’s an example of the built-in mechanism in Entity Framework Core to apply the Retry patten in requests to Azure SQL Database.

services.AddDbContextPool<ConcertDataContext>(options => options.UseSqlServer(sqlDatabaseConnectionString,
    sqlServerOptionsAction: sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(
          maxRetryCount: 5,
          maxRetryDelay: TimeSpan.FromSeconds(3),
          errorNumbersToAdd: null);
    }));

You may write code like this when adding a class that inherits from the Entity Framework Core’s DbContext (in this case ConcertDataContext) to the ASP.NET Core’s dependency injection container. In the initialization options there is a built-in mechanism to specify that should any transient database errors occur, to retry a maximum of 5 times (maxRetryCount), waiting 3 seconds between each try (maxRetryDelay).

Custom code

You should use the Polly library when the service your app is calling does not supply a built-in mechanism to support retries natively. Polly is a .NET resilience and transient-fault-handling library. With it you can use fluent APIs to describe retry behavior in a central location of the application.

The following example uses Polly during the ASP.NET Core dependency injection configuration. Polly enforces the Retry pattern every time the code constructs an object that calls the IConcertSearchService object. The code that implements the retry pattern is found in the GetRetryPolicy function. It is applied any time the RelecloudApiConcertSearchService encounters an HTTP error when making a request to a web API. It uses HandleTransientHttpError to detect only transient faults that it can safely retry. And it retries up until a specified number of times.

private void AddConcertSearchService(IServiceCollection services)
{
    // read the web API's url from the app settings
    var baseUri = Configuration["App:RelecloudApi:BaseUri"];

    if (string.IsNullOrWhiteSpace(baseUri))
    {
        services.AddScoped<IConcertSearchService, DummyConcertSearchService>();
    }
    else
    {        
        services.AddHttpClient<IConcertSearchService, RelecloudApiConcertSearchService>(httpClient =>
        {
            httpClient.BaseAddress = new Uri(baseUri);
            httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/json");
            httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, "Relecloud.Web");
        })
        .AddPolicyHandler(GetRetryPolicy()) // Add the Polly retry policy for transienct HTTP errors
        .AddPolicyHandler(GetCircuitBreakerPolicy());
    }
}

private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    var delay = Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromMilliseconds(500), retryCount: 3);
    return HttpPolicyExtensions
      .HandleTransientHttpError()
      .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
      .WaitAndRetryAsync(delay);
}

You can find more info on the retry pattern here.

Circuit breaker pattern

You should use the circuit breaker pattern with the retry pattern. The circuit breaker pattern handles faults that are not transient. The goal is to prevent an application from repeatedly invoking a service that is down.

You can implement the circuit breaker pattern with Polly. In the previous example a GetCircuitBreakerPolicy was added to the configuration. Here is the implementation of that function:

private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
}

Again, this code is applied any time RelecloudApiConcertSearchService encounters an HTTP error when invoking a web API. It uses the HandleTransientHttpError logic to detect which HTTP requests it can safely retry but limits the number of aggregate faults over a specified period of time. In this case, 5 faults in a 30 second period.

For more information, see the Circuit Breaker Pattern.

Improve performance

Applications use a cache to improve repeated access to information held in a data store. Loading data on-demand into a cache from a data store can improve performance and help maintain consistency between data held in the cache and data in the underlying data store.

However, it’s impractical to expect that cached data will always be completely consistent with the data in the data store. You need implement a strategy that helps to ensure that the data in the cache is as up-to-date as possible, but can also detect and handle situations that arise when the data in the cache has become stale.

Cache-aside pattern

The cache-aside pattern is used to manage in-memory data caching. The pattern makes the application responsible for managing data requests and data consistency between the cache and persistent data store. When a data request reaches the application, it first checks the cache to see if the cache has the data in memory, if it doesn’t the application queries the database.

Most applications have pages that get more views than other pages. You should cache data that supports the most-viewed pages of your application to improve responsiveness for the end user and reduce demand on the database.

The code below caches the data that supports an Upcoming Concerts page. The cache-aside pattern caches the data after the first request for this page to reduce the load on the database.

public async Task<ICollection<Concert>> GetUpcomingConcertsAsync(int count)
{
    IList<Concert>? concerts;

    // Try to read data from the cache first
    var concertsJson = await this.cache.GetStringAsync(CacheKeys.UpcomingConcerts);

    if (concertsJson != null)
    {
        // There is cached data. Deserialize the JSON data.
        concerts = JsonSerializer.Deserialize<IList<Concert>>(concertsJson);
    }
    else
    {
        // There's nothing in the cache. Retrieve data from the repository and cache it for one hour.
        concerts = await this.database.Concerts.AsNoTracking()
            .Where(c => c.StartTime > DateTimeOffset.UtcNow && c.IsVisible)
            .OrderBy(c => c.StartTime)
            .Take(count)
            .ToListAsync();

        concertsJson = JsonSerializer.Serialize(concerts);

        var cacheOptions = new DistributedCacheEntryOptions {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
        };

        await this.cache.SetStringAsync(CacheKeys.UpcomingConcerts, concertsJson, cacheOptions);
    }

    return concerts ?? new List<Concert>();
}

You should periodically refresh the data in the cache to keep it fresh and relevant. The involves getting the latest version of the data from the database to ensure the cache has the most requested data and the most current information. The frequency of the refreshes depends on the application.

You also need to change cached data whenever a user creates or updates a record. The following shows an implementation of a create and update method:


public async Task<CreateResult> CreateConcertAsync(Concert newConcert)
{
    database.Add(newConcert);
    await this.database.SaveChangesAsync();

    // Remove data from the cache
    this.cache.Remove(CacheKeys.UpcomingConcerts);

    return CreateResult.SuccessResult(newConcert.Id);
}

public async Task<UpdateResult> UpdateConcertAsync(Concert existingConcert), 
{
   database.Update(existingConcert);
   await database.SaveChangesAsync();

   // Remove data from the cache
   this.cache.Remove(CacheKeys.UpcomingConcerts);

   return UpdateResult.SuccessResult();
}

For more info, see the Cache-aside pattern overview.

Summary

The Reliable Web App Pattern (RWA) is a pattern to help your application take its first step on the cloud journey. It’s a set of best practicess built on the Azure Well-Architected Framework that will help you migrate your application to the cloud with minimal code changes necessary. In this article we took a look at some of the code changes that you might want to consider to make your application more resilient and performant.

The retry pattern handles transient faults in services that your application calls. These are faults that you expect the other services to recover from quickly so your application can succesfully call them on subsequent attempts.

If the service does not come recover, the circuit breaker pattern stops your application from calling the service over and over again.

And the cache-aside pattern improves performance of your application by checking to see if high demand data is already included in an in-memory cache before querying a persistent data storage for it.

Be sure to check out the documentation that explains RWA in-depth, deploy the source code, and watch the videos to get you up and running quick!

The post Introducing the Reliable Web App Pattern for .NET appeared first on .NET Blog.



source https://devblogs.microsoft.com/dotnet/introducing-the-reliable-web-app-pattern/

Share this post

Search This Blog

What's New

The "AI is going to replace devs" hype is over – 22-year dev veteran Jason Lengstorf [Podcast #201]

Image
Curriculum for the course The "AI is going to replace devs" hype is over – 22-year dev veteran Jason Lengstorf [Podcast #201] Today Quincy Larson interviews Jason Lengstorf. He's a college dropout who taught himself programming while building websites for his emo band. 22 years later he's worked as a developer at IBM, Netlify, run his own dev consultancy, and he now runs CodeTV making reality TV shows for developers. We talk about: - How many CEOs over-estimated the impact of AI coding tools and laid off too many devs, whom they're now trying to rehire - Why the developer job market has already rebounded a bit, but will never be the same - Tips for how to land roles in the post-LLM résumé spam job search era - How devs are working to rebuild the fabric of the community through in-person community events Support for this podcast is provided by a grant from AlgoMonster. AlgoMonster is a platform that teaches data structure and algorithm patterns in a structure...

Labels

Programming Video Tutorials Coursera Video Tutorials Plurasight Programming Tutorials Udemy Tutorial C# Microsoft .Net Dot Net Udemy Tutorial, Plurasight Programming Tutorials, Coursera Video Tutorials, Programming Video Tutorials Asp.Net Core Asp.Net Programming AWS Azure GCP How To WordPress Migration C sharp AWS Project Git Commands FREE AWS Tutorial OldNewThings Git Tutorial Azure vs AWS vs GCP New in .Net javascript AI Google I/O 2025 Wordpress jquery Generative Video Git Git Squash Google Flow AI PHP SQL Veo 3 squash commit CSS Cloud Services React Tutorial With Live Project Source Code git rebase CPR Nummer Dropdown Reset Javascript Figma Figma Beginner Tutorial Geolocation Non-Programmer Content Python Free Course Think Simply Awesome Tutorial UI UX Live Project UI/UX Full Course Wireframing dotnet core runtime error html API Gateway AWS EKS vs Azure AKS All in one WP stuck C++ C++ Coroutines CPR Denmark ChatGPT Cloud Database Cloud DevOps Cloud Security Cloud Storage Contact Form 7 Dropdown Unselect Javascript E commerce Free AWS Terraform Project Training Git Commit Google Drive Files Google Drive Tips Http Error 500.30 Http Error 500.31 Interview Questions Learn Courutines C++ Microservices for Live Streaming PII Denmark Pub Sub SQL Server SSIS Terraform Course Free Terraform Tutorial Free USA E commerce strategies UpdraftPlus UpdraftPlus Manual Restore Website Optimization Strategies dropdown javascript select drop down javascript smarttube apk error 403 smarttube next 403 Error 413 Error 503 504 524 AI & ML AI Assistants AI Course CS50 AI in daily life AWS API Gateway AWS EBS AWS EC2 vs Azure VMs vs GCP Compute Engine AWS EFS AWS IAM AWS Lamda AWS RDS vs Azure SQL AWS Redshift AWS S3 AZ-104 AZ-104 Free Course AZ-104 Full Course AZ-104 Pass the exam Abstract Class C# Abstract Method Ajax Calender Control Ajax Control Toolkit All In One Extension Compatibility All In One WP Freeze All In One WP Migration All in one WP All-in-One WP Migration Android 15 Android TV Applying Theme html Asp.net core runtime Error Audio Auto Complete Azure AD Azure APIM Azure Administrator Certification Azure Blob Storage Azure Data Lake Azure Files Azure Function Azure Managed Disk Azure Synapse Base Class Child Class Best Grocery Price Big Data BigBasket vs Grofers Bing Homepage Quiz Blogger Import Blogger Post Import Blogger XML Import Bluetooth Connectivity Browser Detail Building Real-Time Web Applications Bulk Insert CI/CD CPR Address Update CPR Generator CPR Generator Denmark CS50 AI Course CS50 AI Python Course CS50 Artificial Intelligence Full Course CVR Centrale Virksomhedsregister Change Workspace TFS ChatGPT Essay Guide ChatGPT Usage ChatGPT vs Humans Cloud API Management Cloud CDN Cloud Computing Cloud Data Warehouse Cloud Event Streaming Cloud IAM Cloud Messaging Queue Cloud Monitoring and Logging Cloud Networking CloudFront Cloudflare Cloudwatch Compute Services Connect a Bluetooth Device to my PC site:microsoft.com Containers ControlService FAILED 1062 Corona Lockdown MP CosmosDB Covid19 Covid19 Bhopal Covid19 Home Delivery MP Covid19 Indore Covid19 Susner Covid19 Ujjain Cypress Javascript Cypress Javascript framework Cypress Javascript testing Cypress Javascript tutorial Cypress Javascript vs typescript DNS Danish CVR Data Analytics Data Analytics Course Free Data Engineering Data Structure Full Course Data Visualization Database Database Diagram Visualizer Davek Na Dodano Vrednost Dbdiagram export seeder Deep Learning Course Denmark Numbers Det Centrale Personregister Det Centrale Virksomhedsregister DevOps Device Compatibility Dictionary Dictionary in C# Digital Economy Disaster Recovery for Web Applications Disaster-Proof Infrastructure Dmart Frenchise Dmart Home Delibery Dmart Mumbai Address Dmart Pickup Points Doodle Jump Drive Images On Blog Drive Images On Website Driver Problems DropDown Dropbox Dropdown jquery DynamoDB ETL ETL Package Ecommerce Store using AWS & React Embed Drive Images Escape Sequences in c#.Net Event Hub Explicit Join Extract Facebook App Fake CVR Denmark Fake DDV Slovenia Fake VAT Number Fake Virk Number Faker Feature Toggle Find CPR Information Find a Word on Website Firestore Flappy Bird Game Form Selectors using jQuery Free React Portfolio Template FreeCodeCamp Frontend Best Practices for Millions of Users Full Text Index View G Drive Hosting GAN certification course GCP Cloud Data Lake GCP Filestore GCP Functions GCP IAM GCP Persistent Disk Gemini Git Checkout Google Adsense Setting Google Beam Google BigQuery Google Conversion Tracking Google Docs Advanced Tutorial Google Drive Clone Google Drive Clone Bot Google Drive Clone HTML CSS Google Drive Clone PHP Google Drive Clone React Google Drive Clone Tutorial Google Drive Clone VueJS Google Drive File Sharing Google Drive Images Google Drive Sharing Permissions Grocery Price Compare Online Grocery in Corona Grocery in Covid19 Grofers vs DMart vs Big basket HAXM installation HTML Storage HTML to PDF Javascript HTML2Canvas HTML5 HTML5 Append Data HTML5 Audio HTML5 Data Storage HTML5 Storage HTML5 Video Harvard University AI Course Header Sent Height Jquery High Availability in Live Streaming Platforms High-Concurrency Frontend Design High-Concurrency Web Applications How to Search for a Word on Mac Html2Canvas Black Background issue Http Error 413 Http Error 500.35 IIS INNER Join Image Gallery Blogger Image Gallery Blogger Picasa Image Gallery Blogger Template Image Gallery Blogger Template Free Implicit Join Indexing in SQL Instagram Clone React Instagram Clone Script Install NodeJS Ubuntu Internet Infrastructure Interview IoT IoT Core IoT Hub JS Game Tutorial Java Feature Toggle Javascript game tutorial JioCinema Case Study Keep Me Login Key Management Kinesis Learn Scrappy with a live project List Live Streaming Data Delivery Live Streaming Performance Optimization Load Load Balancer Looping Dictionary MTech First Semester Syllabus MTech Syllabus MVC Mac Mac Finder Shortcut Media Controller Media Group Attribute Microservices Architecture for Scalability Missing MySQL Extension Mobile Optimization Multiple Audio Sync Multiple Video Sync Mumbai Dmart List MySQL MySQL ERD Generator Next.js Beginner Tutorial Ngnix NodeJS NodeJS Ubuntu Commands Numpy OOPS Concepts OOPS in C# Object Oriented Programming Object Storage Outer Join PHP Installation Error PHP WordPress Installation Error Pandas Personligt identifikations nummer Pipedrive Pipedrive Quickbooks Integration Portfolio Website using React Project Astra PyTorch Quickbooks Quote Generator RGPV Syllabus Download Random SSN Generator ReCaptcha Dumbass React Feature Toggle Real-Time Video Processing Architecture Real-Time Video Processing Backend RegExp Regular Expression Reinstall Bluetooth Drivers Remember Me Remove NodeJS Ubuntu Renew DHCP Lease Reset IP Address Linux Reset IP Address Mac Reset IP Address Windows Reset Remote Connection Reset Remote Connection Failure Resize Textarea Restore Errors Restore Failed UpdraftPlus Route 53 SOS Phone SQL Indexed Tables SQL Joins SQL Seed generator SQS SSIS Package SSIS Tutorial SSN Generator for Paypal SSN Number SSN Number Generator SSN Validator Safari 8 Safari Video Delay SageMaker Scalable Backend for High Concurrency Scalable Cloud Infrastructure for Live Streaming Scalable Frontend Architectures Scalable Live Streaming Architecture Scrapy course for beginners Search A word Search for a Word in Google Docs Secret Management Serverless Service Bus Slovenian VAT Generator SmartTube Software Architect Interview Questions Software Architect Mock Interview Sparse Checkout Spotlight Mac Shortcut Stored Procedure Subtree Merge T-Mobile IMEI Check TFS TMobile IMEI check unlock Team Foundation Server Terraform Associate Certification Training Free Text Search Text color Textarea Resize Jquery Theme Top WordPress Plugins Transform Trim javascript Troubleshooting TypeScript Beginner Tutorial Ubuntu Unleash Feature Toggle Update Computer Name UpdraftPlus 500 UpdraftPlus Backup Restore UpdraftPlus Error 500 UpdraftPlus Error 504 UpdraftPlus Error 524 UpdraftPlus HTTP Error UpdraftPlus New Domain UpdraftPlus Restore Not Working UpdraftPlus Troubleshooting Upstream Reset Error Use Google Drive Images VAT Number Generator Verizon imei check Verizon imei check paid off Verizon imei check unlock Verizon imei check\ Version Control Vertex AI Video View Indexing SQL Views in SQL Virksomhedsregister Virtual friends Visual Studio 2013 WHERE Clause WHPX expo Web Security Web scraping full course with project Web3 What is Feature Toggle WordPress Backup Troubleshooting WordPress Backup UpdraftPlus WordPress Database Backup WordPress Error 503 WordPress Installation Error WordPress Migration UpdraftPlus Wordpress Restore Workspaces Commands Your ip has been banned Zero Click angle between two points bing homepage quiz answers bing homepage quiz answers today bing homepage quiz not working bing homepage quiz reddit bing homepage quiz today byod Verizon imei check chatgpt essay example chatgpt essay writer chatgpt essay writing check tmobile imei contact form 7 captcha contact form 7 captcha plugin contact form 7 recaptcha v3 cpr-nummer engelsk cpr-nummer liste cpr-nummer register cpr-nummer tjek dbdiagram dom load in javascript dotnet core hosting bundle dotnet failed to load dotnet runtime error get url in php how to search for a word on a page how to search for a word on a page windows ipconfig release is cypress javascript istio transport failure jQuery AutoComplete jQuery Input Selector jQuery Menu jQuery Options joins in mySql jquery selector jquery selectors jsPDF jsPDF images missing key key-value keypress event in jQuery kubernetes upstream error localStorage metro by t-mobile imei check nemid cpr-nummer react native expo setup react native on Windows react native setup recaptcha v3 contact form 7 recaptcha wordpress contact form 7 reset connection failure resize control jQuery response code 403 smarttube round number in javascript select sessionStorage smarttube 403 エラー smarttube apk smarttube beta smarttube download smarttube reddit smarttube unknown source error 403 smartube sos iphone top right sos on iphone 13 sos only iphone substr substr in javascript tmobile imei tmobile imei check paid off tmobile imei number total by Verizon imei check trim trim jquery turn off sos iphone turn off sos on iphone 11 unknown source error 403 unknown source error response code 403 smarttube upstream connect error url in php view hidden files mac finder zuegQmMdy8M ошибка 403 smarttube
  • ()
  • ()
Show more
an "open and free" initiative. Powered by Blogger.