The SMTP server requires a secure connection or the client was not authenticated – Easy fix

When trying to send an email via SMTP you may get the dreaded “The SMTP server requires a secure connection or the client was not authenticated” error. This error is annoying but is actually really easy to fix!

The SMTP server requires a secure connection or the client was not authenticated.

Why did I receive the SMTP server Authentication error?

This authentication error actually happens because Google is blocking you from signing into your Gmail account. The reason for this used to be a setting called “Allow less secure apps.” but now you will have to generate an App Password and use that in your code.

Google doesn’t initially allow any application to log into your Google account. You will have to give permission for applications to access your Gmail account. This used to require a simple setting change to allow unsecured applications. Google has since changed that policy and you will have to generate a password for your application. I will show you how to do that and include an example code below!

How to fix “The SMTP server requires a secure connection or the client was not authenticated” – Old Method

Previously, To fix this error, we simply need to enable the following setting in your google account: “Allow less secure apps.” You will see this method suggested a lot all over the internet but it does not work anymore. I will provide the new solution below!

Old Method to enable “Allow less secure apps.”:

  • Login to your Gmail Account
  • Navigate to the security settings for your Google Account
  • Navigate to “Less secure App Access” and turn on “Allow less secure apps”

Once you click the toggle switch and it has been enabled, your app should now be working, or at least… It would have before the latest Google update! Previously this would have fixed your authentication issue but now you just receive this error message.

Google has actually disabled this super easy fix as of May 30th 2022. Now we have to generate a unique password for our application, which is thankfully really easy to do!

Google disabled Less Secure App setting

How to fix “The SMTP server requires a secure connection or the client was not authenticated” – after May 30th 2022

Google has now disabled the ability to enable the use of less secure applications. Instead, we will be getting an App Password and using that in our application. Follow the steps below to get your app password and then we will discuss how to use it in your application with an example.

Generate an App Password to fix the SMTP client not authenticated issue

  1. Log in to your Google account

    Navigate to Gmail.com and log in with your Google account. After that, click on “Manage your Google account”

  2. Navigate to the security section of your Google account

    Click on “Security” in the menu on the left

  3. Search for “App Passwords” in the top search box.

    Navigate to the App Passwords page by searching in the search box at the top of the page.

  4. Generate a new App Password

    Once on the App passwords screen, click “Select App” and choose “Mail” and then for the “Select Device” drop down, choose “Windows Computer”. After you have those options selected, click the Generate button.

  5. Use your new App Password

    Now that you have your app password, it is time to use it in our application to fix the client was not authenticated error message!

app password generated

Example code to send an email using the new app password:

using System;
using System.Net;
using System.Net.Mail;

namespace GmailSmtpConsoleApp
{
    class Program
    {
        private const string ToAddress = "testemail@testing.com";
        private const string FromAddress = "testemail@testing.com";
        
        private const string GoogleAppPassword = "XXXXXXXX";
        
        private const string EmailSubject = "Test email!!";
        private const string EmailBody = "<h1>Hi</h1>";
        
        
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            
            var smtpClient = new SmtpClient("smtp.gmail.com")
            {
                Port = 587,
                Credentials = new NetworkCredential(FromAddress , GoogleAppPassword),
                EnableSsl = true,
            };
            var mailMessage = new MailMessage
            {
                From = new MailAddress(FromAddress),
                Subject = EmailSubject,
                Body = EmailBody,
                IsBodyHtml = true,
            };
            mailMessage.To.Add(ToAddress);

            smtpClient.Send(mailMessage);
        }
    }
}

This code should be pretty straightforward, we are just passing our application password to the Network Credential object that we made. We then pass that NetworkCredential object off to Gmail when we send our message.

Thanks for reading and I hope this helped you fix your “The SMTP server requires a secure connection or the client was not authenticated” error message! If you are still having problems, feel free to ask any questions in the comments below and I would be happy to help!

How to install WordPress on Linux

How to install WordPress on Linux

Installing WordPress on Linux can be a bit intimidating for those who are new to the process, but with the right steps and tools, it can be quite simple. In this article, we will go over the steps to install WordPress on a Linux server using Ubuntu as an example.

Before you begin, you’ll need to have the following prerequisites:

  • A Linux server running Ubuntu 20.04 or later.
  • A web server (such as Apache or Nginx) installed on your server.
  • PHP 7.4 or later and a database server (such as MySQL or MariaDB) installed and configured on your server.

Step 1: Install LAMP stack

The first step is to set up the LAMP stack (Linux, Apache, MySQL, and PHP) on your server. You can do this by running the following command:

sudo apt-get install lamp-server^

During the installation, you will be prompted to create a root password for MySQL. Make sure to choose a strong and secure password.

Step 2: Create a MySQL Database and User

The next step is to create a database and a user for your WordPress installation. You can do this by logging in to the MySQL command-line interface by running the following command:

mysql -u root -p

