WHAT'S NEW?
Loading...

Day 9 Programming in C# 70-483

Index


  • Introduction
  • How Garbage Collector works
  • Unmanaged resources
  • Weak references
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

How Garbage Collector works


Within your applications you will find plenty of different types of elements. Some of them are regular strings or numbers, which are called managed resources. Some others, like connections to databases or object references to files are called unmanaged resources. .Net knows exactly how to handle the first type and when to get rid of them but with unmanaged resources is other story...

There are two places in your CPU where the CLR stores these elements: the heap and the stack. Think about the stack as what's executing in your code and the heap who keeps track of your objects. Value types can go on both and for each object in the heap there's always a reference in the stack. The stack is cleared automatically at the end of each method but the heap is managed by the Garbage Collector.

The GC works with a mark and compact algorithm which checks if an item in the heap is still referenced by a method / local variable or register and takes all those objects and moves them together. During the process, all is frozen and references to the objects are fixed. This happens only if there's not enough memory and the usage of the application is low.

The process only focus on Generation 0 elements, which are elements who survived to a previous clean up and are likely to be removed in the next one. Next generations are touched only if the memory released by Gen0 is not enough.

Unmanaged resources

In order to vanish these unmanaged resources .Net provides a couple of mechanism like: finalizers and IDisposable interface. Finalizers are called only when the GC occurs and they are similar to constructors but adding a tilde (~) as a prefix name, and including your code to release your resources. You can trigger the GC clean manually by calling GC.Collect(); but this is not a recommended practice. Bear in mind that the finalizers increase the life of your objects just because those objects will get an special treatment by being added into the finalization queue. This delays GC for types that have a finalizer.

In some cases you don't want to depend on the GC to release your resources, actually, you should act proactively doing the cleaning by implementing the IDisposable interface which contains only a method: Dispose();. .Net also provides an special wrapper (using) for your unmanaged resources which implement this interface


This using is the same as having a try/catch/finally statement where you call the Dispose() method within the finally case, but all in one expression. See here below an example of how to implement this interface:


As you can see, the Dispose method with the parameter is a way to know if the dispose has been triggered explicitly or from the finalizer. If the finalizer made the call, you don't have to perform anything because the Stream already comes with a finalizer in it which the GC will run. If the call is explicitly, then close the FileStream. Bear in mind this can be called several times and you need to perform a defending code strategy. 

The regular Dispose() method calls GC.SuppressFinalize(this); to make sure that the object is removed from the finalization list that the garbage collector is keeping track of.

Weak references


Imagine you are retrieving a large list of elements from a database which implies a large amount of memory consume. You can't store this information forever, but you might want to access it in the future in case the GC has not removed it yet. In this cases, the type WeakReference can be used.

These references doesn't hold a real reference to an element on the heap so they can't be removed by the GC. If garbage collection has not occurred yet, you can still access the object through your WeakReference type.

Downgrade NuGet package and dependecies in multiple projects

Introduction


Today I had a problem with a NuGet package which was updated and it made my solution stop working for some weird compatibility problems. I decide to downgrade the package to revert the package to its original version but the Package Manager Console didn't help.


Researching in "The Internet" I found Marcelo Volmaro's blog which contains a post about how to fix this issue. He uses some power shell command through the Package Manager console to fix it. I recommend to go his blog (see references) and take a look.

Here is my script which I used to revert my SimpleInjector from version 3 to version 2.8.3. I've made some adjustments to get it working. This particular nuget package comes with other dependencies you have to downgrade too, that's why my script is a bit longer compared with Marcelo's, although, I think the script can be improved.



References

http://www.extremefx.com.ar/blog/downgrading-a-nuget-package
http://jameschambers.com/2011/06/powershell-script-examples-for-nuget-packages/
https://technet.microsoft.com/en-us/library/ee177028.aspx
https://simpleinjector.org/index.html
https://docs.nuget.org/consume/package-manager-console

Day 8 Programming in C# 70-483

Index


  • Introduction
  • Manage attributes
  • Access your code at runtime
  • Generate code at runtime
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Manage attributes


In a .Net application you have mainly code and data, but there's also something called metadata which could be defined as some information about the data in your app. There are types of metadata which contain info regarding the types, code, assembly and other elements in your applications.

