Could Block-Level Replication Replace Database Backup?

Had an interesting talk with DBAs and System Admins. The topic was about whether Block-Level Replication replace database backup.

To simplify, traditional database backup provides point-in-time recovery naturally. Replication is just duplication of the same data, whether it is good or bad. In order for replication to provide similar features like database backup, we have to add other DR strategies.

Reference:

Backup and Replication: What is the Difference?

Backup vs Replication

Advertisements

Visual Studio Continued Executing Even After Stopped Debugging!

Debugged some complex business scenario in multiple applications, and found out the cause. In order to show the problem at that particular moment, I had to stop the Visual Studio debugger during the first repetition of a for loop. I examined the result. The result was not what I had expected. It was the result after all repetitions in the for loop were executed.

I did it the second time, and the result was still the same. It was after all repetitions in the for loop were executed. Strange!

Did research, and found nothing.

To speak the truth, I almost wanted to unplug the network cable at that moment.

Continued to search, and found this article, How to: Stop Debugging or Stop Execution, in MSDN. It solved my problem.

Normally, if the program is launched from Visual Studio, stop debugging terminates the process you are debugging.

However, if you use local IIS and attach to the process, instead of launching it from Visual Studio, the process continues running. This was the problem I met.

There are a few options to terminate all attaches processes:

  1. On the Debug menu, choose Terminate All.
  2. Kill all those processes in Task Manager
  3. Restart IIS

 

Reference:

How to: Stop Debugging or Stop Execution

 

“The breakpoint will not currently be hit”

Tags

Set up breakpoints, and began to debug. The debugger couldn’t stop at the breakpoint. Paused mouse over the information icon of breakpoint, and the message said “The breakpoint will not currently be hit”.

According to a SO article, we basically have two choices. I used option 1.

  1. Make sure that .pdb file is the search paths of Load System Information (Debug -> Windows -> Modules), or
  2. Remove the assembly from GAC

 

Reference:

https://stackoverflow.com/questions/2155930/fixing-the-breakpoint-will-not-currently-be-hit-no-symbols-have-been-loaded-fo

Fluent Validation – Separate Main Business Logic from Validation Logic

We all have nice business objects at the beginning. However, the codes become bloated, hard to read and maintain after we put in numerous complex business validation logic. We always hope that we can separate main business logic from validation logic, and reuse the validation logic to some degrees.

For example, we use IValidatableObject as the main validation mechanism (self-validating models) in MVC applications.  The validate method will be called after the model binder has assigned values to each of the model properties. There are a few variations. Some use abstract methods, and some use events inside Validate method of the base class to achieve some kinds of separation of main business logic from validation logic.

I came across the small library at github recently, Fluent Validation. This library is the best library that can separate the main business logic from validation logic I can find so far.

The following codes show how to add validation logic  to a customized validator using the popular fluent syntax.

public class CustomerValidator: AbstractValidator<Customer> {
  public CustomerValidator() {
    RuleFor(customer => customer.Surname).NotEmpty();
    RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
    RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
    RuleFor(customer => customer.Address).Length(20, 250);
    RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
  }

  private bool BeAValidPostcode(string postcode) {
    // custom postcode validating logic goes here
  }
}

The following codes show how to call the validation method.

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

 

Reference:

Fluent Validation

 

 

 

 

Google Analytics API – 5 Minutes Crash Course

Google Analytics is very popular for measuring how users interact with your website. Most of the times, simply follow the instructions, and copy the following codes to every page you intend to track. It just magically works.

<!-- Google Analytics -->

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

<!-- End Google Analytics -->

However, sometimes we have to dig deeper to achieve our goals. For example, how do we track each virtual page in Single Page Application (SPA)?

In order to answer this question, we have to understand how the script above works. From the reference, as quoted: “The above code does four main things:

  1. Creates a element that starts asynchronously downloading the analytics.js JavaScript library from https://www.google-analytics.com/analytics.js
  2. Initializes a global ga function (called the ga() command queue) that allows you to schedule commands to be run once the analytics.js library is loaded and ready to go.
  3. Adds a command to the ga() command queue to create a new tracker object for the property specified via the 'UA-XXXXX-Y' parameter.
  4. Adds another command to the ga() command queue to send a pageview to Google Analytics for the current page.”

