Monday, January 7, 2019

Protecting SQL Server Data Using Static Data Masking

Are you providing adequate protection to your sensitive and confidential data? I’m sure we all do our best to protect our confidential data in a production environment by allowing only approved methods to access production data. But how are you protecting your development and testing environments when they contain copies of production databases?

Generating good development and test data is a tough job. Not only that but sometimes it is tough to reproduce production data issues in generated test data. Because of these two issues and a slew of other issues, many DBAs and developers fall into the simple method of generating test data by just copying production data down to non-production environments. By definition, non-production environments are typically less secure than production environments. Developers have different, normally more elevated, rights in these lower environments which means they can see data they are not able to see in production. Because of this, it is a bad idea to copy production data to non-production environments without cleansing the data first. This is where Static Data Masking can help.

What is Static Data Masking?

Static data masking is the process of permanently replacing sensitive data in your database with meaningless values. These meaningless values can be created by obfuscating part of or the complete column value with a generated value. Diagram 1 shows how static data masking replaces the complete CreditCardNum column value with a single generated value for all credit card numbers.

 

Diagram 1: Example of Single Value Static Data Masking

Performing Static Data Masking

Obscuring your sensitive data when copying your production data to non-production environments is one way to protect your confidential/sensitive production data. To help with performing static data masking, the Microsoft Security team incorporates static data masking as a new feature in SQL Server Management Studio (SSMS) 18.0 preview 5, or above. With the introduction of this new feature, you are now able to create a cloned copy of an on premises SQL Server database, where the confidential/sensitive data is statically masked in the cloned copy of the database.

Preview 5 and above of SSMS allows you to identify which columns are to be masked, and the functions that will be used in the masking operations. These masking definitions are then used to create a copy of your database that contains cleansed, statically masked data, where defined. The static data masking feature works on SQL Server 2012, or newer databases, as well as Azure SQL Database (DTU and vCore-based hosting options, excluding Hyperscale), and SQL Server on an Azure Virtual machine.

How to Get the Latest Version of SSMS

In order to learn how to perform static data masking, you first need to obtain the bits for SSMS 18.0 preview 5 or higher. To download the bits that have the static data masking feature, look at this page to find the latest download that supports Static Data Masking (at the time of the writing of this article, that was preview 6).

Run the exe to install the preview 6 bits, and you may have to reboot your machine. With the installation of the newest version of SSMS, you are ready to test out this new static data masking feature.

Methods of Masking Data

Before I can demonstrate how to mask data using SSMS Preview 6, I’ll first review the static data masking functions that are available in this new version. There are five static masking options available: NULL, single-value, shuffle, group shuffle, and string composite. The masking requirements will dictate which one of these masking functions will be used. Here’s a closer look at each of these functions.

NULL masking:

The NULL masking function will replace the original column value with a null in the cloned database. Note the masked column needs to support null columns in order to use this masking option.

Single-Value masking:

The single-value masking function replaces the original column values with a single value of your choice. Keep in mind the single value needs to be convertible to the column data type of the column being masked.

Shuffle masking:

With shuffle masking, the original column values are shuffled around. These shuffled values are then used to replace the original value in a row, with one of the shuffled values. If your original data has NULL values, you have the option of not replacing the NULL value or shuffling the NULL values around.

Group Shuffle masking:

The group shuffle masking binds multiple columns together for the shuffle operation. This function is useful when there is a relationship that you want to maintain between the multiple columns like, city, state and postal code.

String Composite masking:

String composite masking allows randomly generating masked data using a pattern. This pattern can replace and format the entire column value or only a portion of the column value. Patterns are provided using Regex-like expressions.

Sample Database for Testing Static Data Masking

In order to demonstrate creating a statically masked database, create a demo database named StaticMaskingDemo, using the T-SQL code in Script 1.

USE master;
GO
-- Drop Database 
DROP DATABASE IF EXISTS StaticMaskingDemo
GO
-- Create Sample DB
CREATE DATABASE StaticMaskingDemo;
GO 
USE StaticMaskingDemo;
GO
-- Create Sample Tables
CREATE TABLE CreditCard (
ID int,
CreditCardNum varchar(16),
SecurityCode int); 
CREATE TABLE Client ( 
ID int, 
CreditCardID varchar(16), 
ClientName varchar (50), 
BirthDate date, 
EmailAddr varchar(100), 
AddrLine varchar(60), 
City varchar (30), 
PostalCode varchar(15));
-- Populate with data
INSERT INTO CreditCard VALUES 
(1, 1000100010001000,100),
(2, 1234123412341234,123),
(3, 1111222233334444,333),
(4, 1234567890123456,456);
INSERT INTO Client VALUES 
(1, 1, 'John A. Smith','12-23-1954','JSmith@SmithWorks.com','1000 Smith Ave.','Portland','97035'),
(2, 2, 'Sally Johnson','07-12-1974','SallyJ@WLTS.gov','1234 Marine View Dr.','San Francisco','94016'),
(3, 3, 'Mary Sullivan','09-01-1972','MSS@InsComp.org','1111 Soundview Dr.','Bellingham','98225'),
(4, 4, 'Thomas J. Storm','11-17-1959','TJStorm@SutterSmith.com','2345 Water Street','Bloomington','47401');

Script 1: Create Sample Database

The script created two tables: Client and CreditCard. Table 1 contains the masking specification in to mask the sample database.

Table.Column

Masking Specifications

CreditCard.CreditCardNum

String Composite (replace first 10 digits with X’s).

CreditCard.SecurityCode

Single Value (replace all values with 123)

Client.ClientName

Shuffle

Client.BirthDate

Null

Client.EmailAddr

String Composite (keep domain, but replace portion prior to @ sign with a random value)

Client.AddrLine

Group Shuffle

Client.City

Group Shuffle

Client.PostalCode

Group Shuffle

Table 1: Masking Specification

Identifying Masking Criteria using SSMS

Once the database is created, make sure you are running the new version of SSMS. The new task named Mask Database… (Preview) is used to identify the masking criteria. To bring up this new task, connect to your local instance of SQL Server. Right-click on the StaticMaskingDemo database in Object Explorer. In the drop-down display, hover over the Tasks item and then finally select the Mask Database… (Preview) task from the second drop down, as pointed to by the red arrow in Figure 1.

Figure 1: Selecting the Mask Database Task

After selecting the task, the window shown in Figure 2 is displayed.

Figure 2: Static Masking Steps

Figure 2 shows that there are three steps to perform in order to identify the masking requirements for the database.

Step 1: Masking Configuration

By looking in the Masking Configuration step (Step 1), you can see there are two tables contained in the database: Client and CreditCard. To specify the static data masking, start by specifying the masking configuration for the CreditCardNum column in the CreditCard table. To show the columns within CreditCard table, click on the down arrow icon, next to the table name. Upon doing this, Figure 3 is displayed.

Figure 3: Columns in CreditCard table.

Use the String Composite masking function for the CreditCardNum column and the Single Value masking function for the SecurityCode column.

The String Composite masking function is used for the CreditCardNum column in order to show the last 6 digits of the credit card number with the first 10 digits replaced with X’s. The “advanced” masking option is needed to specify this complex masking criteria. First click on the checkbox next to the CreditCardNum column to indicate that you want to mask this column. Then select the String Composite item from the drop down. Then, finally, click on the Configure… hyperlink option as shown in Figure 4.

Figure 4: Masking criteria for CreditCardNum column

After clicking on the Configure… hyperlink, the pattern specifications window appears which is shown in Figure 5.

Figure 5: Pattern Specifications

The pattern specifications window can be used to define a random value criteria based on a pattern expression. To mask part of the CreditCardNum column using a complex masking criteria, click the Advanced check box to configure more complex masking requirement.

The advanced masking specification allows you to specify the complex masking requirements. As previously stated, just the first ten characters of the CreditCardNum should be replaced with X’s. Therefore, on Figure 6 shows a Pattern of ten X’s (XXXXXXXXXX) which identifies the pattern that will be used to masked the first ten characters of the credit card number column. To identify which characters in the source will be replaced with the ten X’s, specify a Source Regex pattern value of (\d{10}). This pattern identifies the first 10 digits of the CreditCard column will be the characters replaced with the ten X’s. Figure 6 shows the window once it’s configured.

Figure 6: Advanced Masking Specifications

The other column to mask in the CreditCard table is SecurityCode. This column will be masked with a single value of 123 in all rows. To select this column to be masked, select the checkbox next to this column and pick the Single Value masking function. Then click on the Configure… hyperlink.

Figure 7: Single Value Specification

On the single value specification screen, enter 123 for the value. By specifying this, the SecurityCode column will be replaced with the static value of 123 on every row in the CreditCard table. Now that the static masking criteria for the CreditCard table is defined, it’s time to move on and specify the masking criteria for the Client table.

To mask the Client table, first display the columns. Figure 8 shows what is displayed.

Figure 8: Client table columns

In Figure 8, you can see all the columns in the Client table. Click on the checkbox next to each column that must be masked, as identified in Table 1, and then select the appropriate masking criteria for each column as shown in Figure 9.

Figure 9: Identifying masking criteria for Client table

Figure 9 identifies all the columns and the type of masking to be performed for each column. As you can see, the Shuffle and the String Composite items support providing additional masking specifications.

To configure the Shuffle masking configuration specification for the Name column, click on the Configure… hyperlink. After clicking, the window in Figure 10 is displayed.

Figure 10: Masking Configuration for Name column.

As you can see the Shuffle masking criteria only has one configuration option that can be specified, and that is to Maintain NULL positions or not. Remember the Shuffle criteria will use all the column values for masking but will shuffle the values around randomly amongst the rows. Therefore, when selecting Maintain NULL positions, any NULL values in the Name column will not be moved to different rows. When the box is not selected, then the NULL values can be moved around. For this column, leave the box unchecked.

The BirthDate column will be masked using the NULL masking specification. This specification will replace all the BirthDate column values with NULL in the cloned database.

