.NET Archives - Stackify Fri, 12 Apr 2024 15:17:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.4 https://stackify.com/wp-content/uploads/2023/02/favicon.png .NET Archives - Stackify 32 32 What is IIS? https://stackify.com/iis-web-server/ Wed, 27 Sep 2023 23:50:00 +0000 https://stackify.com/?p=18342 In this post, we’re going to take a close look at IIS (Internet Information Services). We’ll look at what it does and how it works. You’ll learn how to enable it on Windows. And after we’ve established a baseline with managing IIS using the GUI, you’ll see how to work with it using the CLI. Let’s get started!

What Is an IIS Web Server?

An IIS web server runs on the Microsoft .NET platform on the Windows OS. While it’s possible to run IIS on Linux and Macs using Mono, it’s not recommended and will likely be unstable. (There are other options, which I’ll present later). It’s versatile and stable, and it’s been widely used in production for many years. Version 10 is the most current. Once it’s installed you’ll see this welcome page in your browser. “Tervetuloa!”

What is IIS

But before we dig into the nitty-gritty of IIS, let’s start by defining a web server in a general sense.

What Is a Web Server?

The internet is good. And the internet cannot exist without web servers. But what exactly is a web server? Let’s define that in the abstract so we can have some context for how IIS fills this role.

A web server is a process for hosting web applications. The web server allows an application to process messages that arrive through specific TCP ports (by default). For example, the default port for HTTP traffic is 80, and the one for HTTPS is 443.

When you visit a website in your browser, you don’t typically specify the port number unless the web server is configured to receive traffic on ports other than the default. Visiting http://www.example.com will send your request to port 80 implicitly. You could specify the port number if you’d like http://www.example.com:80, and https://www.example.com:443 for TLS (Transport Layer Security).

Assuming the default configuration and TLS is configured for your web application, the web server will receive all inbound traffic to ports 80 and 443. What the web server does with the traffic from there depends. There are countless options for how the web server can process those requests.

The two main process models for web servers are to either handle all requests on a single thread, or to spawn a new thread for each request

How does IIS handle web requests?

The two main process models for web servers are to either handle all requests on a single thread, or to spawn a new thread for each request. Although the single-thread model (Node.js, for example) has some worker threads available, it typically only uses them for certain kinds of work, such as file system access. The thread-per-request model that IIS (and its lightweight cousin IIS Express) uses will grab a thread from a thread pool for each request.

Web servers typically handle requests using a request-response pattern. The client sends a request and receives a response if all goes well. HTTP protocol is the ubiquitous choice when communicating between a client and web server over the internet.

Benefits of an IIS Web Server

IIS offers a range of features that make it a compelling choice for hosting web applications.

  • IIS is rich with features. Most commonly, IIS is used to host ASP.NET web applications and static websites. It can also be used as an FTP server, host WCF services, and be extended to host web applications built on other platforms such as PHP.
  • There are built-in authentication options such as Basic, ASP.NET, and Windows auth. The latter is useful if you have a Windows Active Directory environment—users can be automatically signed into web applications using their domain account. Other built-in security features include TLS certificate management and binding for enabling HTTPS and SFTP on your sites, request filtering for whitelisting or blacklisting traffic, authorization rules, request logging, and a rich set of FTP-specific security options.
  • Application pools. We’ll have to take a closer look at the application pool, as it’s a critical component of the IIS process model.
  • Remote management. IIS can also be managed via the CLI or using PowerShell. You can script everything, which is great if you like the power that comes with being able to do so.

By now, you should have a good impression about the configurability and versatility of IIS. You should also be aware that it can be extended to serve (pun intended) many purposes besides hosting ASP.NET apps. Through extension, IIS becomes a highly versatile and stable web server for the Windows platform. Let’s take a look at how to install IIS on Windows 10. (The same process applies to Windows 7 and 8.)

Before we dive into the technicalities of application pools, let’s understand how to set up an IIS web server.

Steps to Set Up IIS

Setting up IIS is a straightforward process, and it involves the following steps:

Calling it “installing” would be a bit much. After all, IIS is a feature in Windows. What you really need to do is enable the feature. In Windows 10, you can press the Windows key and type “turn win.” You should see “Turn Windows features on or off.”

https://www.hitsubscribe.com/wp-content/uploads/2018/04/TurnWindowsFeaturesOnOrOff.png

Select that to open the “Windows Features” dialog. From here, you can turn on all sorts of additional features, including PowerShell 2.0, a deep directory tree of options for Internet Information Services (IIS), and a subsystem for Linux. (I have to say, that last one has come in handy for me numerous times, like when a Node app has some shell scripts as part of the npm build).

The Internet Information Services (IIS) option is the one we want!

Just clicking the box for it will give you a good starting point. You may, however, want to dig deeper. World Wide Web Services > Application Development Features is where you enable ASP.NET, CGI, and WebSocket Protocol. You can always come back to this if you need to make adjustments.

To enable IIS on Windows Server, you can either use PowerShell or Server Manager to install the “Web Role (IIS).” See this walkthrough for details.

Once you have all the desired IIS features selected, click OK and go get a fresh cup of coffee. When the install is done, you can get to the IIS GUI by typing “IIS” in the Windows search or by running “inetmgr.”

The GUI

Before we get into details, I want to give you a quick intro to IIS Manager. I’ve highlighted the areas of interest because this thing is such a mess. It takes some getting used to, but there are a few things I can offer to help with, as it concerns getting around in here.

IIS Manager

First of all, there are three panes. The left has the connected servers. (You can connect to remote servers too.) The middle pane is where you find all the features like application security, logging, filtering, and redirecting. Or when you select “Content View,” you’ll see the contents here in the middle instead. On the right is the actions pane. This changes depending on the selected context.

I’m not sure why that little extra icon at the bottom right is there, but you can resize the window down there too.

TIP: you can right-click most of the icons and use the context menu to perform the most common actions.

If you expand the “connection” in the connections pane, the first thing you should see is “Application Pools,” followed by “Sites.” We’re going to focus on those in the next two sections.

Application Pools: What Are They and How Do They Work?

Here’s a look at the application pools that are set up by default in IIS. As you can see, there are combinations of v2.0 and v4.0, and of classic and integrated.

IIS Application Pools

The integrated pipeline differs from the classic pipeline in that ASP.NET is integrated into the request pipeline of IIS. In classic mode, requests had to pass through one pipeline for IIS and another for ASP.NET. Integrated has been the preferred mode since IIS 7 was released with Windows Server 2008 and Vista. Don’t use classic unless you have to. Same goes for v2.0. They’re only for legacy support. In fact, if you don’t need those application pools, you might as well just go ahead and remove them. We don’t need any cruft hanging around!

A single application pool has zero to many worker processes (w3wp.exe) running at any given time. The worker processes run instances of your application.

https://www.hitsubscribe.com/wp-content/uploads/2018/04/IIS_Worker_Processes-1024x44.png

Creating Application Pools

In the “Actions” pane on the right side of the IIS window, click “Add Application Pool…” to bring up the dialog. It’s pretty straightforward. You can usually just enter a name and press “enter” or click “OK.”

Create IIS Application Pool

You can also add an application pool by right-clicking the “Application Pools” node in the “Connections” pane. The tip from earlier proves its value already!

App pool users

IIS creates a virtual user for each app pool (common nomenclature for application pool). These worker processes run as the app pool’s virtual user by default. They can run as a different user (a domain account, for example) if they need special permissions.

Even though I removed the app pools from the server, the virtual users live on!

IIS Application Pool Users

These virtual users still get their own standard folders, such as “Desktop,” “Music,” and “Pictures.” They don’t chew up that much space (110 MB), but once the app pool is removed, those user folders are cruft and can be deleted.

App pool recycling

One key feature of app pools is recycling. By default, app pools recycle every 1740 minutes (29 hours), and when the configuration file changes. You can configure recycling to suit your needs. App pool recycling frees up the memory consumed by applications running in an app pool. Recycling can prevent runaway processes from chewing up all the memory on your server.

What kinds of things use memory in your process? Everything on the stack and heap—static variables and properties, anything in the memory cache, any objects that are referenced by another object, any blocks of memory waiting to be garbage collected, you get the picture.

IIS Application Pool Recycle Conditions

Logs

You can choose which events you would like to log (or not log). As you can see, not all options are shown in the previous dialog—”Runtime recycling events” don’t appear to be configurable. This isn’t entirely true.

IIS Application Pool Recycle Events to Log

A recycle starts a new process then spins down the current process. The new process will, as you would expect, have a new PID. You can change this behavior as well as other recycling behavior in “Advanced Settings…”. In fact, you can edit any of the recycling configurations in this menu. The “Recycling…” dialog is redundant in that respect. However, you can turn off recycling for config changes here. You probably don’t want to though. Your running app wouldn’t get the config updates.

IIS Application Pool Recycle Advanced Settings

Note that “overlapped recycle” implies that it’s possible to have more than one instance of the application. You should disable this only if your application requires it. Overlapped recycle prevents disruptions that would occur if the recycle waited for the current process to drain requests before starting the new process. In other words, no new requests would be handled until the current requests completed or the configurable timeout period elapsed (90 seconds by default).

Advanced Configuration

There are far too many app pool configurations to iterate in detail in this post. For now, a brief overview will have to suffice. I’ll quickly rattle off some points about each of the areas of “Advanced Settings,” as shown below.

IIS Application Pool Advanced Settings
  • The “General” setting will let you
    • Change .NET CLR versions
    • Allow 32-bit applications
    • Change pipeline mode
    • Set queue length (1000 requests by default)
    • Set to run always or on demand
  • The “CPU” option covers
    • Throttling
    • Processor affinity
  • “Process model” will let you choose settings for
    • Identity
    • Idle timeout
    • Max worker processes
    • Health monitoring (You should turn this off locally for debugging because a halted debugger won’t respond to ping)
  • “Process Orphaning” is useful for debugging unresponsive processes
  • “Rapid-Fail Protection” is good for when you want to configure load balancer responses to failures

Sites

“Sites” is the node next to “Application Pools” in the server node of IIS manager. It’s here that you add and manage websites and FTP sites (if installed). While application pools have an advanced settings dialog, sites have many more configuration options! Sites have many features, each with their own configurations.

These features fall under three headings in the IIS manager:

  • ASP.NET (if you have it installed)
  • IIS
  • Management

Context menu

You can toggle between “Features” and “Content” when you have a site selected. You can right-click the site and open the folder from the context menu by selecting “Explore.” There are other things you can do from this context menu, such as edit permissions.

IIS Application Pool Context

This actually just brings up the properties of the site’s folder. From there, you’ll have to switch to the “Security” tab to actually edit the permissions.

IIS Application Pool Permissions

In typical Windows fashion, there are several other ways you can edit permissions. See your favorite Windows help sites for more information on how to set folder permissions.

You can perform several common tasks from the context menu. Inside the “Manage Website” item, you can start and stop the website, open it in your browser, and go to advanced settings. We’ll definitely want to look at those, but first, let’s talk about what you’ll see when you select “Edit Bindings…” which is also available in the “Action” pane as “Bindings…”.

Bindings

You’ll need to add a site binding in the “Bindings…” dialog if you’re enabling HTTPS for your site. You can also set the host name and port numbers there. If you have additional binding for your site, you can add those here as well. Perhaps you’re using the net.tcp or a net.pipe bindings (if you’ve added the features on the server and enabled them for the site). Or you can set an IP address here.

It’s possible to run more than one site listening on the same port. To do this, you’ll use different host names. For example, you could have admin.example.com bound to your admin site and blog.example.com bound to your blog. All example.com traffic would go to the same IP (load-balancer/server), but IIS would use the host header to direct traffic to the appropriate site. These are useful for white-label apps as well: acme.example.com, foo.example.com, bar.example.com.

Basic settings

“Basic Settings…” is the same dialog as you get when you first set up the site. You probably won’t need to go there unless you want to change the application pool or the location of the site or if you want to connect as a different user, rather than IUSR (pass thru). If you need to use a service account to access the site directory, you can choose “Connect as…” from the “Edit Site” dialog.

https://www.hitsubscribe.com/wp-content/uploads/2018/04/Sites_Basic_Settings-300x167.png

Note: you should take care to secure any directories you use in IIS. You can benefit from reading about how the default inetpub directory is secured.

Sub-sites and virtual directories

You can host several applications and virtual directories under one site. Applications can run in their own application pools, but virtual directories cannot. As shown below, I’ve set up an admin application and a blog virtual directory under Site2. They can be accessed using http://localhost/admin and http://localhost/blog as seen below. Both will respond with built-in error pages unless there’s something in the directories.

https://www.hitsubscribe.com/wp-content/uploads/2018/04/Sites_Subsites_Virtual_Directories.png

The source directories for sub-applications and virtual directories need not be subdirectories of the parent site. You can keep those directories anywhere you wish. You may want to map some common web resources (images or JS files) to a relative path for multiple sites. Virtual directories are perfect for this.

Default and error documents

When a user visits the root of your site (www.example.com/), they’ll be presented with a default document. The defaults are shown below. You can add your own documents, remove documents, or disable them altogether. If you disable them, the user will get an ugly 403 error screen unless you’ve given permission to list folder contents (not recommended). It’s best to have a default document in place.

https://www.hitsubscribe.com/wp-content/uploads/2018/04/Sites_Default_Document-300x234.png

I’ve put an index document in each directory: the site, the application, and the virtual directory.

  • Site2
    • Admin
      • index.html
    • Blog
      • index.html
    • index.html
  • http://localhost/ will load the default document at Site2/index.html
  • http://localhost/admin/ will load the default document at Site2/Admin/index.html
  • http://localhost/blog/ will load the default document at Site2/Blog/index.html

If you’re worried about IIS taking up memory and CPU on your machine, don’t. Unless the worker processes are running (and handling requests with heavy processing), it sits idle. If you’re seeing heavy CPU usage, this troubleshooting guide can help, provided you’re using ASP.NET.

CLI and remote management

AppCmd.exe

AppCmd is the built-in CLI tool for configuring and managing IIS. You can use it to create sites and app pools, link virtual directories, and edit configurations. Let’s look at a few things it can do.

First of all, add %systemroot%\system32\inetsrv\ to your path so that you can run appcmd from a command prompt in any location.

Run the command prompt as administrator.

setx PATH "%PATH%;%systemroot%\system32\inetsrv\"

Try the following commands to explore appcmd:

  • Run appcmd /? to see the help text
  • See what apps are running with appcmd list app
  • Use appcmd list backup to see backups of your IIS config

Add site