The reference also points out, as quoted: “Custom implementations may require modifying the last two lines of the JavaScript tracking snippet (the create and send commands) or adding additional code to track more interactions. ”

Back to our tracking each virtual page of SPA question. I will use an example here. There are six menu items, ‘Home’, ‘About’, ‘Services’, ‘Projects’, ‘Qualifications’, and ‘Contact’ in this website, http://www.hdsoftwareconsulting.com, which is a SPA. Under normal circumstance, if we simply insert the script above to the page, it only logs “/home” to tracking. However, we do want to know the users browser navigation to other menu items as well.

Luckily, Google Analytics API is flexible and powerful. We can create a solution like this:

  1. Insert the following script to the page.


(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');

<!-- End Google Analytics -->

2. Attach an onclick event handler to each menu item. For example, we attach the following script to ‘About’ menu item, and will do the same for the other menu items.

ga('set', 'page', '/about'); 
ga('send', 'pageview');

In this 5-minute crash course, we introduce Google Analytics API, and show how to apply it to a SPA.

Bonuses:

  1. Look at network tab of Chrome to inspect what’s going between your browser and Google Analytics API
  2. The API exposes an object ‘ga’ as mentioned above. We can also inspect its internals.
ga(function() {
  // Logs an array of all tracker objects.
  console.log(ga.getAll());
});
ga(function(tracker) {
  // Logs the trackers name.
  console.log(tracker.get('name'));
});

 

 

References:

https://developers.google.com/analytics/devguides/collection/analyticsjs/

Design Pattern – Chain of Responsibility

Design pattern Chain of Responsibility (COR) belongs to the general design concept Divide-and-Conquer.

Imagine that we have a complex business logic with inputs and outputs, and its content is filled with numerous statements.

One of Divide-and-Conquer techniques is to apply COR in the form of a single pipeline and multiple handlers. For example, each handler implements one or multiple statements as a logical unit. The inputs are implemented as requests, and the outputs are implemented as response. The requests are passed through the pipeline and each handler is given a chance to process the requests and add something to responses. In the end, one of the handlers or end of chain handler will return the responses back to the caller.

The real life analogy will be a car assembly line (pipeline). Each worker (handler) only knows how to work on the item on hand, and pass the item down the line to next worker (handler)…

The immediate observations are:

  1. Each worker (handler) is very good at the item that he/she is assigned to.
  2. Each worker (handler) really doesn’t care who the worker up the pipeline. They just work on the item passed to them, and make sure to pass the item on hand to next worker (handler)
  3. Each worker (handler) can be easily to be replaced with another worker (handler)
  4. The quality of the item that each worker (handler) works on can be easily verified.
  5. The workflow is efficient and easy to understand and be maintained

 

References

Chain of Responsibility at Wikipedia

https://sourcemaking.com/design_patterns/chain_of_responsibility

http://www.dofactory.com/net/chain-of-responsibility-design-pattern

https://www.tutorialspoint.com/design_pattern/chain_of_responsibility_pattern.htm

 

 

 

Is the HttpContext.Current.Cache shared among different user sessions?

During one of discussion about caching, one senior developer pointed out that the HttpContext.Current.Cache is NOT shared among different user sessions.

I felt very shocked because I thought HttpContext.Current.Cache is shared among different user sessions. I quickly did research over internet, and confirmed that HttpContext.Current.Cache is shared among different user sessions.

MSDN – HttpContext.Cache: “There is one instance of the Cache class per application domain. As a result, the Cache object that is returned by the Cache property is the Cache object for all requests in the application domain.”

 

References:

HttpContext.Cache

StackOverflow – Is the HttpContext.Current.Cache available to all sessions

https://forums.asp.net/t/1410077.aspx?HttpContext+Current+Cache+shares+data+between+browsers

https://forums.asp.net/t/1792625.aspx?HttpContext+Current+Cache

MVC ModelState De-Confused!

I used to confuse about ModelState in MVC. I begin to realize that there are two ModelState concepts often referenced in MVC discussion.

Most people know the first concept of ModelState, Controller.ModelState, which is a property of System.Web.Mvc.Controller. I am going to use Controller.ModelState property here to avoid any confusion.  Controller.ModelState property represents the model state dictionary object  (ModelStateDictionary) that contains the state of the model and of model-binding. The important properties of ModelStateDictionary  are:

  • Count. Gets the number of key/value pairs in the collection.
  • IsValid. Gets a value that indicates whether this instance of the model-state dictionary is valid.
  • Keys. Gets a collection that contains the keys in the dictionary.
  • Values. Gets a collection that contains the values in the dictionary.
One of ModelStateDictionary properties, Values, is particularly interesting. It basically is a collection that contains the values of the model-state dictionary.
public ICollection Values { get; }

Type: System.Collections.Generic.ICollection<ModelState>

You are right. ModelState is the type of objects in the collection, not the property of controller. It confused me years ago, and most people like me might never pay attention to.

Here comes the second concept of ModelState, which is from System.Web.Mvc.ModelState. There are only two properties in this class, Errors and Value.

  • Errors. Returns a ModelErrorCollection object that contains any errors that occurred during model binding.
  • Value. Returns a ValueProviderResult object that encapsulates the value that was being bound during model binding.

If we organize our thinking a little bit, here is the structure for easy memorization.

Controller.ModelState

References:

Controller.ModelState

ModelStateDictionary

ModelStateDictionary.Values

ModelState

ModelErrorCollection

ModelError

Microsoft Small Basic – Robotic Programming for Kids 10+

While looked for robotic programming languages for kids 10+, I tumbled upon Microsoft Small Basic. It is a surprising simple language with only 14 keywords, simple data types, conditional branching, and looping. It also comes with a beautiful Integrated Development Environment with intellisense and in-editor documentation access on the sidebar.

If we trace the origin, it is a simplified and  trimmed version of BASIC. Small Basic also includes a few libraries such as Turtle, Flickr, etc., so that beginners can jump start.

When we add the extension EV3 Basic, Small Basic can program against Lego MindStorm EV3 robot.

I strongly recommend Small Basic for kids 10+ to learn programming.

References:

  1. Microsoft Small Basic
  2. https://en.wikipedia.org/wiki/Microsoft_Small_Basic

SOAP vs REST

Let’s look at SOAP vs REST.

First, the technology stacks of SOAP and REST are quite different.

SOAP REST
Communication Protocol Quite complex. Simple,  reuse HTTP verbs
XML Yes  No
HTTP Yes Yes

Second, let’s look at what problems SOAP and REST try to solve. I will use Microsoft’s implementation as examples. Microsoft’s implementation of SOAP is ASP.NET web service, and REST is Web API.

ASP.NET web service (SOAP) was designed to solve complex business problems around 2000. The architecture was similar to remote procedure call (RPC) style, and based on complex protocol. The protocol can be described using XML. Visual studio makes programming ASP.NET web service a breeze and hide most of the complexity. Visual Studio creates a local proxy to program against, and make the RPC seamless and effortless. In addition, WSDL, a web service description language, was created behind the scene to make all these possible. However, it is very cumbersome to create the HTTP posts manually without Visual Studio because we have to know the protocol instead, which is not an easy task.

Around 2006, WCF was created. WCF is a superset of ASP.NET web service. So use WCF unless you maintain legacy applications.

With the coming of mobile devices and single page applications, etc., the business requirements shift. We don’t just solve complex business problems, and we need to solve simple business requests as well and more efficient. More developers from other technology stacks other than Microsoft find communication through short and simple message exchange more appealing. WCF including ASP.NET web service cannot solve the new business requirements naturally and efficiently. The overhead came with WCF and ASP.NET web service was too much.

JSON emerges as the default communication protocol on top of HTTP. Web API takes advantage of HTTP Verbs and the popular MVC style, and provide a solid foundation for REST. The business requirements are exposed as resources, and HTTP verbs are the actions again these resources. We can think about the resources as objects, and these objects offer implicit methods such as GET, POST, DELETE, PUT, etc. So we can say the programming paradigm changes. Although less descriptive, REST and JSON is easy  to learn, flexible, and have a light footprint.