The Group Shuffle masking criteria will be used for the AddrLine, ZipCode and City columns. The group shuffle is like the shuffle option, but instead of shuffling each column value independently of the others, it randomly shuffles all the grouped column values together in the cloned database rows. Group Shuffle has a Configure… option, as well. Figure 11 shows the option when this is clicked.

Figure 11: AddrLine group shuffle configure option

The only configuration option is to name the shuffle group which is group1 by default. This shuffle group name will be used to identify all the columns that will be shuffled together. The Shuffle Group masking criteria is set on the three address columns in the Client table. By default, all three of these columns were defined with a Shuffle group name of group1. Therefore, the address attributes on each row will be shuffled together, thus making sure the address attributes stay together when they are shuffled and randomly associated with new rows. If you want to have different sets for columns grouped and shuffled together, all you would have to do is define more than one Shuffle group name.

The last column to mask is the EmailAddr column. For this column, select the String Composite masking criteria. This masking criteria is used to create a masking rule where the email domain stays the same, but the address portion prior to the @ sign is set to a random pattern. To create this masking rule, click on the Configure… hyperlink next to the email address column. Then check the Advanced checkbox, and, finally, select the Email Address (keep domain) hyperlink at the bottom of the pattern window, as shown in Figure 12.

Figure 12: Email Address masking configuration

Figure 13 shows that the Pattern and Source Regex fields were populated with expressions after clicking on the email example hyperlink. These expressions define that the email address domain will be kept when this column is masked, but the email address portion prior to the @ sign will be replaced with a generated value.

Figure 13: Email masking rule

At this point, all of the masking requirements have been defined and you can move on to Step 2.

Step 2: Identify Clone Backup Location

In this step, you must identify the location where you want SQL Server to save a backup the database you are trying to mask. This database backup will be used in the cloning process but does not contain masked data. In my case, I will store my backup in the C:\temp directory as shown in Figure 14.

Figure 14: Clone Backup File Location

Step 3: Identify Masked Database name

In this step, you must identify the name of the cloned database. In Figure 15, you can see I named my cloned database StaticMaskingDemo_Masked.

Figure 15: Masked database name

At this point the following has been configured:

  • Database and columns that will be masked.
  • The masking rules for each column to be masked.
  • A location and name of where to store a backup copy of the database being masked.
  • The name of the masked database.

This was a lot of point, click and typing just to identify a few masking specifications. Suppose you had a bunch of tables and columns that needed to be masked. If this were the case, it would take a very long time to use the GUI method of identifying masking requirement. At this point you can save the masking configuration by click on the Save Config button as show in Figure 16.

Figure 16: Save masking configuration.

When you click on this button, you’ll be promoted for a location to store the XML that makes up the masking configuration. In this case, I stored the XML in C:\temp\StaticMaskingDemo_Masked.xml. Saving the configuration will make it easy to change the masking criteria in the future if you need to.

At this point, everything is in place to clone the database by clicking on the OK button. When the masking and cloning process is completed, the window in Figure 17 is displayed.

Figure 17: Masking completed!

By looking at the text in Figure 17, you can see that the cloning process actually deployed a masked database. My cloned database was stored on the same instance as the databases being cloned. In addition, a backup file that contains the masked database was created in the location that previously identified. This backup could be used to restore the masked database to another instance of SQL Server.

Validation of the Masked Database

To verify that static data masking feature actually masked the data based on the masking specification, compare the original data in database StaticMaskingDemo with the cloned database named StaticMaskingDemo_Masked. To compare the data in the two databases, use the TSQL code in Script 2.

-- Original Client Data
SELECT [ID],[CreditCardID],[ClientName],[BirthDate]
      ,[EmailAddr],[AddrLine],[City],[PostalCode]
  FROM [StaticMaskingDemo].[dbo].[Client];
-- Cloned Client Data
SELECT [ID],[CreditCardID],[ClientName],[BirthDate]
      ,[EmailAddr],[AddrLine],[City],[PostalCode]
  FROM [StaticMaskingDemo_Masked].[dbo].[Client];
-- Original CreditCard Data
SELECT [ID],[CreditCardNum],[SecurityCode]
  FROM [StaticMaskingDemo].[dbo].[CreditCard];
-- Cloned Cloned CreditCard Data
SELECT [ID],[CreditCardNum],[SecurityCode]
  FROM [StaticMaskingDemo_Masked].[dbo].[CreditCard];

Script 2: TSQL code to display data from both databases

The code in Script 2 returns output similar to Figure 8.

Figure 18: Review Original and Cloned data

If you look at the masked data (outlined in blued) in Figure 18 and compare it against the original data (not outlined), you can tell the data was masked in the cloned database just as specified.

XML to Support Static Data Masking

In a prior section you saved the XML configuration for the masking requirements. The configuration was stored in an XML file named: C:\temp\StaticMaskingDemo_Masked.xml. When you open that file up it looks like the text in Script 3.

Script 3: Static Data Masking XML

By reviewing this XML file, you can see that all the columns masked are identified in the XML. Each column contains the masking requirements that were identified.

If you had a really big list of tables and columns you needed to mask, you can imagine how long it might take to identify the masking requirement using the GUI interface. Not only that, if you made a mistake, re-identifying all the masking requirements manually a second time would be a real pain. Being able to identify masking requirements in an XML file will make it much easier to identify all the masking requirements manually than using the SSMS GUI.

After creating or modifying this XML, you can load into SSMS. To load this XML file, just click on the Load Config button as shown in Figure 19.

Figure 19: Loading masking criteria for XML file

Limitations

Not all database/columns can be masked using the new Static Data Masking feature. Here is a list of limitations that will keep you from masking your database/column using this new Static Data Masking feature:

  • Does not support databases with temporal tables.
  • Does not mask memory optimized tables.
  • Does not mask computed columns or identity columns.
  • Does not support geometry or geography data types.
  • Does not update histogram statistics, so cloned database may still contain your confidential data in the statistics. To resolve this issue all you need to do is run the update statistic function in the new database once the masking process is completed.
  • When a masking operation fails, a masked database might be created and contain unmasked data.
  • Unmasked data could still be stored in unallocated data pages for on-premises SQL Server databases, and therefore someone could use a hex editor to view these unmasked values.

For more information about these exceptions please refer to this documentation. If you are interested in having a process that can be automated and that can use more complex rules, such as keeping certain columns synchronized across tables, take a look at Redgate’s SQL Provision.

Observations

While exploring and testing out Static Database Masking, I made the following observations:

  • It is great you don’t need to have your database on SQL Server 2019 to use the static data masking feature. The only requirement is to have SSMS 18 preview 5 or above available, and your database needs to be on SQL Server 2012 or above.
  • When you clone/mask a database, the cloned database is created on the same instance as the source database. I can see times when you will not be able to clone your production database on the instance where it lives. Therefore, I would have preferred a dialog box that would allow me to place this database on an instance other than the instance where the original database lives.
  • A FULL backup of your original database is created during the cloning/masking process. This backup is not a copy only backup, therefore it might impact your normal backup chain. I think I would have preferred this backup to be a copy only backup so it doesn’t interfere with your normal backup routine of the database being cloned/masked. I’ve reported this to Microsoft and they have informed me that this will be changed in a future release.It is easy to create complex masking rules if you are familiar with Regex expressions. Even if you are not versed in Regex expressions, the tool has examples to help you start and build your Regex expressions. Having these examples make it somewhat easier to develop masking criteria even if a person that doesn’t speak Regex fluently.
  • Using the GUI tool to specify masking requirements might be a bit cumbersome. Therefore, it might be worthwhile to consider creating masking requirement using an XML file. Using XML files to identify the masking requirements makes the cloning/Masking process much more repeatable and will make it easier when entering lots of masking requirements.
  • At the time this article was written, I could not find a way to automate the static masking process. Hopefully by the time this feature is fully baked, the static data masking team will provide you a way to automate the masking process via a script.

Obscuring Confidential Data Easily

It has always been a challenge to cleanse production data when moving a database to a non-production environment. With the new Static Data Masking feature introduction in SSMS version 18 Preview 5, a DBA or developer can now easily cleanse their confidential data, by clone production databases in non-production environments. All it takes is to specify some masking criteria manually or with an XML file, and then running your source database through the masking/cloning process. This new feature in SSMS supports masking a database provided the database is on SQL Server 2012 or above. All DBA’s and developers that are concerned about security should be looking at using this the Static Data Masking feature every time they clone a production database for a non-production environment.

 

The post Protecting SQL Server Data Using Static Data Masking appeared first on Simple Talk.



from Simple Talk http://bit.ly/2LTjeos
via

Thursday, January 3, 2019

The New Year Has Started, So It Must Be SQL Saturday Nashville Time!

Happy New Year everyone! Hope the holiday season’s passing finds you well rested, well fed, and ready to hit the ground running. As year’s go, it was a relatively great year last year… as far as the SQL community goes in any case. But now that 2019 has started, it is time to get back down to business…

The first bit of business for me is to dust off, update, and get ready to give a presentation for SQL Saturday Nashville in just 10 days! It is always a delight to head back to the city where I lived the longest part of my life. The food, the entertainment, the sights, and more importantly, since these SQL Saturday trips are pretty much whirlwind affairs where I never get to do much of those things… hang out with a a great group of folks at the center of the local SQL community for a day.

This year, I will be presenting a session that I haven’t done for quite a while, but I submitted it again because last year when I was doing my full day database design session, I realized how much fun it was to simply discuss the things that make a database great, because it often gets lost in the process because users don’t so much see the database as they do feel it. The goal naturally is for this to be a pleasant experience all around, so it is important to think about all different characteristics necessary for a great database.

Characteristics of a Great Relational Database

When queried, most database professionals would mention normalized as one of the most important characteristics that tell the difference between a good and bad relational database design (whether they know what the term “normalized” means or not.) Normalization is a key to great relational designs, but there is so much more to be considered. A normalized database that suffers from poor naming, too many or too few indexes, terrible interfaces, and so on can derail your design’s value to the user. In this session I will present primary characteristics of a design that differentiates between an ugly design that will have your colleagues nitpicking you to death and one that will have them singing your praises. Characteristics such as comprehendible, documented, secure, well performing, and more (including normalized, naturally) will be discussed.