You will be prompted to enter the root user’s password. Once logged in, you can create a new database and user by running the following commands:

CREATE DATABASE wordpress;
CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON wordpress.* TO 'wpuser'@'localhost';
FLUSH PRIVILEGES;

Make sure to replace ‘password’ with a strong and secure password for your new user.

Step 3: Download and Install WordPress

The next step is to download and install WordPress. You can do this by visiting the official website and downloading the latest version of WordPress or by running the following command:

wget https://wordpress.org/latest.tar.gz

This command will download the latest version of WordPress to your server in a compressed (tar.gz) format. Once the download is complete, extract the files by running the following command:

tar -xvzf latest.tar.gz

You will then need to move the extracted files to the appropriate directory for your web server, which is /var/www/html for Apache and /usr/share/nginx/html for Nginx. For example, if you’re using Apache, you can run the following command to move the files:

sudo mv wordpress /var/www/html/

Step 4: Configure Apache or Nginx

You will now need to configure your web server to serve the WordPress files. If you are using Apache, you can do this by creating a new virtual host configuration file.

sudo nano /etc/apache2/sites-available/wordpress.conf

and add the following contents:

<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    DocumentRoot /var/www/html/wordpress
    ServerName example.com
    <Directory /var/www/html/wordpress>
        AllowOverride All
    </Directory>
</VirtualHost>

If you are using Nginx, you will need to create a new server block configuration file and make sure it points to your WordPress installation. You can do this by creating a new file in the /etc/nginx/sites-available/ directory and adding the following contents:

server {
    listen 80;
    server_name example.com;
    root /usr/share/nginx/html/wordpress;
    index index.php;
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Make sure to replace example.com with your actual domain name and to check the path of the root and location of fastcgi_pass

Step 5: Configure WordPress

Once you’ve configured your web server, you can now access the WordPress installation by visiting your domain name or IP address in a web browser. You should be directed to the WordPress setup page, where you will be prompted to provide your database details and create an admin account.

You will need to provide the following information:

  • Database name: wordpress
  • User name: wpuser
  • Password: (the password you set for the wpuser in step 2)
  • Database host: localhost
  • Table prefix: (you can leave this as the default value wp_ )

Fill out the form and then click submit. After that, you will be prompted to run the WordPress installation script and you can simply press “Run the installation” button.

You will then be asked to provide some basic information about your site, such as the site title, admin username and password. Once you’ve provided all of the required information, click on the “Install WordPress” button and wait for the installation to complete.

Wrapping up

And that’s it! WordPress should now be installed and configured on your Linux server. You can now access the admin dashboard by visiting your domain name or IP address followed by /wp-admin and logging in with the admin account you created during the installation process.

Please note that this is just a simple guide on how to install WordPress on Linux using Ubuntu, and there are many other ways to install and configure WordPress. Also, it’s always a good idea to secure your installation using SSL, using security plugins and keeping your system and WordPress updated.

How to write a New Line in C#

How to write a New Line in C#

Today we are going to discuss how to write a New Line in C#! This is a simple question but the answer changes based on what you are working on. If you are creating a console application, something like Console.Writeline(); will work but if you are creating a string, you will need something like “\n”. So with that being said, let’s dive right in!

How to write a new line in a console application

To write a new line inside of a console application in C# you can use Console.Writeline. This is really easy to use since you will just write a blank line out before or after your other lines. I’ll give an example below.

Console.Writeline("Apples");
Console.Writeline(); //This is our new line
Console.Writeline("Oranges");

With the above code, you will be able to see the new line between apples and Oranges. If you are creating a console application, that is all there is to it!

How to write a New Line inside of a string in C#

When you want to write a new line inside of a string, you can use “\n”. This will cause whatever is interpreting the string to add a line break where the “\n” is located. This can be handy when sending text to a rich textbox or saving a newline character to a database. Below is a code example using “\n” to add new line into a string in C#

Console.WriteLine("This is the first line.\nThis is the line after.");

The simple way to write a new line in C#

The easiest way to write a new line in C# is to use the Environment.Newline method. This method is super simple, it’s just like the above method with “\n” but instead you append Environment.Newline to the string! This inserts a special character that Rich textboxes and the console will read as a new line.

Below you can see a code example with the usage for Environment.Newline. This is the method I use the most because of how simple it is. This makes it really easy for other people to know what you are trying to do when they read your code.

Console.WriteLine("This is the first line." + Environment.NewLine + "This is the second line.");

This method for writing a new line will work in a console application or in a windows forms application.

Wrapping up

I hope this helps you add line breaks to your C# applications. This method works almost identically in VB.Net as well. The concept it’s self works the same in PHP and many other languages. Thanks for reading and I’ll see you in the next one!

How to write to Excel files in CSharp

We are going to be writing data to Excel files using C#. Writing code to add data to an Excel sheet in C# is really easy! You can write to Xlsx, Xlsm and Xls formats all in the same way! We will go over how to do that step by step! Follow along and you will be able to write values to excel files with ease!

I’ve also created a video guide on how to do this that is embedded below and that will show you the entire process! If you would like to learn how to write to excel files from a text-based format though, read on!

Include the Required Assembly File

The first thing we need to do is include the Microsoft.Office.Interop.Excel assembly. This will contain all of the functions we will be using to write an excel document out using C#.

To include that assembly we will need to do two things, the first of which is add it to the references section.

Add reference to Excel Interop Assembly

  1. Right click References and click “Add a reference”

    In solution Explorer, right click on “References” and then click “Add a reference” to bring up the Reference Manager.
    Add reference C#

  2. Click COM and then search for excel

    Click COM on the left of your Reference Manager and then go to the search box on the right. Once there type “excel” to search for Microsoft Excel 16.0 Object Library.Add excel Reference Manager

  3. Click OK to Add the reference to your project

    Make sure the reference is checked and then hit OK to add it to your project.

Add the using statement

Next, we are going to add the Using statement to the top of our class. This will look like the code below.

using Microsoft.Office.Interop.Excel;

Create a button to write to Excel

Next, head over to your designer and add a button. This new button will be named “CmdWrite” and when pressed is going to call our write excel code. After dragging the new button from our toolbox, renaming it “CmdWrite” and then changing its text to “Write”, it’s time to double-click it to get back to the code screen.

Call our WriteExcel function

In our Form1.cs code behind the designer class, we are only going to have one line of code. This line of code will call our writeExcel function inside of our WriteExcel class. I’ll write out the code below to make it easy to copy/paste.

private void CmdWrite_Click(object sender, EventArgs e) {
     WriteExcel.writeExcel();
}

Create a new Class with a writeExcel function

Create a new file in your solution explorer called “writeExcel.cs” This new class needs to be a “code file” and it will be .cs because we are writing in C#. Once you create that file, you need to add a static void function called writeExcel. I’ll write the class out below.

class WriteExcel
{
     public static void writeExcel()
     {
      
     }
}

Create an Excel application and declare our file path

First, we are going to declare our filePath variable, to keep track of where our excel file will be saved. Next, we are going to create a new Excel Application and then declare a worksheet and a workbook. I’ll

public static void writeExcel {
     {
         string filePath = "c:\\Simple\\ExcelTest.xlsx";
         Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
         Workbook wb;
         Worksheet ws;
     }     
}

Open a worksheet inside of a workbook

Open a worksheet inside of an existing workbook to begin editing that sheet. Excel starts it’s indexes with 1 instead of 0, so you want to use worksheets[1] to get the first worksheet in your workbook.

wb = excel.Workbooks.Open(filePath);
ws = wb.Worksheets[1];

Select an Excel Range and change it’s value

Next, we are going to select an Excel range. In our example, this range is going to be C1 to C1, which is just the C1 cell. We are going to set that range’s value to “Pizza!” in our example code below.

Range cellRange = ws.Range["C1:C1"];
cellRange.Value = "Pizza!";

Save and Close the Excel Document

Lastly, we need to save and close our excel document. To save your changes to the Excel document and close it, you will need to add the 2 lines of code below. I will include all of the above code though, so you can easily copy/paste the finished product.

public static void writeExcel {
     {
         string filePath = "c:\\Simple\\ExcelTest.xlsx";
         Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
         Workbook wb;
         Worksheet ws;

         wb = excel.Workbooks.Open(filePath);
         ws = wb.Worksheets[1];

         Range cellRange = ws.Range["C1:C1"];
         cellRange.Value = "Pizza!";

         wb.SaveAs("c:\\Simple\\ExcelTest5.xlsx");
         wb.close();
     }     
}

We now have Pizza written to our Excel Document

At this point, you should be able to run your application and it should add “Pizza!” to your excel document just like it did in mine here. If you are having trouble with this, be sure to watch my video above for step by step instructions.

Opening an Excel file with C#

I wanted to toss in a tip about how to Open the excel file after you have saved your changes to it. You can use Process.start to open the excel file. The only trick is that you need to add a Using statement for System.diagnostics. I’ll add the two lines of code below, keep in mind the Using statement goes at the top of your class and the Process.Start will go in our writeExcel function.

using System.Diagnostics;

Process.start("c:\\Simple\\ExcelTest5.xlsx");

In Closing

Well, that’s about it for the absolute basics on writing to an Excel file! I hope this quick guide helps you get started and if you have any questions, feel free to ask in the comments below!

How to read Excel files in CSharp

We are going to be reading data that is stored in Excel files using C#. Writing code to read Excel sheets in C# is really easy! You can read from xlsx, xlsm and xls formats in the same way! We will go over how to do that step by step! Follow along and you will be able to get values out of your sheets with ease!

First, I’ve created a video guide that is embedded here that will show you the entire process! If you would like to learn how to read from excel from a text-based format though, read on!

The first step is to create a new C# Application in Visual Studio, I create a new WinForms application in the above example and use a simple button. You can create a Console application or WinForms application to do the following task.

I would also like to add that this code can be easily converted to work with VB.Net! Most of the code I write to read excel documents is actually written in VB.Net. If you have any questions about how to read from Excel files in CSharp or VB.Net, leave a comment below or on the Youtube video and I will help as soon as I see it!

This is the simple Windows Forms application that I created to read from an excel file. It just contains a simple button.

WinForms app to read Excel Files

Next, you need to double-click on the button to handle the click event. This will get us into the code behind with an event handler already written! That should look like the screenshot below!

After that, we need to include the Excel Object Library. To do this, you need to right-click on References, then click add a reference. Next, you click on COM on the left and search for “Excel”. This will bring up “Microsoft Excel 16.0 Object Library”. This can have different version numbers if you have different versions of Excel installed.

You will have to have a version of Microsoft Office installed for this to work. What the application does, in the end, is create an instance of Excel that we use to open and read the file. So if you don’t have Excel installed, the application can’t create an instance of it. You will know this by not being able to find the Object Library. So if you can’t find the excel reference, it’s most likely because Excel isn’t installed on the box and needs to be installed.

Adding Excel Object Library reference

Once you have the reference added, the next step is to use that reference in the heading of your code. The line of code for this is below. I’ve included the other two lines that will be there already, just so you know where to put the using Excel line.

using System;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;

Alright, now we have our references all set up and it’s time to start writing our code to read from the excel document! I created a new function called readExcel, which gets called from the new button click event handler. I’ll show what that looks like in the picture below.

Doing it this way just keeps the excel code out of the designer code. In a perfect world, you would put this function in another class file and not in the same file as the designer code (event handler in this case).

The following code is used to open the workbook

private void readExcel() {
     string filePath = "c:\path\to\file.xls";
     Microsoft.Office.Interop.Excel.Application excel = new Excel.Application();
     Workbook wb;
     Worksheet ws;
     wb = excel.Workbooks.Open(filePath);
     ws = wb.Worksheets[1];

}

Obviously, you will need to change the filePath to your desired file path. I also recommend using a file browser dialog or something to that nature, if the path changes frequently.

So to work through this code, we declare the file path, then we create a new excel application, next we create an object to hold an excel workbook, then we create an object to hold an excel worksheet. After that, we open the file located at the path and it is stored in the wb Workbook variable. Now that we have the book open, we can then get the first sheet and store that in ws, our worksheet variable.

Now that we have everything set up it is time to start reading values from cells!

The simple way to read a value from the excel file would be to just message box out the results using the line of code below.

private void readExcel() {
     string filePath = "c:\path\to\file.xls";
     Microsoft.Office.Interop.Excel.Application excel = new Excel.Application();
     Workbook wb;
     Worksheet ws;
     wb = excel.Workbooks.Open(filePath);
     ws = wb.Worksheets[1];

     MessageBox.Show(Convert.ToString(ws.Cells[1, 1].Value));

}

In my excel file, the cell at 1,1 has the word Apple and the resulting message box looked like this:

Messagebox with Excel data

Below I have broken that line down into parts that make it easier to understand:

private void readExcel() {
     string filePath = "c:\path\to\file.xls";
     Microsoft.Office.Interop.Excel.Application excel = new Excel.Application();
     Workbook wb;
     Worksheet ws;
     wb = excel.Workbooks.Open(filePath);
     ws = wb.Worksheets[1];

     Range cell = ws.Cells[1, 2];
     string CellValue = cell.Value;
     MessageBox.Show(CellValue);

}

The last 3 lines are the important bit. The first line creates a Range object called cell and stores the Range located at position 1,2 in the Excel file in it. Next we create a string variable called CellValue and pull the Value out of the cell variable and store it in the CellValue string. Lastly, we message box out that value. The resulting message box in my example said “Wine”

Another method you can do is to use excel’s own naming convention to read cells and ranges from the sheet. What I mean by that is being able to say “A1” or “A1:B1” to read from the sheet. This will make it easier for you to know where in the document you are reading at a glance. The code for that is below.

Range cell = ws.Range["A1"];

If you attempt to read a range using the above code, you are going to get Object[] as the result. This is because the value is an array instead of a single value. To read in a range of cell values, you will need to loop through the array to display each value. The code for this is located below.

private void readExcel() {
     string filePath = "c:\path\to\file.xls";
     Microsoft.Office.Interop.Excel.Application excel = new Excel.Application();
     Workbook wb;
     Worksheet ws;
     wb = excel.Workbooks.Open(filePath);
     ws = wb.Worksheets[1];

     Range cell = ws.Cells["A1:A2"];
     foreach (string Result in cell.Value)
     {
           MessageBox.Show(Result);
     }
}

The result of this will be a message box for each cell in the range which will contain the value of each cell. In my case, the first message box said Apple, and the second said Banana.

If you are reading a lot of values out of an Excel sheet, you are going to want to read the data in as a range and store that in an array. At that point, you can manipulate the array in code really quickly. If you read the data in one cell at a time, instead of as a range, it will be much slower with large datasets.

One last thing to note is that you will want to use .close() and .dispose() on your workbook after you are done reading values. This way your excel sheet isn’t continually locked out!

Steps to Read an Excel Sheet with CSharp

  1. Create a new Project

    Create a new windows forms or console application in Visual Studio

  2. Include the Excel Reference

    Include a reference to the Excel Interop Assembly

  3. Add the using statement

    Add the using statement to the top of the class to use the new reference.

  4. Create new excel objects

    Create a new Excel application, workbook object and worksheet object

  5. Open the workbook using the excel application class

    Use excel.workbooks.Open to open the file and store it in the excel workbook object.

  6. Open a worksheet in the workbook

    Use the .worksheets property to open the worksheet from the workbook and store it in the worksheet variable.

  7. Use worksheet.cells[].value to read the value

    Use MessageBox.Show(Convert.ToString(ws.Cells[1, 1].Value)); to read the value from a particular cell in the worksheet and show it to the user. That’s it and thanks for reading!

  8. Close and dispose of the objects

    You will also want to close and dispose of the workbook after you read your data. Otherwise the excel sheet will stay open and locked out.

I hope this was helpful and if you have any questions, feel free to leave a comment!

How to draw in C# using the Graphics Class – CSharp Programming

Basic overview of drawing in C#

How to use the Graphics class to draw to the screen in C#

The Graphics class is one of the fundamental classes used in programming with Windows Forms and GDI+. Through the Graphics class, you gain access to information about the display resolution and device capabilities. In this article, you’ll learn about the Paint event and how it supplies you regarding an adequately initialized Graphics object. This article also covers the most common operations performed using the Graphics object.

The first thing we will do is open Visual Studio and click “Create a new project” to get started. We are going to create a new Windows Form in C#. You could choose any project name you would like and its destined location on your desktop/pc. 

A blank project will be generated to serve as your canvas. You could change the width and height based on your preference. The next thing we need to handle is the paint event for the form. When the form is drawing itself, it will call this paint event, and then inside of that, we will get a handle to the graphics object. Afterward, we could paint the form ourselves. It is a step-by-step process that we need to accomplish. 

Declare a new graphics object with this syntax above. With this step, we could make new shapes like rectangles. 

How to draw a rectangle

To draw rectangles and squares in C#, the GraphicsObject provides the DrawRectangle() method. There are two ways to use the DrawRectangle() method. We will begin by drawing a rectangle without a pre-created Rectangle object.

  • The first step is to create a new brush. The syntax above is the code that you can use to alter the color and name of the brush.
  • It also needs the coordinates of the rectangle you want to create. To do that, you can encode the x, y coordinates like in the syntax attached. 
  • Since we’ve used 100×100 as the coordinates, it came out as square, but you could change the coordinates to generate your desired shape.

For the second method

  • To draw a rectangle, you will draw four lines. We will make a drawing pin and set that equal a new pen in this method. You could also set the color for your rectangle. The syntax above is the example that will generate your rectangle. 

How to draw a circle

Ellipses and circles are drawn in C# using the DrawEllipse() method of the GraphicsObject class. 

We made a drawing scene representing the “sun,” a circle in one of our examples. 

  • You could declare a “new brush” to create the round object. The syntax above shows the various brushes for different objects: the ground and the sun in the said scene.
  • An ellipse will be generated using the declared sun brush and filled with this syntax in the next step.

How to draw a line

Lines are drawn in C# using the DrawLine() method of the Graphics Object. This method takes a pre-instantiated Pen object and two sets of x and y coordinates (the start and endpoints of the line) as arguments.

A “ground” was made to complete the drawing scene in the example. A straight line represents it. 

Coordinates were also filled up to determine the width, height, and length to set up the ground.

The next step in this project is to try drawing a person! A stickman person, to be exact. It will be composed of a circle for its head, a line for its limbs and body.

  • We added another drawing pen to change its color, white. 

In the syntax above, we tried to make a whole component to make a stickman. With various lines and objects, it resulted in the image below. 

The background is also changed to the color blue! And there you go, a scene with a stickman was made using simple objects and lines. 

How to draw an image

To draw an image, it will require creating a bitmap from the file. To do this, the syntax below will help to run the image.  We will use the image above as the background for our generated image.

The syntax above draws the image, but the problem is that our form and image aren’t the exact sizes.  We could stretch the image to fit the form by doing a new rectangle.

The image will be stretched to fit the form better with this code. 

We will also try to attach some images to the scene. We will do next to draw an image bitmap from the file again. 

The attached image is quite big, so you could opt for a smaller size of the image you want. 

This is the revised image of the cat once you’ve scaled it correctly. 

Here is the complete syntax for the background and the cat. Make sure to layer your drawings correctly to make them appear in the correct order. After the cat image, we will draw the bird. 

Here is the image after the code for the bird image is generated and run. 

To add an extra effect, we will add a line object in the scene. 

The last thing that we will add to this project is text. To include text in your image, follow this syntax below. Make sure to set a font style first!

The text is added and repeated three times. The project is done!

This article shows how various graphical objects can be drawn within a drawing programmatically using C#. It may be quite challenging, but first but with troubleshooting, patience, and creativity, you could also finish a project in no time!

How to use Breakpoints in Visual Studio 2019 – Breakpoint Guide – Csharp VB.Net

Breakpoints are one of the best features when debugging in Visual Studio! Let’s look at how to set and use breakpoints!

What are breakpoints?

A breakpoint indicates where Visual Studio should suspend your actively running code. This allows you to look at the value of variables, the behavior of memory, or whether or not a branch of code is being run. Stepping through your code is one of the best things you can do to learn how to program.

How to set a breakpoint

To start, you can set a breakpoint on any line of executable code by clicking in the margin of the code editor (The green line in the picture above) or simply by right-clicking on a line of code and selecting Breakpoint > Insert Breakpoint. Another option is to press F9 and a breakpoint will be inserted on whatever line you have selected.

Now we have a breakpoint, and we can work on our application!

How to access the Breakpoint Pane

To access the breakpoint pane, hover over to Debug > Windows > Breakpoints. One thing you may want to do is to disable a breakpoint. You can enable/disable or delete breakpoints from this window, search and sort them. You can change breakpoint settings directly from this dialog. There is also an option to delete and export your breakpoints as well. 

You need to start your app with the debugger attached to debugging the app process. F5 (Debug > Start Debugging) is the most common way. However, you may not have set any breakpoints to examine your app code, so we will first debug. 

If you want to jump to the currently selected breakpoint, you could just click it, and it will jump into that right line. 

For more options, you could navigate through “Show Columns.” There is also a search box that is very handy to hover through your code!

You could also edit the label of a breakpoint. Within Visual Studio, once you’ve created a breakpoint, you can add one or more labels to it by simply right-clicking and choosing Edit Labels.

In terms of Hit Count, it works when you want a breakpoint to break after it has been hit a certain amount of times, you can choose Hit Count in the Breakpoint Settings and specify the number of iterations. You could also come over to Conditions (right-click on the breakpoint symbol (in the editor left margin or in the Breakpoint window) and select Condition… (or press Alt + F9, C), which will open the Breakpoint Settings window.) and you could set a hit count condition.

Lets get to know the Watch window

To navigate to the watch window, you will need to select Debug-> Windows -> Watch -> Watch 1. Once you have opened the watch window, you can use it in conjunction with breakpoints to easily check the value of variables while code executes.

The Watch Window allows you to see the value of variables and expressions while debugging. It’s kind of like the DataTip you get when hovering over a variable, except that you can write any expression you want. It’s available from Debug | Windows | Watch | Watch 1 or Ctrl + Alt + W + 1.

There are four watch windows in Visual Studio, which you can use in different contexts (Watch 1, Watch 2, etc.).

Any expression can be entered into the watch window. The same rules apply to expressions as to code. So if you write an illegal expression, you’ll see the same compiler error.

To add items to watch, do any of the following: Write them manually in a new row of the Watch window—Right-click on a variable and choose “Add Watch” in the context menu. Right-click on a variable in the DataTip and select “Add Watch.” “Add Watch” button from QuickWatch.

Breakpoints are a great part of Visual Studio

One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop. Breakpoints are an essential tool for debugging your applications. You set the breakpoints whenever you want to pause the execution.

Breakpoints really helped me learn how to program. I think they were one of the most valuable tools when it came to understanding code. If you just can’t wrap your head around how a certain block of code works… Just step through it using a breakpoint and watch it work it’s magic! I hope this quick guide on breakpoints helped you and I’ll see you in the next one!

How to Free Up Disk Space on Windows 10

Today we are going to go over multiple ways that will help you free up disk space on your Windows PC. If you have tried to install a game or new application and you just don’t have room then this is going to be super helpful! Be sure to check out the WinDirStat application at the bottom of the list because it helped me the most!

Get an additional hard drive

No matter how large a hard drive or solid-state drive you have in your PC or laptop, there will come a time when you run out of space. If you’re bumping up against your PC’s physical storage limit, here are some quick tricks you can use to reclaim a couple of gigabytes’ worth of storage space. These options will take you only so far; if you need more free space after following these tips, you may need to add a second hard drive or replace your current drive with one with more storage capacity. 

Uninstall Applications using add/remove programs

You probably have some apps and programs on your PC that you don’t use — either apps you’ve installed and forgotten about, or bloatware that came preinstalled on your computer from the manufacturer. To find out which apps are taking up space, open the Settings menu and go to Apps > Apps & features and choose Sort by size. To uninstall an app from this menu, click the app and then click Uninstall.

Run Disk Cleanup

Just one tip, you could also right-click your hard drive, you could click Disk Cleanup. Windows has a built-in disk cleanup utility, aptly named Disk Cleanup, which can help you clear up space by removing various files — including temporary internet files, system error memory dump files, and even previous Windows installations that may still be hanging around. Select the file types you want to delete — from Downloaded Program Files to Thumbnails — and hit OK. If you’re unclear about what files are included for each item listed, click the View Files button to check before proceeding.

Use WinDirStat to find and delete large hidden files

One discovery I’ve also found is WinDirStat. WinDirStat is a disk usage statistics viewer and cleanup tool for various versions of Microsoft Windows. You could opt to download this application here: https://windirstat.net/download.html. Go with the recommended installation.

Launch WinDirStat and select the drive you want to evaluate. Click “OK,” and give the program 5 to 10 minutes to scan your hard disk.

When the scan is complete, you’ll be presented with the summary screen. The top half lists files and folders sorted by file size. If you click on a folder or file, the corresponding color block will be highlighted below.

Alternatively, click the large blocks of color to find out which files are taking the most space.

Once you’ve identified the culprit, right-click the file and choose “Delete (to Recycle Bin)” for later disposal, or “Delete (no way to undelete)” for permanent, irreversible deletion.

Perform this scan in WinDirStat about once a month to clean up any files you no longer need access to. For day-to-day file deletion, follow our instructions for permanently deleting files, as emptying the Recycle Bin still leaves traces of the deleted files on your hard drive

How to Write Speech Recognition Applications in C#

In this article, we will discuss how to use Microsoft’s Speech Recognition Engine to write a virtual assistant application. Speech recognition apps are the way of the future and they are actually easy to write using Microsoft.Speech Recognition.

Speech Recognition Operations

A speech recognition application will typically perform the following basic operations:

  • Start the speech recognizer.
  • Create a recognition grammar.
  • Load the grammar into the speech recognizer.
  • Register for speech recognition event notification.
  • Create a handler for the speech recognition event.

Free Speech Recognition API

If you are looking for a free solution for a hobby application or if you’re just trying to get your MVP built for your application, this is a nice place to start. You could swap over the code later to use for more expensive APIs available.

In this video, I also referenced Microsoft documentation, you could access this through this link. We used this example, they also have a console app built here. 

The first step is to add the following line.

microsoft.speech.recognition

You need to import the speech recognition engine first and to do that, adding the reference is a must. Navigate to your Solution Explorer and find “References” and search for speech. 

You need to add a reference to the System.Speech assembly, which is located in the GAC.

This is the only reference needed. It contains all of the following namespaces and classes. The System.Speech.Recognition namespace contains the Windows Desktop Speech technology types for implementing speech recognition.

Before you can use the Microsoft SpeechRecognitionEngine, you have to set up several properties and invoke some methods. The next step now is to create a new recognizer. In the video, at the top of my class, I’ve created an empty object for the recognizer. 

// Create an in-process speech recognizer for the en-US locale.  
recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));