Reflection is process of retrieving this metadata at runtime.

Attributes are handy to provide information and decorate all kind of types: types, assemblies, methods. Use [Serializable] attribute just above a class definition to tell the compiler this class and all its types can be serialized. It's defined in System.SerializableAttribute (by convention use the "Attribute" suffix to import but not to invoke.)

Attributes can have parameters like [Conditional("CONDITION1"), Conditional("COND2")] meaning a call to a particular method should be ignored by the compiler unless a condition is satisfied. 

Check the AssemblyInfo.cs class to get a hint of how to specify a target when defining an attribute:


Now is the time to read these attributes. The System.Attribute class contains some static methods that can be used with Reflection. Let's start with an example of reading the Serializable attribute in a class and take a decision based on that. Then, by using the ConditionalAttitribute we can run or not one or more methods as shown here:


You can define your own attribute by inheriting from System.Attribute. You can also define the possible targets your custom attributes can point to (classes, methods, etc.). Besides, by using the keyword "AllowMultiple" you define that you attribute can be instantiated multiple times by the same type (means you can write the same attribute multiple times just before the type definition probably because you need to pass different parameter values). Bear in mind, all attribute properties have to be read-write.



In the previous example we've decorated our Developer class with a couple of categories: Human and Person, so we can get that information during runtime by using reflection.

Access your code at runtime

In the previous example we've decorated our Developer class with a couple of categories: Human and Person, so we can get that information during runtime by using reflection. Unfortunately, reading this data by using Reflection is an expensive operation.

Typical example of when use reflection is when playing with plugins. Imagine you have an app with a plugin folder where you can drop anything you want. Then, you need your application smart enough to differ between what is and what's not a plugin.

You can start by creating your own IPlugin interface so you can "force" developers to implement it in order to be used by our main app. Then, when reading the assemblies from the plugin folder with the Assembly.Load("assemblyname"); command you'll end up building a LINQ query with something like this:

There are more functions you can use from Reflection. You can inspect properties or even methods. Imagine you need to iterate over a type and get all the integer defined there. You can use BindingFlags enumeration to control how reflection performs searches for members. For methods, you can trigger a method by using the Invoke function.

Generate code at runtime


But not everything is define attributes and read them, you can even generate your own code at runtime. You can use the CodeDOM framework to create your own source files or a binary assembly that can be executed. This library is placed in the System.CodeDom namespace. To be used you first need to define a container called CodeCompileUnit which contains namespaces, classes, methods and so. Once all is defined, and the compilation unit is complete, you need to call the CSharpCodeProvider to build your source file.

There are two more subjects to mention here: lambda expressions and expression trees. The first was introduced in C# v3 and is closely related with Function and Action delegate classes. You can use Action in case you don't need to return any value and Func when you do. 

Expression trees are representations of code, a description, defined in a tree-way. Commonly used with LINQ, a expression tree describes the query (System.Linq.Expressions).



In the previous example the expression is built with a call to Console.Write and Console.WriteLine, then, the expression is compiled to an Action because it doesn't return anything.

Day 7 Programming in C# 70-483

Index


  • Introduction
  • Inheritance with Interfaces
  • Inheritance with base classes
  • Standard .Net interface implementations
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Inheritance with Interfaces

Inheritance is the process of derive one class form another. For example, you can have the class Animal (base class) and another class called Dog (derived class) and this relation allow the derived class to access to the base class methods and properties. Multiple class inheritance is not supported.

Interfaces are really important in C# because they are used as a contract the users can not break. Interfaces cannot be instantiated. This contract contains the signatures of methods, properties, indexers and events which are implemented on concrete classes. Interfaces have to start with capital "I" and followed by a descriptive name like "IOrdersManagement". There are no access modifiers and all elements are public by default. You can't change this in the interface implementation either. Multiple interface inheritance is supported.

In the following example we have an interface containing a property with just has a get accessor. The concrete class which implements the interface defines both get and set accessor. This ends up with users of the interface just accessing the get and users of the concrete accessing the get and set.


Interfaces can also inherit from other interfaces, then the derived class needs to implement all the derived elements. You can also use generics which is the typical approach when you want to implement the Repository pattern (used to access a data storage system and perform operations with the information).  See here a small example where we have an interface with a generic type defined by "T" which basically helps us to pass any entity (Order, Invoice, Quote...) we want and performs a mapping with a data storage.