If you aren’t into database design (which would be a lot of people who design databases, sadly :)), there are a lot of other great sessions by many people I call friend. I won’t even try to name them, for fear of boring you and/or leaving out someone. You can check out the slate of speakers here on the schedule: https://www.sqlsaturday.com/815/Sessions/Schedule.aspx. Suffice it to say that there are more than enough great names and sessions on the schedule that I would have driven up on a Saturday to see regardless of whether I was speaking or not (and on a day of the NFL football playoff season… this is quite an endorsement coming from me.)

Hope to see you there! Register here: https://www.sqlsaturday.com/815/EventHome.aspx, and if you can, support the event even more by registering for one of their pre-cons!

 

The post The New Year Has Started, So It Must Be SQL Saturday Nashville Time! appeared first on Simple Talk.



from Simple Talk http://bit.ly/2Aqi93e
via

Robotics Process Automation: The New Digital Assistant

By now, most enterprise leaders are well aware of the benefits of robotic process automation (RPA) – financial savings, improved quality and a better customer experience, just to name a few. RPA is an application of technology, governed by business logic and structured inputs, aimed at automating business processes. Using RPA tools, a company can configure software, or a “robot,” to capture and interpret applications for processing a transaction, manipulating data, triggering responses and communicating with other digital systems. With RPA, businesses can automate mundane rules-based business processes, enabling business users to devote more time to serving customers or other higher-value work.

On similar note, a case study was conducted on a Capital Approval tool (tool built for one of the customers) to verify the benefits and results of applying RPA to a business process with different roles activities. The results show that productivity improvement is the main benefit of RPA as well as time reduction achieved in this case.

Introduction

For any business process execution, different roles are involved in spending substantial time in dealing with downstream applications, i.e., Resource Planning, Customer Relationship Management (CRM), Payroll system etc.

Robotic process automation is designed to help primarily with office type functions, which requires the ability to do several types of tasks in order. This is in contrast to traditional manufacturing automation that focuses on taking one portion of a workflow or even just one task and creating a robot to specialize in it. Office work often requires the same types of repetition of jobs/task, but it is data being manipulated across downstream platforms and applications so a physical robot is not necessary. Instead a software robot is deployed with the ability to launch and operate other software. RPA works like a digital assistant for workers by clearing the onerous, simple tasks that eat up part of every office worker’s day. Simplicity and relative low costs can make RPA a more attractive solution for many companies, particularly if the company has legacy systems and applications. Robotic process automation is designed to play nice with most legacy systems and applications, making it easier to implement compared to other enterprise automation solutions.

Consider that some highly structured, routine and manual tasks could be handled by a robot, so that skilled workers have more time for value added tasks. This is the promise or Robotic Process Automation (RPA) that has emerged in the last five years as a set of software tools and automation platforms that can automate tasks on rules-based business processes. Robots in the RPA processes or systems or tools doesn’t exactly mean physical robots, but instead it means that there are software blocks or applications that can take over responsibilities or tasks from Humans. These are tasks that can be performed by robots more quickly and efficiently.

While existing capabilities of screen-scraping and macros software technology may come to mind, RPA is an evolution beyond these solutions. RPA is becoming an important automation tool driving digital transformation and the future of work. As a user-friendly and cost-effective tool, robotic process automation provides a number of advantages that are drawing interest from different organizations across many industries.

The industry benefits of RPA include –

Extreme accuracy: Bots are extremely accurate and consistent – they are much less prone to making mistakes or typos than a human worker. Higher percentages of mistakes and typos have been observed when humans are copying data or feeding other systems.

No programming skills: To configure a software robot, you don’t need to be expert in programming. As this is code-free technology, any non-technical staff can use a drag and drop process designer to set up a required bot or even record their own steps to automate a process through a process recorder feature. Once the bot is deployed, it would execute same steps.

Regulatory compliance: Bots only follow the instructions they have been configured to follow and provide an audit trail history for each step. Several aspects of compliance oversight operations can be enhanced through robot implementation. Monitoring and testing is an especially promising automation candidate. RPA’s capability to pull and aggregate data from multiple sources could also enhance the efficiency of regulatory, non-financial, and risk reporting as it can help eliminate or reduce the time-consuming processes of collecting, compiling, and cleansing, and summarizing large amounts of information. The controlled nature of bot work makes them suited to meeting even the strictest compliance standards

No impact on existing technology: RPA involves no disruption to underlying systems or technologies. Robots work across the presentation layer of existing applications just as a person does. Robots are useful for legacy systems, where APIs may not be immediately available, or in situations where organizations do not have the skilled resources to develop a deep level of integration with existing legacy applications.

Improved productivity: Robots process cycle times are fixed and more efficient and can be completed at a faster speed compared with manual process approaches where humans are involved.

Reliability: Operations can be performed 24/7 as these bots can work tirelessly and autonomously without requiring staff to manually trigger bots to initiate. If a human does need to intervene, it is to make a decision or resolve an error.

Consistency: RPA also offers the benefit of consistency of process. These bots can perform routine tasks same way each and every time based on defined captured flow.

Improved morale: RPA can handle some of the most routine tasks a business completes each day. Bots enable workers to offload manual offload tasks like filling out forms, data entry and looking up information from websites. This will improve morale in the HR and administrative areas of your business, which are crucial to helping your business grow. Employees will have more time to invest their talents in more engaging and interesting work.

Case Study

This case study was carried out on a Healthcare provider firm. As part of organizational strategy, the company created a shared platform to manage process automation, innovation and better customer experience. This was all orchestrated using BPM (Business Process Management) and hosted a number of processes.

To understand RPA and the benefits associated with it, company started by evaluating and prototyping this automation technology on some of its customer business process – Capital Approval process.

Figure 1 is the AS-IS process. Once a case is approved by all roles, then finalizers logged in to the approval digital tool to open the case and at the same time create case in JDE system with relevant detail taken from approval tool and generate the JDE IO number. This whole process is manual and often leads to error.

Figure 1: Capital Approval AS-IS process.

Figure 2 is the TO-BE automated process. The finalizer’s role activities were assumed by a software robot (RPA). After the case approval is done by other process roles, the robot accesses the data store, creates the case in the JDE system and generates JDE IO number, copies the JDE IO and pastes it on the approval tool to complete the case and generates notification for case completion.

Figure 2: Capital Approval TO-BE process with RPA.

Results

To evaluate results of TO-BE process implementation, capital request were monitored in two sets, one set with finalizers and another set without finalizers (Finalizers replaced with Robot) as finalizers activities were performed by robot. The measure used for evaluating the results was case duration for fixed number for requests. With RPA, overall duration reduced by 62% and finalizers duration reduced drastically by 99.99%. The results may vary based on the nature of the process.

The Need for an RPA Center of Excellence

We must have heard so far about technology, quality, project management and some other Center of Excellence (CoE) but not about RPA. When the number of automated processes increases, RPA becomes more complicated hence RPA requires a suitable operating and governance model for effective implementation. After RPA implementation, it doesn’t mean that we don’t need expertise to maintain robots. A CoE is essentially the way to embed RPA deeply and effectively into the organization, and to redistribute accumulated knowledge and resources across future deployments. The structure for RPA can consist of many teams across the organization and CoE can support those teams. Identify an RPA sponsor, change manager, solution architects, developers, infrastructure and service support to take on key roles in the RPA CoE and they can work across different implementation. The team needs to understand how to work well together and with stakeholders to deploy automation technology, adhere to standard processes and procedures, and measure business metrics and performance goals, including return on investment and customer satisfaction.

All automations can’t be candidates for RPA hence CoE can also work across the organization units with the primary objective of identifying processes, priorities processes for automation and then developing processes in robotic software before they go into production. They can also take care of controlling and monitoring the robot in production.

In the above case study, the RPA team interacted and collaborated with Capital tool development, support, business, testing CoE, and the change management team. This collaboration can be governed by CoE to meet strategic objectives and outcomes.

Conclusion

This article has covered what Robotic Process Automation means, the benefits that an Organization can enjoy when implementing Robotic Process Automation and also need of RPA center of excellence which can help effective implementation. When deciding on the use of RPA, companies should consider that RPA is more suitable for high volume standardized tasks that have rules and driven by fixed paths and where there is no need for subjective judgement, creativity or interpretation skills. In the above case study, the finalizer role was never involved in subjective judgement hence it was acknowledged as a suitable candidate for RPA implementation.

The main benefits of RPA are cost reduction, increasing process speed, error reduction (as robots follow the instruction which have been provided) and productivity improvement by reducing execution duration as the case study reveals.

 

The post Robotics Process Automation: The New Digital Assistant appeared first on Simple Talk.



from Simple Talk http://bit.ly/2SDqA2g
via

Cyber Insecurity in Pakistanin

On 26th October, almost all Pakistani television channels (followed by print and web media) were flooded with the breaking news saying that Pakistan is encountering a new layer of cybercrime scam affecting all commercial banks (more than 20 different banks having thousands of branches in country and abroad). The news in detailelaborated that some 20 thousand credit/debit cards of customers have been compromised during the last week of October with a reported loss of Rs 2.7 million. This flow of news stirred the nation as according to State Bank of Pakistan at present (last quarter 2018) there are 18,778,525 debit cards (excluding hundreds of thousands of credit cards and other ATM cards) being under usage in the country. Consequently, scores of the banks moved a step ahead and blocked myriads of international transactions through credit-debit cards. Some even temporary halted disbursement of cash via ATM machines to save their customers from any mishap.

To double check this stormy news I visited PakCERT (Pakistan’s Computer Emergency Response Team) website. PakCERT is a business concern dealing with ICT solutions in Pakistanwhich revealed that on October 26, 2018, hackers posted over 9,000 debit cards on the dark web for sale at a price ranging from $100 to $160 per card. The data was placed in two different formats. First, with a text-based credit/debit card details, like name, phone number, card number, address and even expiry of the card to facilitate the illegal purchases. The second format was skimmed stuff making it easy for someone to scan details of the cards at a compromised ATM machine.