On load, I have the following code.

loadSpeechRecognition(); 

This is a function that has the loading code for the recognizer. We create a new speech recognition engine and pass it as a language because this works in multiple languages. 

private void loadSpeechRecognition()
{
    // Create an in-process speech recognizer for the en-US locale.  
    recognizer = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-US"));

    var gb = new GrammarBuilder(getChoiceLibrary());
    var g = new Grammar(gb);
    recognizer.LoadGrammar(g);

    // Add a handler for the speech recognized event.  
    recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

    // Configure input to the speech recognizer.  
    recognizer.SetInputToDefaultAudioDevice();

    // Start asynchronous, continuous speech recognition.  
    recognizer.RecognizeAsync(RecognizeMode.Multiple);
}

Instantiate your recognizer and then you are going to build this choice library.

If you look back to the SpeechRecognitionEngine Class that is linked in this article, they created a list of choices. In your application, you may create a function that returns a list of choices.

    public Choices getChoiceLibrary()
    {
        Choices myChoices = new Choices();
        //greetings
        myChoices.Add("hey " + Agent.charName);
        myChoices.Add("hi " + Agent.charName);
        myChoices.Add("hello " + Agent.charName);
        myChoices.Add("bye " + Agent.charName);
        myChoices.Add("thanks " + Agent.charName);
        //open things
        myChoices.Add(Agent.charName + " open notepad");
        myChoices.Add(Agent.charName + " open youtube");
        myChoices.Add(Agent.charName + " open excel");
        myChoices.Add(Agent.charName + " open discord");
        myChoices.Add(Agent.charName + " open davinci");
        myChoices.Add(Agent.charName + " play some music");

        //Rocket
        myChoices.Add(Agent.charName + " say nice shot");
        myChoices.Add(Agent.charName + " say sorry");
        myChoices.Add(Agent.charName + " say no problem");
        myChoices.Add(Agent.charName + " say thanks");
        myChoices.Add(Agent.charName + " say great pass");
        myChoices.Add(Agent.charName + " say good game");

        //Chrome
        myChoices.Add(Agent.charName + " close this tab");
        myChoices.Add(Agent.charName + " refresh this tab");
        myChoices.Add(Agent.charName + " open gmail");

        //close things
        myChoices.Add(Agent.charName + " close notepad");

        myChoices.Add(Agent.charName + " lets play chess");
        myChoices.Add(Agent.charName + " open chess");

        myChoices.Add(Agent.charName + " move");
        myChoices.Add(Agent.charName + " move somewhere else");
        return myChoices;
    }