Bare in mind that you should program against interfaces not concrete classes. You don't need to care about how something works, just to know that it works.

Inheritance with base classes

We've seen how can we use generics to create a class which performs lookups against a data storage following the Repository pattern. In the following example you can see how to implement that interface:


What if we want to do something explicit for a particular entity, for example, if we want to add a method to search between orders by date and amount. Then, you can use inheritance to reuse your code while adding some extra behaviour. Here we defined an order entity which is used in our own OrderRepository class which is a more customized version of our old Repository class.


You can also replace/extend the behaviour of your base classes by using virtual (base class) and override (derived class) keywords. There another decorator called new which hides the virtual method in the base class but this one is not recommended to use. 

Abstract classes are something in between of Interfaces and regular classes. They can have implemented methods (not required) and also abstract elements that need to be implemented in the derived class by using the override decorator. They can't be instantiated.

On the other hand are the sealed classes. They prevent other class to inherit from them. Structs are implicitly sealed in C#. 

When talking about inheritance in a OOP language you better bear in mind the Liskov substitution principle (remember the SOLID principles) which says that every derived class could be used in place of the base class without changing the behaviour in any of the cases.

Standard .Net interface implementations

There are some interfaces provided by .Net which can help you to define some typical behaviours required in OOP languages. See the following examples:
  • IComparable: it contains just a method which helps you to stablish if two objects are the same or not. It returns an integer type and if its value is zero means both objects are the same. In case of returns less than zero means that the current precedes the object specified. Greater than zero means the current object follows the object specified. See the following implementation:
  • IEnumerable: it helps you to implement the iterator pattern in an array, list or your own collection. The interface exposes a GetEnumerator method that returns an enumerator, this can be used to move to the next element by calling MoveNext().
  • IDisposable: this is a very useful interface used to release resources like files or database connections, which are known as unmanaged resources. The garbage collector can handle these kind only by telling him how to do that implementing this interface. It contains only a method called Dispose(). 
  • IUnknown: not very common nowadays but it turns handy when you need to make use of a particular COM reference but the COM interop classes fails the build by the compiler.

Day 6 Programming in C# 70-483

Index


  • Introduction
  • Applying encapsulation
  • Properties
  • Use explicit interface implementations
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Applying encapsulation


Encapsulation is one of the pillars of Object-oriented programming languages (with inheritance and polymorphism) and gives you the ability to hide specific content within a class to make better software. A class must be built for an specific purpose and only allow access to some particular bits of the class. You don't need to understand how it works just know how to use it. See the following access modifiers from less to more restricted:
  1. public: no restriction to access. "Private" is the most restricted access modifier, only accessible by members within the same type. "Protected" brings the option of share data between objects with a inheritance relation.
  2. internal: only access to classes in the same assembly. "Internal" is more restricted than "Public" but less than "Private" and is useful when you have a helper class or an implementation detail you just want to share within the assembly you are building. There can be cases when you want to expose internal types or type members to another assembly, you can use the attribute: InternalsVisibleToAttribute. For example, when you write a unit test for a particular piece of code which has been decorated with Internal you need to specify this attribute inside the AssemblyInfo.cs stored in the properties folder of your project: [assembly:InternalsVisibleTo("ClassA")]
  3. protected: only access from the containing class and derived classes
  4. protected internal: only access from the current assembly or derived classes
  5. private: only access from the containing class.
 The following list shows which access modifiers can be used in specific situations:
  • enum;
    • default (if nothing is declared): public
    • allowed: none
  • class:
    • default: private
    • allowed: public, protected, internal, private, protected internal
  • interface:
    • default: public
    • allowed: none
  • struct:
    • default: private
    • allowed: public, internal, private.
Keep in mind the access modifier for enclosing types. For example, a public method within an internal class has an accessibility of internal. There are some exceptions to this like when an internal class implements a public interface or when a class overrides a public virtual member of a base class. As good practice, use always the most restrictive access modifier because we want to hide as much information as possible.

Properties

It's always a good practice to use properties in our code because they give you a good view of what's going in on in your data when someone pull (get) or push (set) information to them. The default implementation in C# comes with a shorthand version (public int Value { get; set; }). You can define different access modifiers for get and set. 