However, on the following day, media flashed more news saying that the storm is over (probably to avoid panic). But the consequent day (31st October) brought an aftershock saying that some 12,000 more cards were uploaded on the dark web including 11,000 cards from Pakistan.

Sensing this paradoxical scenario, I decided to unfold the issue as in recent years Pakistan has faced similar incidents of cyberspace scams (among which the recent one was the worst ever) that remained active for some time and then faded away unchecked and unresolved.

Some Recent Scams

Last December, a private bank confirmed that hundreds of its bank accounts were hacked through ATM (Automatic Teller Machine) cards. The bank official later confirmed to the media that Rs 10 million had been stolen from 559 of its accounts. A couple of similar incidents were followed until FIA (Federal Investigation Agency) started a comprehensive action and arrested several foreigners for allegedly stealing data from banks with skimming devises at ATM facilities. This kind of stealing and skimming devices was a new phenomenon in Pakistan and all those arrested were foreigners. However, after a gap of eleven months, when the recent cyber scam is hovering, scores of such incidents related to ATM machines were reported. Accordingly, during last two months scores of local hackers involved in ATM hacking were arrested from different parts of the country including the federal capital. In other words, this ATM scam not confined to foreigners but local hackers in different cities have access to the same misdemeanour.

Apart from other such scams, there was one major scam in recent times. In April 2018 a ride-hailing company Careem (having operations in 13 countries in over 90 cities) announced that data of its 14 million customers and drivers was stolen in a cyber attack. However, officials of the company revealed that they have seen no evidence of fraud or misuse related to the issue. But it was a major blow for the leading online transport company in the country as most its customers quit using the app and the service to avoid any mishap to their personal data on their cell phones.

The Issue

Sensing the issue followed by contradictory news, I approached CEO PakCert Qazi Muhammad Musbahuddin and asked him if the crises is over or still looming. He replied, “At present I can’t comment on the issue as all the relevant sector or working on the issue”. He added said that no further information will be shared on this regard until complete investigation of the issue. However, soon after the issue was raised on 26th of October, Mr Qazi told Pakistan leading Television channel Dawn TV “No doubt the problem is there however we are working to assess that either bank database is compromised or another kind of security breach occurred.”

Now the question is, if government departments are working on it, no one knows about it particularly the worried customers. For example all cards (ATM, Debit, Credit Cards etc) are bank generated.

Meanwhile, most of the customers have no or little information about the digital complexities and if stuck with any technical issue find themselves in hot waters. For instance, a local customer from the provincial capital Khyber Pakhtunkhwa Province Peshawar, Adnan Afridi told me that during last week of October 70 thousand Pakistani rupees were stolen from his account but now he doesn’t know how and where to complain about it.

Commenting on the issue of Adnan Afridi and other such mishaps, Iftikhar Firdus, Bureau Chief Express Tribune Peshawar, who also has expertise on the issue, said that cyber crimeshave many types and the one related to the recent scam comes in the category of financial cyber crime. In the said case, usually hackers enter via coding in the dark net. And the problem is most of the time such entries remain untraced. In Pakistan, they are also using other tactics like calling from unknown numbers, using pressure tactics to get pin codes, etc. International hackers are even faster. On the contrary, Pakistan has little or no preparation to counter such threats, and most of the banks here have no counter mechanism. Accordingly, recent reports say that a sufficient number of customers are flexing their muscles to go for analogue transactions.

Challenge at Present

If the issue of cyber scam was something to be worried a couple of yearsago, it seems to be really alarming now. Most of the activitiesonce tackled traditionally (manually) in Pakistan are now transforming into digital and the online amphitheatre. The phenomenon like e-commerce, e-health, e-Tag and online banking, etc., which were once aliens to our economic structure are now the lifeline of the system. It’s obvious that a major part of Pakistani community is now dependent on cyberspace.

Meanwhile, most of the government functions suchas hospitals, sensitive defence offices, election commission of Pakistan, Civil Aviation System, NADRA (National Database and Registration Authority), National Assembly, Senate, Emergency Services, and even nuclear arsenals containing sensitive information are on the digital front.

However,this improvement on the national cyber world also brought with itself cyber security and cyber threat. Recent reports say Pakistan is one of the few leading countries being constantly under threat by foreign cyber offenders. Cyber security threats with recent threats to the banking sector and other relevant enterprises are hard to be avoided.

Comparison

No doubt cyber crimes and cyber insecurity are global issues, and the digital system is vulnerable to cyber attacks throughout the world. However, most of the countries respond to the issue in a smarter way, particularly in developing countries. There are various international fora for the purpose of having a quick response with highly professional staff comprising Computer Security and Incident Response Team (CSRIT), Forum for Response and Security Team (FIRST), etc. Most countries have such security watchdogs like US-CERT, CNCERT, AUS-CERT,JAPCERT, SING-CERT, etc.

Talking on the issue, a senior level official in Islamabad from United Bank Limited explained on condition of anonymity that unfortunately Pakistan’s public and private systems are neither fully automated nor fully secured. He added that unlike developed countries (US, UK, China, etc.), Pakistan don’t possess dedicated cyber warfare units and, as a result, we are more vulnerable events like the recent one as compared to developed countries.

He also gestured to another misfortune that, unlike developed countries, Pakistan don’t have international cyber space treaties with online portals such as Google or Facebook resulting in further vulnerability when any cyber space scam appears.

Government Response

Talking to a media outlet, Assistant Director FIA Cyber Crime Cell Abdul Wajid Khan Safi has said that there are some alarming reports over the issues. He added that the rapid increase have many reasons like the recent boom of social media (making people’s personnel information vulnerable), lack of awareness, and most probably the involvement of international hackers. This is whythere are some 1600 complaints registered in his covered area during last 10 months. However, FIA Cyber Crime Cell is actively addressing such complaints. He added that, on one hand, there are strict penalties being promulgatedin the laws and at the same times scores of arrests have been made in the recent past. According to Cyber Crime Law, if proven guilty, there is a 3 to 7 month imprisonment and Rs 10 million fine.

No doubt government is taking some action to fix the issue and in recent days some arrest were also made by FIA Cyber Crime Cell. In one recent incident, FIA Cyber Crime Wing arrested two hackers stealing Rs 500,000 from a private person. The gang was involved in stealing money from random banks. In another incident at Faisalabad city of Punjab province, a seven-member gang was arrested where data of about 300 customers were recovered from the gang.

However, as the magnitude of the offence is concerned, it’s not a matter of few arrests, but needing a comprehensive strategy by different concerned departments of the public and private sector.

Despite the above-mentioned steps, as magnitude of the threat is concerned, the government is still thousands of miles behind and little effort has been done to tackle the issues. There seems to be no concrete security policy or any guidelines for the public. A few months back, the Senate Standing Committee on Defence tabled a seven point agenda to improve cyber security in the country. The seven points also emphasises having a joint Asian Strategy in collaboration with neighbour states for countering these threats. But these efforts have gone unnoticed and no implementation appeared on board.

Recommendations:

Assessing the overall situation followed by talks with expertsis a prime concern. Pakistan should evolve a comprehensive cyber space strategy and implement it in letter and spirit. No doubt some progress has been made by FIA Cyber Wing, but it needs to be further expedited. PAKCERT offices should be further equipped with contemporary innovations and, if needed, its branches should be open in different units/provinces of the country.

Most of the banks have made sufficient investments for security purposes, but they need more attention and investment to strengthen their firewalls, use of anti-virus protection on their computers, and encrypted websites.

As precautions by the customers are concerned, a legal expert and lawyer at Islamabad Salahuddin Khan said that, apart from banks and other government and private organizations, the customers should adopt some precautionary measures. They should avoid sharing personnel information like CNIC number, account number, pin code, credit/debit card numbers and other such information which are the primary source for most of the hackers.

Mr Khan added, that if a person is still trapped, he or she should immediately contact Cyber Crime Cell (particularly NRC3 wing) to have the complaint either written or online.

Other experts also have the same opinion and are of the view that encrypted and anti-virus software should be updated on home computers and cell phones.

Moreover, the government should go for immediate agreements and treaties with international online portals. Experts say in presence of such agreements almost 90 percent of such cyber issues can be solved.

Continued awareness among the public with liaisons among security intuitions (FIA Cyber Crime Wing, PAKCERT, etc)will help the public bring further strength to cyber security. Adding Cyber Space and Cyber Security as a subject in the syllabus at the university level would no doubt be helpful for a safe and secure cyberspace in the country.

References

State Bank of Pakistan Quarter Analyses/Report: http://bit.ly/2LNBSOG

PakCert report on Intelligence threat:

http://bit.ly/2s8k73m

Dawn (Pakistan’s most reliable and leading English paper) Report: RS 10 million from 559 bank accounts in ATM Fraud: http://bit.ly/2B0fVsF

Data of 14 million customers of Careem Stolen:

https://cnb.cx/2s3Dvif

 

The post Cyber Insecurity in Pakistanin appeared first on Simple Talk.



from Simple Talk http://bit.ly/2AtFZeq
via

Monday, December 31, 2018

Introduction to SQL Server Security — Part 1

Security can be one of the most complex issues to contend with when managing a SQL Server instance, yet it’s also one of the most important, especially when sensitive and personal data are on the line. In fact, for many organizations, security is their number one priority, which should come as no surprise, given what’s at stake.

Fortunately, SQL Server includes a variety of tools for protecting data from theft, destruction, and other types of malicious behavior. In this article, the first in a series about SQL Server security, I introduce you to many of these tools, with the goal of providing you with an overview of the options available for safeguarding your data. In subsequent articles, I’ll dig deeper into the different technologies, providing a more in-depth look at how they work and what it takes to protect a SQL Server instance.

SQL Server Authentication and Authorization