This code creates a new “choices” object and then adds your choices to it.

These pertain to the words the user can say. Make sure to add a list of choices because it heightens the accuracy of your command. 

After you have built your set of choices, it will return back over here to this grammar builder. This is where you can tell the API how a sentence should look.

The next step is the speech recognized event handler.

    public void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
       bombini.processSpeech(e.Result.Text);
    }

This action is what your recognition engine hears (something that matches with one of the choices), it will call whatever function you have built. I have it calling a function with a few different commands that it can run.

public void processSpeech(string speechText)
    {
        string currWinTitle = currentWindow.GetActiveWindowTitle();
        switch (speechText)
        {
            //open things
            case charName + " open excel":
                myActions.startProcess("excel.exe", "");
                myActions.animate(gestures.Write);
                break;
            case charName + " open notepad":
                myActions.startProcess("notepad.exe", "");
                myActions.animate(gestures.Write);
                break;
            case charName + " open youtube":
                myActions.startProcess("chrome.exe", "http://youtube.com");
                myActions.animate(gestures.Search);
                break;
            case charName + " open davinci":
                myActions.startProcess("G:\\DaVinci Resolve\\Resolve.exe", "");
                myActions.animate(gestures.Search);
                break;
        }
    }

You could also take a look at “e.result.text” which is going to be the result that the recognizer will generate. 