appcmd add site /name:"Dummy Site" /id:10 /bindings:http/*:81:

Now list apps again. You won’t see the new site you’ve added because it isn’t considered an app. If you go to the GUI and refresh your sites, you’ll see the new site there, but it’ll be broken. We need to add an app using appcmd.

appcmd add app /site.name:"Dummy Site" /path:"/"

This will only add the app to the site at the root. It will create an app named “Dummy Site/”. We still need to link the app to a virtual directory then point that to a physical path.

appcmd add vdir /app.name:"Dummy Site/" path:"/"

appcmd set vdir "Dummy Site/" /physicalPath:"c:\inetpub\wwwroot"

This is the verbose way to use appcmd to create an IIS site. There’s an easier way.

The EZ way

You can save a lot of keystrokes while creating the site if you set the physicalPath parameter in the first command. This will do the whole thing in one shot:

appcmd add site /name:"Dummy Site" /id:10 /bindings:http/*:81: /physicalPath:"c:\inetpub\wwwroot"

But knowing the other commands gives you a better idea of how an IIS app really works under the hood. In the past, I’ve used appcmd in the post-build script of ASP.NET proj files to ensure the site was set up locally on new developer machines. You can also do a backup and restore of IIS config using appcmd.

Deploying updates

To give you one more idea about using appcmd, consider doing the following:

  1. Create a “sites” folder.
  2. Create a subfolder for each site.
  3. Deploy versions to subfolders under each of those.
  4. Stage new versions.
  5. Use appcmd to update the site to use the new folder.

Given an app named “Hello World” pointing to C:\Sites\HelloWorld\1.0.0  and a new build “1.0.1” that’s been staged in C:\Sites\HelloWorld\1.0.1 , when it’s time to go live, then you can use the following command to flip the site to the new version:

appcmd set vdir "Dummy Site/" /physicalPath:"c:\Sites\HelloWorld\1.0.1"

appcmd recycle apppool /apppool.name:defaultapppool

And if you need to roll back your site, run the following:

appcmd set vdir "Dummy Site/" /physicalPath:"c:\Sites\HelloWorld\1.0.0"

appcmd recycle apppool /apppool.name:defaultapppool


Here’s a great guide from Microsoft with more information on using AppCmd.

IIS reset

“iisreset” is a separate executable used to stop, start, restart IIS or event to reboot the computer (/REBOOT). You can pass it a “computername” parameter to have it control IIS on another computer. You will need to run this as admin. Many developers and system admins like to use this after a deployment, and that’s not a bad idea either!

PowerShell

PowerShell has a powerful set of tools for managing IIS. You could also send the iisreset command remotely using Invoke-Command -ComputerName “computername” -ScriptBlock {iisreset}, provided you allow remote command invocation of arbitrary commands on your servers—and that’s generally not a good idea!

Despite my own security concerns with sending arbitrary remote commands using PowerShell, the IIS administration cmdlet are really useful for DevOps-style web server admin. You can check this documentation for IIS administration using PowerShell to get an idea of what it can do.

Shutting down

Despite all the features, configurations, and commands we’ve covered in this post, we’ve only scratched the surface. Each feature has its own configurations, and there are many extensions that you can add by installing the Web Platform Installer extension.

And with that, let’s bring this post and the IIS server to a conclusion:

iisreset /stop

But before we completely end this article, keep in mind that there are solutions such as Stackify Retrace that can help you with your IIS journey. Retrace is an Application Performance Management (APM) solution that can provide server health metrics and error log integration that improves your application performance.

Try your free 14-day trial today!

Check out Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.

]]>
OOP Concepts in C#: Code Examples and How to Create a Class https://stackify.com/oop-concepts-c-sharp/ Thu, 27 Jul 2023 13:52:00 +0000 https://stackify.com/?p=12877 Object-oriented programming (OOP) is a paradigm (a sort of “style”) of programming that revolves around objects communicating with each other, as opposed to functions operating on data structures. C# is the flagship language of the .NET ecosystem. Despite being a multi-paradigm language, its forte is certainly OOP.

OOP is a recognized programming paradigm, but programming languages differ in how they interpret and implement its tenants. In this post, we’ll offer you a guide on OOP concepts using C# as the language for the examples.

What you’ll get, then, is OOP through C#-colored lenses. That won’t diminish your experience in any way at all for two reasons. First, C# is one of the most popular languages wide there, and learning it is an asset for your career. Secondly, most of the main concepts of OOP—such as encapsulation, abstraction, and polymorphism—are applicable no matter what the language, even if the specifics of how they’re implemented change.

So, what you’ll learn today will certainly be transferable to other languages. With that in mind, let’s get started by first defining what an object is.

What is an Object?

As the name implies, object-oriented programming revolves around the concept of object. So, nothing is more appropriate than to start our guide by defining this concept and giving examples.

In the context of object-oriented programming, an object is a cohesive unit of data and behavior associated with such data | C# oops concepts

Definition

In the context of object-oriented programming, an object is a cohesive unit of data and behavior associated with such data. An object represents a concept or entity in the given business domain the program resides on. The data it carries describe the characteristics or properties of said entity. The object’s behavior represents actions that can be operated on its data, and it’s expressed to external objects via the object’s methods.

How is programming with objects different than the alternatives? Pick procedural programming, for example. In that paradigm, there’s a stark divide between data and behavior. Generally speaking, in this paradigm, you have data structures that carry data around and don’t do anything and functions that operate on said data structures.

Examples

Let’s say you have a string and want to split it according to a delimiter—for instance, a comma. In a procedural programming context, you’d probably do something like this:

input = "123,asd,345"
parts = split(input, ",")

The example above isn’t any particular programming language—it’s pseudo-code. As you can see, we called the split function and provided both the complete string and the delimiters as arguments.

In an OOP language, the string itself would be an object containing a split method. Here’s the same code, now in C#:

string input = "123,asd,345";
var parts = input.Split(",");

Classes

In many OOP languages, the class is a first-class concept. C# is one of those languages, so let’s examine now what a class is.

In simple terms, a class is a blueprint from which you create an object, a process we call instantiation. A class defines both the data and the behavior the objects created from it will have.

Let’s see a basic example of a C# class:

public class Person
{
	private readonly string _name;
	private readonly int _age;

	public Person(string name, int age)
	{
		_name = name;
		_age = age;
	}

	public string Introduce()
	{
		return $"My name is {_name} and I'm {_age} years old.";
	}
}

In the class above, we define both the data—the name and age fields—and the behavior—the Introduce method—that objects instantiated from the class will have.

And how do we create objects? By instantiating them, using the new keyword. Let’s see a few examples:

Person p = new Person("John Doe", 25);
Person p2 = new Person("Mariah Silva", 32);
Assert.AreEqual("My name is John Doe and I'm 25 years old.", p.Introduce());
Assert.AreEqual("My name is Mariah Silva and I'm 32 years old.", p2.Introduce());

Properties

In the class above, we made use of fields to store the person’s name and age. More specifically, we used private fields, which means other objects can’t access those values. What if we wanted to let other objects know those values? Would it be possible to define the fields as public?

Yes, and that would be terrible because it’d break encapsulation. You’ll read more about encapsulation in a minute, but for now, understand that an object’s internals is no one else’s business. If an object B knows about the internals of object A, then we say that B depends on A.

That means that when A changes, B probably has to change as well. In order to avoid that, we need to make use of encapsulation: the access to an object’s internal has to be protected in such a way that other objects aren’t affected in case a change in implementation occurs.

In C#, the mechanism we use for that is properties. Let’s see a new version of the previous class:

public class Person
{
	private readonly string _name;
	private readonly int _age;

	public Person(string name, int age)
	{
		_name = name;
		_age = age;
	}

	public string Introduce()
	{
		return $"My name is {_name} and I'm {_age} years old.";
	}

	public string Name { get { return _name; } }

	public int Age { get { return _age; } }
}

Now, via properties, we define getters that return the value of the private fields in a safe way. As you can see, we simply return the values as they are, so you might wonder why to bother.

Let’s imagine that some changes made it necessary to split the _name field into _firstName and _lastName. If our clients—that is, the objects that use our class—know about the fields, they would have to change. But if they only depend on the property, we can make this instead:

public class Person
{
	private readonly string _firstName;
	private readonly string _lastName;
	private readonly int _age;

	public Person(string firstName, string lastName, int age)
	{
		_firstName = firstName;
		_lastName = lastName;
		_age = age;
	}

	public string Introduce()
	{
		return $"My name is {Name} and I'm {_age} years old.";
	}

	public string Name { get { return $"{_firstName} {_lastName}"; } }

	public int Age { get { return _age; } }
}

The property now hides the fact that, internally, the name is split into two fields. (Of course, the constructor for the class now gets the two parameters, which means clients would still need to change, but you can get the idea.)

Methods

Methods are the functions that we define in classes and, generally speaking, operate on the data of the object. They have different visibility options: the main ones are private, internal, and public, but there are several more.

Abstraction is important because it can hide unnecessary details from reference objects to names | C3 oop concepts

Data Abstraction

This provides essential features without describing any background details. Abstraction is important because it can hide unnecessary details from reference objects to names. It is also necessary for the construction of programs. Instead of showing how an object is represented or how it works, it focuses on what an object does. Therefore, data abstraction is often used for managing large and complex programs.

Encapsulation

This binds the member function and data member into a single class. This also allows for abstraction. Within OOP, encapsulation can be achieved by creating classes. Those classes then display public methods and properties. The name encapsulation comes from the fact that this class encapsulates the set of methods, properties, and attributes of its functionalities to other classes.

Polymorphism

This is the ability of an object to perform in a wide variety of ways. There are two types:

1. Dynamic polymorphism (runtime time). You can obtain this type through executing function overriding.

2. Static polymorphism (compile time). You can achieve static polymorphism through function overloading and operator overloading.

Within OOP, polymorphism can be achieved using many techniques including:

  • Method overloading (defining several methods at the same time)
  • Method overriding (this allows a subclass to override a specific implementation of a method already issued by one of its super-classes)
  • Operator overloading (some or all of the operators are handled has polymorphic functions with different behaviors depending on the types of its arguments)

Inheritance

Through inheritance, a class can “inherit” the characteristics of another general class. To illustrate, dogs are believed to be the descendants of wolves. All dogs have four paws and can hunt their prey. This function can be coded into the Wolf class. All of its descendants can use it. Inheritance is also an is-kind-of relationship. For instance, a golden retriever is a kind of animal. Here’s an example:

class BaseClass

{

}

class DerivedClass : BaseClass

{

}

How to Create a Class

We’ve covered several topics related to classes but not how to create one. Let’s rectify that now.

All you have to do to create a class is to add a class file to your project. The next step is to right-click on your project within the solution explorer and click Add, then choose New Item. You’ll see a new window. On the left side of the window, click Class in the Code template. Select a name for your class and click Add. It looks like this:

namespace OOPLearning

{

class Cat

{

}

}

method is an action an object can execute. In most instances, you can declare a method within a class definition. Yet, C# supports extension methods that let you add methods to an existing class outside the definition of a class.

Here’s an example of a simple C# program called “Hello World” from C# Corner that illustrates many of OOP fundamentals:

using System;

namespace oops
{

//class definition
public class SimpleHelloWorld
{
//Entry point of the program
static void Main(string[] args)
{
//print Hello world"
Console.WriteLine("Hello World!");
}
}
}

In order for a programming language to be object-oriented, it must have the ability to work with classes and objects. Moreover, it must use the fundamental object-oriented principles of abstraction, inheritance, polymorphism, and encapsulation.

Additional Resources and Tutorials

For more information on OOP concepts in C# and how you can best utilize OOP, visit the following resources and tutorials:

Summary

In the short and medium terms, we expect C# and .NET to continue being highly influential, so it’s worth learning the fundamentals if you’re not already familiar. Check out some of our other posts for more basics and advanced concepts in C#, such as throwing C# exceptions, how to handle C# exceptions, catching them and finding application errors, and other tips.

]]>
IIS Error Logs and Other Ways to Find ASP.Net Failed Requests https://stackify.com/beyond-iis-logs-find-failed-iis-asp-net-requests/ Thu, 27 Jul 2023 10:38:15 +0000 https://stackify.com/?p=6798 As exciting as it can be to write new features in your ASP.NET Core application, our users inevitably encounter failed requests. Do you know how to troubleshoot IIS or ASP.NET errors on your servers? It can be tempting to bang on your desk and proclaim your annoyance. 

However, Windows and ASP.NET Core provide several different logs where failed requests are logged. This goes beyond simple IIS logs and can give you the information you need to combat failed requests.

Get to Know the 4 Different IIS Logs

If you have been dealing with ASP.NET Core applications for a while, you may be familiar with normal IIS logs. Such logs are only the beginning of your troubleshooting toolbox.

There are some other places to look if you are looking for more detailed error messages or can’t find anything in your IIS log file.

1. Standard IIS Logs

Standard IIS logs will include every single web request that flows through your IIS site.

Via IIS Manager, you can see a “Logging” feature. Click on this, and you can verify that your IIS logs are enabled and observe where they are being written to.

iis logs settings

You should find your logs in folders that are named by your W3SVC site ID numbers.

Need help finding your logs? Check out: Where are IIS Log Files Located?

By default, each logged request in your IIS log will include several key fields including the URL, querystring, and error codes via the status, substatus and win32 status.

These status codes can help identify the actual error in more detail.

#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2019-09-13 21:45:10 ::1 GET /webapp2 - 80 - ::1 Mozilla/5.0 - 500 0 0 5502
2019-09-13 21:45:10 ::1 GET /favicon.ico - 80 - ::1 Mozilla/5.0 http://localhost/webapp2 404 0 2 4

The “sc-status” and “sc-substatus” fields are the standard HTTP status code of 200 for OK, 404, 500 for errors, etc.

The “sc-win32-status” can provide more details that you won’t know unless you look up the code. They are basic Win32 error codes.

You can also see the endpoint the log message is for under “cs-uri-stem”. For example, “/webapp2.” This can instantly direct you to problem spots in your application.

Another key piece of info to look at is “time-taken.” This gives you the roundtrip time in milliseconds of the request and its response.

By the way, if you are using Retrace, you can also use it to query across all of your IIS logs as part of its built-in log management functionality.

2. Can’t Find Your Request in the IIS Log? HTTPERR is Your IIS Error Log.

Every single web request should show in your IIS log. If it doesn’t, it is possible that the request never made it to IIS, or IIS wasn’t running.

It is also possible IIS Loggin is disabled. If IIS is running, but you still are not seeing the log events, it may be going to HTTPERR.

Incoming requests to your server first route through HTTP.SYS before being handed to IIS. These type of errors get logged in HTTPERR.

Common errors are 400 Bad Request, timeouts, 503 Service Unavailable and similar types of issues. The built-in error messages and error codes from HTTP.SYS are usually very detailed.

Where are the HTTPERR error logs?

C:\Windows\System32\LogFiles\HTTPERR

3. Look for ASP.NET Core Exceptions in Windows Event Viewer

By default, ASP.NET Core will log unhandled 500 level exceptions to the Windows Application EventLog. This is handled by the ASP.NET Core Health Monitoring feature. You can control settings for it via system.web/healthMonitoring in your appsettings.json file.

Very few people realize that the number of errors written to the Application EventLog is rate limited. So you may not find your error!

By default, it will only log the same type of error once a minute. You can also disable writing any errors to the Application EventLog.

iis error logs in eventlog

Can’t find your exception?

You may not be able to find your exception in the EventLog. Depending on if you are using WebForms, MVC, Core, WCF or other frameworks, you may have issues with ASP.NET Core not writing any errors at all to ASP.NET due to compatibility issues with the health monitoring feature.

By the way, if you install Retrace on your server, it can catch every single exception that is ever thrown in your code. It knows how to instrument into IIS features.

4. Failed Request Tracing for Advanced IIS Error Logs

Failed request tracing (FRT) is probably one of the least used features in IIS. It is, however, incredibly powerful. 

It provides robust IIS logging and works as a great IIS error log. FRT is enabled in IIS Manager and can be configured via rules for all requests, slow requests, or just certain response status codes.

You can configure it via the “Actions” section for a website:

The only problem with FRT is it is incredibly detailed. Consider it the stenographer of your application. It tracks every detail and every step of the IIS pipeline. You can spend a lot of time trying to decipher a single request.

5. Make ASP.NET Core Show the Full Exception…Temporarily

If other avenues fail you and you can reproduce the problem, you could modify your ASP.NET Core appsettings.json to see exceptions.

Typically, server-side exceptions are disabled from being visible within your application for important security reasons. Instead, you will see a yellow screen of death (YSOD) or your own custom error page.

You can modify your application config files to make exceptions visible.

asp net error ysod

ASP.NET

You could use remote desktop to access the server and set customErrors to “RemoteOnly” in your web.config so you can see the full exception via “localhost” on the server. This would ensure that no users would see the full exceptions but you would be able to.

If you are OK with the fact that your users may now see a full exception page, you could set customErrors to “Off.”

.NET Core

Compared to previous versions of ASP.NET, .NET Core has completely changed how error handling works. You now need to use the DeveloperExceptionPage in your middleware.  

.NET Core gives you unmatched flexibility in how you want to see and manage your errors. It also makes it easy to wire in instrumentation like Retrace.

6. Using a .NET Profiler to Find ASP.NET Core Exceptions

.NET Profilers like Prefix (which is free!) can collect every single exception that is .NET throws in your code even if they are hidden in your code. 

Prefix is a free ASP.NET Core profiler designed to run on your workstation to help you optimize your code as you write it. Prefix can also show you your SQL queries, HTTP calls, and much, much more.

profiled asp.net iis error log

Get Proactive About Tracking Application Errors!

Trying to reproduce an error in production or chasing down IIS logs/IIS error logs is not fun. Odds are, there are probably many more errors going on that you aren’t even aware of. When a customer contacts you and says your site is throwing errors, you better have an easy way to see them!

Tracking application errors is one of the most important things every development team should do. If you need help, be sure to try Retrace which can collect every single exception across all of your apps and servers.

Also, check out our detailed guide on C# Exception Handling Best Practices.

If you are using Azure App Services, also check out this article: Where to Find Azure App Service Logs.

Schedule A Demo
]]>
How C# Reflection Works With Code Examples https://stackify.com/what-is-c-reflection/ Thu, 27 Jul 2023 06:58:00 +0000 https://stackify.com/?p=13054 To write code that can read, examine and even write code in runtime. Sounds like magic? Welcome to the world of C# reflection.

Being able to write code that can examine and modify other pieces of code dynamically is quite a useful power. That’s what we call reflection, and in this post, you’ll learn how C# reflection works.

We’ll open the post by covering some fundamentals. What is reflection in C#? Why do people use it? We’ll break all that down for you in plain English. Then, we’ll examine a pressing question: is C# reflection slow?

After that, we’ll do justice to the “examples” part of the title: you’ll learn how to get started with C# reflection in practice. By the end of the post, you should have a solid understanding of the fundamentals of C# reflection and how you can write code that leverages its power.

Let’s jump right in and discover the world of C# reflection!

C# Reflection: The Fundamentals

As promised, let’s begin by covering the basics of C# reflection.

We call "reflection" the ability that some programming languages have to inspect their own constructs dynamically

What Is Reflection In C#?

We call “reflection” the ability that some programming languages have to inspect their own constructs dynamically. Using reflection, you can, for instance, load a class dynamically from an Assembly, test whether a given type has a specific member, and even create code dynamically.

To understand reflection in C#, there are a few basics you should understand about the hierarchy of its programming constructs:

  • Assemblies contain modules
  • Modules contain types
  • Types contain members

Why Is Reflection Used?

You need to use Reflection when you want to inspect the contents of an assembly. For example, you can get all members of the object by typing “.” before an object when viewing your Visual Studio editor IntelliSense.

A program reflects on itself when it extracts metadata from its assemblies, then uses it to modify its own behavior or inform the user. You can compare Reflection to C++RTTI (Runtime Type Information), except that it has a much wider swath of capabilities. When you write a C# program that uses reflection, you can use either the TypeOf operator or the GetType() method to get the object’s type.

Several important tools make use of reflection to enable their working. One example is unit test frameworks, which use reflection to identify test classes and methods marked with the necessary attributes.

Is Reflection In C# Slow?

Now, the million-dollar question: Is reflection slow in C#? The short answer is “yes.” Generally speaking, code that utilizes reflection is slower than code written in a conventional manner.

But is this a problem? Most of the time, it shouldn’t be. Reflection should be employed when the problem cannot be solved using traditional methods. Consequently, if you use reflection only in specific scenarios, your code should remain performant.

A Simple Use Case of C# Reflection

Reflection can be used to create applications called type browsers which allow users to select types and then read the data provided about them. This example illustrates how to use the static method GetType to find the Type of a variable:

// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

The above example results in the following output:

System.Int32

Examples of Reflection in C#

Implementing reflection in C# requires a two-step process. You first get the “type” object, then use the type to browse members such as “methods” and “properties.”

This is how you would create instances of DateTime class from the system assembly:

// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));

To access the sample class Calculator from Test.dll assembly, the Calculator class should be defined as the following:

namespace Test
{
    public class Calculator
    {
        public Calculator() { ... }
        private double _number;
        public double Number { get { ... } set { ... } }
        public void Clear() { ... }
        private void DoClear() { ... }
        public double Add(double number) { ... }
        public static double Pi { ... }
        public static double GetPi() { ... }
    }
}

Then, you can use reflection to load the Test.dll assembly:

// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");

To create an instance of the calculator class:

// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");

// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);

And access its members (the following examples illustrate getting values for the public double Number property):

// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");

// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);

// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);
The main class for reflection is the System.Type class, which is a partial abstract class representing a type in the Common Type System (CTS)

How Reflection in C# Works

The main class for reflection is the System.Type class, which is a partial abstract class representing a type in the Common Type System (CTS). When you use this class, you can find the types used in a module and namespace and also determine if a given type is a reference or value type. You can parse the corresponding metadata tables to look through these items:

  • Fields
  • Properties
  • Methods
  • Events

The System.Type class also comes with several instance methods you can use to get information from a specific type. Here’s a list of some of the most important ones:

  • GetConstructors() – gets the constructors for the type as an array of System.Reflection.ConstructorInfo.
  • GetMethods() – gets the methods for the type as an array of System.Reflection.MethodInfo.
  • GetMembers() – gets the members for the type as an array of System.Reflection.MemberInfo.

The System.Reflection namespace, as the name suggests, holds several useful classes if you want to work with reflection. Some of those are the three ones you’ve just read about. Here are some more important ones:

  • ParameterInfo
  • Assembly
  • AssemblyName
  • PropertyInfo

Late bindings can also be achieved through reflection. To illustrate, you might not know which assembly to load during compile time. In this instance, you can ask the user to enter the assembly name and type during run time so the application can load the appropriate assembly. With the System.Reflection.Assembly type, you can get three static types which allow you to load an assembly directly:

  • LoadFrom
  • LoadFrom
  • LoadWithPartialName

When you consider that an assembly is a logical DLL or EXE and a manifest is a detailed overview of an assembly, then it makes sense that a PE (portable executable) file for CTS would have the extension of .dll or .exe. Within the PE file is mainly metadata, which contains a variety of different tables such as a:

  • Filed definition table
  • Type definition table
  • Method definition table

When you parse these tables, you can retrieve an assembly’s types and attributes.

Uses for Reflection C#

There are several uses including:

  1. Use Module to get all global and non-global methods defined in the module.
  2. Use MethodInfo to look at information such as parameters, name, return type, access modifiers and implementation details.
  3. Use EventInfo to find out the event-handler data type, the name, declaring type and custom attributes.
  4. Use ConstructorInfo to get data on the parameters, access modifiers, and implementation details of a constructor.
  5. Use Assembly to load modules listed in the assembly manifest.
  6. Use PropertyInfo to get the declaring type, reflected type, data type, name and writable status of a property or to get and set property values.
  7. Use CustomAttributeData to find out information on custom attributes or to review attributes without having to create more instances.

Other uses for Reflection include constructing symbol tables, to determine which fields to persist and through serialization.

Additional Resources and Tutorials

For more information, including some helpful tutorials, visit the following resources:

At Stackify, we think C# and .NET Core will continue to be big in the near future, so brush up on your C# skills by checking out some of our other resources on topics such as .NET logging best practicesunderstanding and profiling C# sync await taskshow to find unhandled exceptionshow to convert a C# string to int, and more.

]]>
How to Use LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging With C# https://stackify.com/net-core-loggerfactory-use-correctly/ Fri, 21 Jul 2023 07:40:00 +0000 https://stackify.com/?p=7114 Do you use .NET (formerly .NET Core)? If so, you’re probably familiar with the built-in .NET Core LoggerFactory which is in Microsoft.Extensions.Logging. Back when it was introduced, it created a lot of confusion around logging with ASP.NET Core. Several years latter, the dust has settled down, and .NET logging has become somewhat “boring”, which means predictable and consistent.

In this post, we’ll offer you a guide on .NET logging. These are the topics we’ll cover:

  • Basics of the .NET Core Logging With LoggerFactory
  • Where is the LoggerFactory Created?
  • Accessing the LoggerFactory Object via Dependency Injection and Services
  • Accessing the Logging API Outside of a MVC Controller
  • How to Use the Logging API from Everywhere
  • Extend the Microsoft.Extensions.Logging API Functionality by Using NLog or Serilog Providers

Let’s get started.

Basics of the .NET Core Logging With LoggerFactory

It is designed as a logging API that developers can use to capture built-in ASP.NET logging as well as for their own custom logging. The logging API supports multiple output providers and is extensible to potentially be able to send your application logging anywhere.

Other logging frameworks like NLog and Serilog have even written providers for it. So you can use the ILoggerFactory and it ends up working sort of like Common.Logging does as a facade above an actual logging library. By using it in this way, it also allows you to leverage all of the power of a library like NLog to overcome any limitations the built-in Microsoft.Extensions.Logging API may have.

Where is the LoggerFactory Created?

Configuring the .NET logging facilities used to be way harder than it is today. In recent versions of .NET (6 and newer), the configuration of web apps has been greatly simplified. For starters, the Startup class is gone. You can have it back if you really want it but by default, it’s no longer there.

Instead, all configuration now lives in the Program.cs class.

Currently, if you start a new ASP.NET web API (making sure you don’t choose to use the minimal API format), your Program.cs class should look like the following:

var builder = WebApplication.CreateBuilder(args);


// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Right after the first line, we’ll add two more lines and that will be the start of our logging configuration:

builder.Logging.ClearProviders();
builder.Logging.AddConsole();

Accessing the LoggerFactory Object via Dependency Injection and Services

In the example code below, I am showing off 2 different ways to access the LoggerFactory from your MVC controller. Dependency injection can give you the factory or a logger either one.

public class ValuesController : Controller
{
        private ILoggerFactory _Factory;
        private ILogger _Logger;

        //set by dependency injection
        public ValuesController(ILoggerFactory factory, ILogger logger)
        {
            _Factory = factory;
            _Logger = logger;
        }

	[HttpGet]
	public IEnumerable Get()
	{
            var loggerFromDI = _Factory.CreateLogger("Values");            
            _Logger.LogDebug("From direct dependency injection");
            loggerFromDI.LogDebug("From dependency injection factory");
	}
}

Accessing the Logging API Outside of a MVC Controller

OK, so this is where the new logging API quickly becomes a nightmare. Dependency injection works great for accessing it in your MVC controller. But…how do you do logging in a class library that is consumed by this MVC project?

1. You could pass your existing LoggerFactory into every object/method you call (which is a terrible idea).

2. You could create your own LoggerFactory within your class library

This is an option as long as you don’t use any providers like a File provider that can’t have multiple instances writing at the same time. If you are using a lot of different class libraries you would have a lot of LoggerFactory objects running around.

3. Create a centrally located static class or project to hold and wrap around the main LoggerFactory reference

I see this as the best solution here unless you aren’t using any providers that have concurrency issues.

How to Use the Logging API from Everywhere

My suggestion is to create a little static helper class that becomes the owner of the LoggerFactory. The class can look something like this below. You can then use this ApplicationLogging class in any code that you want to use logging from and not have to worry about recreating LoggerFactory objects over and over. After all, logging needs to be fast!

public class ApplicationLogging
{
	private static ILoggerFactory _Factory = null;

	public static void ConfigureLogger(ILoggerFactory factory)
	{
		factory.AddDebug(LogLevel.None).AddStackify();
		factory.AddFile("logFileFromHelper.log"); //serilog file extension
	}

	public static ILoggerFactory LoggerFactory
	{
		get
		{
			if (_Factory == null)
			{
				_Factory = new LoggerFactory();
				ConfigureLogger(_Factory);
			}
			return _Factory;
		}
		set { _Factory = value; }
	}
	public static ILogger CreateLogger() => LoggerFactory.CreateLogger();
}    

Extend the Microsoft.Extensions.Logging API Functionality by Using NLog or Serilog Providers

Both NLog and Serilog both have a provider that you can use to extend the functionality of the built-in logging API. They essentially redirect all of the logs being written to the new logging API to their libraries. This gives you all the power of their libraries for the output of your logs while your code is not tied to any particular library. This is similar to the benefit of using Common.Logging.

Conclusion

Logging is an essential part of most non-trivial applications. As such, it shouldn’t be hard to integrate it into your application. The idea behind .NET’s built-in logging capabilities represents exactly that: by making logging a first-class citizen of the framework, friction is greatly reduced.

Back in the day, a great option when it came to .NET logging was to simply use NLog or Serilog and don’t even worry about the new logging API. Even though the built-in logging capabilities are now easier than ever to use, the advice still remains. If you want to capture the built-in ASP.NET logging, you can plugin the NLog/Serilog provider and it will map those messages over. By doing it this way, you can use a different logging library directly and you don’t have to even think about LoggerFactory even existing.

]]>
How to Catch All Exceptions in C# & Find All Application Errors https://stackify.com/csharp-catch-all-exceptions/ Wed, 12 Jul 2023 14:01:00 +0000 https://stackify.com/?p=11901 Exception handling is a critical component of every software application. The last thing you want your users to see is errors, or even worse, your application crashing. In this article, we will discuss how to find and catch all exceptions in C# applications. .NET provides several different ways to catch exceptions and view unhandled exceptions.

Topics in this article:

  • The Basic of Catching Exceptions: The try-catch Block
  • Catching “First Chance Exceptions”
  • ASP.NET Exception Handling
    • Including MVC, Web API, WCF, & ASP.NET Core
  • .NET Framework Exception Events
  • Find all exceptions with Retrace with no code changes
  • Windows Event Viewer

The Basic of Catching Exceptions: The try-catch Block

Let’s open the post with a refresher on the basics of exception handling. More specifically, we’ll cover the basics of the try-catch block.

The try-catch block, as its name implies, has two parts. In the first one—the “try” block—we put the code we believe might throw an exception. The second part—the “catch” block—contains the code that handles the exception, should it occur. So, the code inside the try block starts executing normally. If an exception happens, the flow of code is interrupted, and control is handled to the catch block.

Example

Let’s illustrate that with a simple example. That a look at the following excerpt of code, considering it part of a plain-old .NET console application:

try 
{
    Console.WriteLine("Displaying first message!");
    Console.WriteLine("Displaying second message!");    
    Console.WriteLine("Displaying third message!");
}
catch
{
    Console.WriteLine("Now we're inside the catch block!")
}

If you run the code above, you’ll see, unsurprisingly, the console displaying the three messages:

try catch block

As you can see, the code inside the catch block wasn’t executed. Let’s see how we can change that. First, let’s create a new method with the sole purpose of throwing an exception:

void MethodThatThrows()
{
    throw new NotImplementedException();
}

Then, let’s call this new method from our code between the second and third messages:

try 
{
    Console.WriteLine("Displaying first message!");
    Console.WriteLine("Displaying second message!");
    MethodThatThrows();
    Console.WriteLine("Displaying third message!");
}
catch
{
    Console.WriteLine("Now we're inside the catch block!");
}

If you now run the code, you’ll the following messages:

Displaying first message!
Displaying second message!
Now we're inside the catch block!

The first and second messages were executed as expected. Then the code hit the call to the MethodThatThrows() method, which, making justice to its name, did throw an exception. As expected, the control flow was diverted to the catch block, which contains a single line of code that displays a message.

That’s the gist of how the try-catch block works. Of course, things grow from there. For starters, you can specify the type of exception you expect to get as a parameter for the catch block. Additionally, you can have multiple catch blocks, each one dealing with a different type of exception. If none of the blocks match the type of exception that was thrown, the exception doesn’t get caught and bubbles up until either some other code handles it or it reaches the top levels of the application, causing it to crash.

The following excerpt contains an example of multiple catch blocks:

try 
{
    Console.WriteLine("Displaying first message!");
    Console.WriteLine("Displaying second message!");
    MethodThatThrows();
    Console.WriteLine("Displaying third message!");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine("Now we're inside the catch block for invalid operation!");
}
catch (DivisionByZeroException ex)
{
    Console.WriteLine("Now we're inside the catch block for division by zero!");
}

Finally, let’s cover the finally block—pun totally intended. You can use this block for code that should always run, regardless of whether an exception occurred or not.

First, let’s see an example of what happens when no exception occurs:

try 
{
    Console.WriteLine("Displaying first message!");
    Console.WriteLine("Displaying second message!");
    // MethodThatThrows();
    Console.WriteLine("Displaying third message!");
}
catch
{
    Console.WriteLine("Now we're inside the catch block!");
}
finally
{
    Console.WriteLine("We're inside the finally block: this will always run!");
}

Running the Code

If you run the code above, you’ll see four messages being displayed: the three messages from the try block and the one inside the finally block:

Displaying first message!
Displaying second message!
Displaying third message!
We're inside the finally block: this will always run!

Now, let’s simulate the scenario in which the exception occurs by simply uncommenting one line:

try 
{
    Console.WriteLine("Displaying first message!");
    Console.WriteLine("Displaying second message!");
    MethodThatThrows();
    Console.WriteLine("Displaying third message!");
}
catch
{
    Console.WriteLine("Now we're inside the catch block!");
}
finally
{
    Console.WriteLine("We're inside the finally block: this will always run!");
}

The result changes:

Displaying first message!
Displaying second message!
Now we're inside the catch block!
We're inside the finally block: this will always run!

Now, the flow diverts to the catch block—as expected—and then goes to the finally block.

Catching “First Chance Exceptions”

If you want to find and catch every single exception in your application, you need to be aware of “First Chance Exceptions.” Throwing an exception with no catch block to handle it is when this exception occurs.

The .NET Framework provides an easy mechanism to subscribe to every exception thrown in your code. This includes exceptions that are caught deep inside your code that never get surfaced anywhere. Although you can’t technically “catch” all exceptions in C#, you can subscribe to .NET Framework events so you can log these exceptions. Finding these exceptions is a great way to improve performance and eliminate inconvenient application behaviors.

It is also important to note that First Chance Exceptions can include a lot of noise. Some exceptions happen because they are expected to occur, or may only occur, as various warnings when an application starts up. Don’t be alarmed if you see some of this noise all of the sudden if you start logging all these exceptions in C#.

By subscribing to the event, you can potentially log every exception to help identify weird and hidden problems in your application. Doing this long-term on a production application isn’t recommended due to the sheer volume of noise and data it can cause. It is best used during development or to help find pesky production problems.Set this event handler up at the start of your application in Program.cs, Startup.cs or your Global.asax file.

AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
	Debug.WriteLine(eventArgs.Exception.ToString());
};

ASP.NET Catch All Exceptions

For ASP.NET web applications, you can’t prevent users from receiving 500 level HTTP internal server error responses when an exception is thrown in an ApiController. How you can handle this depends whether you are using various ASP.NET frameworks or ASP.NET Core. For starters, be sure to enable custom errors within your web.config file so your users never see exception pages.

Subscribe to Global.asax Application_Error Event

If your application has a Global.asax, which is essentially a HttpApplication, you should set up events around unhandled exceptions. It is important to know that if you are using MVC, Web API, Nancy, SerivceStack, WCF, etc., not all exceptions may bubble up to your Global.asax error handler. Those specific web frameworks may also have their own error handling mechanisms. We will cover those below as well!

//Global.asax
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        if (exception != null)
        {
            //log the error
        }
    }

    protected void Application_Start()
    {
        //may have some MVC registration stuff here or other code
    }
}

MVC Error Handling

With MVC, you can utilize the HandleErrorAttribute to do custom error handling per MVC controller action. It also has an OnException event within the Controller. In general, you should be safe with global error handling via your Global.asax file to catch all exceptions.

Read More: Best Practices for Error Handling in ASP.NET MVC

Web API Error Handling

Web API has more advanced exception handling capabilities that you need to be aware of.

  • The Exception filter – Ability to customize error handling for specific controllers and actions.
  • Exception logger – Enables logging all unhandled exceptions.
  • Exception handler – Global handler to customize the response back to the calling party of your API.

An example of using the unhandled exception logger:

public class UnhandledExceptionLogger : ExceptionLogger  
{
    public override void Log(ExceptionLoggerContext context)
    {
        var log = context.Exception.ToString();
        //Write the exception to your logs
    }
}

You then need to register your exception logger as part of the startup configuration of Web API.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        //Register it here
        config.Services.Replace(typeof(IExceptionLogger), new UnhandledExceptionLogger());

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

WCF Error Handling

Like Web API, WCF has a lot of customization options around exception handling. If you are using WCF, it is critical that you set up an IServiceBehavior and IErrorHandler to catch all exceptions properly. Check out this example on CodeProject for the proper way to do it: WCF Global Exception Handling

ASP.NET Core Error Handling

A lot has changed with ASP.NET Core. An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.

public class ErrorHandlingFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        //log your exception here

        context.ExceptionHandled = true; //optional 
    }
}

You must also register your filter as part of the Startup code.

//in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(options =>
    {
        options.Filters.Add(new ErrorHandlingFilter());
    });
}

.NET Framework Exception Events

The .NET Framework provides a couple of events that you can use to catch unhandled exceptions. You only need to register for these events once in your code when your application starts up. For ASP.NET, you would do this in the Startup class or Global.asax. For Windows applications, it could be the first couple lines of code in the Main() method.

static void Main(string[] args)
{
  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
  // Log the exception, display it, etc
  Debug.WriteLine(e.Exception.Message);
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
  // Log the exception, display it, etc
  Debug.WriteLine((e.ExceptionObject as Exception).Message);
}

READ MORE: AppDomain.UnhandledException Event (MSDN)

Find and Catch All C# Exceptions With Retrace

One of the great features of Retrace is its error monitoring capabilities. Retrace can automatically collect all .NET exceptions that are occurring within your application with no code changes. This includes unhandled exceptions but can also include all thrown exceptions or first chance exceptions.

The best thing about this is it works with all types of ASP.NET applications. It works perfectly with MVC, WCF, Web API, .NET Core, etc.

Retrace provides excellent reporting around all of your exceptions. You can even set up alerts for high application exception rates or when a new exception is found.

Retrace offers three modes:

  • No exceptions
  • Unhandled exceptions only
  • All exceptions thrown – Use this to catch all exceptions

View Exceptions in Windows Event Viewer

If your application has unhandled exceptions, that may be logged in the Windows Event Viewer under the category of “Application.” This can be helpful if you can’t figure out why your application suddenly crashes.

c# global exception handler

Windows Event Viewer may log two different entries for the same exception. One with a .NET Runtime error and another more generic Windows Application Error.

From the .NET Runtime:

Application: Log4netTutorial.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IndexOutOfRangeException
   at Log4netTutorial.Program.Main(System.String[])

Logged under Application Error:

Faulting application name: Log4netTutorial.exe, version: 1.0.0.0, time stamp: 0x58f0ea6b
Faulting module name: KERNELBASE.dll, version: 10.0.14393.953, time stamp: 0x58ba586d
Exception code: 0xe0434352
Fault offset: 0x000da882
Faulting process id: 0x4c94
Faulting application start time: 0x01d2b533b3d60c50
Faulting application path: C:UsersmattDocumentsVisual Studio 2015ProjectsLog4netTutorialbinDebugLog4netTutorial.exe
Faulting module path: C:WINDOWSSystem32KERNELBASE.dll
Report Id: 86c5f5b9-9d0f-4fc4-a860-9457b90c2068
Faulting package full name: 
Faulting package-relative application ID: 

Summary

Having good best practices around logging and exceptions is critical for every software application. Logging is typically the eyes and ears of the developer. In this guide, we covered several ways to find and catch all exceptions in C#. Be sure to check out our exception handling and logging best practices guides.

Retrace by Netreo gives developers unparalleled visibility into the performance of their applications. With Retrace, find all application exceptions and get a complete transaction traces of what happens when exceptions are thrown.

START YOUR FREE TRIAL NOW!

]]>
Learn C#: Tutorials for Beginners, Intermediate, and Advanced Programmers https://stackify.com/learn-c-sharp-tutorials/ Fri, 17 Mar 2023 09:30:00 +0000 https://stackify.com/?p=13429 Are you trying to teach yourself to code? Or are you already an experienced developer who wants to pick another language?

In both cases, you know how frustrating it can be to find good tutorials online. Sure, it’s easy to find “tutorials”, but separating the chaff from the wheat is a whole different story.

Of course, you have to pick a programming language to learn, and that’s far from being an easy choice, too. There are already a huge number of programming languages, and with each passing year, the list gets longer.

The goal of this post is to help you with both problems. We’re going to give you an answer to the “which language” question in the form of C#, which is a solid choice for novice and seasoned developers alike.

Then we’re going to offer you a list of 30 C# tutorials, from beginner to advanced level.

At the end of the post, you’ll be (hopefully) convinced that C# is the right choice for you, and you’ll have plenty of good references to help you on your journey. Let’s get started.

Why Learn C#?

There are many programming languages out there. In this post, we argue that C# is the best choice for a new language to learn, be it your first programming language or not. How can we be so sure?

Well, C# is a solid choice for a number of reasons. Unlike C++, for instance, C# offers automatic memory management.

It also offers solid type safety, compared to JavaScript and node.js. C# has robust base class libraries; the .NET framework includes hundreds of libraries for working with the file system, managing security, and more.

Microsoft heavily supports C#, issuing fixes and updates rapidly – so it’s a more readily updated language compared to other languages, such as Java.

The community can also contribute to the language’s design—filing bugs, sending corrections, or submitting features proposals—through the official repository on GitHub

Like Java, C# is one of the most popular programming languages, and as such, it has a large, active user community, making it easy to find troubleshooting solutions and coding help on StackOverflow and other online communities.

Microsoft released the C# language back in 2001. However, as of 2019, C# continues to be in huge demand. This is especially true since the release of .NET Core, and the trend is likely to go up.

With the new incarnation of the popular .NET framework, the C# language has become more versatile than ever. 

But the main point in favor of C# is that it’s very approachable. It has lots of sophisticated and advanced features that seasoned developers can put to use, while beginners can safely ignore those until they’re ready to handle them.

30 of the Best Tutorials to Learn C#

1. Tutorials Teacher

Tutorials Teacher

This tutorial is from Tutorialsteacher.com, which features free online web technology tutorials for beginners and professionals alike.

In addition to C#, you can also learn LINQ, ASP.NET MVC, jQuery, JavaScript, AngularJS, or Node.js. This C# course is especially interesting because it goes straight into programming after a brief version history and setup.

Key Topics:

  • Data types, classes, and variables
  • Switches and loops
  • Strings and arrays
  • Stream I/O

2. Lynda.com – Learning C#

@Lynda

Lynda

In this tutorial by author Gerry O’Brien, topics covered include core language elements such as data types, variables, and constants. It also features a short tour of two fully-functional Windows Phone and Windows Store apps to motivate you.

There are also five challenge videos that allow you to test yourself, along with another five videos that explain the answers.

Key Topics:

  • Working with loops
  • Building functions
  • Catching errors
  • Managing resources with the garbage collector

[adinserter block=”33″]

3. C# Station

C# Station

The C# Station Tutorial is a set of lessons suited for a beginner to intermediate-level programmers who are ready to learn hands-on with a compiler and an editor.

Topics cover everything from the basics right up to Polymorphism and Overloading Operators.

Key Topics:

  • Expressions, Types, and Variables
  • Namespaces
  • Introduction to Classes
  • Indexers and Attributes
  • Working with Nullable types

4. Deccansoft -C# Training

@deccansoft

Deccansoft

This series of tutorials from Deccansoft is led by Mr. Sandeep Soni, a Microsoft Certified Trainer, and cover almost all C# topics from the ground up. Each concept is explained at length using different walkthroughs and practical approaches.

The entire course is quite lengthy and features 26 modules split up into about 83 hours of video! It is advisable to have a working knowledge of any one programming language before you take this course.

Key Topics:

  • .NET Framework
  • Concepts behind CLR (Common Language Runtime)
  • Building a standard GUI for Windows based applications using WinForms.
  • Developing scalable applications using multithreading features of .NET

5. edX – Programming with C#

@edXOnline

edX

This tutorial comes from edX, an online educational services provider which also offers some courses from top universities and colleges. This is not a beginner’s course and requires you to have a prior understanding of programming concepts.

This tutorial by Gerry O’Brien is better-suited for existing programmers who want to learn a bit more about C# and the .NET environment.

Key Topics:

  • The C# syntax
  • C# language fundamentals
  • Object oriented programming
  • The .NET Framework concept

6. Microsoft Virtual Academy – C# fundamentals for absolute beginners

@MSLearning

Microsoft Virtual Academy

This C# tutorial from none other than Microsoft takes you through 24 practical and easy-to-understand episodes with Bob Tabor from the Developer University.

Apart from teaching you the fundamentals of C#, this course also covers the tools, how to write code, debug features, explore customizations, and more. The cool thing is that each topic is a separate video that’s quite straightforward.

This course also teaches you to apply your C# skills to video games and mobile apps.

Key Topics:

  • Creating and understanding your first C# program
  • Understanding Data types and Variables
  • Understanding Arrays
  • Working with Strings
  • Learning how to work with Date and Time data

7. Tutorials Point – Basic and Advanced C#

@tutorialspoint

Tutorials Point

Tutorialspoint, which is quite a popular online destination for learning, has 2 tutorials on C#, one for beginners and another for more advanced programmers.

Both are great learning resources, and between the two, they cover the basics of C# programming and also delve into more advanced C# concepts. These are text-based guides with step-by-step instructions and examples.

Basic Key Topics:

  • Program structure
  • Decision making
  • Encapsulation
  • Exception handling
  • File I/O

Advanced Key Topics:

  • Reflection
  • Indexers
  • Unsafe code
  • Multithreading

8. Udemy – C# Programming projects for beginners

@udemy

Udemy C# Programming for Beginners

Udemy is one of the largest online learning platforms with thousands of courses and a big budget to spend on advertising. If you watch YouTube videos or even just browse the web, you’ve likely come across their advertisements.

While the website has many video tutorials on C# programming, the good ones aren’t free but aren’t unreasonably expensive either. This particular course helps students think like programmers and learn C# practically by working on programming projects.

The course consists of about 49 lectures and is just under 9 hours in length.

Key Topics:

  • Practicing loops, arrays, and structures
  • Start coding beginner projects immediately
  • Thinking like a programmer
  • Using the right approach

9. LearnCS.org

LearnCSharp.org

This is a free online interactive tutorial for C#. In fact, the entire website is dedicated exclusively to teaching C#.

This site is different in its teaching approach in the sense that it teaches you with two windows, one for code and one for your output.

Key Topics:

  • Variables and types
  • Dictionaries, strings, and loops
  • Methods
  • Classes and class properties

10. Abbot – C# Tutorial

@janbodnar

C# Tutorial

This all-text tutorial from Zetcode focuses on both basic and advanced topics and is suitable for beginners and advanced programmers alike.

This tutorial covers the basics like loops, strings, and arrays and then moves on to more complicated stuff like delegates, namespaces, and collections. It also covers the new features of C# 4.0.

Key Topics:

  • Data types
  • Strings
  • Lexical structure
  • Flow control
  • Delegates
  • Namespaces
  • Collections

11. Channel 9 – Programming in C# Jump Start

@ch9

Udemy Programming in C#

What they mean by “Jump Start” fashion is that every topic of this course is example-driven and illustrated by Microsoft’s Jerry Nixon and the co-founder of Crank211, Daren May.

The key to this tutorial is repetition as the duo work with multiple examples in real-time to make sure you get the most from the experience. There are some videos in the Jump Start series, and the topics get more advanced as you progress.

Key Topics:

  • Basics of object oriented programming
  • Fundamentals of a managed language
  • Why C# is the best for OOP
  • C# Syntax

12. Java2s – C# Tutorial

C# Tutorial

More popularly known as a place that indexes Java examples, java2s.com has a good C# tutorial as well.

This is quite an in-depth tutorial, starting with language basics and moving on to graphics, designs, XML, .NET frameworks, networking, directory services, and security.

Key Topics:

  • Language basics including predefined exceptions, parameter throw, and parameter reference
  • Data types including boolean, decimal, and bitwise
  • Operators including shift, arithmetic, shortcut, short circuit, bitwise, and ternary operators
  • Windows, XML, and XML LINQ

13. JKU – C# Tutorial

JKU

This two-part course is by Hanspeter Mössenböck from the University of Linz. It is a C# tutorial for programmers who are already familiar with Java or similar languages.

It starts out with basic C# features such as types, expressions, statements, and object-orientation, and continues with more advanced features like threads, attributes, namespaces, and assemblies. It also briefly goes over .NET’s base class library.

Key Topics:

  • Overview, types, and expressions
  • Declarations and statements
  • Classes and structs
  • Namespaces, assemblies, and XML comments

14. Eduonix – Learn C Sharp Programming From Scratch

@Tutor_Eduonix

Eduonix

This course is by Eduonix, a premier online institution, and the C# course is an instructor-led video that covers basic programming structures, LINQ, C# network programming, and more. A bonus to doing this course is the option to get certified on completion.

Key Topics:

  • Introduction to C#
  • Iteration and Jumps
  • Object Oriented Programming
  • LINQ and C # Network Programming

15. SoloLearn – C# Tutorial

@SoloLearn

Sololearn

This tutorial from Sololearn.com is fun and teaches C# concepts by going through short interactive texts, games, and quizzes. The instructors believe in a hands-on approach and that the best way to learn to code is to practice coding.

A well-designed code editor lets you make changes to existing code and see the output on your mobile device. The games are especially useful since they’re fun, and the more you play, the better you get!

Key topics:

  • Basic concepts including variables, printing, and arithmetic operators
  • Conditions, loops, and methods
  • Arrays and strings
  • Inheritance, polymorphism, and generics

16. RB Whitaker – A C# Crash Course

@rb_whitaker

RB Whitaker

This is a list of over thirty tutorials by RB Whitaker, a software developer at Autonomous Solutions, Inc. (ASI). This course is quite extensive and covers everything from the basics to generics, error handling, and more.

The author encourages you to skip over parts that you are already familiar with, meaning you can get through this course more efficiently if you’re not a novice.

Key Topics:

  • Introduction, installation, and your first C# program
  • Math, more math, decision making, and looping
  • Inheritance, polymorphism, generics, and error handling

17. HyperionDev – C# Programming Essentials

@HypDev

Hypdev

This is a three- to six-month part-time micro-degree from hyperiondev.com. It’s not free, but it is CSA accredited, making it worth consideration.

This micro-degree is for beginners with no programming experience and features one-on-one pairing with a mentor as well as additional career guidance and placement advice on completion.

Key Topics:

  • Introduction to C#
  • Control statements
  • Craps game to assess knowledge of prior task
  • Data structures, files, and functions

18. TheNewBoston

@TheNewBoston

The New Boston

This set of coding tutorials created by Bucky Roberts on his YouTube channel called TheNewBoston is especially popular.

It is currently one of the most popular computer/technology related channels on YouTube, with close to 900,000 subscribers and over 200 million views.

Key Topics:

  • Overview of C#
  • Where to download Visual C# 2010 Express edition
  • Installation
  • Basics of C# Programming

19. PluralSight – C# fundamentals with C# 5.0

@pluralsight

Pluralsight

Pluralsight has many courses dedicated to C# programming. This particular course is about six hours long and has a 4.5-star rating across close to 5,000 user surveys.

The tutorial is by Scott Allen, a Microsoft MVP who has authored several books on ASP.NET, C#, and Windows Workflow.

Key Topics:

  • Basic setup and introduction to .NET, CLR, and FCL
  • Editing, compiling and debugging
  • Classes and objects in C#
  • Flow control and object oriented programming

20. Udemy – C# Basics for Beginners: Learn C# Fundamentals by Coding

@udemy

Udemy C# Basics for Beginners

This is another tutorial from Udemy. It’s not just for beginners but also for students looking for a refresher course in C# and .NET. It focuses more on a programming mindset and uses videos, real-world examples, and lots of exercises.

With 4.6 stars from 7,515 ratings and 30,380 students enrolled, this course by Mosh Hamedani is a great way to learn the fundamentals of C# and .NET Framework.

Key Topics:

  • Fundamentals of coding
  • Working with date and time
  • Debugging
  • Classes, interfaces, and object oriented programming

21. Java T Point – C# Tutorial

@JavaTpoint

JavaTPoint

This C# tutorial from javatpoint.com is quite extensive and comes with a prerequisite that you have a basic working knowledge of C. Like most other courses, it starts off very basic and then goes into detail in the later chapters.

What makes this one different, however, is that it’s quite student-oriented and features comparisons with Java, interview questions, and an additional ASP.NET tutorial.

Key Topics:

  • History and introduction
  • Control statement, functions, arrays, and object classes
  • Properties, inheritance, polymorphism, and abstraction
  • Namespaces, strings exception handling, file IO

22. Microsoft – Getting started with C#

@Microsoft

This is a fun little tutorial from Microsoft and is different from all the others as it’s customizable.

You can choose your degree of difficulty before you start by selecting whether you are a beginner or have previous programming experience. It also lets you choose the languages you already know and then modifies your course accordingly.

Key Topics:

  • Writing your first hello world program
  • Strings, looping, dates, and times
  • Arrays, collections, and calling methods
  • Namespaces
  • Testing your code and troubleshooting

23. Brackeys

@BrackeysTweet

Brackeys

YouTube videos are a great way to learn to program, and Brackeys is a YouTube channel that specializes in game development tutorials.

However, he has a pretty decent and in-depth introductory C# series that is quite popular as well.

Key Topics:

  • Introduction and basics
  • Variables, If and Switch statements
  • Classes, Inheritance, and enums
  • Properties, interfaces, and Generics

24. Complete C# Tutorial

Complete C# Tutorial

This tutorial is from CompleteCsharpTutorial.com and is essentially is a list of free tutorials ranging from C# to SQL, RAZOR Syntax, ASP.NET, Java, and CSS.

The site is really well organized, and each topic opens up into about five sub topics that you can choose from. Each topic is short and sweet and does a good job of explaining things without wasting a lot of time.

Key Topics:

  • Variables and data types
  • Operators and Conditional constructs
  • C# Statements, loop constructs, and exception handling
  • Inheritance, polymorphism, and generics

25. Guru99 – C# Tutorial

@guru99com

Guru99

This is an introductory tutorial into the .NET framework using the C# language. It also covers various topics like accessing data, classes & objects, file commands, and Windows forms.

This is not a beginner’s course, and a basic understanding of C is required.

Key Topics:

26. Certification Guru – C# .NET Programming

@mycertguru

C# .NET Programming

This course from CertificationGuru.in provides a solid foundation and covers the fundamentals skills required to design and develop object-oriented applications.

This course especially focuses on developing apps for the Web and Microsoft Windows using Microsoft Visual C#, .NET, and the Microsoft Visual Studio .NET development environment.

Another plus is that this class is intended for beginners with little or no knowledge or C# or .NET. Training is conducted live in virtual classrooms by Microsoft-certified trainers with over a decade of training experience.

Key Topics:

  • .NET framework architecture
  • Event driven programming
  • Lambda expressions
  • Exception handling
  • Deployment

27. Lynda – C# 6.0 First Look

@lynda

Lynda

This tutorial at Lynda.com is all about getting a firm grasp of the new features in C# 6.0. The course is conducted by Reynald Adolphe, who takes you through all the new features like new expression-level features, extension add methods, null-conditional operators, and much more.

The enhanced IDE (with IntelliSense syntax) and improved debugging features in Visual Studio 2015 is also covered.

Key Topics:

  • Introducing the new IDE in Visual Studio 2015
  • Leveraging nameof expressions
  • Using index initializers
  • Using await in catch and finally blocks
  • Using static and debugging

28. Alison – Diploma in C# Programming

@AlisonCourses

Alison Diploma in C# Programming

This free online course is published by Channel 9 and begins with showing you how to properly install Visual Studio Express, followed by a tour of the features and functions of the Visual Express Integrated Development Environment (IDE).

Next, comes the .NET Framework and how C# can be used to create .NET applications.

Key Topics:

  • Installing Visual Studio Express
  • Write basic code and reviewing for errors
  • Creating branches with the if decision statement and the conditional operator
  • Correct syntax for operators, expressions, and statements of duration

29. Coursera – Beginning Game Programming with C#

@coursera

Coursera

The Beginning Game Programming with C# course from Coursera.org is all about learning how to develop games in C#. This is an advanced course, so while it’s not impossible to jump right in, it might be a bit frustrating for beginners.

C# is great for games because it lets you use the open-source MonoGame framework used to make games for Windows, Android, iOS, and Mac OS X. C# can also be used with the Unity game engine, which is very popular among indie game developers.

Key Topics:

  • Course Introduction, First C# Program, and Storing Data
  • Classes and Objects, MonoGame/XNA Basics
  • MonoGame/XNA Mice and Controllers, Arrays, and Collection Classes
  • Class Design and Implementation

30. Udemy – Learn to Code by Making Games – Complete C# Unity Developer

@udemy

Udemy Learn to Code by Making Games

This is another great course from Udemy, and it’s different in the sense that it’s a gaming course for beginners in which you learn C# while building interesting games on the Unity engine.

The plus side here is that it makes learning C# fun and interactive while also teaching you about the Unity engine. The course is 100% project-based, so you will not just be learning theory but actually creating real indie games as you go.

The entire course syllabus consists of names of indie games, and for each demo game you build, you are given a set of challenges. The key topics here are especially interesting.

Key Topics:

  • Number Wizard: Basic Scripting
  • Laser Defender
  • Glitch Garden: A Plants vs. Zombies Clone
  • Block Breaker
  • Zombie Runner FPS

C# is still one of the most widely-used programming languages out there today. It is a powerful programming language with an incredibly wide array of functions and uses, allowing developers to create almost anything, ranging from server apps to mobile development to 3D games.

C# 8.0 will be released later this year—although you can already preview many of its feature using Visual Studio 2019—and with the number of tutorials online, now’s as good a time as ever to start learning.

Once you’ve become a C# guru, check out our other resources on the popular programming language, such as logging best practices for .NET, exception handling best practices, how to find and handle unhandled exceptions, and more.

Need a code coverage tool? We’ve got you covered there, too, in this post.

]]>
ASP.NET Core Testing Tools and Strategies https://stackify.com/asp-net-core-testing-tools/ Fri, 17 Mar 2023 08:25:00 +0000 https://stackify.com/?p=20933 Don’t be that developer who is woken up in the middle of the night because of some problem with the web application. After all, you need your beauty sleep – some of us more than others. The best way to avoid problems with your application is to test thoroughly. Of course, there is a cost to testing, and it is easy to jump in too deeply such that every piece of code is outrageously well tested. Finding the right balance of just what to test and which ASP.NET Core testing tools to use is something that comes with experience.

Testing simple code that has a low impact too thoroughly is not as bad as failing to test complex code with a high impact, but it will still have a negative impact on the success of your project. Complicating the problem is that we have a number of ways to test code. You may be familiar with the idea of the testing triangle or, for those who think a bit higher dimensionally, the testing pyramid.

Testing triangle

The Testing Triangle

The purpose of the triangle is to demonstrate the number of tests you should have of each type. The bulk of your tests should be unit tests: these are tests which test a single public method on a class. As you move up the testing triangle the number of tests at that level decrease; conversely the scope of the tests increase. The cost of an individual test increases towards the top of the triangle.

In this article, we’ll look at testing tools which can help us out on each level of the pyramid. Some of these tools will be specific to .NET, but others will be portable to almost any development platform, and we’ll call out which is which as we progress. You will notice that as we increase the level of abstraction by moving up the triangle, the testing technologies become broader and applicable to more web development technologies.

The testing triangle is a good guide for your ASP.NET core testing strategies.

Unit Tests

Unit tests are the smallest sort of tests that you’ll write. Ideally, they exercise a single method and should be trivial to write. In fact, many people suggest that if you find unit tests difficult to write then it is an indication that the code being tested is doing too much and should be split up. I use unit tests as an indicator that methods should be split up into multiple methods or even split into separate classes. These are the sorts of tests you should create during test-driven development.

Unit testing tools are not new in .NET or in any modern language. The migration to .NET Core has brought with it most of the first-class unit testing tools. Unit testing tools are divided into a number of categories: test frameworks, test runners and assertion libraries. The frameworks are a set of attributes that allow you to decorate your code such that they can be found and run.

Typically the testing frameworks also include a runner which will run the tests without starting up your entire application. Finally, there are assertion libraries that are used to check the conditions inside a test – most people stick with the assertions provided by their testing frameworks. All of these tools can run against any .NET project, not just ASP.NET.

code

Test frameworks

My personal favourite testing framework is xUnit, which is now part of the open source .NET Foundation. This ensures that it will have a long life and is well recognized in the community. xUnit is a fairly opinionated framework that spends a lot of effort on being fast. Its terminology is slightly different from what you might have seen in the past, substituting terms like Fact and Theory in place of Test and ParameterizedTest. During the incubation of .NET Core, xUnit was the only unit testing framework that kept up with the constant betas.

Recently Microsoft open sourced their MSTest framework as v2. MSTest has been around for years and has been sorely in need of updating for much of that time. However, the new version is quite good and remarkably fast. Even two years ago I would not have even considered MSTest over xUnit, but it is now quite competitive.

Erik has an excellent post on this very blog doing a deeper comparison of several .NET unit testing frameworks.

Test runners

Tests Runners execute the tests in your suite and present the results in an understandable format. If you’re using Visual Studio then there is no need to look any further than the built-in unit test runner. It works very well for ASP.NET core testing.

This part of the tooling has received a lot of love from the team over the last few releases. The speed of running tests and of test discovery is remarkably better. In addition to the standard runner, there are now live unit tests. This tooling runs your tests continuously as you write your code to tighten up the feedback loop between writing code and getting feedback.

Command-line tooling for running tests is also excellent on .NET Core. Tests can be run as easily as running dotnet test. The official documentation has a thorough entry on running command-line tests, and this approach is suitable for running on a build server. xUnit will actually detect that is running in a continuous integration (CI) environment and alter its output format to one that the CI server can parse.

Microsoft visual studio

Assertion libraries

Almost everybody makes use of the built-in assertion libraries that come with the testing frameworks. However if, like me, you’re particular about the way your assertions are constructed there are some really nice alternatives. Shouldly and Fluent Assertions provide a more BDD style of assertion. What does that mean? Instead of writing

Assert.That(location.X, Is.EqualTo(1337));

we can write the much more legible

location.X.ShouldBe(1337);

The error messages produced by these libraries are also much easier to read, saving you time tracking down testing failures.

Unit tests for other languages

Because these tools run on the .NET framework, they can be used to test F# code as well, just as F# code can be used to test C# code. There are some very nice testing tools in the F# space which, if you’re feeling adventurous, are worth looking at in more detail. F# for Fun and Profit have a wonderful series of entries on F# and unit testing.

Integration Tests

Integration tests are larger than unit tests and typically cross over the boundaries between modules. What is a module you might ask: that’s a great question.

A module could be as small as a single class, so an integration test could be as small as just exercising the interactions between two classes. Conversely, a module may cross process boundaries, and be an integration between a piece of code and a database server.

While the catchword for unit tests is speed (so you can run them rapidly on your development box without interrupting your flow), the catchword for integration tests is parallelization. Each test is inherently going to take a long time, so to compensate we find something for all those dozens of cores you can get on your machine these days to do.

Request-based testing tools

More often than not, the integration tests on a web project will involve submitting requests to the web server and seeing what comes back. Previously integration tests of this sort have been quite tricky to write. For ASP.NET Core testing, the situation has been improved with the introduction of the TestServer. This server allows you to submit requests to an in-memory HTTP server. This is much faster and provides a more realistic representation of what a fully-fledged server would return. You can read a much more in-depth article on integration testing at ASP.NET Core in the official docs.

One handy tool for integration tests which examine the HTML returned from an endpoint is AngleSharp. AngleSharp provides an API for parsing and exploring the DOM which makes checking attributes of the returned HTML a snap.

code static void

Database integration testing

In the past, I’ve written some pretty impressive pieces of code that stand up and tear down databases against which integration tests can be run. Although it was a pretty snazzy piece of code at the time, the speed at which the tests could run was quite limited. Fortunately, we’ve moved a little bit out of the dark ages with Entity Framework Core. Just like the TestServer, EF Core provides an in-memory implementation of a database. This database can be used to test LINQ based queries with great rapidity. The one shortcoming of this approach is that queries written in SQL for performance or clarity reasons cannot be tested with the in-memory implementation. In those cases, I recommend reading Dave Paquette’s article on integration testing with EF Core and full SQL Server.

Acceptance Tests

Acceptance tests cross-module boundaries like integration tests, but they are written from a user’s point of view. These tests are usually written in a way that describes the behaviour of the system rather than the function. By this, I mean that your tests simulate a user’s experience with the application.

In .NET are two major flavours of tools that facilitate these tests: SpecFlow and NSpec. The primary difference between these tools is their approach to describing the tests. SpecFlow uses the Gherkin language from the Cucumber tool language to describe tests. NSpec uses its own dialect to describe similar tests. Either of these tools will do a good job building tests, but I find SpecFlow to be a more usable tool; your mileage may vary.

UI Tests

The highest level of automated tests are UI tests. These tests actually drive the web browser in an automated fashion performing mouse clicks, typing text, and clicking links. In the .NET space, I actually like Canopy more than any other. In my experience, UI tests tend to be incredibly fragile and inconsistent. I’d like to believe that it is just my own incompetence that leads them to be such, but in discussions with other people I’ve yet to uncover any counterexamples. Much of the issue is that web browsers are simply not designed for automation and are missing hooks to program against. Typically testing ASP.NET web apps becomes an exercise in adding sleeps in the hopes that the UI has updated itself. Recently I’ve been hearing good things about a new tool called Cypress, but I’ve yet to use it. If you have I’d love to hear about it in the comments.

UI test tools are portable to any web application and not limited to ASP.NET.

Manual Tests

Manual testing is often seen as terrible drudgery. A lot of companies try to avoid manual testing in favor of cheaper automated tests. Automated tests cannot tell you what the user experience of your website is like. It is important to get a real variety of typical users to look at your site. The problems that manual testers are able to find are different from the ones you will find using unit, integration, or any other test.

A screen showing a manual test run in VSTS

Bonus: Performance Testing ASP.NET Core

ASP.NET Core is really, really fast. The benchmarks for it place it in the top two or three web frameworks. This is a very impressive accomplishment considering that the team started their performance optimizations near the bottom of the list. However, as performant as the framework is, its performance can easily be ruined by running poor code on top of it. There are two classes of tests which can be run in this space: low-level and load tests.

Low-level tests

Low-level performance tests answer questions like “what is the quickest way to deserialize this data stream?”, or “will heavy load in this section of the code cause too many memory allocations?”. These questions are rarely asked and for most applications that simply retrieve data from the database and display it, they don’t matter a great deal. But as soon as your code starts doing anything computationally expensive or memory intensive, they become important. The most popular tool in this space, and the one which you’ll frequently see used by the .NET Framework team itself is BenchmarkDotNet.

benmarkdotnet testing tool, one of many testing tools discussed in this article

This ASP.NET Core testing tool provides attributes and a test runner, not unlike xUnit, but focused on testing. The output looks something like

Benchmarkdotnet output example

As you can see in this example, the code is tested on a number of platforms with varying sample sizes. These tests can be used to find issues and then kept to ensure that there aren’t any regressions in performance as your application matures.

Load testing

The best thing that could happen to your web application is that it becomes very popular and people flock to it; it can also be the worst thing. Knowing how your application performs under load will help keep your nights and weekends uninterrupted. The best tool in this space and one that I’ve seen recommended even by those who won’t otherwise touch the Microsoft stack is Visual Studio Team Services’ load testing tool. Using the power of the millions of machines in Azure VSTS is able to spin up very high-scale load tests that can stress your website far beyond what any desktop tool could. It is priced very reasonably and I highly recommend it.

VSTS LogoVSTS load testing uses Azure for testing, consequently it scales to the moon

Request Tracing

Both load testing and low-level tests are great tools for gauging the performance of your application before launching it. However, nobody can predict what actual user load on your website might look like. It is really useful to have a tool like Retrace which is able to drill into the performance of your live site highlighting slow queries, code bottlenecks and hidden errors.

took ms

During development Prefix, the sister tool to Retrace is invaluable at showing a high level overview of application performance. Load testing will only tell you that your site is slow while Prefix will give you the why. The price for Prefix (free!) is certainly attractive too.

Double Bonus: Accessibility Testing

Accessibility testing unlocks your application to more people. Your users may be blind, have limited mobility, or be color blind, and your site should be usable by all of them. There are as many tools in this space as there are different impairments. This article is too short to do a full analysis, but others have done so.

A Zillion Choices

Decision fatigue is a real problem in the modern world and the variety of testing tools available to you will not make the problem any better. I hope that this article will at least point you in a direction that resembles success. If you’re testing ASP.NET Core at all, then that is a huge win, since any tests are better than none. Go forth and testify!

]]>
Top .NET Developer Skills According to Tech Leaders and Experts https://stackify.com/net-developer-skills/ Wed, 15 Mar 2023 14:35:00 +0000 https://stackify.com/?p=11615 Microsoft’s .NET Framework is incredibly popular, and its widespread use is one of the reasons C# gained ground as one of the most popular and most-used programming languages. What’s more, .NET Core, a modular, open-source (check out the code on GitHub) development stack that’s already used by ASP.NET and .NET Native, quickly found popularity, heavily influencing the demand for top .NET developer skills. In fact, we’ve been playing with .NET Core for 4+ years now at Stackify by Netreo, and many of our customers have adopted it as well.

In other words, .NET is hot and here to stay, at least for the foreseeable future. At the time of this writing, there are more than 1,700 jobs for .NET developers on LinkedIn and more than 13,000 on Indeed. But what if you’re a company or development leader looking to hire the next great .NET developer? What skills, traits, and experience should you be looking for to weed out the top talent from the mediocre candidates?

For some answers, we reached out to a panel of development leaders and .NET experts and searched the web to unearth some insights on this question:

“What are the most common characteristics & skills of great .NET developers?”

Find out what you should be looking for when you’re hiring your next .NET developer by reading what our experts had to say below.

Meet Our Panel of Development Leaders and .NET Experts:

  • Andy Gray
  • Kornilios Ampatzis
  • Janet Attard
  • Craig J. Lewis
  • Katy Imhoff
  • Steve Pritchard
  • Adam Amrine
  • Cristian Rennella
  • Rob Reagan
  • David Wanat
  • Nahian-Al-Hossain Basunia
  • Scott Poliziani
  • Bob Tabor
  • Marek Kaluzny
  • Robert Half Technology
  • Mantra Malhotra
  • James Burgess
  • Moshin Khan

Andy Gray

@Pro_sapien

Andy Gray is Principal Consultant at Pro-Sapien Software, who provide enterprise solutions on Microsoft SharePoint and Office 365 for EHS management in global enterprises. Andy has extensive experience in architecting, designing and implementing Microsoft SharePoint and Business Intelligence solutions.

“Having a constant positive attitude is key…”

This to me means being able to take feedback, even if it is negative, as well as caring deeply about the task at hand (even if it isn’t the most exciting piece of work in the world!)

Good time management is also among the top .NET developer skills. It might be the default answer to an interview question to say you possess this, but it is certainly key when you are working to tight deadlines for clients who’s business relies on our technology to function.

The ability to plan and project-manage might take up a little more of the developers time at the start of a project but ultimately will save time at the end (from a client’s perspective, this could also save them support hours and time testing).

Debugging is also an essential skill i.e. someone who has attention to detail to examine their code for errors, and fix it accordingly. Also, be prepared that things might not work the first time around (see positive attitude above). Things won’t always work first time: patience is key. Accept frustration, as working out the solution is very satisfying!

As programmers will spend time with clients, both excellent written and verbal communication skills are a pre-requisite.


Kornilios Ampatzis

@test4u_eu

Kornilios Ampatzis is a .NET developer who has worked at Test4U for four years. Test4U has been creating educational software for 14 years.

“There are some characteristics common for any developer and some more specialized for top .NET developers…”

I will start with the most common.

Computer programming is based in logic. From its most fundamental form, to the highest-level programming languages, logic is the main ingredient to a working software. As most of the skills, computer programming needs studying to acquire, and since it is constantly evolving, this studying is a never-ending process. I believe that programming requires a certain level of creativity and love of creation. It is common for most programmers to have a Gollum-ring relation to their software. Since the basis of programming is logic and creativity, all programming languages require these two feats.

A .NET developer, in particular, needs some more skills:

  • Proficiency with C# is a must, with a familiarity of its coding environment (which is mainly Microsoft’s Visual Studio).
  • Knowledge of the .NET framework and its newest features. Which means constant studying as mentioned before.
  • Strong understanding of the structure and logic of Object-Oriented programming.
  • The ability to write a clean and readable code in C#. Since most projects tend to grow in size, this could be a life saver when you want to find a bug in code you wrote a few months earlier.

Janet Attard

@JanetAttard

Janet Attard is the founder and owner of ZenBusiness, a popular small business website that provides ideas and strategies for marketing and managing small businesses.

“From my perspective, a great .NET developer is one who…”

  • Listens to the customer.
  • Asks enough questions to know – and gets the customer to identify what they want to accomplish.
  • Explains what they’re going to do and answers customer questions in terms the customer can understand.
  • Doesn’t reinvent the wheel when there are existing scripts or tools to get things done.
  • Gives a reasonable (i.e., reasonably accurate) estimate of the cost and time to do a project.
  • Gets the project done on time.
  • Alerts the customer if it will go significantly over budget – and tells them why.
  • Works well with the customer’s team and, if necessary, the web host/data center tech, and occasional other programmers.
  • Doesn’t talk down to people they think don’t understand programming or web development.


Craig J. Lewis

@gigwage

Craig Lewis the Founder and Chief Entrepreneur Officer of Gig Wage, a Dallas-based tech startup that provides a payment, support and management system for small, US-based businesses.

“Here’s what I’m looking for when identifying great .NET developers with top .NET developer skills…”

A constant learner, who likes to be around people smarter and more experienced than they are, and who can deep dive technically and solve complex business problems. Not a purist, but someone open to other ways of doing things. Someone who challenges the way things are done, but is driven by being productive. A person who takes ownership of their part and drives it through, asking questions when needed.

Tech Requirements:

  • Strong C# web development experience
  • Web and Backend
  • Web API
  • MVC
  • .NET Core


Katy Imhoff

@KatyMImhoff

Katy Imhoff is currently Owner/CEO of Camden Kelly Corporation, an Information Technology Recruiting firm headquartered in Dallas, TX with offices in the DFW area and Southern California. Prior experience includes VP of a publicly-held recruiting and staffing firm and founding a national recruiting firm headquartered in Chicago, IL.

“A great .Net developer has…”

Excellent communication skills so they can collaborate effectively, a passion for learning and staying up to date with the latest technologies, and a knack for analytical thinking that helps them problem solve. Additionally, great .NET developers are often self-driven and self-motivated so they don’t need a boss to hand hold them through the development process.


Steve Pritchard

@giffgaff

Steve Pritchard is a consultant for giffgaff.

“Aside from being able to write code…”

A good .NET developer will be skilled at swiftly responding to the changes and modifications of an application, saving time and money. They should be able to restructure code to improve its quality, without actually altering the external behavior of the site. The good .NET developer knows how to only test the essential parts of code and not waste time testing all of it unnecessarily. They usually have around three years’ experience to have enough ‘standard’ experience to be considered competent in dealing with such complex tasks.


Adam Amrine

@AmrineA

Adam Amrine has been a software developer for over 17 years working primarily with the .NET Framework using ASP.NET, starting with version 1.0. He’s worked in various industries in several different roles, primarily as a software engineer and architect.

“The same characteristics & skills of great .NET developers …”

Are the same as those that make a developer of any language or framework great. Communication is a key skill of a great software developer. Oftentimes, outsiders assume that great developers are those that sit in a dark corner and can hammer out a ton of code. However, great communication skills set apart great developers from the good ones. A great developer needs to be able to communicate complex technical ideas and solutions to nontechnical product owners and stakeholders. They also need to be able to take the ideas, requirements, and requests of nontechnical individuals and be able to understand their needs and what they’re requesting to create a solution.

Problem Solving

This leads me to the second top .NET developer skill, which is problem solving. Great problem solving skills help a developer to overcome problems while developing and create elegant solutions. Many developers can come up with a solution to a problem, but whether or not they build an efficient, scalable solution is based on how they approach the problem. Developers with great problem solving skills look at the big picture, know how their solutions will fit into a bigger ecosystem, and evaluate how the end user will use their solution to ensure that they don’t overbuild or over engineer the end product.

Technical Prowess

An additional skill that I believe many developers should have is an understanding of the full stack. This especially comes in handy when diagnosing or debugging issues. A developer who understands how networks, servers, databases and infrastructure work is able to more easily find issues and point those in charge of correcting issues in the right direction. This helps when communicating with other technical people, such as network and server administrators, by building a rapport on a foundation of familiar information.

Really the only thing that differentiates a great .NET developer from any other great developer of another language or framework is their familiarity with the .NET Framework. A great .NET developer has a deep understanding of what the framework can do, so as they develop a solution, they can quickly refer to the knowledge they have of the framework and know where to look when trying to implement specific functionality.


Cristian Rennella

@crisrennella

Christian Rennella is the CEO & CoFounder of elMejorTrato.com.

“Personally, I think that the most important characteristic of a .net developer is…”

Being focused. Although it may seem a general view, let me tell you that it is really hard to achieve in such an intrusive world.


Rob Reagan

@Text_Request

Rob Reagan is the CTO of TextRequest.com, a managed online business texting platform. Rob has worked in software development for more than two decades with companies such as ExxonMobil, BP, Weatherford, Microsoft, Standard & Poor’s and Fidelity. Be sure to check out his book on developing web applications with Microsoft Azure.

“Here’s the Cliff Notes for what I look for in great candidates…”

1. Humility

This might sound strange, but is extremely important. Developers who are sure that they’re the smartest guy or gal in the room are a recipe for disaster. Developers who think they’re geniuses and always have the best ideas are difficult to work with, rarely listen to or evaluate other ideas, and impact team dynamics in a negative way.

A great developer approaches the craft with humility, realizing that our brains are woefully inadequate for the task at hand. These devs will listen to others and collaborate to arrive at optimal solutions. They’re also easier to work with.

When hiring, pass on the know-it-alls.

2. Passion for the Craft

Let’s face it: developing software is hard, grinding work. You’ll get better results from a developer who loves what they do than from someone who went into computer science for the paycheck.

Also, technology changes rapidly. Developers who don’t love the craft oftentimes fall behind in keeping up with new tech. Developers who enjoy what they do can’t wait to buy the next Apress book and learn about the newest technology.

I generally gauge a programmer’s passion by asking what they’re working on outside of work, or what’re the latest tech books they’ve read that they really enjoy.

3. Being Deadline-Aware

Developing software is very expensive, and the bulk of expense is in developer salaries. Great devs are aware of time constraints and will make optimal choices contingent on deadlines. They’ll also keep a dialog going with management concerning technical debt incurred in a project. Joel Spoelsky once wrote a great piece on Architecture Astronauts, which is the complete opposite of the deadline-aware developer.

4. Comfortable Reading & Reusing Code

Reading code is an acquired skill. Novice devs oftentimes want to write everything themselves. Great devs want to write as little code as possible and will save time by leveraging existing work. This drives down project cost.

5. Doesn’t Chase the Hottest New Tech Stack

In tech, there’s always the latest silver bullet technology that receives tons of hype. Irresponsible devs can’t wait to jump into the next project with the hottest and often unproven tech stack. Great devs are comfortable working with tried and true tech stacks.


David WanatDavid Wanat

@BlueCompass

David Wanat has been a C# developer at Blue Compass for over eight years. Through his time at Blue Compass and his previous jobs, he has gained experience with multiple development stacks, but prefers .NET!

“As we look to hire new .NET developers at Blue Compass we try to make sure they fit the following four criteria…”

1. Are They Willing to Learn New Things?

It is important for .NET developers to be open to trying new features, methods and languages. We also appreciate when people are adaptable and receptive to fellow developers’ ideas and implementation techniques. In our office, we encourage our programmers to have personal projects that allow them to continue experimenting and testing new approaches.

2. Can They Keep an Eye on the Big Picture?

a. The last thing anyone wants is to arrive at the end of a project and realize they missed a key feature. When looking for a developer, we look for someone who asks the correct questions at the beginning of a project to eliminate surprises in the end. It is also critical to understand and remain aware of the time and resource constraints, because these factors should determine the approach and development path.

b. To be a good developer you also need to recognize the importance of your team. We value team players who share the credit and the spotlight with team members. We also ask our developers to work together, point each other in the right direction and share successes and failures with each other instead of just handing off code.

3. Do They Know Their Limits?

While .NET development can be challenging even to the experts; we look for individuals who are open to a challenge as long as they can admit when they are in over their head. To be successful, we are always seeking help and advice from other developers who have accomplished something similar to the project at hand. At Blue Compass we look for programmers who understand they do not need to be an expert in every area available, as long as they are not afraid to try new things.

4. Are They Tenacious & Self-Motivating?

Last but certainly not least, it is important to find a .NET developer who is okay with failing or getting something wrong as long as they continue to motivate themselves and avoid becoming discouraged. In our world, you need to be able to put code down for a while and circle back on it later or the next day with a fresh perspective. There are some menial and repetitive tasks that are a part of the job description. When applicable, it is good for our developers to find new ways to automate repetitive tasks!

The bonus trait we look for that sets .NET developers apart is someone who has good people skills. From an internal communication perspective, developers often need to communicate effectively with coworkers outside of the development department, including relaying project difficulties to project managers and management. There are also occasions that our developers need to communicate with the end user or client to accurately describe project limitations.


Nahian-Al-Hossain Basunia

@NasceniaIT

Nahian was a Management Trainee at Nascenia and has since become an Associate Manager for a bank in Bangladesh, where he still seeks out top .NET developer skills.

NOTE: The following information is excerpted from What are the essential skills of a .NET developer? via Quora. 

“Though technical knowledge is a must…”

Some other qualities are also essential for a good .NET developer. In my tenure at Nascenia, I met some expert .NET developers. I noticed that good .NET developers possess some traits in common which are as follows:

Sound Technical Knowledge

A sound foundation in .NET framework and any technology on top of it is a prerequisite of a good .NET developer. He must have good command on C# or VB.NET. For web technologies, he should have knowledge on the Official Microsoft ASP.NET Site, JavaScript, Angular JS, or other scripting languages and MVC. For Windows desktop applications, he should have knowledge of WPF and MVVM techniques.

Experience

Experience is a very important quality of a good .NET developer, and obtaining top .NET developer skills takes 3-4 years of experience to be considered as having standard experience.

Ability to Respond Immediately

.NET developers should be able to quickly respond to the changes and modifications of the application to save both time and money.

Ability to Refactor Code

Sometimes a developer needs to start working on an existing application where the code quality may not be good. To improve the code quality, he should be able to restructure the code without changing the external behavior.

Ability to Use Existing Code

A good developer is an expert in finding code already available in different sources and use it, thus saving time and money.

Ability to Test

A good .NET developer can test the essential part of the code, knows what to test, only tests the essential parts and does not waste time testing unnecessary code.

Trustworthiness

Trustworthiness is a quality of a good developer. A good developer maintains the confidentiality of ideas and code. To check trustworthiness, you can talk to the previous clients.


Scott Poliziani

@SWSpecialists

With over 20 years of staffing experience in finance, planning and organization, Scott was responsible for all of SSi People’s financial and operational functions. His duties included annual operating plans, financial reporting, budgetary controls, banking and contract management.

NOTE: The following information is excerpted from What are the Essential Skills of a .NET Developer via SSi People.

“The most important skills for a great .NET developer include…”

  1. ASP.NET MVC

Without knowledge of ASP.NET, a developer won’t be able to develop the best web applications. ASP.NET facilitates rapid development and connections between client-side development and backend development, so it’s definitely among top .NET developer skills.

  1. SQL Databases

Data and databases are a huge influence on development today. The more advanced a .NET developer is in database technology, the more useful they will likely be. Microsoft SQL, Oracle, and even MySQL are heavily used in conjunction with .NET, though naturally Microsoft SQL tends to be popular when using .NET. Additional important knowledge may include general data science, as .NET developers often need to work with large sets of data for their applications.

  1. Full Stack Development

A .NET developer is valuable, but a .NET developer who can also do front-end development is even more valuable. Knowledge of CSS, JavaScript, and HTML can make a .NET developer a Swiss army tool who will be able to contribute to every level of the project. JQuery knowledge and Bootstrap knowledge is an excellent plus on a functional level.

  1. MCSD/MCTS/MVP Certification

.NET developers may have a variety of certifications: Microsoft Certified Solutions Developer, Microsoft Certified Technology Specialist, or Microsoft Most Valuable Professional… An entry-level position may require an MCTS, a mid-level position may require an MCSD, and MVPs will go only for the most high-ranking positions. Certifications can sometimes make up for a deficit in either experience or education, as they do prove that an employee has the basic skills for a position.


     Bob Tabor

Bob Tabor is focused on helping absolute beginners to programming receive the guidance, training and mentoring they need to successfully interview and obtain an entry level software development position focusing on Microsoft development platform-enabled businesses. His views are clearly frontrunners when it comes to identifying the top .NET developer skills.

NOTE: The following information is excerpted from .NET Developer Career Advice – Getting Started Later in Life via DevU. 

“At a minimum, [a great .NET developer] must…”

(a) Know a lot about C# (or your chosen language), particularly about object-oriented programming keywords and concepts (static, base, override, overload, inheritance stuff, etc.), LINQ and now async features.

(b) Have a solid grasp on the .NET Framework Runtime, the compiler, garbage collection, reference versus value, etc.

(c) Be familiar with the .NET Framework Class Library … know the major namespaces, what they’re there for, etc.

(e) Know basic architectural ideas like layers, the development lifecycle, etc.

(f) Know basic patterns like dependency inversion, SOLID, etc. (These lead you to a deeper knowledge of object oriented programming, btw.) You simply need to be exposed to these … understand when it makes sense to invert / inject your dependencies, how to apply the ‘S’ in SOLID when designing your classes and methods, etc.


Marek Kaluzny

@devskiller

Marek Kaluzny is the CPO & Co-founder at Devskiller. He calls himself a one-man-army, but he knows the worth of his team. He always finds a solution for all tech challenges, advises first-time customers to assist them in fully grasping the Devskiller platform, and works hard on making applications easier for users without a technical background.

NOTE: The following information is excerpted from How to screen .NET developer programming skills to find the best – guide for IT recruitment via Devskiller. 

“The most important skills and characteristics for .NET developers are…”

Certificates are a bit [of a] controversial subject in [the] .NET world. Some companies and specialists say that it is the best proof of a candidate’s in-depth knowledge. On the other hand, others point out that exams hardly test any practical skills, concentrating on exceptions and rather theoretical knowledge.

It is safe to say that certificates don’t have to prove anything. Many great developers don’t have any, just because they think it is not worth trying to pass them. Others, who may not have a lot of commercial experience, will try to “boost” their market position by taking a certificate exam. Obviously one can say that having a certificate is better than not having any, but recruiters should remember that it is rather a “nice to have” requirement and [a] candidate’s best proof of quality is his commercial experience and references.

In .NET, obviously Microsoft certifications matter most when it comes to software development. They can be divided into several groups:

1. Microsoft Certified Technology Specialist (MCTS)

MCTS is used to be an entry point for Microsoft certifications and proves skills on a particular Microsoft technology, like WPF, but also SQL Server, SharePoint, SQL Server, Windows Server, etc. Here are a couple of examples:

  • MCTS: Microsoft .NET Framework 4, Windows Applications (511) – covers WPF, XAML and Windows Forms (C# 4.0 and .NET 4.0),
  • MCTS: Microsoft .NET Framework 4, Web Applications (515) – covers ASP.NET MVC, WCF, IIS (C# 4.0 and .NET 4.0),
  • MCTS: Microsoft .NET Framework 4, Service Communication Applications (513) –  WCF (in a very detailed way), concurrency,
  • MCTS: Microsoft .NET Framework 4, Data Access (516) –  Entity Framework, LINQ to SQL, stored procedures and SQL (briefly).

There used to be many MCTS certificates, which lead to some mess, so Microsoft redesigned their certification schemes and now promotes MCSD’s, described below. That means MCTS’s will expire soon and are no longer issued.

2. Microsoft Certified Solutions Developer (MCSD)

MCSD proves that you possess full-stack skills to create applications which are built with many frameworks and technologies. Usually, MCSD certification requires passing several exams in certain technologies. Some of the examples are:

  • MCSD: Web Applications (covers HTML 5, JavaScript, CSS3, ASP.NET MVC 4, ASP.NET WebApi 2, WCF, Azure),
  • MSCD: SharePoint Applications (covers HTML 5, JavaScript, CSS3, ASP.NET MVC 4, SharePoint Server 2013).


Robert Half Technology

@RobertHalfTech

Robert Half Technology offers a full spectrum of technology staffing solutions to meet their customers’ project, contract-to-full-time and full-time IT recruitment needs.

NOTE: The following information is excerpted from 5 Skills That Could Boost Your .NET Developer Salary via Robert Half Technology. 

“The Microsoft MVP program is prestigious. Earning MVP status can position you as a…”

Major player in the job market and help you make a case for a higher .NET developer salary, based on your top .NET developer skills. When employers see that you are a Microsoft MVP, they understand that you have been thoroughly vetted by Microsoft and have a proven track record of leadership and technical excellence in Microsoft technologies.

There are no set requirements to earn the MVP award, except that you must demonstrate an extremely high dedication to the .NET ecosystem and to helping and mentoring others. The MVP award is given only to those with a visible commitment to the .NET community; individuals need to be re-nominated and selected every year.

Skilled .NET developers are some of the most sought-after technology professionals in today’s market.


  Mantra Malhotra

@mantracoder

Mantra Malhotra is a Business IT Consultant for ValueCoders.

NOTE: The following information is excerpted from 5 Skills Your Microsoft .Net Developer Should Have via ValueCoders. 

“One of the most important skills for great .NET developers is…”

.NET MVC (Model View controller):

ASP.NET MVC is spreading over the web market replacing many others competing with it. As the web programming is progressing up ahead, a developer should master this skill. With the help of this framework, developers can make beautiful, fast and secure web applications easily. Therefore, this parameter can be considered as the first place while evaluating applicants.


James BurgessJames Burgess

James Burgess is a technology writer and software developer at ValueCoders.com who has been covering digital technology for more than a decade and has a huge knowledge of development, as well.

NOTE: The following information is excerpted from What are the essential skills of a .NET developer? via Quora.com.

“The skills of a Pro-level Microsoft .Net developer are…”

1) .NET MVC (Model View controller)

The Official Microsoft ASP.NET Site MVC is spreading over the web market replacing many others competing with it. As the web programming is progressing up ahead, a developer should master this skill. With the help of this framework, developers can make beautiful, fast and secure web applications easily. Thereby, this parameter can be considered at the first place while evaluating applicants.

2) Understanding of Client-Side Technologies

A dedicated .NET developer should have skills of creating highly creative, catchy and interactive web applications. This increases his value in the market. In order to achieve that, understanding of client side technologies like HTML, CSS and JavaScript, jQuery and Bootstrap is a necessity. Thereby while hiring, check once if they are comfortable with your language demands.

3) Database Application

Data is one of the most important aspects of app development, and .NET is no exception. Your offshore .NET development team must be well-versed not only with Microsoft’s own SQL databases but also updated technology like NoSQL. The more .NET developers know about this field, the better performing and optimized of web pages will be developed.

4) MCSD (Microsoft Certified Solutions Developer)

The Microsoft Certified Solutions Developer (MCSD) certification is a highly demanded certification in the market. This skill is valued as its development and maintenance come from Microsoft itself, which requires rectification after every two years. Hence, this competency level can be looked for enhancing code quality of your offshore .NET development team.

5) Microsoft MVP(Most Valued Professional)

Microsoft MVP is one of the most valued certifications in the market. A .NET developer with the same certification is considered to have leadership quality and high skill level in the said framework. Moreover, it will augment the scalability of your project. If you are hiring someone with such a skill set, you will have a mentor in your project.


Moshin KhanMoshin Khan

Moshin Khan is a Global Talent Advisor, Recruitment and Sourcing specialist. He now works with World Wide Technology.

NOTE: The following information is excerpted from Khan’s How to screen .NET developer programming skills to find the best via LinkedIn.

“There are certain tips which can be valuable for IT recruiters when it comes to .NET…”

Just like in Java’s world, knowledge about language (in most cases it will be C#) is simply not enough. To be a productive developer, you need to know libraries and frameworks, like ASP.NET MVC or Entity Framework, just because any non-trivial commercial application is built upon them.

It is important not to rule out candidates if they don’t know a single framework from the requirements list. Quite often frameworks are similar, and if a candidate has a decent knowledge of one of them, he can easily migrate to the required one, because he knows the idea and principles behind it. 

Furthermore, it is the commercial experience that counts and brings real value for an employer. .NET knowledge from university, unless it’s very practical, doesn’t bring much to business coding. Of course, if you recruit junior .NET developers, education does matter. But remember that you can take into account programming experience, even if it is a non-commercial one – ask for their hobby or open source programming project that was done in .NET technology.

Last but not least, .NET is currently evolving intensely. Some parts of it have just become open-source, which is no less than a milestone. Moreover, soon it will be possible to host fully functional .NET web applications on Linux OS. Both of those could have a great impact on .NET popularity and growth of open-source frameworks, just like it happened with Java.

.NET Development with Retrace

Some of the best-skilled .NET developers couldn’t do things alone. As mentioned many times in this article, collaboration and teamwork is important. Moreover, to hone your top .NET developer skills, one should also show proactiveness and continuous learning in development.

The best .NET developers go for efficiency. This is why they use tools and technology to make their work more effective and productive.

Retrace by Netreo is one sure-fire way to improve your skills as a .NET developer. This tool allows you to monitor the performance of your program as you are writing it.
Start your FREE 14-DAY TRIAL today!

]]>
Log4net for .NET Logging: The Only Tutorial and 14 Tips You Need to Know https://stackify.com/log4net-guide-dotnet-logging/ Wed, 09 Oct 2019 16:30:59 +0000 https://stackify.com/?p=6963 Logging is one of the most essential parts of modern, real-life app development. If you’ve been writing code for any reasonable amount of time, then you’ve definitely handled logging in some way.

If you’re a .NET developer, then you’ve probably used some of the many famous logging frameworks available for use at this platform. Today’s post will cover one of these frameworks: log4net.

Getting started with logging, as well as the concept of a logging framework itself, can be a daunting task. This post features a gentle but complete introduction to log4net.

After following this tutorial, you’ll have a firm grasp on what’s log4net about, how to install log4net and use it. Also included are the most important best practices you should try to adopt. Let’s get started.

What Is log4net and Why Should You Use It, or Any C# Logging Framework?

Before we dive into the nuts and bolts of how to use log4net, we need to understand what  this thing is about.

So, What is log4net?

The most popular logging framework for .NET platforms, log4net is not the only framework for .NET.

Logging frameworks are tools that dramatically reduce the burden of dealing with logs.

.net logging framework

When you employ a framework, it takes care of many of the important yet annoying aspects of logging: where to log to, whether to append to an existing file or create a new one, formatting of the log message, and many more.

Adopting a logging framework makes writing your logs to different places easy, by simply changing your configuration.

You can write your .NET logs to a file on disk, a database, a log management system or potentially dozens of other places, all without changing your code.

Getting Started: How to Install log4net Using NuGet

1. Add log4net Package

Starting with log4net is as easy as installing a NuGet package. You can use the Visual Studio UI to search for log4net and install it, or just run this quick command from the Package Manager Console:

PM> Install-Package log4net

2. Add log4net.config File

  1. Add a new file to your project in Visual Studio called log4net.config and be sure to set a property for the file 
  2. Set Copy to Output Directory to Copy Always 

This is important because we need the log4net.config file to be copied to the bin folder when you build and run your app.

log4net.config file

To get you started quickly, copy this log4net config and put it in your new log4net.config file. Doing so will log messages to both the console and a log file. We will discuss more about logging appenders further down.

 <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="file" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="file" type="log4net.Appender.RollingFileAppender">
      <file value="myapp.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
  </log4net>

3. Tell log4net to Load Your Config

The next thing we need to do is tell log4net where to load its  configuration from so that it actually works. I suggest putting this in your AssemblyInfo.cs file.

You can find it under the Properties section in your project:

log4net to Load Your Config

Add the following to the bottom of your AssemblyInfo file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

4. Log Something!

Now you can modify your app to log something and run a test!

    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            log.Info("Hello logging world!");
            Console.WriteLine("Hit enter");
            Console.ReadLine();
        }
    }

Log Appenders: What They Are and Which Ones You Need to Know

Appenders enable you to determine the destination of your log outputs. Among the standard appenders, the RollingFileAppender and ConsoleAppender are arguably the most favored. 

For those who wish to view their log statements directly in the Visual Studio Debug window, bypassing the need to open a log file, employing the DebugAppender is recommended.

If you are using a Console, checkout the ColoredConsoleAppender.

Colored console for log4net
Colored console for log4net

 

Make Good Use of Multiple Log Levels and Filter by Them

Be sure to use Debug, Info, Warning, Error, and Fatal logging levels as appropriate within your code.

Don’t log everything as Debug. Be sure to think about how you will be viewing the logs and what you want to see later when coding your logging statements.

In your log4net configuration, you can define which log4net logging levels you wish to record.

These steps are really valuable if you want to specify only certain levels to be logged to a specific log appender or to reduce logging in production. Proper levels and filters also  allow you to log more or less data without changing your code.

log4net levels:

  • All (log everything)
  • Debug
  • Info
  • Warn
  • Error
  • Fatal
  • Off (don’t log anything)

Advanced Topics & log4net Best Practices

1. Define Your LogManager Object as Static

Declaring any variable in your code has overhead. When doing some profiling sessions in the past to optimize code, I have noticed that the constructors on the LogManager object can use a lot of CPU.

Declare LogManager as static and use this little trick so you don’t have to hard code the class type.

   private static readonly log4net.ILog log 
       = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

2. How to Enable log4net’s Own Internal Debug Logging

From time to time, you may have problems with a specific appender or issues working with it.

Enabling internal log4net logging via your web.config file will help resolve these issues.

<configuration>
   <appSettings>
      <add key="log4net.Internal.Debug" value="true"/>
   </appSettings>
</configuration>

You can then specify where the logging is written to.

<configuration>
...

<system.diagnostics>
    <trace autoflush="true">
        <listeners>
            <add 
                name="textWriterTraceListener" 
                type="System.Diagnostics.TextWriterTraceListener" 
                initializeData="C:\tmp\log4net.txt" />
        </listeners>
    </trace>
</system.diagnostics>

...
</configuration>

3. Do Not Send Your Logs to a Database Table with the AdoAppender

Trying to query logs in SQL is very difficult if you log any real volume. You are much better off sending your logs to Elastic Search or a log management service that can provide full-text indexing and more functionality with your logs.

4. Do Not Send Emails on Every Exception

The last thing you want to do is send any sort of emails from an appender. They either get ignored over time or something starts throwing a lot of exceptions and then your app starts sending thousands of errors. Although, there is an SmtpAppender if you really want to do this.

5. How to Send Alerts for Exceptions

If you want to send alerts about exceptions, send your exceptions to an error tracking product, like Retrace. The full lifecycle APM solution consolidates logs for enhanced troubleshooting, simplified error tracking and more.

Error tracking tools will also de-dupe your errors, so you can figure out when an error is truly new, track its history, and track error rates.

6. Send Your Logs to a Log Management System to View Them Across Servers

Capturing logs and logging them to a file on disk is great. But if you want to search your logs across multiple servers and applications, you need to send all of your logs to a central repository.

There are a lot of log management solutions that can help you with this, or you can even set up your own elasticsearch cluster for added search capabilities.

Log management system

If you want to query all the files on disk, consider using VisualLogParser.

7. Use Filters to Suppress Certain Logging Statements

Configuring filters to block certain log messages is possible. Consider the following illustrations on how to apply filters based on the text within the log messages.

<filter type="log4net.Filter.StringMatchFilter">
  <stringToMatch value="test" /> <!-- Can filter by string or regex -->
</filter>

And here, you can filter by the log level:

<filter type="log4net.Filter.LevelRangeFilter">
   <levelMin value="INFO" />
   <levelMax value="FATAL" />
</filter>

8. You Can Make Your Own Custom log4net Appenders

If you need to do something that the usual appenders can’t do, look online or make one yourself. 

For example, we once created an appender to send our logs to Azure Table storage. This helped us collect our logs in one place. Although we couldn’t search them easily because they weren’t fully indexed, we were still able to see them. 

As an example of a custom appender, you can review the source code for our appender for sending logs to Retrace.

9. Customize Your Layout in Your Logs with log4net Pattern Layouts

You can modify your configuration to change what fields are outputting and in what format using pattern layouts.

    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="stackify.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p %d{MM-dd hh:mm:ss.ffff}  [%thread]  %m%n" />
      </layout>
    </appender>

Using the layout above, write the level (%p), current date time (%d), thread # (%thread), the message (%m) and a new line (%n). The -5 in the %-5p is to set the width of the field to 5 characters.

Here are additional fields you might consider logging, but be aware they can significantly impact your app’s performance and are not advisable for extensive logging in a production environment. 

  • %method: name of the method where the log message was written
  • %stacktrace{level}: output a stack trace to show where the log message was written
  • %type: type of the caller issuing the log request. Mostly likely your class name
  • %line: the line number from where your logging statement was logged

A layout like this:

<layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p%d{ yyyy-MM-dd HH:mm:ss} – [%thread] %m method:%method %n stacktrace:%stacktrace{5} %n type:%type %n line: %line %n" />
</layout>

Produces a log message like this:

ERROR 2017-02-06 09:38:10 – [10] Error downloading web request method:ThrowWebException 
 stacktrace:Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly > System.AppDomain.ExecuteAssembly > System.AppDomain._nExecuteAssembly > ConsoleApplication1.Program.Main > ConsoleApplication1.Class1.ThrowWebException 
 type:ConsoleApplication1.Class1 
 line: 26 

10. Use the Diagnostic Contexts to Log Additional Fields

You can also log custom fields to help give some more context about the user, customer or transaction related to the log statements.

The below example sets a custom property called customer. You can then modify your log4net pattern layout to include %property{customer} to output it in your logs.

            log4net.ThreadContext.Properties["customer"] = "My Customer Name";

            log.Debug("We are going to try and do a web request");

            try
            {
                Class1.ThrowWebException();
            }
            catch (Exception ex)
            {
                log.Error("Error trying to do something", ex);
            }
            log.Debug("We are done with the web request");

11. How to Correlate Log Messages by Web Request Transaction

Furthermore, objects can be designated within contexts to utilize what is referred to as active property values. As the log message is composed, the ToString() method is invoked, enabling dynamic operations. 

This can be used to write transaction IDs to help correlate messages to a web request or transaction!

        //Create our little helper class
        public class ActivityIdHelper
        {
            public override string ToString()
            {
                if (Trace.CorrelationManager.ActivityId == Guid.Empty)
                {
                    Trace.CorrelationManager.ActivityId = Guid.NewGuid();
                }

                return Trace.CorrelationManager.ActivityId.ToString();
            }
        }

In your global.asax or Startup.cs class, subscribe to an event for when a request first starts.

        public override void Init()
        {
            base.Init();
            this.Error += WebApiApplication_Error;
            this.BeginRequest += WebApiApplication_BeginRequest;
            this.EndRequest += WebApiApplication_EndRequest;

        }

        void WebApiApplication_BeginRequest(object sender, EventArgs e)
        {
            //set the property to our new object
            log4net.LogicalThreadContext.Properties["activityid"] = new ActivityIdHelper();

            log.Debug("WebApiApplication_BeginRequest");
        }
  • If you add %property{activity} to your pattern layout, you can now see a transaction ID in your logs like so.
  • Your log messages may still look like spaghetti, but at least you can easily see which ones go together.
DEBUG 02-06 02:51:58.6347 – a69640f7-d47d-4aa4-99c9-13cfd9ab93c2 WebApiApplication_BeginRequest 
DEBUG 02-06 02:51:58.6382 – a69640f7-d47d-4aa4-99c9-13cfd9ab93c2 Starting KitchenAsync - Call redis
DEBUG 02-06 02:51:58.9315 – b8a3bcee-e82e-4298-b27f-6481b256b5ad Finished KitchenAsync
DEBUG 02-06 02:51:59.1285 – a69640f7-d47d-4aa4-99c9-13cfd9ab93c2 Call Webclient
DEBUG 02-06 02:51:59.1686 – 54218fab-bd1b-4c77-9ff8-ebef838dfb82 WebApiApplication_BeginRequest
DEBUG 02-06 02:51:59.1746 – 54218fab-bd1b-4c77-9ff8-ebef838dfb82 Starting KitchenAsync - Call redis
DEBUG 02-06 02:51:59.4378 – a69640f7-d47d-4aa4-99c9-13cfd9ab93c2 Finished KitchenAsync
DEBUG 02-06 02:51:59.6450 – 54218fab-bd1b-4c77-9ff8-ebef838dfb82 Call Webclient
DEBUG 02-06 02:51:59.9294 – 54218fab-bd1b-4c77-9ff8-ebef838dfb82 Finished KitchenAsync

12. How to Log ASP.NET Request Details

You could use the same strategy as above to dynamically grab ASP.NET request info to add to your log message.

        public class WebRequestInfo
        {
            public override string ToString()
            {
                return HttpContext.Current?.Request?.RawUrl + ", " + HttpContext.Current?.Request?.UserAgent;
            }
        }

        void WebApiApplication_BeginRequest(object sender, EventArgs e)
        {
            log4net.LogicalThreadContext.Properties["activityid"] = new ActivityIdHelper();
            log4net.LogicalThreadContext.Properties["requestinfo"] = new WebRequestInfo();

            log.Debug("WebApiApplication_BeginRequest");
        }

 

13. How to Do Structured Logging, or Log an Object or Properties with a Message

Typically, when you log an object, it gets serialized using the default rendering settings.

log.Debug(new {color="red", int1 = 1});

Output:

DEBUG 2017-02-06 15:07:25 – [8] { color = red, int1 = 1 }

But what if you want to log your entire log message as JSON?

There are several nuGet packages related to log4net and JSON, but the support and docs for all of them seem a little sketchy.

I would recommend just making your own JsonLayout class. There is a good sample on GitHub. You could then control exactly how you log the JSON and which fields you log.

Output from the GitHub JsonLayout:

{
	"processSessionId" : "225ba696-6607-4abc-95f6-df8e0438e898",
	"level" : "DEBUG",
	"messageObject" : "Finished KitchenAsync",
	"renderedMessage" : "Finished KitchenAsync",
	"timestampUtc" : "2017-02-06T21:20:07.5690494Z",
	"logger" : "WebApp2.Controllers.TestController",
	"thread" : "69",
	"exceptionObject" : null,
	"exceptionObjectString" : null,
	"userName" : "IIS APPPOOL\\WebApp2",
	"domain" : "/LM/W3SVC/1/ROOT/WebApp2-10-131308895921693643",
	"identity" : "",
	"location" : "WebApp2.Controllers.TestController+d__27.MoveNext(C:\\BitBucket\\PrefixTests\\WebApp2\\Controllers\\TestController.cs:477)",
	"pid" : 14428,
	"machineName" : "LAPTOP-1UJ70V4E",
	"workingSet" : 352481280,
	"osVersion" : "Microsoft Windows NT 10.0.14393.0",
	"is64bitOS" : true,
	"is64bitProcess" : true,
	"properties" : {
		"requestinfo" : {},
		"activityid" : {},
		"log4net:UserName" : "IIS APPPOOL\\WebApp2",
		"log4net:Identity" : "",
		"log4net:HostName" : "LAPTOP-1UJ70V4E"
	}
}

If you want to get the value of structured logging, you will want to send your logs to a log management tool that can index all the fields and enable powerful searching and analytics capabilities.

Learn more here: What is structured logging and why developers need it.

14. How to View log4net C# Logs by ASP.NET Web Request

Log files can quickly become a spaghetti mess of log messages. Especially with web apps that have lots of AJAX requests that all do logging.

I highly recommend using Prefix, Stackify’s FREE .NET Profiler to view your logs per web request, along with SQL queries, HTTP calls and much more.

transaction trace annotated

Start Logging ASAP

Logging is an essential part of modern software development.

Nowadays, deploying software to a production environment without implementing any form of logging is unimaginable. Doing so is equivalent to wandering through a vast city, at peak hour, with a blindfold on. 

Software is a very complex thing.

When you release an app to an unfamiliar environment, you can’t be certain your app will work as planned. 

If something goes wrong—and something always does—logging is one of the few ways you can use to “go back in time,” understand the problem, and fix it.

Today’s post discussed the log4net logging framework. You learned what a logging framework is and how it can help you avoid the hassle of creating a logging strategy. We also shared some best practices and tips to help you use log4net more effectively. 

Thanks for reading, and we’ll see you in the next post.

]]>