Protecting data starts with the ability to authenticate users and authorize their access to specific data. To this end, SQL Server includes an authentication mechanism for verifying the identities of users trying to connect to a SQL Server instance, as well as an authorization mechanism that determines which data resources that authorized users can access and what actions they can take.

Authentication and authorization are achieved in SQL Server through a combination of security principals, securables, and permissions. Before I get into these, however, it’s important to note that SQL Server supports two authentication modes: Windows Authentication, sometimes referred to as integrated security, and SQL Server and Windows Authentication, sometimes referred to as mixed mode.

Windows authentication is integrated with Windows user and group accounts, making it possible to use a local or domain Windows account to log into SQL Server. When a Windows user connects to a SQL Server instance, the database engine validates the login credentials against the Windows principal token, eliminating the need for separate SQL Server credentials. Microsoft recommends that you use Windows Authentication whenever possible.

In some cases, however, you might require SQL Server Authentication. For example, users might connect from non-trusted domains, or the server on which SQL Server is hosted is not part of a domain, in which case, you can use the login mechanisms built into SQL Server, without linking to Windows accounts. Under this scenario, the user supplies a username and password to connect to the SQL Server instance, bypassing Windows Authentication altogether

You can specify the authentication mode when setting up a SQL Server instance or change it after implementation through the server’s properties, as shown in Figure 1.

Figure 1. Selecting an authentication mode for a SQL Server 2017 instance

At the heart of the authentication and authorization mechanisms are the principals, securables, and permissions that must be configured to enable users to access the data they need, while preventing unauthorized users from accessing data they shouldn’t.

You can view and work with principals, securables, and permissions through SQL Server Management Studio (SSMS), using either the built-in GUI tools or the available T-SQL statements. Figure 2 shows Object Explorer in SSMS with the expanded Security folder for the WideWorldImporters database and, below that, the expanded Security folder for the SQL Server instance.

Figure 2. Working with security features in Object Explorer

Principals are individuals, groups, or processes that are granted access to the SQL Server instance, either at the server level or database level. Server-level principals include logins and server roles, which are listed in the Logins and Server Roles subfolders in the Security folder:

  • A login is an individual user account for logging into the SQL Server instance. A login can be a local or domain Windows account or a SQL Server account. You can assign server-level permissions to a login, such as granting a user the ability to create databases or logins.
  • A server role is a group of users that share a common set of server-level permissions. SQL Server supports fixed server roles and user-defined server roles. You can assign logins to a fixed server role, but you cannot change its permissions. You can do both with a user-defined server role.

Database-level principals include users and database roles, which are listed in the Users and Roles subfolders in the database’s Security folder:

  • A database user is an individual user account for logging into a specific database. The database user commonly maps to a corresponding server login in order to provide access to the SQL Server instance as well as the data itself. However, you can create database users that are independent of any logins, which can be useful for developing and testing data-driven applications, as well as for implementing contained databases.
  • A database role is a group of users that share a common set of database-level permissions. As with server roles, SQL Server supports both fixed and user-defined database roles.

For each security principal, you can grant rights that allow that principal to access or modify a set of securables. Securables are the objects that make up the database and server environment. They can include anything from functions to database users to endpoints. SQL Server scopes the objects hierarchically at the server, database and schema levels:

  • Server-level securables include databases as well as objects such as logins, server roles, and availability groups.
  • Database-level securables include schemas as well as objects such as database users, database roles, and full-text catalogs.
  • Schema-level securables include objects such as tables, views, functions, and stored procedures.

Permissions define the level of access permitted to principals on specific securables. You can grant or deny permissions to securables at the server, database, or schema level. The permissions you grant at a higher level of the hierarchy can also apply to the children objects, unless you specifically override the permissions at the lower level.

For example, if you grant the SELECT permission to the user1 principal on the Sales schema in the WideWorldImporters database, the user will be able to query all table data in that schema. However, if you then deny the SELECT permission on the Sales.Customers table, the user will not be able to query that table, but will still be able to access the other tables in that schema.

You can use SSMS or T-SQL to view the permissions that have been explicitly granted to a user on a securable. For example, Figure 3 shows the permissions granted to the user2 principal on the Sales.Customers table. In this case, the user has been granted the DELETE, INSERT, SELECT and UPDATE permissions, with no permissions explicitly denied.

Figure 3. Viewing a user’s permissions granted on a schema object

Configuring permissions for multiple principles on multiple securables can be a complex and sometimes frustrating process. If you don’t get it right, you could end up denying permissions to users who should have access to specific data or, worse still, granting access to users who should not. The safest bet is to follow the principles of least privilege, working at the most granular level practical for a given situation.

Additional Access Control Features

SQL Server also provides several other features for controlling access to data. For example, you can implement row-level security on a specific table by creating a security policy that calls one or more predicates. A security policy defines the structure necessary to apply row-level security to a table. A predicate is a table-value function that provides the logic necessary to determine which rows the security policy applies to.

A security policy supports two types of predicates: filter and block. A filter predicate filters the rows available to read operations, and a block predicate blocks write operations that violate the predicate. You can include both filter and block predicates within a security policy, and you can call the same or different predicate functions within that policy.

For example, the WideWorldImporters database includes the FilterCustomersBySalesTerritoryRole security policy, which defines both a filter predicate and block predicate. Figure 4 shows the security policy as it is listed in Object Explorer, along with the policy definition. In this case, both the filter predicate and block predicate call the DetermineCustomerAccess function, which determines which rows the current user can access.

Figure 4. Viewing a security policy definition in SSMS

Another SQL Server security feature is the application role, which is similar to the database role, except that it is used specifically to assign permissions to an application. However, unlike database roles, application roles do not contain members. In addition, they’re invoked only when an application connects to SQL Server and calls the sp_setapprole system stored procedure, passing in the name of the application role and password. SQL Server enforces the permissions granted to the application role for the duration of the connection.

Another access mechanism that SQL Server provides is the credential, a server-level object (record) that contains authentication information such as a username and password. The credential makes it possible for a SQL Server user to connect to a resource outside of the SQL Server environment. For example, you can use a credential to run an external assembly or to access domain resources if you’ve logged in using SQL Server Authentication.

SQL Server Data Encryption

Also important to SQL Server security are the encryption capabilities built into the database engine. Encryption provides a way to encode—or obfuscate—data so that only authorized users can view the data in an unencrypted state. To everyone else, the encrypted data looks like gibberish.

Encryption is not an access-control mechanism, that is, it does not prevent unauthorized users from accessing data. However, encryption can limit the exposure of sensitive data should unauthorized users manage to break through SQL Server’s access-control defenses. For example, if cybercriminals acquire encrypted credit card information from a database, they will not be able to make sense of that data unless they’ve also figured out a way to decrypt it.

SQL Server supports several approaches to encryption to accommodate different types of data and workloads. For example, you can encrypt data at the column level by taking advantage of SQL Server’s built-in encryption hierarchy and key management infrastructure. Under this model, each layer encrypts the layer below it, using a layered architecture made up of a public key certificate and several symmetric keys. In this way, the column data is always protected until it is specifically decrypted.

Another tool available to SQL Server is Transparent Data Encryption (TDE), which encrypts and decrypts both data and log files in real-time, working at the page level to ensure that data at-rest is protected. The database engine encrypts the pages before writing them to disk and decrypts them when reading the pages into memory. Unlike column-level encryption, an application does not have to take specific steps to decrypt the data. The entire process occurs behind the scenes.

SQL Server also supports the Always Encrypted feature, which makes it possible for a client application to handle the actual encryption operations, without the encryption keys being revealed to the database engine. However, to implement Always Encrypted, you must first generate the column encryption keys necessary to support Always Encrypted. To do so, you can use the Always Encrypted wizard in SSMS, as shown in Figure 5.

Figure 5. Running the Always Encrypted wizard

Once the columns have been encrypted, the data is ready for client access. However, for a client application to connect to encrypted data, it must incorporate a driver that is enabled for Always Encrypted and can handle the encryption and decryption operations.

Another useful SQL Server security feature is Dynamic Data Masking (DDM), a tool for masking all or part of data values. Although DDM doesn’t actually encrypt the data, it does limit the amount of exposed data to non-authorized users. For example, you can use DDM to mask all but the last four digits of a credit card number or national identifier such as a social security number.

SQL Server Tools

SQL Server includes a number of other tools to help protect data and limit risks. For example, you can use SQL Server Configuration Manager to configure startup or connection options, or use the sp_configure stored procedure to configure global SQL Server settings. SQL Server also provides the Surface Area Configuration facets for enabling or disabling features at the instance level, as shown in Figure 6.

Figure 6. Accessing the Surface Area Configuration facets for a SQL Server 2017 instance

You can use these tools to ensure that only those features essential to supporting your users and applications are enabled at any given time, helping to reduce the exposed surface area and consequently the level of risk.

SQL Server also provides tools for identifying potential database issues. For instance, SQL Server provides the TRUSTWORTHY property as one of its database properties. The property shows whether the current SQL Server instance can trust the database and its contents.

In addition, SSMS provides the Data Discovery & Classification feature for classifying, labeling, and reporting on potentially sensitive data in a database, as well as the SQL Vulnerability Assessment (SVA) tool for discovering, tracking, and addressing potential database vulnerabilities. Figure 7 shows the results of running an SVA assessment against the WideWorldImporters database in SQL Server 2017.

Figure 7. Viewing a SQL Vulnerability Assessment report

One of the most valuable SQL Server security tools is SQL Server Audit, which provides a structure for tracking and logging events that occur within the database engine. With SQL Server Audit, you can monitor events at the server level, database level, or both.

SQL Server Audit comprises three primary component types. The first is the audit object, which provides a structure for carrying out the auditing process. The audit object defines a target for the audited events. The target can be log files, the Application log, or the Security log. The audit object also includes configuration settings such as the number and size of the log files.

In addition to the audit object, an audit usually includes a server audit specification, a database audit specification for each applicable database, or a combination of any of these. The specifications determine which events should be audited at the server level or database level. For example, Figure 8 shows a database audit specification that audits UPDATE and DELETE events on the Sales.Customers table.

