🤷♂️ Why is this Series (also called a book?)?
Introduction
At first, this post was intended to write a short story about Blazor, but I wrote it and wrote it, thinking of a younger person who asked me about teaching how to use the LEVEL51 web engine and never taught it...and someone who The office told me that Went to give scholarships for high school students. My sister said "study from the blog LEVEL51" 🤩 ...and then thought that I used to write a book to teach web writing with ASP.NET ...and it fits the mother ship (Microsoft USA) ) Send me the MVP Reconnect badge (it's like you've been gone for a long time. Let's help make a living) so I'm full of heart. Write it for you to read to your heart's content one more time. After being gone for a long time since writing down Coresharp.net
This series intends that even if I have never written a program never write a website can follow So read it calmly. This post is long enough for 1 chapter of the book and should be read on a computer. Because there is a table (it's not Responsive) and also a lot of pictures, it should eat a decent amount of GB~
The story happened where...
It's all about Starting from the fact that I secretly take a peek at .NET Core from a distance to see where it will go exactly. And secretly hoping for .NET Framework, .NET Core, .NET Standard, it all came together and finally .NET 5.0 that includes everything was Released around the beginning of November last year. The thing that made me turn around and look at it was Massive Performance Boost Proven by Stackoverflow Web Popular among programmers like us that just Porting from Framework 4.8 to .NET CORE 3 causes the time to render the question page reduced from 21ms to 15ms or about 30% faster and the CPU Usage of Server down 80%
And the sad news for me too is NancyFx which is an Opensource Framework to do in the backyard. my favorite Because creating a Route (URL that will come to use the web) in NancyFx is much easier than ASP.NET MVC, it is in Readonly (Unmaintained) mode because people say that the new ASP.NET Core has close capabilities. It's already similar to NancyFX, and Contributor (who helped write NancyFx) moved to write a new framework instead called Carter - by Carter, this brought the ease of creating NancyFx's route to be perched on ASP.NET Core again. It's a beautiful farewell to NancyFx over 10 years of development, where the "Super Duper Happy Path" concept continues to run on ASP.NET Core, saying it's "Super Duper Happy Path". Let's look at this code for comparison.
"SUPER DUPER HAPPY PATH!" 😍
ASP.NET Core MVC 💢
That 's not enough. AngularJS ( not Angular ) is our frontend framework of choice on LEVEL51 and all the web sites we've ever built for our clients. (Which is not a lot, hehe) It will end its lifespan by the end of 2021 . The main reason why we continue to choose AngularJS since Angular came out and React is coming is when we do web design. We let customers choose a ready-made Template from the Envato website and then develop it. To sit and change a Template that is already "finished" (that is, it's both Responsive, already tested, has all scripts) to be a component of React/Angular, it seems wrong. Wearing AngularJS designed for It's an extension of the HTML code that is more appropriate.
The last thing that made me decide that by 2021 our company would have to start adopting some new technologies or frameworks with them was AngularJS , it's 10 years old, NancyFx is 10 years old too, and we're fighting against AngularJS. It's been quite a while (but I really like NancyFx, nothing to complain about). It's been 10 years and we haven't learned anything new!
It might be time to move! How can I use 10 years old technology to live!
1) There are many ways to develop Web Application in this era, why not choose one?
According to my duty as the direction of the company will have to sit and choose What will we use next? I just judged by watching the first tutorial. and try something don't play seriously By trying to connect with our AngularJS experience with NancyFX, let's take a look at some of the interesting ones right now. And why didn't I choose it?
💥 1.1) React
Although React has React Native and Expo , which means we learned React once. Able to use knowledge to write apps on Android/iOS very quickly (Quick enough to write on the web.) Plus, there's Bridge.Net that allows writing React in C# , however, I'm not really into React here.
- React thinks of a Single Page App (SPA) First : I mean, we'll see that it has a concept like everything is "Component" or if you call the language that people who used to use Visual Basic or Windows Forms is "Control" which is nice, but. It means that we will have to convert the Templates that we can buy from the Envato website into Component first, and the important thing is It won't be able to be used directly because those templates will have a lot of Kubgi script added.
- React has the concept of View and related code. It has to go hand in hand. Why separate Model View Controllers? (Check out Introducing JSX – React (reactjs.org) , which is not our way of thinking. Developed from Windows Application line and used to separate View (screen), Controller (code that controls the screen) and Model (data / what we will work with).
- From the understanding in React's first tutorial, if we are going to create a photo album, we will need a component that combines the images. in the album and there is another component that is the image in the album , making the Code View (HTML) of this album distributed in two places Check it out in React's docs, he really told me to think like this.
Whereas if we wanted to do this in AngularJS, we would put ng-repeat in the image part of the album to say: To display the code of this image repeatedly according to the number of images in the album only. Make it when editing the web page code. The output structure can be seen immediately, but for LEVEL51 we use Razor, AngularJS is mostly in the backend. - React is not designed to do 2 Way Data Bidning in the first place. Another look is that React's component is responsible for creating views of the received data (model) as in the picture above. You can see that they recommend 1 Row of Product. i.e. 1 Component, for example, but it doesn't define how to get data from View back to Model. It's clear how to do it. Answers in Stackoverflow. It is recommended to use to catch Event onChange
, that is, React , so we have to write code to update the model ourselves, like in the past, we had to write code like currentStudent.Name = txtName.Text for every incoming Text Field, while AngularJS can use ng-model="currentStudent.Name" . (or can be called as a function Getter/Setter) like this and the Input will automatically update the model when the text is typed in. You can go to the Validation stage and create animations with CSS Animation. - Making a website to support SEO is too busy. Since everything is a component that is rendered on the client side, to do SEO, it becomes necessary to make React able to run on the server in order to pre-render the web page. Of course, we may use some original writing and give some React, but like that, would it be better to use Vue???
All in all, I feel that React is an advanced concept. But it doesn't really solve the problems I've encountered, and it's causing other problems. followed by another
💔1.2) Vue - Not qualified....just because it's JavaScript.
For us humans who have been using AngularJS for almost 10 years, Vue seems like the best choice. And there is a way of writing that is very close to AngularJS, with the idea that Vue's views are separate from JavaScript code and can create components (in AngularJS, they call Directives). You can tell that if anyone is using AngularJS. Moving to Vue is probably the most accurate. You can use the same concept. The main ones that LEVEL51 uses are the Admin page at the back of the house and the Custom Laptop page (which is often broken). We use the traditional method. Submit the page first and AngularJS does the UI Config one more time.
But since it's JavaScript, it would still create the same problems. for us to stay What's the biggest problem with us? And we fight with it a lot. is that it doesn't have Static Type Checking (requires additional tools) is when typing We have to remember for ourselves what this has to offer. Make it hidden bugs without our knowledge, and debug (bug detection process) is rarely encountered . Will learn something new. Then find something that is not the same problem would be better!?
🤔1.3) Angular, Flutter - Not Qualifying Because we are looking for a framework to make a website, not just a Web App / Mobile App.
If you want to escape JavaScript, come to TypeScript ! Angular is probably the next option. Of course if we were to use Angular, we would have used it but almost 10 years ago, what I didn't like about it is that it's similar to React, that everything is a component and it's designed to be a SPA rather than a web site. It doesn't look bad to learn Flutter/Dart at all. It can also be used as an app, but the important part is that Flutter/Dart has become a new language we have to learn. (It looks like React) instead of using our C# expertise.
😯 1.4) Bridge.NET
Another very interesting option. Give it the best idea of the decade award. Is to write a Web Application with C# and C# code will be converted to JavaScript again, allowing us to use all the outstanding capabilities of C# language. Can share code that is Data Type as well. And also about Static Type Checking. as we dreamed
But the dead point is that you can't use JSX in Bridge.NET because when you do View, you have to write it yourself like this. Can't write like HTML (web-writing language) mixed in if it can. Might take a risk and try it.
( From a blog introducing React with Bridge.NET )
But even if you can, there will still be the same annoying part. really big story
If you think about it, almost 30-40% of the code I wrote is the code that makes Frontend (webpage) and backend (backend and database) talk. By calling the REST API, we can fix the can share code Fix the issue of language that can hurt us. What if there was a way to fix the issue of having to write Front/Back separately?
💖2) Then come to Blazor.
After sitting, update the information until here. Reminds me of Blazor, which at first I had read about a year ago, but didn't care because I felt that It works like Web Forms of ASP.NET 1.1/2.0 - that is, it uses the Browser as a Dumb Terminal , that is, when we press a button. Code for the function of that button. It will be processed directly on the Server and the Server sends the changed part of the screen back to display in the Browser.
In the era of Web forms ( which I am very specialized While writing the book ASP.NET 2.0 together with Mr. Naret ) The screen that we see is purely rendering from the server side, such as pressing a button. And to display the text on the web page is that the ASP.NET Server will receive the button press. do code processing and update the screen status in the server's memory, and then send that screen come back to the whole page (We can see that the web screen is Refresh), which is actually in those days (that is, about 15 years ago), writing Web Applications, the whole screen Refresh like this is very normal.
So how can Blazor be good like this? It's 2021, not 2005!
2.1) Advantages of the Blazor Method (and the Web Forms Method)
- It doesn't take a lot of web savvy, about CSS Selector, about DOM, about jQuery, about Ajax, about Json, a lot. Just having basic knowledge of HTML/CSS and C# can start writing a Web Application that is a Single Page App right away.
- Frontend and Backend are the same code. written in the same language And it can be said that there is no division of the front of the house / back of the house. When there is nothing in front of the house/back of the house So we don't have to do the code in the part that connects between the front of the house (REST API) because the code we write Able to run data on the server such as open, read/write data directly to the database, just like writing a program that works on the desktop.
- Without an API, there's no need for cross-technology data transmission between JavaScript and back-end languages. So there is no serialize problem, no date conversion, no timezone mismatch problem that I often see.
- It renders the full web page straight from the server , so you don't have to worry about Search Engine Optimization (SEO) .
- If you have an old Line of Business Application (LOB Apps) that is Windows Form and written in .NET, you might be able to port it on the web. Without having to edit the code in parts that are not related to the View, just rewrite the View as HTML . This is probably a major selling point of Blazor.
2.2) Disadvantages of the Blazor Method
- everyone who opened Will consume resources on the server because the server must remember the state of everyone, like everyone, open the program in one window on the server. According to testing by Microsoft, for a VM with 1 vCPU, 3.5GB of RAM can support up to 5000 concurrent users. Without affecting the Latency , then it is up to us how much memory our App will consume.
- Cluster / Load Balance is difficult because if the client does not connect to the original server, the state will be lost . In the past, there would be this problem. Makes us try to write a Web App as Stateless and leave the State at the Browser (Client) instead, so Ajax, REST API, jQuery, AngularJS, React, Vue come in order of the more complex requirements of the Web App running in the Browser page.
- Interaction Time will be slower because the processing takes place on the Server, so if you don't understand it well And to write code in a way that everything must be sent back to the server to process, the work will be very slow and if you don't understand this point There might be a mess later in an attempt to break out of Blazor code that doesn't need to be run at the server.
In conclusion, Blazor has disadvantages in terms of server resource consumption, state storage and Response Time, which is a traditional problem since the days when we wrote the same Web App 15-20 years ago. Therefore, if we are going to use Blazor, we will need to know how to plan well. If we follow the tutorial exactly, we will get its drawbacks.
But if you read about Blazor, you will find that there is talk about how Blazor can run on all browsers. Without having to rely on a server , the web page that is Blazor can use the ability WebAssembly (WASM) to take the C# code and run it in the Browser. directly to the database I can't do it
As for me, Buy in that it is an advantage. Is that there is no need to make APIs and the code on the web page and the server side can be used together.
🚀3) Start web writing with Blazer
for starting something It should not be a playful experiment. because try to play In addition to wasting time alone It also encourages learning to decrease gradually as well. In a good way, learning new things, new languages, like having to learn a new elementary school like this. must have goals
So I started a Blazer learning project with the goal of rebuilding my original blog, CoreSharp, with Blazor, along with learning notes. never write a website You can follow, so let's learn together!
3.1) Prepare the tools
For the tool that I recommend to use is Visual Studio Community Edition - Many people may recommend to use VS Code, but before VS Code can be used for everything, it would be out of date before installing Visual Studio. Choose to install web tools as well, namely ASP.NET and web development .
3.2) Choose a Web Template
During VS installation, we come to find a template that we like. It's good for us to sit and make Templates to understand HTML better. But in today's life that anyone can create a website from the Wix.com website like this, learning HTML, creating templates by yourself, testing with all devices makes it Responsive - meaning that it can be scaled to the size of the screen with a single website. No need to separate Mobile/Desktop Site. Probably not. It is recommended that you learn from the villagers by finding a free Web Template to use.
for the recommended website Check out this website 🤩 https://www.free-css.com/free-css-templates Try to find a template that has two pages, a home page and a detail page, like this Template Ramayana .
Home Page | Detail Page |
The template that I will use will come from Envato Elements because it will be a web site. Coresharp.net really new, so if you want to Must be able to apply what is read from this EP post to the selected template itself. Therefore it is called through the lesson.
3.3) Create a project
After installing Visual Studio Follow the steps to Login, choose a usage style, choose C#, as for the color, it is recommended to choose Dark Mode so that your eyes will not be very tired when working. (This is a direct experience From this old programmer 😅) Press the Create a New Project button on the right, you will see a screen to choose Template, type Blazor .
Then select Server App - we can change to WebAssembly later, don't worry about the option, remove HTTPS/Docker first, we can mess with it one more time.
On the Configure your new project page, name the project. "CoreSharp.Web", we usually name the project like this, which is the name of the project, and then hang at the back to be the project type. As for the Solution Name, it will be named after the Project Name itself, just set it CoreSharp and find a folder. to remember where it is
I don't know why it came back to this page again. It's set as follows
3.4) Get to know the IDE
For those of you who have never used Visual Studio or any IDE (Integrated Development Environment) before, here's a quick guide.
- This middle screen It will be the part that we use to write the code.
- Solution Explorer is where we see what files are in our project.
- Toolbar to run the IDE
- Toolbox, a tool used to draw the screen. (But we rarely use it) with Test Explorer, which we will use next time.
The screen of this IDE program can be modified. by moving the window left to right can be divided in half according to preference and if there is a budget It is recommended that you buy one more monitor as well, it would be great. Writing code on one screen and can read the information on another screen Makes life a lot better. As for me, I use a 4K TV screen and divide the screen into 4 parts using the PowerToys program. Compared to buying 4 Full HD 24 inch screens, the price is cheaper. no need to buy a stand It can also be used to watch movies as well.
Once opened You don't have to wait for anything, press F5 or press the Play button at the Toolbar to start the Blazor program from the Template.
If pressing F5 doesn't happen, let us reset the same settings first by going to Tools , Import and Export Settings... then Reset Settings , select No..., and then select Visual C#. before pressing Finish
🚄4) For those who write programs for the first time : What happens when we order Run?
To run the program, the Visual Studio program will go to work in many backgrounds until it arrives at the browser page that opens for us to see. For those who have never written a program before. You should know a little bit of the process behind it. in order to gain a better understanding of the overall picture What happens when and where. In conclusion, according to many books, they will say that there is a process like this.
- Compile is the process where the compiler program reads our source code (Source Code, hereinafter referred to as code) and understands it. What do we want to do? (If you are interested in the internal steps again, I recommend you to read this article. If you want to be more thorough, then this article ) After this step, Compiler will give you another code result. that we can't read But the computer understands, call the Object Code (or sometimes call the Object File) out.
- Most Link is another program called Linker, which is in the Compiler again (I haven't seen anyone doing it separately). Linker will link the compiled code with other code sets, that is, when we write. that program We didn't write everything ourselves. Instead, it's about taking what someone else has written and then using it, sometimes called a Library (a .dll file), sometimes called a Framework (a combination of .dll files), or sometimes called a Platform (e.g., Write an App in Android is that we use Framework/Library/IDE for Android) The code that we actually write is very little, but it will be the part that makes our app or program. or our website different from others By the result obtained from the link, we will get Executable .
If on Windows the file that is executable is a .exe or .dll file, others can link our .exe or .dll to them. Linking in Visual Studio is called Add Reference . - Load after we have .exe or .dll if we want the program to run. We have to read all the data from the SSD or HDD (collectively called Disk) secondary storage in the computer up to the RAM, which is the Primary Storage of the computer. This is because CPU i5 i7 or Ryzen doesn't know what is SSD/HDD, and it doesn't recognize Drive C, Drive D, it only recognizes RAM.
- Run This is the step where our program actually starts. The program that we write will always have an Entry Point that they have agreed where it is. Our program will start from this Entry Point if in the corner of the CPU it will be the first Instruction of our program. that it will read up to work
If you want to see, after pressing Run (in Visual Studio), you can follow. By right-clicking on our project name in Solution Explorer and selecting Open Folder in File Explorer , then looking in Folder obj and Folder bin will find that there is a file with the same name as the project we named it.
and if we try to double click to open the .exe file to run We will be able to open the Browser to press to play our website immediately! Because the web written in Blazor, which is running on ASP.NET Core again, can be Self-Host or it has a built-in HTTP Server ( Kestrel ) in the same way that in our SystemX program , you can click to view the sensor values via the web page. or from your mobile phone
(The screen is not beautiful because the file that the web page needs it is not complete Because opening .exe directly like this means that we run the wrong way, but run like this to see the picture)
As for running through Visual Studio, it will be running our website through IIS Express again. We can choose to have IIS as a Reverse Proxy that calls Kestrel again, or let our website run in IIS, just like writing a website. old days Must install Web Application Server such as IIS (Express), Apache, Nginx, Lighttpd first and then call our website through those servers.
👨💻5) Start learning Blazor!
best learning is to see an example from the villagers And try to make it ours, so let's start by opening the Counter page first and see how it can be done so he can make the button pressed. Its number can keep increasing.
The file of Counter page is located in Folder Pages within Solution Explorer. Notice that when we click on the file, Visual Studio will open the file for us immediately, but the file's tab is on the right and when we switch to another file. The screen will be overlapped. if you want to say We will open this file, do a Doube Click or if we start typing something. It will leave the file open as well.
5.1) Razor file structure
Writing a website with Blazor uses a Razor file type (a technology name for creating views of ASP.NET MVC that comes after Web Forms once more). Counter.razor files have 3 parts to pay attention to as follows:
- is the Route or URL to access this file. in the case of the page Counter.razor is able to come in with the Url /counter if we put this website on the Server at https://www.coresharp.net/ , the general public will be able to come to this page with the URL https://www. coresharp.net /counter etc.
- is View , that is what visitors to our website will see. This section is written in HTML, the original language we used to make website screens a long time ago. And it's still in use today, but notice that in this section there is a dot with an @ sign in it.
- The code is the part that controls the view or the web page. This section is written in C#. You can see that currentCount and IncrementCount exist in both 2 and 3 because they are related.
5.2) For those who have never written a website : Understand HTML first.
If just starting to write code for the first time And still don't know HTML, that's fine. Let me explain briefly.
Here's what we need to understand in HTML:
- <h1>....</h1> This is called Tag .where <h1> is called Open Tag and </h1> is called Close Tag . We use Tag to determine that How will the text between the Tag be displayed? For example, h1 or Header Level 1 will be the largest letter, Counter is bigger than friends.
- There are 3 types of tags:
- Block e.g. h1 h2 h3 h4 h5 p div will be a Tag that occupies the entire line.
- Inline e.g. button input span img will be an inline Tag , notice that:
- h1 and p in that sample code. The text in the p will be on a different line than the text in Tag h1.
- The button that says Click me is on a different line from the current count text in Tag p.
- The text This is not New Line is on the same line as the Click me button , even though we start a new line in the source code.
- The text that says This is another Line is on a different line from the text This is not New Line, where the starting point of a new line is the point where there is a <br/> tag.
- Note that the line spacing with the Click me button and the Current Count button is not equal to the line spacing Click me and This is another line. This is because Tag p can add margin to push the text further apart. To know that they are in different paragraphs (Tag p means Paragraph is a paragraph)
- Self-Closing Tag i.e. br img is a Tag that does not have the same </...> written on the back , but only opens and closes the Tag itself. It is a type of Tag that does not specify the display of what is in the middle. But it itself is to render something like br , so we get the line wrap. to create a new line, the img section to display an image , for example. We don't need anything between the images. And it's impossible to have characters in between line cuts, right?
- Anything between the tags is called an Attribute . Notice that the Tag is already fixed. For example, h1 is capitalized if p is a paragraph, but some tags allow us to specify additional information to the tag, which is not the text to be rendered.
- When displayed in the browser page, the parts rendered by the tag are called elements
. The key attributes that are present in every tag are:- A class is used to group elements that are displayed, for example h1 elements may be present in several places. But we would like to state that the first h1 and this h1 are also the largest subjects. We can also put <h1 class="topic">....</h1> like this, and we'll see the next implementation.
- The id is used to specify the name of the element that displays that particular character. For example, the h1 element in the topic group has 3 digits if we want to easily identify the first h1 tag. We can add an id such as <h1 id="firstTopic" class="topic">...</h1> etc. This will be used in programming to identify (Identify) this element.
And actually, in the latest version of HTML, version 5, we can collapse all tags, leaving only the div, block and span, inline, and then use another language, CSS , to modify the display. It can actually change the div. It can also be Inline and span can also be Block. We'll take a look at this part one more time later.
5.3) For those who have never written programs : Basic understanding of C# language.
As for C#, it is more complex than HTML and requires more and more learning. Let's start with enough knowledge for understanding the code in this counter.
- Line is a line. Notice that in the screen There will also be a line number. One line in C# must end with a ; always, which is very problematic. For newbies who are new to programming because often forget to put ; Regularly, this one must practice to be fluent in writing one thing that you want to do, then put ; immediately, otherwise It often leads to other problems later.
- Block is a group of lines. Note that the block contains { and } around the line. When we write code in a line that is between { and } will create a scope , that is, things outside the scope can't interfere with what's inside our scope useful to prevent confusion in reading the code of the program block In the picture, on line 13, there is also a code. Its meaning is that this block is the code associated with this line 13.
5.4) For someone who has never written a program: Basic components of the C# language.
We understand that we have Line and Block. Let's take a look at the components of Line 11 for a better understanding. (This picture shows line 13 because the code has been added)
- Call it Keyword. Notice that it will be blue. We don't have to keep in mind that in this language, when writing, we have to put the blue color in it. It's just Visual Studio's syntax hilighting system that can actually change colors.
- Called Literal is a number or a letter, 0 is Number Literal. If it is a letter called String Literal, it must always be enclosed in quotation marks (rat teeth). But forgot to put the latter. Visual Studio now puts the latter for itself. would be less problematic
- Called Expression means something that has a value. From the sentence currentCount = 0, if read by direct translation of the model when we read the equation, it will say "let currentCount equal 0", which seems like an order, but actually Expression currentCount = 0, that in C# language will get "answer", that is, it will get 0 value
and actually this Literal 0, besides it is Literal, it is also an Expression because 0 will get value. Like "CoreSharp", it's an expression because it gets the value. - All 1 2 3 together, called Statement , is an instruction, which is the most sub-unit of a program code. that can work
- The last part is not numbered. Because they are scattered everywhere, including currentCount, myName, IncrementCount, these are called Identifiers or "names".
5.5) For those who have never written a program : Basic code that you should know
As long as we understand these 5 parts, it is enough to understand the C# code and all the code. It will cycle only in these 5 things, that is, take an identifier to write an expression to come out as a statement.
Let's look at another example. to understand more
- is a statement (statement) to "declare a variable" . It's mathematically similar to where we say let X be equal to 1 and later we say let Y = X - 1. But in the case of C#, variables can't be used. can come floating around. It must always be declared to Compiler first, so if we use a variable named i, we have to do Announced before
. Notice:- In this statement, compared to the example provided by Visual Studio, you can see that there is no word private , so keep your skeptical. Then we'll talk about one more time in the next EP, why this time. so there is no word private
- int is a type of variable, if we try to put int i = "CoreSharp" and leave it for a moment, you will find that Visual Studio doodles (Squiggle) in red, and if we point the mouse over it It is advised that "Cannot implicitly convert type 'string' to 'int'" (Cannot implicitly convert type string to int). This is the Static Type Checking mentioned above.
- Notice that we can say let currentCount = 1 and let i = currentCount = 1 . Mathematically, this is called a Transitive Property, but in the programming language of C# there is no such thing . in programming will always be substituting, that is,
- i = currentCount = 1 The Compiler creates an instruction for the CPU to insert the value 1 into the variable currentCount first, and the Expression currentCount = 1 returns the value that was last inserted, which is 1.
- i = currentCount = 1 1 In CPU comprehension, the next step, currentCount = 1, is now represented by 1.
- i = 1 and then the value 1 is put in the variable i.
- is operator plus, subtract (*), multiply and divide (/) has the same meaning as we understand. nothing complicated Some textbooks may show power. By teaching about Operator Precedence, you have to multiply first, then subtract something like this, and try to explain that if you write 1 + 3 * 5 / 7 - 2, what will be the final value ? I gave it to a new one If you want to do anything, make it clear. Put the parentheses down.
- is the Unary Operator , which is rarely recommended . because the meaning is ambiguous and can be put in both the back (i++) and the front (++i), which have different meanings. The more confused write big programs We don't just sit and show our power on this topic 🤣 Remember that coding focuses on writing and reading in one go. You don't have to open the textbook again to check if you're right. Do you understand?
Its meaning is:- i++ means i = i + 1, but if put in the Statement that int q = 1 + i++; q will be equal to 1 + i
- i-- means i = i - 1, but if you put it in the Statement that int q = 1 + i--; q is equal to 1 + i
- ++i is i = i - 1, but if put in Statement that int q = 1 + ++i; q will equal 1 + (i + 1)
- --i means i = i - 1, but if you put it in the Statement that int q = 1 + --i; q is equal to 1 + (i - 1)
5.6) Exercises
Alright, by this point, you should be able to read the Blazor example code in Counter page enough to understand. to check if you really understand try changing the code Give it time to click the Click Me button and its value increases by 5 instead of by 1, see?
Don't forget that to edit the code, we need to stop our program first. Because the code that has already been loaded into RAM cannot be modified. (There is a way to fix it while running, but not now) by closing the Browser screen that Visual Studio opened first, then edit the code and then press Run (F5) again to start the process. When Compile, Link, Load, Run again
👨💻6) Start a Web Blog with Blazor
Before going further, let's review that. What have we learned?
- We already know that HTML has tags, each tag is responsible for changing the display, and there are two types of tags: Block and Inline.
- We already know that in C# we can create new variables, either numbers or letters, and understand what is currentCount++, and understand the size that can be changed from adding one by one to adding one by one. 5 already
With this knowledge, believe it or not, we can create a (fake) Web Blog!
6.1) Find Layout of Template
Still have a downloaded Template file? If downloaded, then open Zip and look until you find .html files in Folder css, images, js like this, then copy files with Folder css, images, js and put them in Folder wwwroot of our project ( For those of you wondering why my Explorer screen has Tabs - I use Clover )
Then we press Run (F5) as usual and put the URL as the html file name into it. Try to select a page that doesn't have anything in the middle, such as a 404 page or a Contact Form page, etc.
In case if you load the Template from the website, Free Css Templates may only have 2 pages. If you choose to use a template that has a Home page and a Detail page as mentioned, use the Detail page.
The reason why we want to remove a simple page like this is because we have to find a point that is the content of every page so that we can separate the Layout of that page from the Source Code to use as a Layout or structure of our website. Once again, notice that the website will have the same section on every page, not above, below, or both, they are duplicates on every page. is the part that we want to remove.
When we find a page that we think should be able to penetrate easily. without which we are not confused We will use the Microsoft Edge/Chrome tool to distinguish which part is the content part of the page (that is, the part that has changed. Not all pages are the same) by pressing the F12 key on the keyboard, which will open the Developer Tools, and then use the Source Code click in the Elements tab to browse through it. It will highlight us to see that the code. we point Where is it on the web page?
If, for example, the template that I downloaded, it's a Tag div that id says content .
and to ensure that we found the right one Then try to open another page and check that as well. It's the same one on the other page that opens.
Then come back to Visual Studio and open the file first. Then press Ctrl + E, then release both keys and press D (in the menu it will say Ctrl + E, D means to do this. In Status, it will say that the button is waiting after Ctrl + E. )
This command Visual Studio will organize the code in one round to make it easier for newbies like us. Then press Ctrl + M, L again. This will collapse all messy HTML code into F12 proportions of the browser. We can lead ourselves to find the phase of our content easier. It will be in the same order that we clicked on the web page just now.
When you find it, delete the inside of the Tag that covers Content (for me it's Anything between <div id="content"...> </div>) during deletion, be careful not to delete too much. Note that Visual Studio will indentify the nested tags for us. When deleting, just be mindful. Delete only the inside of our target tag.
Once deleted, CTRL+A will copy all the text and paste it at the beginning of the _Host.cshtml file, on the line before <!DOCTYPE html>.
Then cut the part in between. <body>....</body> in the original _Host.cshtml file that is written <component...>... and end with </script> put it in the area where our content is
For example, if the Layout that I have chosen is between Tag <div id="content" ...> </div>
Then cut only the part that says <script src="...."></script> which will be the last line that we have prepared. Move it before </body>
Then delete the code from <!DOCTYPE html> until </html> of the original, leaving only the things we copied.
Then go to the MainLayout.razor file. Then delete everything, leaving only @Body.
Then you can run it (press F5). You will see that our Blazor web page has changed to the Template that we have selected. Yay 🥳
In case you forget: If the Browser page that Visual Studio currently has open is still open, close it or press Stop in Visual Studio and run it, otherwise the change will not be visible.
but....
- There is no menu on the left. (because we removed <NavMenu /> from MainLayout.razor)
- There's also a word part that says "An Error...." (number 1) pops up.
Don't panic, this will be the next thing we will learn.
✨6.2) It's all about Style.
The reason why the word An unhandled... that shows up is because the Style that controls the display of this tag has been removed. Hint that it was here that used to be on the _Host.cshtml page, but that didn't provide. Copy it with, because it will come to hit with Style that is in the Theme that we have loaded.
Try looking at the css/site.css file and looking at lines 33 and above at the same time.
- called CSS Selector , where we specify that We want to define the display of which Element. In the screen of the website, Element refers to the tag that we created in the source code. 1 Tag will get 1 Element.
- #blazor-error-ui that means We want this style to be applied to elements with the attribute id "blazor-error-ui".
- #blazor-error-io [space] .dismiss means that We want this style to be applied to an element that has an attribute class "dismiss" inside of an element that has an attribute id "blazor-error-ui".
- Called CSS Property is the display that we want. For example, enclosing it in line 37 is to set display to none , meaning that the elements selected by this style will not be displayed at all.
Now, it might be enough to guess, right? The reason why the message that says Error is displayed is because the Style that Visual Studio has set for it. It is not used in our newly created Theme. So we see the message that an error has occurred even though it really didn't happen.
If you take a look at the code that we copied a lot from the original _Host.cshtml page in section 6.1, you'll see:
- There is a tag div element with id blazor-error-ui , which will match the CSS Selector on line 33 ( #blazor-error-ui ) that should be rendered off by the CSS Property on line 37 ( display : none), but when we don't apply Styles in this file, the div is rendered by its default value (display : block), giving us the ability to see the message "An unhandled exception....".
- There is an element of Tag a defining class dismiss nested inside an Element div with id defined as blazor-error-ui , which will match the CSS Selector on line 45.
🤔 6.3) You know it's going to be broken, why don't you just copy the above code?
You might be wondering, right? Why do you already know that it's going to be broken, why don't you tell me to copy it? If in doubt Next, you should try it right away!
You can try putting the Style back in. You can do this by opening the _Host.cshtml code again. Then paste this code between the Tag Header, which if we load the Theme, you will find that there are already many Tags like this.
<link href="css/site.css" rel="stylesheet" />
Alternatively, we can drag the css/site.css file from the Solution Explorer page and paste it. Visual Studio will create this tag for you. Notice that in the example, I have also removed the ~. I'll explain later in the next section.
When we put it in, notice that there will be a change as follows on the web page that uses the Theme that I have selected. This one is tested from the /counter page.
before inserting a Tag Link | After adding a tag link, style in css/site.css is applied. |
The difference is...
- fonts on web pages will be different fonts The font after adding Style will be Font Arial.
- The Click Me button has been filled with blue.
- An Unhandled exception message has disappeared.
That's because the Stylesheet (site.css) is already implemented. If you are wondering how each Style came about? Developer Tools can be found by using Elements (Inspect) tools.
😎6.4) Exercises
Let's try editing css/site.css for our web page. back to original and let the text An Unhandled... disappear if it is, of course, the effect of the Style that is applied will affect each person differently, depending on the Template that was chosen) For my Template, it will be as shown in this picture.
After adding a tag link, style in css/site.css is applied. | After editing, the Style returned to the original (notice that the font has changed and the button is no longer blue). |
🔥 6.5) VERY IMPORTANT: The Complexity of Entering the Correct Path
For href, when we drag and drop the file, we get the path ~/ css/site.css - having ~/ like this means that the ASP.NET system will automatically convert the path. because in actual use This may cause URL Rewriting to be confusing. I want you to pay attention to read this topic carefully. (but if you notice You can see that in the example, I removed the ~.)
You can try it for fun. If we try to modify the URL of that page to have a sub folder overlapping it, our web page will crash immediately if we enter it from a URL that has a Sub Folder (eg /counters/add5) even on the same page. Can be used on URLs that do not have a subfolder (/counter) normally.
6.6) Summarize the understanding of Path before continuing.
- If we put the path in the href without a / prefix, for example css/site.css , the route with the sub folder will always be wrong. Will not get any Style or Script coming out because not putting / in front of the Path, the Web Browser will call the file. Referring to the same Level as the current URL.
- If we put the path in the href with a / prefix eg /css/site.css , it means that the browser retrieves the file, referring to the root of the current URL, which is always correct. Except in the case of doing Url Rewrite with Reverse Proxy
, for example, we wrote a website at http://internalserver/ but the IT department doesn't want our Server to be accessed from the Internet directly, so we Rewrite http://www.coresharp.net /blogs/ to call http://interalserver to continue again, that is, the person who enters the Url http://www.coresharp.net /blogs /homepagewill be like calling http://internalserver /homepage Now when the web page of http://internalserver add path with / prefix eg /css/site.css which when we ride And test internally, we mean http://internalserver/css/site.css, but because Browser doesn't know about us either. when the web page http://www.coresharp.net /blogs are called from http://www.coresharp.net So it will become a file. http://www.coresharp.net/css/site.css instead, which is the wrong file.
- If we put the path in the href with ~/ prefix, for example ~/css/site.css, it means that Blazor's system will convert the URL for us to make it the right placement. By referring to the Application Root/Virtual Path of our website, which will happen in a case similar to point 2, that is, we can put our website as a sub folder of another website. (but requires a little more setup to make it work I don't want to talk about it right now)
And if so, should I put / or ~/ or not at all?
For not wearing it at all, that will definitely not work, so it must be put in.
For 99.99% of usability, it can be put/prefixed for all Style (.css) and Script (.js) paths, because when we need to use Url Rewrite or Application Root there is a very low chance of having to use a URL rewrite or application root. In real life, most of us will have a server, who server it, each person has their own URL or use a sub domain such as https://blogs.coresharp.net . Using ~/ will waste server resources. that it will have to think for us every time that ok what url to put
So before we go on doing anything else The path should be changed to the correct one first. This can be done in two ways:
- Make multiple line edits at once. This can be done by holding down Alt and dragging the cursor down. This will allow us to type multiple lines of code at the same time.
- Use the Search & Replace tool to fix it, which has a very low chance of crashing and is fast too. You can do this by pressing Ctrl + H and entering in the search (top) and replace (bottom) fields as follows:
- Search for [paste field]href=" and replace it with [Paste field]href="/ , then press Replace all.
- Search for [space]src=" and replace it with [space]src="/
- Find [Paste Field]href="// and replace it with [Paste field]href="/ to fix the path that has // preceding it from the first time we replace and it hits the path already inserted / preceded.
- Find [space]src="// and replace it with [space]src="/
- Search for [paste field]href=" and replace it with [Paste field]href="/ , then press Replace all.
📡7) Displays (fake) data.
Let's sum it up first. What have we learned?
- We have seen a rough structure of Blazor that it consists of _Host.cshtml which is the theme of our web page. and it took the file MainLayout.razor, Counter.razor mixed with this file Create a web page for us.
- We have already understood basic HTML language enough to copy and paste the villagers' code.
- We know what a CSS Selector is and what a Style is and how it affects a web page. And how can we link Style files to our website?
- We understand that the effect of copying, what effect it has on our website. and learned how to use the Developer Tools to figure out what's where
- We've learned how to write (very) short C# programs until we've mastered the code a bit.
The next step that many of you may have been waiting for. is to let our Blazor web page show some information from the database. But about the database, let's keep EP. EP page. Let's be fake information first.
7.1) Generate pseudo-data
If the data will be displayed First of all, there must be information. For Object Oriented Programming (OOP) languages such as C#, data and actions related to that data will keep together In what is known as a class, so if our block system can occur, it must have a class to store the block first. Let's follow along as follows:
1) Create a new folder in the project named Core, ContentSystem, Nested Types by right-clicking on the project, selecting Add and New Folder. Then add the class by pressing Shift+Alt+C (or use the Add menu and select New Class) and name it BlogEntry.cs . |
|
2) In the BlogEntry.cs file is our Class . In order to store data into a Class, there must be a Property (some textbooks call Attribute), so let us add a Property for storing data. According to what a blog post should include:
By doing this:
You can see that we can type code very quickly. Practice to be fluent We should also add a description to our properties and classes. We mean what it means by typing / three times and typing it into the <summary> Tag. |
|
3) Create another class named BlogDatabase, then add 2 properties as follows:
|
|
3) Create pseudo data as follows, allow copying. It's good. Create 4-5 of them and change the text. or the date inside to be different as well and let Id = 0, Id = 1, Id = 2 and so on public List<BlogEntry> BlogEntries { get; } = new() |
7.2) Use fake data
The first thing we have to do is to copy the code for the home page of our template. If we open Pages/Index.razor , we can see that there is only Hello World right now. We don't need Hello World, but we want. The first page with a list of our posts. because we are doing blogging
For my Template, the Content part of the Home page is everything inside the <div id="content"...> of the index.html page, which I will go to open the index.html page of the downloaded Template. Then copy and paste it to Pages/Index.razor.
Then, in my template, there is a list of Posts, so we pointed it out with Inspector to see if What part is it in the code that we copied so that it can be corrected? For example, the template that I have chosen is the div that the class name is blog-simple .
We came back to search on the Index.razor page where we copied the code from the Template on the Home page (or index) and then deleted his example, leaving only 1 left.
Don't forget: Before fixing, press Stop or close the browser page first.
Then add the line
@ using Core . ContentSystem . Types
at the top of the Index.razor file, the line after @page.
Then in the area where we will show the list of posts, add the code:
@ foreach ( var entry in BlogDatabase . Default . BlogEntries) { }
Then move the preview of one post to the middle between @foreach.
Then try running it! Boom
😈7.3) Hello first Bug!
As soon as you press run, you will immediately see a screen like this. get used to This is what is called a Bug. We will have to face it every day. All day long. If you want to be a programmer 🤣
In this screen, Visual Studio tells us that our program has an exception (error in the program), which if Visual Studio is not open. The program will shut down completely. If it's a game, it's a Crash to Desktop symptom that we encountered.
The terms Exception and Bug are related to each other. Now, the program has a bug so it causes an exception, but there are some cases where there is a bug but no exception occurs, for example wrong number added, data not saved, receipt number skipped. is a mistake at the level of thinking of the programmers themselves which is a very complex program Sometimes it's confusing to write.
Now, this is a Null Reference Exception (Null-Ref-Ex), which is the number 1 exception that we encounter quite often than our peers. If the program is not well written Caused by we call the value of some variables. But we haven't put a value for it before. Now Visual Studio tells us that when trying to use BlogDataBase.Default.BlogEntries is causing NullRefEx, so we have to go back and look at the code in the file. BlogDatabase.cs again, why does this happen?
7.4) Exercises
If you write the code exactly as you say The code should be the same as in the picture. Let's look at (2) and compare with (1) to see what the difference is. And how can we fix it to make our website run? Hint that (1) has never been correct = anything. Don't skip to see it. Give it a try for 5 minutes.
7.5) Binding data to be displayed
If it can be fixed which is solved by adding = new(); Go behind Property Default (according to the code) will see that it occupies the area that is a list of posts. is displayed equal to the number of samples we've put in, yeah~ but the displayed data It's the sample data that we copy from the template, not the one we typed.
public static BlogDatabase Default { get ; } = new();
Therefore, we have to do Binding, which is to take out our real (fake) data. By inserting the code as follows:
|
Then when we try to run, we will find that our sample data that we have inserted can now be displayed~!
7.6 Make a page for passing the post
A complete Web Blog, in addition to having a listed homepage. There must be a page to read the full post as well. We'll have to create one more page, so we'll have to create one first. This can be done by right clicking and selecting Add -> Razor Component named BlogDetail.razor. and to modify the code like this
@page "/blogs/{BlogEntryId:int}" < h1 > Blog Detail of @ this . BlogEntryId </ h1 > @code { [ Parameter ] public int BlogEntryId { get ; set ; } }
Can you guess that? What do we fix? 😊 What we do is
- Tells this page to capture a patterned path as /blogs /(numbers) , eg /blogs /1 or /blogs /2 , etc. (specify it as a number by entering :int ).
- Command that the numbers captured from the URLs are inserted into the Property BlogEntryId. Note that the Property name matches the pattern in @page and has [Parameter] above it.
And if we test by opening the Url /blogs/1 (or /blogs/1548832489) we will get a screen with Element H1 that shows the number according to the URL we put in. This is called sending Parameter to our Razor Component page with URL.
Now that we can send Parameters, we just have to read the values and display them. which we can do by adding the code
@page "/blogs/{BlogEntryId:int}" @ using Core . ContentSystem . Types < h1 > @ this . CurrentEntry . Title </ h1 >< p > @( ( MarkupString ) this . CurrentEntry . Content ) </ p >@code { [ Parameter ] public int BlogEntryId { get ; set ; } public BlogEntry CurrentEntry { get ; set ; } protected override void OnParametersSet () { this . CurrentEntry = BlogDatabase . Default . BlogEntries . Where ( entry => entry . Id == this . BlogEntryId ) . FirstOrDefault (); }}
😱 The code is getting long. Can you guess what we added?
- We added a Property CurrentEntry, as its name suggests, is a post (BlogEntry) that web visitors want to read.
- exactly written OnParametersSet... If read in Thai, that is, when Parameter is set, then CurrentEntry of this one is equal to selecting an entry (Where) from BlogDataBase.Default.BlogEntries. Get only the ones whose Id is equal to BlogEntryId, then either omit the first (First) or remove the standard (Default).
- We changed it from showing Blog Detail of (incoming numbers) to CurrentEntry.Title or removing CurrentEntry Title.
And if wondering how from the URL /blogs/0 it came to be linked? Take a look at this illustration It might look a bit messy, so pay attention to follow the lines.
- From the URL that the audience typed in.....
- is replaced according to the pattern of the route that we define
- and is stored in the Property BlogEntryId
- The value of BlogEntryId is used in OnParametersSet() is used to select the BlogEntry in the BlogEntries list by looking at the value of the Id must be equal to the number in the Property BlogEntryId.
- The BlogEntry that meets the conditions is stored in the Property CurrentEntry.
- CurrentEntry values are used in lines 4 and 7, but we don't just use CurrentEntry. We use Property Title and Property Content to extract Title and Content of BlogEntry.
for making this page It has the same design as the template that we received, so I won't mention it. Because it does the same as the Index page and the last section. Is to make the Index page when clicked and then change to this page. By editing the href of Tag a in our Template when listing the post in item 7.2 from this code.
< a class = "post-link" href = "blog-single.html" > @ entry . Title </a> _ _
to be
< a class = "post-link" href = "/blogs/ @( entry . Id ) " > @ entry . Title </a> _ _
which is to create a link from the index page to the detail page. Is displayed in the browser will see that the URL will be changed to /blogs/0 or /blogs/1 according to our pseudo
At this point, the Index page can go to the BlogDetail page according to the post that we have chosen.
What's Next!?
First of all, let's review what we have learned in this EP?
- We are familiar with basic HTML and C# code at a level that is enough to copy the code of their villagers. Can read the code easily enough and can edit the villager's code (from adding 1 each to adding 5 each)
- We've learned how to use CSS basics, .css link files to HTML pages, and especially the CSS Selector. We've seen real CSS Selector effects once with #blazor-error-ui.
- We know the path why it is necessary to put / in front of it and how it differs from not putting it.
- We have learned how to create a class in C# and create a property in a class.
- We have known that List is a list of things that interest us. And we have tried to create data and put it into List as fake data in Source Code.
- We have tried copying the for command to display information from a list on a web page.
- We encountered the first Bug in our lives.
- We have learned to pass Parameter, or call it a variable, it's not wrong. to our web page and how to use that parameter
- We have seen the use of Where and FirstOrDefault with List.
- And finally, we have created a link from the Index page that sends the parameters to the BlogDetail page.
What a lot to learn!
for this chapter It lays the foundations for all of the things we need to know. In the next chapter, we'll try something more in-depth. is to save data from web pages really enter the database how it will be
See you in the next EP.