Posts

Showing posts with the label c#

Immutability

Last time, we looked at pure vs impure functions and we said that functional programming favors pure over impure functions. Using pure functions leads to another concept: immutability . Immutability means that a variable can only have its value set once. After that, the value never changes. So much so that in functional programming, the phrase "assigning to a variable" is often replaced by "binding to a symbol", since the word "variable" is not applicable anymore. Let's consider a non-immutable example: // Declare a class named Car public class Car { public string Color { get; set; } public bool IsStarted { get; set; } } // Instantiate a new instance var myCar = new Car { Color = "Red", IsStarted = true }; // After that, change the values of the car's properties myCar.Color = "Blue"; myCar.IsStarted = false; The properties inside of the Car class are not immutable since they can be changed after...

Pure vs Impure Functions

Image
My partner, who is also a developer, once asked me what the difference between functional and object-oriented programming is. There are many differences, and this post explores one of them: the usage of pure and impure functions. What are pure and impure functions? A pure function does not have side effects. A side effect is a change in state that happens outside of a function that gets persisted even after the function goes out of scope. Impure functions are everything else. Here are some examples to clarify. First, a pure function: // Pure int GetSum(int a, int b) { return a + b; } That is a pure function, because it does not affect any state that is outside the scope of the function. Consider this impure equivalent: // Impure int sum = 0; void ComputeSum(int a, int b) { sum = a + b; } That is an impure function, because it modifies the sum variable, and the modification persists even after the method has gone out of scope. When using an object-or...

Auditing Changes with Entity Framework

Image
Today we will see how we can keep an audit record of entity changes using Entity Framework. This is a very useful feature that can also be a business requirement when dealing with important or sensitive information.

Design Pattern Spotlight: Adapter Pattern

Image
The Adapter Pattern 's intent is: "convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces" (taken from the Design Patterns book). That statement seems intimidating at first, but the core concept is really simple. In fact, I won't be surprised if you are already using this pattern in your application. Let's talk more about it below.

AngularJS AJAX GET and POST Example with ASP.NET MVC JsonResult

Image
A while back I blogged about Using JQuery AJAX GET with ASP.NET MVC JsonResult . This time, we will be talking about using AngularJS for making GET and POST methods using the $http service.

Some Tips on Organizing Code

Image
One of the signposts pointing to clean code is well-organized code files. Contrary to popular belief, aesthetics and organization are important when it comes to writing code, because having organized and structured code improves readability. A piece of code written once will get read multiple times, so it's worth the time to put a little more effort into improving the code's readability. In this post I will be sharing some tips on how to make more organized and readable.

End-to-End Image Upload with Azure Storage, AngularJS, and Web API

Image
A common feature in web applications is image upload. Images can be stored on disk, in the database, or in some other server. In this post we will take the third approach and store images using Azure Storage. We will also be using AngularJS on the front-end and Web API in the back-end.

Converting JSON Data Into C# Objects

Image
There are times when we would need to convert JSON string data into C# objects. An example would be when consuming some Web API that returns JSON data. Although we can work with the JSON string data directly, it would be much nicer if we could somehow convert the data into an object, so that we can work with them more easily. In this post we will talk about how to do this.

Introduction to Dependency Injection - Part 2

Image
In the last post I gave an introduction to dependency injection , where I described what it is, how it can be achieved, and the motivation behind it. We left off by providing an example in an ASP.NET MVC controller, where we manually "newed up" dependencies inside the constructor of a controller. In this post we will take a look at dependency injection frameworks and see how they can help us manage dependencies.

Introduction to Dependency Injection - Part 1

Image
The concept of dependency injection has been around for a long time. But now that dependency injection is baked into ASP.NET Core 1.0, I thought it would be a good time to write about what it is and why and how we can take advantage of it. This post is part 1 of a two-part series on dependency injection. Click here to go to part two.

Creating Custom Filters in ASP.NET MVC

Image
Whenever ASP.NET MVC receives an HTTP request, the request goes through code in the MVC framework before it reaches our controller actions. And then, after we return from our controller, it also goes through framework code before an HTTP response is emitted. The framework code that is involved is typically called the "pipeline". In this post we will talk about how we can insert our own custom code into the pipeline. This is achieved by creating special classes called filters.

Creating a Generic Lookup Service

Image
In a previous post I talked about how we can manage lookup tables with Entity Framework Code First . In that post I suggested using the primary key directly to check for a specific lookup, rather than introducing an arbitrary column that will serve as an identifier. In this post I will talk about how we can make a generic lookup service to simplify how we show lookup values in, say, dropdown lists.

Managing Lookup Tables with Entity Framework Code First

Image
Oftentimes in our applications we will have such things as a "lookup table". I am defining a lookup table as a list of relatively fixed or static choices such as status codes, states or provinces, and so on. In this post I will share how I manage lookup tables using Entity Framework.

Strongly-Typed AppSettings

Image
Application settings for .NET projects provide a way to change the behavior of a program without recompilation. These settings are typically stored as key-value pairs in the web.config or app.config files and can be accessed through the ConfigurationManager class provided by the framework. In this post we will be taking configuration access to the next level by providing a strongly-typed wrapper around the ConfigurationManager class.

Using AntiForgeryTokens in ASP.NET MVC with AngularJS

Image
Protection against CSRF (use of AntiForgery tokens) is supported in both the ASP.NET MVC and AngularJS frameworks. However, they have different implementations. What this means is that the default implementation of ASP.NET MVC for AntiForgery tokens will not work out-of-the box on an AngularJS front-end. In this post we will look at this in more detail and come up with a solution to the problem.

Integrating Custom Validation with ASP.NET MVC ModelState

Image
One common pattern we see in ASP.NET MVC controller actions is a conditional check for ModelState.IsValid , with different branches getting executed based on whether the result is true or false . The ModelState captures errors arising from data annotations such as Required and StringLength . When there are custom validations that cannot be captured using data annotations, what usually happens is that these validations are checked in the success block of ModelState.IsValid . In this post we are going to talk about how to integrate custom validation into ModelState .

Loading Related Data in Entity Framework

Image
There are three behaviors that entity framework can use when loading related data. These are lazy loading , eager loading , and explicit loading . The main difference between the three are in when the related data gets loaded and whether it is done behind-the-scenes or explicitly. In this post we will learn about these behaviors and evaluate when one should be used over the other.

Using AntiForgery Tokens in ASP.NET MVC

Image
Cross-site Request Forgery (CSRF or XSRF) is a type of cyber attack wherein an attacker makes an HTTP request on a user's behalf without the user's knowledge or consent. If successful, a significant amount of damage can be done, depending on the nature of the request. This kind of attack can be prevented by using antiforgery tokens. In this post, we will talk about how we can prevent CSRF attacks in our ASP.NET MVC applications.

Creating Custom Html Helper Methods Part 2

Image
In a previous post we talked about creating custom html helpers . The implementation there involved customizing helpers that already existed in the ASP.NET MVC framework. In this post we will talk about creating our own helpers from scratch. This will allow us to create helpers for any kind of html element and will also provide flexibility on the element building process.

Creating Custom Html Helper Methods

Image
HTML helper methods are used in Razor views to generate HTML markup in a strongly-typed, C-sharpy way. An example is @Html.LabelFor(m => m.Name) , which is used in a strongly-typed view whose model has a Name property. This will generate a label element with the appropriate display name. In this post we will learn how to create a custom HTML helper.