Figure 8. Viewing the audited actions defined in a database audit specification

In this case, both events are specific to the user1 database user. If the user tries to update or delete data in the Customers table, SQL Server Audit will log the event to the target repository.

Along with all these tools, SQL Server also provides a number of catalog views and dynamic management views for accessing security-related data. For example, you can retrieve details about the permissions granted and denied to a specific database user.

Protecting a SQL Server instance

In addition to taking steps within SQL Server to protect data, DBAs should also be certain to implement protections related to the SQL Server instance as a whole, such as disabling unused SQL Server components, applying security patches and service packs in a timely manner, and ensuring that database and backup files are fully protected and secure at all times.

But a protection strategy should not be limited only to SQL Server. The host operating system should also be kept up-to-date and properly patched, with just as much attention paid to surface area reduction.

In addition, DBAs and IT administrators must ensure that the host server is physically protected and that network safeguards such as firewalls and intrusion detection are in place. A SQL Server instance must be both physically and logically protected to achieve the maximum security.

Development teams must also ensure that the applications connecting to a SQL Server instance are properly vetted for security issues. A data-driven application is at risk for a number of attacks, including connection string injections, elevation of privileges, and SQL injections. The teams should factor in data security from the start, when first designing the application, not after it’s been implemented.

Securing SQL Server

SQL Server security is a huge topic, and what I’ve covered here barely skims that surface. You should view this article as only a starting point, meant to alert you to the many security considerations to take into account and the different SQL Server tools available for protecting data.

As this series progresses, I’ll dig deeper into the various security components, fleshing out what I’ve covered here and introducing you to concepts I’ve yet to explore. In the meantime, I recommend you learn as much about SQL Server security as possible, beginning with Microsoft’s own documentation.

The post Introduction to SQL Server Security — Part 1 appeared first on Simple Talk.



from Simple Talk http://bit.ly/2AmO9Fm
via

Getting Started with CQRS – Part 2

The series so far:

  1. Getting Started with CQRS – Part 1
  2. Getting Started with CQRS – Part 2

The first article of the series dove into the main concepts of CQRS along with the project configuration and setup. You learned how to create a basic CRUD-like application with ASP.NET and integrate it with a simple data source structure that relies on the Entity Framework and SQLite.

It’s important to notice, until here, that no CQRS concept was applied yet, since the whole implementation is about CRUD operations. This is intentional, for you to better understand how this pattern can apply in existing REST applications as well as web and even desktop applications that want to take advantage of it.

For the second part of the tutorial, you’ll finish the CQRS configurations by creating the MongoDB code, which is going to be responsible for the query side of the pattern. Also, you are going to create the commands that will operate over the creation and update of the data through normal relational database operations; finish the customer controller, which, in turn, will access the commands and queries to serve each appropriate endpoint; and, finally, set up the event-driven architecture with RabbitMQ for the publishing and subscribing of all the events the application has to deal with.

Creating the Query Side

Start by creating the MongoDB configurations, necessary for the Query side of the CQRS model. Open the CustomerAPI application in Visual you created in the first article and open your Startup.cs class. (You can find the code for this article here.) Add another transient repository setting, right below the SQLite one:

services.AddTransient<CustomerMongoRepository>();

Don’t forget the proper using statement at the beginning of the file:

using CustomerApi.Models.Mongo;

Add a new folder to the project: \Models\Mongo. Create a new class, CustomerMongoRepository in the new folder. This new class will accommodate the same CRUD operations you’ve created in the SQLite repository. However, using the specific configurations provided by the previously imported Mongo driver library. Replace the code:

using System.Collections.Generic;
using MongoDB.Driver;
namespace CustomerApi.Models.Mongo
{
    public class CustomerMongoRepository
        {
                private const string _customerDB = "CustomerDB";
                private const string _customerCollection = "Customers";
                private IMongoDatabase _db;
                public CustomerMongoRepository()
                {
                        MongoClient _client = new MongoClient("mongodb://localhost:27017");
                        _db = _client.GetDatabase(_customerDB);
                }
                public List<CustomerEntity> GetCustomers()
                {
                        return _db.GetCollection<CustomerEntity>(_customerCollection).Find(_ => true).ToList();
                }
                public CustomerEntity GetCustomer(long id)
                {
                        return _db.GetCollection<CustomerEntity>(_customerCollection).Find(customer => customer.Id == id).SingleOrDefault();
                }
                public CustomerEntity GetCustomerByEmail(string email)
                {
                        return _db.GetCollection<CustomerEntity>(_customerCollection).Find(customer => customer.Email == email).Single();
                }
                public void Create(CustomerEntity customer)
                {
                        _db.GetCollection<CustomerEntity>(_customerCollection).InsertOne(customer);
                }
                public void Update(CustomerEntity customer)
                {
                        var filter = Builders<CustomerEntity>.Filter.Where(_ => _.Id == customer.Id);
                        _db.GetCollection<CustomerEntity>(_customerCollection).ReplaceOne(filter, customer);
                }
                public void Remove(long id)
                {
                        var filter = Builders<CustomerEntity>.Filter.Where(_ => _.Id == id);
                        var operation = _db.GetCollection<CustomerEntity>(_customerCollection).DeleteOne(filter);
                }
        }
}

Notice that, this time, you have more operations for retrieving/searching elements from the database than in the SQLite repository. It happens because, as the Query side of the model, some flexibilities like searching by the id or email must exist in order to accommodate the different types of searches the client may perform.

The other operations will help with tests, like creating, updating and removing items from the database for checking purposes.

Also, it’s important to attain to the name of the database and the collection (_customerDB and _customerCollection, respectively). They must be exactly the same as the ones you created before at MongoDB Compass in the previous article. Thanks to the lambda functionalities .NET provides, you can pass summarized functions as arguments to most of the methods of MongoDB database.

Next, it’s time to create the Mongo entities, mapping exactly the same values to expose to the clients, in response to the values saved in the SQLite entities. Inside the \Mongo folder, create a new class called CustomerEntity.cs and add the following code:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;
namespace CustomerApi.Models.Mongo
{
        public class CustomerEntity
    {
                [BsonElement("Id")]
                public long Id { get; set; }
                [BsonElement("Email")]
                public string Email { get; set; }
                [BsonElement("Name")]
                public string Name { get; set; }
                [BsonElement("Age")]
                public int Age { get; set; }
                [BsonElement("Phones")]
                public List<PhoneEntity> Phones { get; set; }
        }
}

The class is basically composed of the same properties found in the corresponding SQLite code. The annotation BsonElement is provided by the MongoDB library and specifies the element name of each field of the entity. This is important, because this is how Mongo will identify each field when saving the document-based values to the database through a key-value system. Add another class to folder, PhoneEntity.

Here is the code for PhoneEntity.cs:

using MongoDB.Bson.Serialization.Attributes;
namespace CustomerApi.Models.Mongo
{
        public partial class PhoneEntity
    {
                [BsonElement("Type")]
                public PhoneType Type { get; set; }
                [BsonElement("AreaCode")]
                public int AreaCode { get; set; }
                [BsonElement("Number")]
                public int Number { get; set; }
        }
}

Both SQLite and MongoDB use the same PhoneType.cs class from the previous article. Make sure that it is in the \Models folder.

Setting up the Event Handler

In order for RabbitMQ to work in an ASP.NET project, besides having a proper RabbitMQ client dependency configured on the project, it’s also necessary to register the publisher and the subscriber beans in the Startup.cs class (ConfigureServices() method):

services.AddTransient<AMQPEventPublisher>();
services.AddSingleton<CustomerMessageListener>();

Don’t forget to import the proper using statements at the beginning of the class.

using CustomerApi.Models.Mongo;

Start with the publisher by creating a new \Events folder on the root folder. Then, create a class called AMQPEventPublisher.cs and add the following code:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using RabbitMQ.Client;
using System.Text;
namespace CustomerApi.Events
{
        public class AMQPEventPublisher
    {
                private readonly ConnectionFactory connectionFactory;
                public AMQPEventPublisher(IHostingEnvironment env)
                {
                        connectionFactory = new ConnectionFactory();
                        var builder = new ConfigurationBuilder()
                                .SetBasePath(env.ContentRootPath)
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                .AddEnvironmentVariables();
                        
                        builder.Build().GetSection("amqp").Bind(connectionFactory);
                }
                public void PublishEvent<T>(T @event) where T : IEvent
                {
                        using (IConnection conn = connectionFactory.CreateConnection())
                        {
                                using (IModel channel = conn.CreateModel())
                                {
                                        var queue = @event is CustomerCreatedEvent ? 
                                                Constants.QUEUE_CUSTOMER_CREATED : @event is CustomerUpdatedEvent ? 
                                                        Constants.QUEUE_CUSTOMER_UPDATED : Constants.QUEUE_CUSTOMER_DELETED;
                                        channel.QueueDeclare(
                                                queue: queue,
                                                durable: false,
                                                exclusive: false,
                                                autoDelete: false,
                                                arguments: null
                                        );
                                        var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@event));
                                        channel.BasicPublish(
                                                exchange: "",
                                                routingKey: queue,
                                                basicProperties: null,
                                                body: body
                                        );
                                }
                        }
                }
        }
}

A few important points to notice here include the ConnectionFactory object. It is part of RabbitMQ Client library and responsible for creating and managing the connections, models and channels to publish the events. The ConfigurationBuilder helps with importing the proper configurations from the appsettings.json file (see its code below). And, finally, the PublishEvent() method was built upon a generic implementation; in other words, the generic T tells this method to expect any type of object to be published, which makes it also reusable for other more abstract constructions you may want.

Once the connection is opened, and the model is created, you can declare the queue, its configs, and perform a basic publish through the BasicPublish method of the model. Notice that three types of events will be published: when a customer is created, updated or deleted. Don’t worry about the compilation errors for now, you’ll soon create those classes as well.

Add the Constants class to the \Events folder:

namespace CustomerApi.Events
{
        public class Constants
    {
                public const string QUEUE_CUSTOMER_CREATED = "customer_created";
                public const string QUEUE_CUSTOMER_UPDATED = "customer_updated";
                public const string QUEUE_CUSTOMER_DELETED = "customer_deleted";
        }
}

The generic T you’ve seen before is also inheriting from an interface called IEvent. It helps to identify what is an event only in the project. Add the IEvent class. The following code represents it (yes, just a marking interface):

namespace CustomerApi.Events
{
        public interface IEvent
    {
    }
}

Now, create the events themselves starting with the CustomerCreatedEvent. The structure is very similar to the entities you created before, mainly because no big changes will be made to avoid adding complexity:

using CustomerApi.Models.Mongo;
using System.Collections.Generic;
using System.Linq;
namespace CustomerApi.Events
{
        public class CustomerCreatedEvent : IEvent
        {
                public long Id { get; set; }
                public string Email { get; set; }
                public string Name { get; set; }
                public int Age { get; set; }
                public List<PhoneCreatedEvent> Phones { get; set; }
                public CustomerEntity ToCustomerEntity()
                {
                        return new CustomerEntity
                        {
                                Id = this.Id,
                                Email = this.Email,
                                Name = this.Name,
                                Age = this.Age,
                                Phones = this.Phones.Select(phone => new PhoneEntity {
                                        Type = phone.Type,
                                        AreaCode = phone.AreaCode,
                                        Number = phone.Number
                                }).ToList()
                        };
                }
        }
}

NOTE: Architecturally, it’s common to give event class names of a past nature, meaning that the event has already happened and you’re dealing with something in the past.

Notice that a method to convert each event to an entity will be useful since they mostly must be persisted after being received and processed (Linq will be used as a good option to iterate and perform operations over the lists of your event models).

The phone created event class (it can be just a single value object if you desire):

using CustomerApi.Models;
namespace CustomerApi.Events
{
        public class PhoneCreatedEvent : IEvent
        {
                public PhoneType Type { get; set; }
                public int AreaCode { get; set; }
                public int Number { get; set; }
        }
}

Next, the updated event class:

using CustomerApi.Models.Mongo;
using System.Collections.Generic;
using System.Linq;
namespace CustomerApi.Events
{
        public class CustomerUpdatedEvent : IEvent
        {
                public long Id { get; set; }
                public string Name { get; set; }
                public int Age { get; set; }
                public List<PhoneCreatedEvent> Phones { get; set; }
                public CustomerEntity ToCustomerEntity(CustomerEntity entity)
                {
                        return new CustomerEntity
                        {
                                Id = this.Id,
                                Email = entity.Email,
                                Name = entity.Name.Equals(this.Name) ? entity.Name : this.Name,
                                Age = entity.Age.Equals(this.Age) ? entity.Age : this.Age,
                                Phones = GetNewOnes(entity.Phones).Select(phone => new PhoneEntity { AreaCode = phone.AreaCode, Number = phone.Number }).ToList()
                        };
                }
                private List<PhoneEntity> GetNewOnes(List<PhoneEntity> Phones)
                {
                        return Phones.Where(a => !this.Phones.Any(x => x.Type == a.Type
                                && x.AreaCode == a.AreaCode
                                && x.Number == a.Number)).ToList<PhoneEntity>();
                }
        }
}

This class has a structure similar to that of the previous one, except for a bolder approach to deal with the phones updating. You’ll only update phones that had, in fact, suffered any change whether it was in the area code or the number. So, for the update in the database, they’ll be overwritten every time. Plus, don’t forget to always check if each attribute inside the event had really changed compared to the received entity object.

The deleted event class:

namespace CustomerApi.Events
{
        public class CustomerDeletedEvent : IEvent
        {
                public long Id { get; set; }
        }
}

The only thing that’s needed to delete an object to the database is the customer id.

Be aware that, in real world applications, it’s against the event-storing patterns to update/delete data in any situation. Events must be preserved in their original precedence as much as possible, to simulate exactly what happened. Here, the implementation tries to go, initially, through the old-fashion design most applications used to be built.

And finally, create the consumer class, CustomerMessageListener, responsible for listening to the events and processing them:

using CustomerApi.Models.Mongo;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.MessagePatterns;
using System;
using System.Text;
using System.Threading;
namespace CustomerApi.Events
{
        public class CustomerMessageListener
        {
                private readonly CustomerMongoRepository _repository;
                public CustomerMessageListener(CustomerMongoRepository repository)
                {
                        _repository = repository;
                }
                public void Start(string contentRootPath)
                {
                        ConnectionFactory connectionFactory = new ConnectionFactory();
                        var builder = new ConfigurationBuilder()
                                .SetBasePath(contentRootPath)
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                .AddEnvironmentVariables();
                        builder.Build().GetSection("amqp").Bind(connectionFactory);
                        connectionFactory.AutomaticRecoveryEnabled = true;
                        connectionFactory.NetworkRecoveryInterval = TimeSpan.FromSeconds(15);
                        using (IConnection conn = connectionFactory.CreateConnection())
                        {
                                using (IModel channel = conn.CreateModel())
                                {
                                        DeclareQueues(channel);
                                        var subscriptionCreated = new Subscription(channel, Constants.QUEUE_CUSTOMER_CREATED, false);
                                        var subscriptionUpdated = new Subscription(channel, Constants.QUEUE_CUSTOMER_UPDATED, false);
                                        var subscriptionDeleted = new Subscription(channel, Constants.QUEUE_CUSTOMER_DELETED, false);
                                        while (true)
                                        {
                        // Sleeps for 5 sec before trying again
                                                Thread.Sleep(5000);
                                                new Thread(() =>
                                                {
                                                        ListerCreated(subscriptionCreated);
                                                }).Start();
                                                new Thread(() =>
                                                {
                                                        ListenUpdated(subscriptionUpdated);
                                                }).Start();
                                                new Thread(() =>
                                                {
                                                        ListenDeleted(subscriptionDeleted);
                                                }).Start();
                                        }
                                }
                        }
                }
                private void ListenDeleted(Subscription subscriptionDeleted)
                {
                        BasicDeliverEventArgs eventArgsDeleted = subscriptionDeleted.Next();
                        if (eventArgsDeleted != null)
                        {
                                string messageContent = Encoding.UTF8.GetString(eventArgsDeleted.Body);
                                CustomerDeletedEvent _deleted = JsonConvert.DeserializeObject<CustomerDeletedEvent>(messageContent);
                                _repository.Remove(_deleted.Id);
                subscriptionDeleted.Ack(eventArgsDeleted);
                        }
                }
                private void ListenUpdated(Subscription subscriptionUpdated)
                {
                        BasicDeliverEventArgs eventArgsUpdated = subscriptionUpdated.Next();
                        if (eventArgsUpdated != null)
                        {
                                string messageContent = Encoding.UTF8.GetString(eventArgsUpdated.Body);
                                CustomerUpdatedEvent _updated = JsonConvert.DeserializeObject<CustomerUpdatedEvent>(messageContent);
                                _repository.Update(_updated.ToCustomerEntity(_repository.GetCustomer(_updated.Id)));
                subscriptionUpdated.Ack(eventArgsUpdated);
                        }
                }
                private void ListerCreated(Subscription subscriptionCreated)
                {
                        BasicDeliverEventArgs eventArgsCreated = subscriptionCreated.Next();
                        if (eventArgsCreated != null)
                        {
                                string messageContent = Encoding.UTF8.GetString(eventArgsCreated.Body);
                                CustomerCreatedEvent _created = JsonConvert.DeserializeObject<CustomerCreatedEvent>(messageContent);
                                _repository.Create(_created.ToCustomerEntity());
                                subscriptionCreated.Ack(eventArgsCreated);
                        }
                }
                private static void DeclareQueues(IModel channel)
                {
                        channel.QueueDeclare(
                                queue: Constants.QUEUE_CUSTOMER_CREATED,
                                durable: false,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null
                        );
                        channel.QueueDeclare(
                                queue: Constants.QUEUE_CUSTOMER_UPDATED,
                                durable: false,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null
                        );
                        channel.QueueDeclare(
                                queue: Constants.QUEUE_CUSTOMER_DELETED,
                                durable: false,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null
                        );
                }
        }
}

Please, keep in mind that for most real CQRS applications, the event subscriber objects/components are usually built out of the publisher application for resiliency purposes. Here, they’ll be together just for simplification.

The class starts with the same RabbitMQ connection factory configs, connections and models. However, two new configs are used:

  • AutomaticRecoveryEnabled: its value is already true, but you’ll use it here to enforce the setup of the auto recovery feature, that instructs RabbitMQ to retry the current connection once it is lost or dealing with connectivity issues;
  • NetworkRecoveryInterval: defines the time it will wait to retry the connection when facing network issues.

There are several approaches, including external frameworks, to consume events from a queue in RabbitMQ. The focus is on simplicity, so basically the queues are going to be declared (just in case they don’t exist yet in RabbitMQ server, so they’ll be automatically created), along with subscription objects.

Subscription objects control a model channel over a specific queue, as well as the acknowledge mode the delivery will be made with. In the example, each queue has its own subscription object set with autoAck mode to false, so you’re the one who must manually acknowledge the channel once the event consuming is done.

Then, an infinite loop will happen (with 5 seconds of delay from one iteration to another) opening three different threads, one for each event type can be received over the subscription objects. The reason for the loop is because new events can arrive at any moment, so you have to guarantee they will be consumed. And the threads are just to make sure no event will delay or alter the state of the others.

In the end, the only action to be performed will be the respective operation in the repository object.

Setting up the Commands

The Command pattern is well known to every OO developer, mainly because it helps to construct structures to process separately objects that act in similar ways. In this case, start with the abstract class that’ll represent it. Create a new folder \Commands and add the Command class.

namespace CustomerApi.Commands
{
    public abstract class Command
        {
                public long Id { get; set; }
        }
}

The Id will be useful since it is used everywhere to identify a customer. Then, the customer created command object, CreateCustomerCommand class, that’ll support the data transit:

using CustomerApi.Events;
using CustomerApi.Models.SQLite;
using System.Collections.Generic;
using System.Linq;
namespace CustomerApi.Commands
{
        public class CreateCustomerCommand : Command
        {
                public string Name { get; set; }
                public string Email { get; set; }
                public int Age { get; set; }
                public List<CreatePhoneCommand> Phones { get; set; }
                public CustomerCreatedEvent ToCustomerEvent(long id)
                {
                        return new CustomerCreatedEvent
                        {
                                Id = id,
                                Name = this.Name,
                                Email = this.Email,
                                Age = this.Age,
                                Phones = this.Phones.Select(phone => new PhoneCreatedEvent { AreaCode = phone.AreaCode, Number = phone.Number }).ToList()
                        };
                }
                public CustomerRecord ToCustomerRecord()
                {
                        return new CustomerRecord
                        {
                                Name = this.Name,
                                Email = this.Email,
                                Age = this.Age,
                                Phones = this.Phones.Select(phone => new PhoneRecord { AreaCode = phone.AreaCode, Number = phone.Number }).ToList()
                        };
                }
        }
}

They are very similar to the event objects regarding the attributes but carry auxiliary methods to construct SQLite records and event objects, translating from one type of model schema to another.

Notice that, here, you’re using a second command for phone data, CreatePhoneCommand. Create the class and add the following code:

using CustomerApi.Models;
namespace CustomerApi.Commands
{
        public class CreatePhoneCommand : Command
        {
                public PhoneType Type { get; set; }
                public int AreaCode { get; set; }
                public int Number { get; set; }
        }
}

See the code for the updated and deleted commands, as well:

using CustomerApi.Events;
using CustomerApi.Models.SQLite;
using System.Collections.Generic;
using System.Linq;
namespace CustomerApi.Commands
{
        public class UpdateCustomerCommand : Command
        {
                public string Name { get; set; }
                public int Age { get; set; }
                public List<CreatePhoneCommand> Phones { get; set; }
                public CustomerUpdatedEvent ToCustomerEvent()
                {
                        return new CustomerUpdatedEvent
                        {
                                Id = this.Id,
                                Name = this.Name,
                                Age = this.Age,
                                Phones = this.Phones.Select(phone => new PhoneCreatedEvent {
                                        Type = phone.Type,
                                        AreaCode = phone.AreaCode,
                                        Number = phone.Number
                                }).ToList()
                        };
                }
                public CustomerRecord ToCustomerRecord(CustomerRecord record)
                {
                        record.Name = this.Name;
                        record.Age = this.Age;
                        record.Phones = this.Phones.Select(phone => new PhoneRecord
                                {
                                        Type = phone.Type,
                                        AreaCode = phone.AreaCode,
                                        Number = phone.Number
                                }).ToList()
                                ;
                        return record;
                }
        }
}

For the deleted one, remember that only the id is important to be passed on:

using CustomerApi.Events;
namespace CustomerApi.Commands
{
        public class DeleteCustomerCommand : Command
        {
                internal CustomerDeletedEvent ToCustomerEvent()
                {
                        return new CustomerDeletedEvent
                        {
                                Id = this.Id
                        };
                }
        }
}

All the command objects need a handler object, that will take care of receiving and distributing the operations through the different service/repository layers. Start with the command handler interface code:

namespace CustomerApi.Commands
{
        public interface ICommandHandler<T> where T : Command
        {
                void Execute(T command);
        }
}

The method Execute() receives the specific command represented by its interface declaration and calls the proper operations for each one. See the following code for the implementation:

using CustomerApi.Events;
using CustomerApi.Models.SQLite;
using System;
namespace CustomerApi.Commands
{
        public class CustomerCommandHandler : ICommandHandler<Command>
        {
                private CustomerSQLiteRepository _repository;
                private AMQPEventPublisher _eventPublisher;
                public CustomerCommandHandler(AMQPEventPublisher eventPublisher, CustomerSQLiteRepository repository)
                {
                        _eventPublisher = eventPublisher;
                        _repository = repository;
                }
                public void Execute(Command command)
                {
                        if (command == null)
                        {
                                throw new ArgumentNullException("command is null");
                        }
                        if (command is CreateCustomerCommand createCommand)
                        {
                                CustomerRecord created = _repository.Create(createCommand.ToCustomerRecord());
                                _eventPublisher.PublishEvent(createCommand.ToCustomerEvent(created.Id));
                        }
                        else if (command is UpdateCustomerCommand updateCommand)
                        {
                                CustomerRecord record = _repository.GetById(updateCommand.Id);
                                _repository.Update(updateCommand.ToCustomerRecord(record));
                                _eventPublisher.PublishEvent(updateCommand.ToCustomerEvent());
                        }
                        else if (command is DeleteCustomerCommand deleteCommand)
                        {
                                _repository.Remove(deleteCommand.Id);
                                _eventPublisher.PublishEvent(deleteCommand.ToCustomerEvent());
                        }
                }
        }
}

Here, roughly, you can already see the command running the code that’ll deal with relational database operations, and its segregation from the event publishing, always at the end of each command processing.

Finally, you need to add the handler as a scoped service. So, open the Startup.cs file again and add the following using command to the beginning of the file and AddScope() operation to the ConfigureServices() method:

using CustomerApi.Commands;
// …
services.AddScoped<ICommandHandler<Command>, CustomerCommandHandler>();

Testing the New Controller

To make sure the new structures are fully working together, change the current customer controller to support the new commands, along with the proper REST results. This is the final CustomersController class:

using CustomerApi.Commands;
using CustomerApi.Models;
using CustomerApi.Models.Mongo;
using CustomerApi.Models.SQLite;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace CustomerApi.Controllers
{
    [Route("api/[controller]")]
    public class CustomersController : Controller
    {
        private readonly ICommandHandler<Command> _commandHandler;
        private readonly CustomerMongoRepository _mongoRepository;
        private readonly CustomerSQLiteRepository _sqliteRepository;
        public CustomersController(ICommandHandler<Command> commandHandler,
            CustomerSQLiteRepository sqliteRepository,
            CustomerMongoRepository repository)
        {
            _commandHandler = commandHandler;
            _sqliteRepository = sqliteRepository;
            _mongoRepository = repository;
            if (_mongoRepository.GetCustomers().Count == 0)
            {
                var customerCmd = new CreateCustomerCommand
                {
                    Name = "George Michaels",
                    Email = "george@email.com",
                    Age = 23,
                    Phones = new List<CreatePhoneCommand>
                    {
                        new CreatePhoneCommand { Type = PhoneType.CELLPHONE, AreaCode = 123, Number = 7543010 }
                    }
                };
                _commandHandler.Execute(customerCmd);
            }
        }
        [HttpGet]
        public List<CustomerEntity> Get()
        {
            return _mongoRepository.GetCustomers();
        }
        [HttpGet("{id}", Name = "GetCustomer")]
        public IActionResult GetById(long id)
        {
            var product = _mongoRepository.GetCustomer(id);
            if (product == null)
            {
                return NotFound();
            }
            return new ObjectResult(product);
        }
        [HttpGet("{email}")]
        public IActionResult GetByEmail(string email)
        {
            var product = _mongoRepository.GetCustomerByEmail(email);
            if (product == null)
            {
                return NotFound();
            }
            return new ObjectResult(product);
        }
        [HttpPost]
        public IActionResult Post([FromBody] CreateCustomerCommand customer)
        {
            _commandHandler.Execute(customer);
            return CreatedAtRoute("GetCustomer", new { id = customer.Id }, customer);
        }
        [HttpPut("{id}")]
        public IActionResult Put(long id, [FromBody] UpdateCustomerCommand customer)
        {
            var record = _sqliteRepository.GetById(id);
            if (record == null)
            {
                return NotFound();
            }
            customer.Id = id;
            _commandHandler.Execute(customer);
            return NoContent();
        }
        [HttpDelete("{id}")]
        public IActionResult Delete(long id)
        {
            var record = _sqliteRepository.GetById(id);
            if (record == null)
            {
                return NotFound();
            }
            _commandHandler.Execute(new DeleteCustomerCommand()
            {
                Id = id
            });
            return NoContent();
        }
    }
}

Basically, what changed is that the commands are now being handled by the REST automatic conversions and a new customer is being added once the constructor of the class runs, to make sure you’ll have some data in the database as soon as the application starts.

Before you run the application, make sure everything is up and running (the MongoDB and RabbitMQ servers) and, once Visual Studio finishes the starting up, you’d have the data stored in the SQLite database (just like you can see in Figure 1).

Figure 1. SQLite data after app started up.

Then, after persisting to the SQLite database, the customer_created event will be published. The RabbitMQ queue will receive the event (Figure 2), prepare a consumer to deliver it directly to the message listener.

Figure 2. RabbitMQ event consuming.

And finally, when the event is received at the listener, process the MongoDB data persisting, to guarantee the data is safe there, all in an asynchronous way.

Figure 3. MongoDB data after event being consumed.

Conclusion

It is now time to go and create more tests. Make sure to try each of your REST API operations with Postman (like the POST to create a new customer), checking to make sure each customer was stored in the SQLite database and, then, posted to RabbitMQ and, subsequently, to the MongoDB database asynchronously.

Some other structures of the architecture could be improved as well. If the application itself (or one of the nodes it is hosted when in a clustered environment) crashes in the very right moment the event would be published. For this, a couple of options are available such as considering a bigger transactional design that thinks of the processing as a whole that’s complete only when everything important is done. Or you could pick up a different messaging tool that guarantees, with more consistency, the delivery of the events (like Apache Kafka, for example, a very popular player at the moment). Just be sure to play with different scenarios, considering that they can happen in the real world.

The next part of this series will explore a totally new architecture considering the paradigm of Event Sourcing and Processing to map the events the application receives, reduce them when necessary, and make the application more scalable.

The post Getting Started with CQRS – Part 2 appeared first on Simple Talk.



from Simple Talk http://bit.ly/2EVCGQQ
via