A single get accessor can come in handy when you want to create a true read-only property or with a property which calculates its value on the fly. A property with only a set accessor is less common, but maybe you can use it as a fire-and-forget where the users sets the value and never checks it.

Use explicit interface implementations


Interfaces are useful with encapsulation. Explicit interface implementation means that an interface type element can be accessed only when using the interface directly. For example, in Entity Framework you use a class called DbContext which is a more handy implementation of the ObjectContext class. Although DbContext implements IObjectContextAdapter which contains an ObjectContext property, you won't access this property from your DbContext directly. You're forced to cast to the interface first as shown below:


This is possibile because DbContext implements the interface IObjectContextAdapter explicitly. Explicit interface implementation means that an interface type element can be accessed only when using the interface directly. You can create one explicit interface implementation by adding the interface name and a period to the implementation.

Only when you cast Implementation to IInterfaceA you have access to MyMethod, this can be used to hide members of a class to outside users. There's another situation when you need this approach and it happens when you implement two interfaces with the same method names.

Day 5 Programming in C# 70-483

Index


  • Introduction
  • Types of "types"
  • Game rules
  • Generics
  • Extending your types
  • Boxing and then unboxing
  • Change types
  • What about dynamic types
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Types of "types"

Types help us to define which information/data can be manage in a particular object. It's a kind of blueprint to construct objects. Types:
  • Value types (Enums, small data structures, something logically immutable which contains the value for a type)
  • Reference types (contains and "address" where the value is contained, ie: URL)
  • Pointer types (not used often)

Another structure very often used in .Net is: Enums, coming from enumeration and it's a short way to list elements which improves readability. First element has index 0 but you can change this, ie:


See how in the previous example we've created an instance of the Enum Days and within we've changed the default index to start on 1. To compare the values of the Enum a casting to byte is required due to that's the data type defined previously in the structure.

You can also decorate your enums with [Flags] attribute which allows you to define multiple values to your enum at once and more actions using bitwise operators, ie:


There are two locations where a type can be stored in memory: the heap and the stack:
  • Reference type: the value is saved in the heap, the address to the value in the stack (faster, smaller and no Garbage collector is needed)
  • Value type: normally is saved in the stack.
In C# you can't inherit from System.ValueType but you can create your own value types using the struct keyword. These are very similar to objects, with methods, properties, constructors,... but you can't create an empty constructor for a struct and you don't have inheritance either.


Game rules

Always keep in mind these two principles when designing your new classes and it will allow you to make changes to code without worrying affect other systems or break anything:

  • High cohesion: all related code should remain together.
  • Low coupling: parts of your code should depend less as possible between them. 
The following list, is a very famous list of principles to bear in mind when you are building a new system, is called the S.O.L.I.D. list and I already talked about in previous posts:
  • S / Single responsibility principle: a class only needs to have one function, ie, a class for saving data and print data on the screen would break this rule.
  • O / Open-closed principle: an object should be open for extension but closed for modification.
  • L / Liskov substitution principle: a inherited class should be replaceable by the base class. Not to overwrite methods from the base class making this class useless.
  • I / Interface segregation principle: use specific interfaces instead of a general interface. A user of an interface should not implement methods he's not going to use.
  • D / Dependency inversion principle: when you use a service in your application, you should not depend on the implementation of that particular service, instead, you should depend on an interface or abstract class so you are less coupled to the service.

Generics