After setting up the event handler is set to listen to input from the default audio device. This determines if it will be listening on your microphone or listening to a headset.

Default audio device

Once you have the above set up your application should be able to listen on the correct device.

Once you have followed all of the above steps, we can start the Speech Recognition Engine asynchronously which will begin listening on another thread. Starting the Engine asynchronously makes it keep listening constantly on a second thread instead of blocking the current thread.

That is it! There are plenty of other possibilities to use the SAPI for, perhaps you could use it for innovative projects!

Thanks for reading and I’ll see you in the next one!

How to check page views of a single page in Google Analytics

Are you curious about how your visitors interact with your one-page website? Do you want to know what interests them the most? Today we talk about how to check page views of a single page! We also deep dive into behavior analytics!

With the right setup, you can easily track your single-page site in Google Analytics just like any other website. Sadly, Analytics doesn’t track pageviews by default on sites that have content on a single page.

Having a single-page website has a lot of benefits over a multi-page site. With a single-page site, your visitors can read your entire content in one place, as they don’t have to explore different pages by making multiple clicks.

Navigate to analytics.google.com in your Web browser. Click the “Access Analytics” button on the right side of the page and enter your Google account email address and password if prompted. If you haven’t yet created an Analytics profile for your website, click on the “Admin” tab and click “Add New Account” to create an account for the website you wish to track.

Just a quick note, you need a javascript line to be added to your website and once you’ve added that to every page on your website, then it gets propagated to every page and all the data streams in for Google Analytics. 

The Behavior section reveals what your visitors do on your website. Specifically, the reports tell you what pages people visit and what actions they take while visiting.

You can access Behavior reports using the menu in the left sidebar of your Google Analytics dashboard.

For example, in this video, I’ve discussed that I made content in regards to Diablo 2, an action role-playing hack-and-slash computer video game. In this webpage, you could keep track of how your pages are ranked according to the number of views.

You could click on your chosen page to see its detailed statistics, as seen in the screenshot above. You could also change the time period from daily, weekly, and monthly, depending on the data that you want to see. 

The Behavior Flow report lets you see the path visitors commonly take on your website—from the first page they view to the last page they visit before leaving your site. This report gives you a visual guide to how long visitors stay on your website and where those visitors end up leaving.

One of the keys to maintaining a successful website is continuous tracking and analysis of its performance metrics. Web analytics programs such as Google Analytics provide numerous reports about user behavior on your site. The Pageviews report in Analytics allows you to see how well a given page engages users relative to other pages. The Pageviews data can also provide insight into whether the content on a page meets the needs and expectations of your visitors.