A generic type (C# v2.0) uses a Type parameter instead of hard-coding all the types. For example, in C#, you can see how generics are used in the Nullable types. Value types and reference types can contain a null value or pointing to a reference containing a null value respectively.

But a regular boolean can be true or false. Here comes the Nullable elements which contains a hasValue flag and the value. Instead of creating a Nullable type for each data type, we use generics to pass any element and get more flexibility. This way generics are used to promote code reuse. See how Nullable class is implemented using generics:


Generics are really powerful you can use them in structs, classes, delegates, arrays, interfaces, methods and properties. You can even specify multiple generics. Now, I'm going to show you how to apply restrictions in your generic definitions by using the keyword where, see list here:


  • where T : struct, the type argument must be a value type (only Nullable is not allowed).
  • where T : class,  the type argument must be a reference type.
  • where T : new(), the type must have a public default constructor.
  • where T : <base class name>, the type argument must be or derive from the specified base class.
  • where T : <interface name>, the type argument must be or implement the specified interface. Multiple interface can be specified. The constraining interface can also be generic.
  • where T : U, the type argument supplied for T must be or derive from the argument supplied for U.

See an example here of using different constrains:



The default value in a reference type is null, in a value type like int for instance is 0 but what is the default value in a generic, you can see how in the previous example the use of default(T) returns the default value of the generic being used.

Extending your types

It's in C# v4.0 when a new capability was implemented to add more functionality to your types called: extension methods. Imagine the class String (your type) and for different reasons you apply always a particular function over your strings. You might want to extend the string type and provide a new method with your logic in it. It's not necessary to build your own types and you end up bringing more capability to your code. See how:

public class Product
{
    public decimal Price { get; set; }
}

public static class MyExtensions
{
    public static decimal Discount(this Product product)
    {
        return product.Price * .9M;
    }
}

public static class Types6
{
    public static void Run()
    {
        Product table = new Product();
        table.Price = 100;
        System.Console.WriteLine(table.Discount());
    }
}
// output
// 90.0

The discount method is an extension method because is not implemented in the Product class. Notice how the Discount uses "this Product" as its first argument transforming it into a extension method. You can have extension methods on a class or struct but you can have extension methods within an interface. Interfaces don't have implementation normally, this way, you end up with methods available in every concrete implementation of the interface.

Another way of extending types is by overriding methods. You need to inherit from a class which contains methods defined as virtual, then you can copy the definition of the method supplying virtual by override keyword. You can block the override by using the keyword sealed in a class definition or within a method level.

Boxing and then unboxing


When you were working with value types, you might want to store its value within a reference type. This is commonly used to send parameters into methods and bear in mind it has some performance implications. For example, if you define a number (int i = 3;) you can easily box it by using: object o = i; Then, in case of unbox this object you have to perform a casting like this: int x = (int)o;

Running an invalid unboxing operation will end up in a InvalidCastException. For example when you use GetType, it always boxes your value because it's defined on an object. Another example is when you save a value in an interface like IFormattable x = 3;


Change types

Don't think we'll try to change an Address object into a House object, nop. We're talking about change a int to a double. Conversion types:

  1. Implicit: implicitly the compiler knows how to change types. Normally by losing precision, ex: change from int to double. A integer value fits inside of a double value. Same happens when changing base classes into derived objects.
  2. Explicit: a.k.a "Casting". Using the same example, casting a double to an integer you need to tell this to the compiler somehow: myInteger = (int)myDouble; And exactly the same behaviour when changing derived objects into base objects.
  3. User-defined: you can define implicit and explicit method to perform converstion between types using the properties within your own classes. You need to specify the return type (casting to) and the type you are casting from. See how: 
    1. See here how to use this class:
    2. Both imlicit and explicit operators are executed and we end up with a value of 42. This improves the usability providing to the user of our class a direct way to convert between types.
  4. Helper class: conversion between noncompatible types you can use System.BitConverter. For compatible types you have the System.Convert class, and the Parse() or TryParse() methods.
This conversions between types may trigger and exception during runtime and instead of wrapping up your code with a try/catch (think in the performance) you can use a couple of expressions to safe you transformations: is and as. The is returns true or false, depending on whether the conversion is allowed. The as operator returns the converted value or null if the conversion is not possible.

if (connection is SqlConnection) {   // do stuff   }

MemoryStream memoryStream = stream as MemoryStream;

Using as is more efficient when you want to use the value afterwards. If you just want to check if your value is a certain type use is.

What about dynamic types

C# is partially static typed language. To deal with JavaScript, COM Interop, JSON or reflection in C#, the data type dynamic was introduced. Which is a like a joker when playing cards, you don't really know which type is containing because all the type checking and necessary conversion take place at runtime. It's a bit dangerous and it may end triggering errors and the performance can be affected so think carefully when to use it.

.Net offers: DynamicObject and ExpandoObject. With the first one, derived classes practically can do whatever they want, from overriding operations, calling methods or performing conversions. On the other side, ExpandoObject is a sealed implementation that enables you to get and set properties on a type. For example, the ViewBag in MVC which allow developers to save whatever value and send it back to the view.