Saturday, August 17, 2019

Working with React Components

React is a library gaining traction in the enterprise. For large solutions, it is good to have a set of reusable components. Often, back-end APIs written in C# can feed data to a front-end UI. This is where React comes in; it is the UI layer that presents the information to the user. The React library then renders markup using React components. React shops can reuse components to maintain consistent branding across a large suite. This reduces code duplication and increases team velocity. In this take, I’ll delve into working with React components and what it means for .NET developers.

React can live outside Visual Studio. For React development, Visual Studio Code or WebStorm are recommended. The canonical way to begin is through Create React App. Be sure to have Node 8.1+ and NPM 5.6+ installed before working with React.

To fire up a React app:

npx create-react-app work-with-react-app

The contents of the new project will be under the work-with-react-app folder. You can test this new project by running npm start in the project folder.

Think of a React component as an abstraction layer. A component encapsulates HTML/CSS/JavaScript in a single module. This makes it easier to conceptualize a complex UI into many components. This enables plug-and-play of many components to gain rich functionality.

The React library prefers component composition over inheritance. Components are often in a hierarchy of components. To use a baseball analogy, a player has a bat, or a glove, or both. In this analogy, think of the player as a parent component that has many children. For example, a player component might hit, and/or catch a ball. This is how React components unlock functionality through a relational hierarchy. The parent component gains functionality simply by increasing its children. Composition has a lot of flexibility, which improves code reusability.

Each React component has its own lifecycle. The component wraps around methods useful for managing state and the component state tells React when it’s time to make updates. The library then finds an optimal way to update the tree hierarchy to reduce repaints. Each lifecycle method can control how updates might occur in the component. To see how React components maintain state, it is essential to understand this lifecycle.

The component lifecycle is broken up into these four phases:

  • Mounting
  • Updating
  • Unmounting
  • Error Handling

With each phase, the component fires a set of lifecycle methods. Error handling only happens when there’s an exception. React treats error handling as a separate and independent phase. Error handling must exclude any logic that belongs in any other phase.

To help visualize the component lifecycle, take a look at this diagram:

To explore each phase, I’ll create a news ticker component. The ticker will update its breaking news every two seconds and show only one headline at a time. To exploit each lifecycle, I’ll freeze, reset, unmount, and throw an error in the component.

Start small by declaring a React component. This can go in a separate file inside the Create React App project. (You can find the completed code for the project here.)

import React from 'react';

class NewsTicker extends React.Component {
}

Mounting

Mounting occurs when the component is created and inserted into the tree hierarchy. This lifecycle executes these methods in the following order:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

React components have the following method signature in the constructor:

constructor(props)

If the constructor does not initialize state, then the component does not need this. The constructor is called before the component is mounted. For this reason, avoid calling this.setState() but initialize this.state directly. Avoid any side-effects in the constructor that mutate state. Because components subclass React.Component, be sure to call super(props) before any other statement. Else, this.props will be undefined in the constructor which can be problematic.

For the news ticker, put in place a constructor that initializes state. The state will begin with an empty news list and initial index:

constructor(props) {
  super(props);

  this.state = {
    news: [],
    tickerIndex: 0
  };

  this.timer = 0;
}

I’ll skip getDerivedStateFromProps() for now since it is unlikely to be useful during the mounting phase. I’ll come back to this lifecycle method during component updates.

React components have the following method signature when it renders:

render()

This is the only method that is required in a React component. The render() method is pure, meaning it should not mutate component state. Instead, it should use this.props or this.state to render the component. This keeps the component predictable and easier to think about. The render method can return React elements, typically via JSX. For example, <div /> or <NewsTicker />. It can return a string or a number which gets rendered as simple text. Returning a Boolean or null renders nothing because this can unmount components from the hierarchy.

The news ticker will render a list with a single item based on the index:

render() {
  return (
    <ul>
      <li>
        {this.state.news[this.state.tickerIndex % this.state.news.length]}
      </li>
    </ul>
  );
}

The modulus operator allows the news item to iterate as the index increases.

After the component mounts, it calls the following lifecycle method:

componentDidMount()

This is called immediately after the component is inserted into the tree hierarchy. Mutating component state after the initial render goes here. For example, when initiating network requests to fetch back-end data. This method can set and initialize timer intervals. When setting an interval, be sure to clear it in the unmounting phase. Calling this.setState() will trigger another render which goes through the update phase. When using this pattern, be careful as this can cause performance issues. One alternative is to set the initial state through the constructor instead.

The news ticker will grab the latest breaking news with a fetch request. Then, mutate state with the latest data and set up an interval. The interval will update the ticker index as it iterates through each news item.

For example:

async componentDidMount() {
  const payload = await fetch('/news.json');
  const data = await payload.json();

  this.setState({news: data});

  this.timer = setInterval(() => this.setState(
    {tickerIndex: this.state.tickerIndex + 1}), 2000);
}

The interval is set to update the news item every two seconds. Using async/await makes awkward async code more readable. This method returns a void type, but it can also return Promise<void>. Prefixing this method with async makes this return a promise that returns void.

This wraps up the mounting phase. So, what happens when the component mutates state through this.setState()?

Updating

An update occurs when there are changes to the component’s props or state. This re-render lifecycle executes these methods in the following order:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapShotBeforeUpdate()
  • componentDidUpdate()

React components spend the bulk of their time updating and re-rendering components. This is what makes the components come alive as state mutates through the tree hierarchy.

The getDerivedStateFromProps() lifecycle method has the following signature:

static getDerivedStateFromProps(props, state)

This is called before the render method, both during mounting and updating phases. It returns an object that mutates state or null to change nothing. This method is unlikely to be useful for most use cases. Deriving state from parent components leads to tight coupling, which is hard to understand. A single state change might ripple unpredictable behavior down the component hierarchy. Be sure to look at other alternatives first before going down this path. For example, mutating state can go in componentDidUpdate(). Or, better yet, wrap the component around a state machine like Redux. This method does not have access to the component instance, so it has no side-effects. Extracting pure functions from this method leads to reusable code that can live outside the component. A cleaner way is to abstract state management and unify the tree hierarchy from a single store. This is one problem a library like Redux, for example, attempts to solve.

For the news ticker, reset the component by setting the index back to its initial state. This illustrates how a parent component can alter state with this method.

For example, say there’s a prop to reset state in the component:

static getDerivedStateFromProps(props, state) {
  const {reset} = props;

  if (reset) {
    return {...state, tickerIndex: 0};
  }

  return null;
}

The ES6 spread, for example, …state, sets current values because all I want is to reset the index. Any existing property gets overridden by what’s on the right in the new object. This method is prefixed with static, which means it does not have access to the instance.

The ShouldComponentUpdate() lifecycle method has the following signature:

shouldComponentUpdate(nextProps, nextState)

This is an optimization method to see if the component is affected by the current change in state and props. This method defaults to true and runs right before rendering. For most use cases, it is good enough to rely on the default behavior. Keep in mind preventing rendering can lead to subtle bugs. Consider using a pure component, not a stateless component, for optimization. Pure components do a shallow comparison of props and state to reduce the risk of skipping updates. To create a pure component, subclass React.PureComponent. A stateless component does not subclass any component class. For example, HelloComponent = ({name}) => <p>Hello {name}<p/>. This does not have any lifecycle methods useful for optimization. Avoid deep comparisons with JSON.stringify() because it is inefficient.

Here a freeze prop determines if the news ticker should update:

shouldComponentUpdate(nextProps, nextState) {
  const {freeze} = nextProps;

  if (freeze) {
    console.log('Ticker frozen at: ' +
      nextState.news[nextState.tickerIndex % nextState.news.length]);
    return false;
  }

  return true;
}

The ES6 destructuring assignment is used to grab the freeze prop variable. Then, log nextState.news and block re-render.

The render method executes as it did during the mounting phase. I’ll move on to the next method lifecycle so as not to repeat myself.

The getSnapshotBeforeUpdate() lifecycle method has the following signature:

getSnapshotBeforeUpdate(prevProps, prevState)

This method is called right before the most recent rendered output is committed. This enables the component to snapshot existing information before any changes. Any return value from this method will go as a parameter to componentDidUpdate(). The use case is rare; the one benefit is gaining access to the raw output. For example, capturing what the DOM has before committing changes. React components do a good job at abstracting away the raw DOM. Striping away useful abstractions can be an anti-pattern.

For the news ticker, say I want to grab a snapshot of the current news item. I only want to capture this information when the news list changes after the initial load.

For example:

getSnapshotBeforeUpdate(prevProps, prevState) {
  if (prevState.news.length > 0
    && prevState.news.length !== this.state.news.length) {
    return this.newsRef.current.textContent;
  }

  return null;
}

This needs refs which gains access to the DOM. To make this work, this needs to be set in the constructor():

this.newsRef = React.createRef();

Then, set which DOM element this has access to in render():

<li ref={this.newsRef}>
  …
</li>

The snapshot itself can be of any type. I’m returning a simple string with raw text content.

The last lifecycle method during update has the following signature:

componentDidUpdate(prevProps, prevState, snapshot)

This method is called after all updates are committed. Mutating state here must be wrapped in a condition, else, run the risk of an infinite loop. Keep in mind calling this.setState() causes re-rending which can affect performance. The snapshot parameter comes from the previous lifecycle method. This is the method where the snapshot might be useful for mutating state.

With this lifecycle method, you can check for any news updates from the back-end data. If so, call this.setState() with the latest breaking news. To avoid too many network requests delay this by a factor of two. This method only mutates state when it detects actual changes. To keep it performant, it’s only checking for differences in news length. Also, if there’s a snapshot available then go ahead and log it in the console.

Here’s the method:

async componentDidUpdate(prevProps, prevState, snapshot) {
  if (this.state.tickerIndex % 2 === 0 // delay network calls
    && prevState.news.length === this.state.news.length) {
    const payload = await fetch('/news.json');
    const data = await payload.json();

    if (data.length !== this.state.news.length) {
      console.log('Breaking news update detected.');
      this.setState({news: data});
    }
  }

  if (snapshot !== null) {
    console.log('DOM snapshot before update: ' + snapshot);
  }
}

A modulus delays network calls by a factor of two. Then, it’s checking if both previous and current state are the same to further optimize calls. There is no need to check anything right after a breaking news update.

Unmounting

The unmount lifecycle method has the following signature:

componentWillUnmount()

This is called right before a component is removed from the tree hierarchy and destroyed. Do any necessary cleanup, such as cleaning up intervals created in componentDidMount(). Avoid calling this.setState() because the component will never re-render. In React components, re-mounts are not allowed.

For the news ticker, all I care about is clearing the timer interval. To do this place a log in the console to note an unmount and clear the interval:

componentWillUnmount() {
  console.log('Unmount component.');
  clearInterval(this.timer);
}

Error Handling

React components catch JavaScript errors using error boundaries. This catches errors during render or any other lifecycle method. Because it is a boundary, it can only handle errors in the tree below them. Also, one gotcha is it doesn’t catch asynchronous errors, only synchronous errors.

An error boundary has the following lifecycle methods:

  • static getDerivedStateFromError()
  • componentDidCatch()

The getDerivedStateFromError() method has the following signature:

static getDerivedStateFromError(error)

The lifecycle method is called right after an error is thrown. This receives the error thrown in the tree hierarchy as a parameter. Then, it should return a value to update state in the component. This method is called during render and does not have access to the instance, so side-effects are not permitted.

The next method in the error phase has the following signature:

componentDidCatch(error, info)

This lifecycle method does have access to the instance, so feel free to use this.setState(). This method gets two parameters, error, and info. The error parameter has the actual error thrown. Info is an object containing the component stack, which is where the error got thrown. This method is called during the commit phase, so side-effects are permitted. When it’s not mutating state, it can be useful for logging error information. Keep in mind, when an error is thrown, a fallback UI can render with this.setState(), but this might be deprecated soon. A better approach is to return the new state from getDerivedStateFromError().

For the news ticker, create an error boundary around the NewsTicker component. In the child component, set a prop that throws a bomb so the error boundary can catch it. Once the error boundary diffuses the bomb, it’ll gracefully show a fallback UI.

Here’s the error boundary component:

class ErrorBoundary extends React.Component {
  state = {
    hasBomb: false
  };

  static getDerivedStateFromError(error) {
    return error ? {hasBomb: true} : {hasBomb: false};
  }

  componentDidCatch(error, info) {
    console.log('Caught error: ' + error.message);
    console.log('Component stack - ' + info.componentStack);
  }

  render() {
    if (this.state.hasBomb) {
      // Diffuse bomb with a user-friendly message
      return <p>Unable to show news ticker.</p>;
    }

    return this.props.children;
  }
}

In the child NewsTicker component, change render() so it can throw a bomb:

const {throwBomb} = this.props;

if (throwBomb) {
  throw new Error('Bomb!');
}

Putting It All Together

Both ErrorBoundary and NewsTicker are ready to go into a parent component. The error boundary wraps around the news ticker. The ticker needs props such as reset, freeze, and throw a bomb.

Begin by creating a parent component:

class App extends React.Component {
  render() {
    return <>
    </>;
  }
}
Then declare  state as a class property:
state = {
  reset: false,
  freeze: false,
  throwBomb: false,
  unmount: false
};

The unmount state property allows components to be removed from the tree hierarchy. This will need a set of checkboxes so you can flip between states. Put these between the empty tags in the render method:

<input type={"checkbox"}
  onChange={() => this.setState({reset: !this.state.reset})} />
<label>reset</label>

<input type={"checkbox"}
  onChange={() => this.setState({freeze: !this.state.freeze})} />
<label>freeze</label>

<input type={"checkbox"}
  onChange={() => this.setState({throwBomb: !this.state.throwBomb})} />
<label>throw bomb</label>

<input type={"checkbox"}
  onChange={() => this.setState({unmount: !this.state.unmount})} />
<label>unmount</label>

Then, lay down the components:

{!this.state.unmount && (
  <ErrorBoundary>
    <NewsTicker reset={this.state.reset}
      freeze={this.state.freeze}
      throwBomb={this.state.throwBomb} />
  </ErrorBoundary>
)}

Once you fire this up, it’ll look like this in the browser:

Conclusion

React components are reusable and come in independent modules. They fit within a tree hierarchy using relationships to reuse functionality. Composition is what makes these components more natural to think about. Each component has its own lifecycle that works within the tree’s lifecycle. As components mutate state, the lifecycle is what makes these components come alive.

 

The post Working with React Components appeared first on Simple Talk.



from Simple Talk https://ift.tt/2yZYeaa
via

Monday, August 12, 2019

Hiding What You Shouldn’t See

Back when I was working on a master’s degree, one of our professors told us a story about a colleague who learned how to navigate the Unix system. She was so thrilled about learning this new skill that, in her exuberance, she stumbled upon some hidden human resource files containing confidential information. Eventually, an administrator realised that the woman had located these files and told her “you can’t do that.” Well, she could and did do that. Even though the files were hidden in the hopes that people wouldn’t find them, they were not secured. Security by obscurity doesn’t work because someone will eventually find what you are trying to hide if they are motivated and put enough effort into it.

On the other hand, there is the problem of showing resources to people when they don’t have rights to them. Nothing is more annoying than clicking on a link and then being told that you do not have permission to view the resource. It would have been better if you hadn’t known about it at all.

In a Windows shop, administrators control what people can do and access by using Active Directory ACLs (access control lists), group membership, and Group Policies. Security in AD can get complicated quickly. To ensure administrators follow the principle of least privilege, proper planning and assigning rights to groups instead of to individual users are essential. I’ve not been an AD administrator, but from a user perspective, it seems to do a good job of both securing and hiding resources.

SQL Server doesn’t always hide what you shouldn’t see. Say an account only has SELECT permission on one table in one database on a server. The account can view all the databases when using SSMS, even those where they can’t connect. After connecting to that one database, they only see the one table in SSMS, but querying other tables returns an error message stating that SELECT permission is denied. A different message appears when attempting to query a nonexistent table. While the specific messages are useful for troubleshooting permissions problems, they give too much information to someone with evil intentions.

Once security has been figured out, it easy for organisations to enable self-service for things like business intelligence or even provisioning virtual machines. It’s essential, however, that the user is not overwhelmed with too many choices. Having too much from which to choose wastes time and can be quite frustrating.

Take a product like SQL Clone, for example, with its new Teams feature. Until the recent 4.0 release, DBAs could only control who could create images and clones, not which ones they could create. For a small shop, that might be good enough. In a bigger team, this might discourage DBAs from allowing self-service to keep someone from creating a clone from an image they shouldn’t see. With the new Teams feature, a DBA has precise control so that developers can only create clones from specific images. This makes self-service more attractive and saves time for everyone involved.

Just hiding what people shouldn’t see never works. Showing them more than they need to see is annoying for the users. Getting security right is a win for both admins and users.

 

 

 

The post Hiding What You Shouldn’t See appeared first on Simple Talk.



from Simple Talk https://ift.tt/2MSENrM
via

Friday, August 9, 2019

Introduction to DevOps: DevOps and the Database

The series so far:

  1. Introduction to DevOps: The Evolving World of Application Delivery
  2. Introduction to DevOps: The Application Delivery Pipeline
  3. Introduction to DevOps: DevOps and the Database

DevOps has been gaining steady ground in the world of application development, with ongoing improvements in delivery processes and the tools needed to support them. For the most part, however, DevOps has focused primarily on the application itself, with databases left to their own devices, despite the integral role they play in supporting many of today’s data-driven workloads.

According to the 2018 Accelerate: State of DevOps report, “database changes are often a major source of risk and delay when performing deployments.” But the report then states that integrating databases into the application delivery process could have a positive impact on continuous delivery. The key, according to the report, is good communication and comprehensive configuration management that incorporates databases. In other words, database changes should be managed in the same way as application changes.

Redgate’s 2019 State of Database DevOps report adds to these findings with their own survey results. According to the report, 77% of the respondents claim that their developers work across both databases and applications, and 75% say that developers build the database deployment scripts. However, 63% acknowledge that DBAs are responsible for deploying database changes to production.

The report also states that the two most significant challenges to integrating database deployments into the DevOps process are “synchronizing application and database changes” and “overcoming different approaches to application and database development.” In contrast, the two biggest reasons for integrating databases into DevOps are “to increase speed of delivery of database changes” and “to free up developers’ time for more added value work.” More importantly, 61% believe that such a move would have a positive impact on regulatory and compliance requirements.

Clearly, integrating database deployments into the DevOps process remains a challenge for many organisations, yet there’s a growing recognition that databases need to be brought into the DevOps fold. And in fact, this is beginning to happen, as more organisations incorporate database deployments into their integration and delivery processes. Not only does this promise to help improve application delivery, but it can also benefit database development itself.

The DevOps Promise

When application and database development efforts are more tightly integrated—with teams working in parallel and sharing a common process—they can release builds that are more consistent and stable, while reducing unnecessary risks and delays. The teams use the same infrastructure to develop and deploy application and database code, making it easier to standardise processes and coordinate efforts.

In a more traditional development environment, database changes can hold up application delivery, impacting productivity and costs. By incorporating databases into DevOps, database deployments can benefit from the established processes, while more tightly integrating database and application development.

A DevOps approach to database development also makes the process more agile and adaptable. Teams implement smaller, more frequent changes as part of a coordinated effort while receiving continuous feedback on the delivery processes and application components. In this way, database development and deployment are no longer disconnected from the larger delivery workflow but become integrated into the process throughout the application lifecycle.

The DevOps Challenge

As good as database DevOps might sound, there’s a good reason that organisations have been slow to jump on board. Transitioning from a siloed-database model to a DevOps-database approach is no small effort.

To begin with, databases were never part of the original DevOps vision. Processes and tools were developed for application code and application deployments, not for the peculiarities of database management. It’s only been recently that databases have been incorporated into DevOps processes in a meaningful way.

Database tools and operations are very specific to database development and management and the environment in which those databases reside. In the early days of DevOps, many viewed the database as existing in a separate world, and both sides of the aisle preferred to keep it that way.

One of the significant differences between application and database deployments comes down to data persistence. With applications, it’s much easier to update or replace code because there’s no data to manage along the way. With databases, however, you can’t simply overwrite schemas or copy changes from one environment to another without pulling the data along with you. Careful consideration must be given to how changes impact existing data and how to preserve that data when changes are made. Otherwise, you risk data loss, integrity issues, or privacy and compliance concerns.

Databases also bring with them size and scalability issues that differ from application code. Implementing schema changes on a massive database in a production environment can be a significant undertaking and lead to performance issues and degraded services. Database changes become even more complicated if the database is being accessed by multiple applications, especially if no single application has exclusive ownership.

Perhaps the biggest hurdle to implementing database DevOps has been a siloed mindset that makes it difficult for various players to come together in a way that makes integration possible. According to the Redgate report, only 22% of the respondents said that their developers and DBAs were “great” at working together effectively as a team, and without a team-focused attitude, an effective DevOps strategy is nearly impossible to implement.

Despite these challenges, however, database DevOps has made important inroads in recent years. DevOps tools now better accommodate databases, and database tools better integrate with DevOps systems. Attitudes, too, are beginning to change as more participants come to understand the value that incorporating databases can offer. Although database DevOps is still a challenge, many teams have now demonstrated that application and database delivery can indeed be a unified effort.

Moving Ahead with Database DevOps

To make DevOps work, the database team must adopt the same principles and technologies as those used by the application team when delivering software. Figure 1 provides an overview of what the database DevOps process might look like when integrated into the application delivery pipeline.

Figure 1. Integrating database deployment into the DevOps process

The first step is to store all database code in source control (also referred to as version control). A source control solution provides the foundation on which all other DevOps operations are based.

With source control, every developer works from the one source of truth, resulting in fewer errors and code conflicts. Source control also tracks who made what changes and when those changes were made. In addition, source control maintains a version history of the files, making it possible to roll back changes to previous versions. Source control also makes it easier to repeatedly build and update a database in different environments, including QA and development.

Database teams should store all their database code in source control. This includes the scripts used to build the databases as well as the migration (change) scripts that modify the database or data. For example, source control should be used for scripts that create, alter, or drop database objects—such as tables, views, roles indexes, functions, or stored procedures—as well as any scripts that select, insert, update, or delete data. The teams should also store static data, such as data used to populate lookup tables, as well as configuration data, when appropriate.

Once all the code and data are in source control, the database deployment operations can be incorporated into the same DevOps continuous integration (CI) and continuous delivery processes used for application deployments. When a developer checks in database code, it triggers an automated build operation that runs alongside the application release process, making it easier to coordinate database and application deployments.

When code is checked into the source control repository, the CI service kicks in and runs a series of commands that carry out such tasks as compiling source code and running unit tests. If a database is part of the deployment, the CI service tests and updates the database—or alerts developers to errors. If problems are discovered, developers can fix them and resubmit the code, which relaunches the CI process.

To incorporate databases into CI, a team might turn to a tool such as Redgate’s SQL Change Automation, which can integrate with any CI server that supports PowerShell. Redgate also provides extensions for CI products such as Jenkins, TeamCity, or Azure DevOps for enabling database integration.

When the CI service processes the SQL code, it produces an artifact that includes the deployment script necessary to update the applicable database objects and static data. The artifact also contains details about the deployment process, including a diff report that shows what has changed in the database. The artifact represents a specific, validated version that can be used as a starting point for the database release process.

At this point, the artifact is deployed against a staging database that is ideally an exact copy of the production database. Here DBAs can verify and confirm the changes to ensure the staging database is production-ready. If necessary, they can also make additional changes. Out of this process, a final deployment script is generated, which can then be passed down the pipeline for deployment against the production database.

Not surprisingly, the exact approach to database delivery is much more involved than what I’ve described here, especially when it comes to migration script versioning, and that process can vary significantly depending on the tools being used and how those tools are configured.

What this does demonstrate is that database DevOps is indeed doable, providing database teams with a process that automates repetitive deployment and testing operations. With DevOps, teams can deliver smaller releases that are easier and faster to deploy, while having in place a consistent, steady mechanism for ongoing database deployments that work in conjunction with application delivery.

Testing and Monitoring

One of the most important aspects of the application delivery pipeline is ongoing testing. Changes to the database should undergo rigorous testing before the release reaches the staging environment. In this way, developers learn of problems quickly and early in the development process. When issues are discovered, they’re immediately alerted so they can check fixes into source control and keep the development effort moving forward.

Developers and DBAs should invest the time necessary to write comprehensive tests that provide for as many scenarios as possible. Many of these tests will be based on frameworks specific to database testing. For example, tSQLt is a popular open-source framework for SQL Server that lets you write unit tests in T-SQL. Regardless of the framework, the goal is the same: to identify as many issues as possible before database changes make it to production.

Unit tests offer your first line of defence against problem SQL code. Because they run when the code changes are checked into source control, they provide the fastest response to possible issues. A unit test is a quick verification of specific functionality or data, such as ensuring that a user-defined function returns the expected result. A unit test should be concise and run quickly, producing a single binary value—either pass or fail.

Also important to the application delivery pipeline is ongoing monitoring, which needs to be as comprehensive as the testing processes themselves. Monitoring can be divided into two broad categories: the feedback loop and system monitoring.

A DevOps application delivery pipeline includes a continuous feedback loop that provides participants with ongoing details about the delivery process. For example, when the CI service notifies developers about problems in their code, those alerts can be considered as part of the feedback loop. Development teams (application and database) should have complete visibility across the entire pipeline. Not only does this help identify issues with the application and database earlier in the delivery cycle, but it also helps to monitor the delivery process itself to find ways to improve and streamline operations.

System monitoring is more typical of what you’d expect of database operations. Once the changes have been deployed to production, you must closely monitor all related systems to check for unexpected issues and ensure that systems are running as they should, before users or data are seriously impacted. To this end, DBAs should monitor database systems for performance and compliance, taking into account regional differences and regulatory requirements. Developers and DBAs alike should have a real-time understanding of issues that might need immediate attention or those that should be addressed in the foreseeable future.

Testing and monitoring also play a critical role in ensuring a database’s overall security. Developers, IT administrators and DBAs must take into account security considerations throughout the entire application lifecycle, addressing issues that range from SQL coding to server security in order to ensure that data is protected at every stage of the application delivery process.

Proper testing and ongoing monitoring can go a long way in helping to enforce these protections. By using source control and automating the delivery process, organisations have a process that is more predictable and easier to manage, while providing an audit trail for tracking potential issues. Database teams still need to ensure proper configurations and secure environments, but an effective DevOps pipeline can also play an important role in your security strategy.

The New Era of Database DevOps

Database DevOps offers the promise of quicker, easier and more secure deployments while bringing application and database development efforts in line with one another. But DevOps is not a one-size-fits-all solution to application delivery, nor is it meant to be a developer-first strategy that leaves DBAs and IT administrators behind.

Developers, DBAs, and operation professionals must work together to implement an application delivery strategy that takes into account the needs of all participants, with the goal of delivering the best applications possible as efficiently as possible in the shortest amount of time. Anything less and your database DevOps efforts are destined to fail.

 

The post Introduction to DevOps: DevOps and the Database appeared first on Simple Talk.



from Simple Talk https://ift.tt/2YZPIGU
via

Saturday, August 3, 2019

Reporting Services Basics: Parameters

The series so far:

  1. Reporting Services Basics: Overview and Installation
  2. Reporting Services Basics: Creating Your First Report
  3. Reporting Services Basics: Data Sources and Datasets
  4. Reporting Services Basics: Parameters

Adding parameters is one of the essential skills to learn when you are new to SSRS. Parameters give end-users the ability to change the filter of the report on-the-fly. Imagine creating a separate report for every sales year or every department. Even worse, imagine creating a report for every combination of years and departments! With parameters, you can create one report that will work for any combination of these variables.

Starting with the Product List Report

To demonstrate parameters, this article will use the list of products found in the AdventureWorks database. To get started, create a new Report Server Project called Parameters with a shared data source. (See previous articles in this series if you need help understanding how to work with projects, data sources, or datasets.) Add a report named Product List with this embedded dataset:

SELECT P.ProductID, P.Name AS ProductName, P.Color, P.Size, 
   P.ListPrice, PC.Name AS Category, PS.Name AS SubCategory
FROM Production.Product AS P 
JOIN Production.ProductSubcategory AS PS 
  ON PS.ProductSubcategoryID = P.ProductSubcategoryID
JOIN Production.ProductCategory AS PC
  ON PC.ProductCategoryID = PS.ProductCategoryID;

Your Solution Explorer should look like Figure 1.

Figure 1: The Solution Explorer

Your Report Data window should look like Figure 2.

Figure 2: The Report Data window

Add a Table control to the report’s canvas and add these fields to the Data row.

  • ProductID
  • ProductName
  • Color
  • Size
  • ListPrice

The table on the report will look like Figure 3.

Figure 3: The table

Preview the report to make sure it works at this point. It should look something like Figure 4.

Figure 4: The report in Preview mode

Spend some time formatting the report. This is not required for learning about parameters, but if you are like me, the unformatted report is quite annoying! Your report might look something like Figure 5 when you are done.

Figure 5: The formatted report

The wizard report from the first article had a header, but you didn’t learn how to add a header to a new report. To do so, make sure that the report is in Design view. Select the report canvas, which makes the Report menu show up in the menu bar. Select Report Add Page Header, as shown in Figure 6. Also, add a page footer.

Figure 6: Add a page header and footer

Move the table so that it is close to the header and the left of the page. Also, drag the top of the footer to the bottom of the table. Drag the right side of the canvas to the table. The canvas should look like Figure 7.

Figure 7: The canvas with header and footer

In the Report Data window, expand Built-in Fields. Drag the Report Name field into the page header, as shown in Figure 8.

Figure 8: Drag the Report Name

Expand the textbox width to the size of the canvas. Increase the font size to 22 and align the text in the centre. You can also drag Execution Time and Page Number to the footer. (Note that you may need to expand the are under the table where you can temporarily drag the first footer item before adding it to the footer.) The report canvas should now look like Figure 9.

Figure 9: Formatted header and footer

Adding Simple Parameters

SSRS will automatically add parameters to your report when you have variables in the WHERE clause of the query. In this case, you’ll add a parameter to filter on color. Double-click the dataset and change the query to this:

SELECT P.ProductID, P.Name AS ProductName, P.Color, P.Size, 
   P.ListPrice, PC.Name AS Category, PS.Name AS SubCategory
FROM Production.Product AS P 
JOIN Production.ProductSubcategory AS PS 
  ON PS.ProductSubcategoryID = P.ProductSubcategoryID
JOIN Production.ProductCategory AS PC
  ON PC.ProductCategoryID = PS.ProductCategoryID
WHERE P.Color = @color;

Click OK, and you’ll see the new parameter @color listed in the Parameters folder and the Parameters section of the report canvas, as shown in Figure 10.

Figure 10: The @color parameter

Preview the report. This time, it will not run automatically. Fill in the color “blue” and click View Report. The report should look like Figure 11 with only blue items displayed.

Figure 11: Filtered by blue

Right now, you must type in a valid color to get the report to return products. If you type in “purple,” for example, no products will be returned.

There are quite a few properties you can set to control the behaviour of parameters. You might allow a blank value, for example, or supply a list of values from which to choose. To see the properties, double-click the parameter. The Report Parameter Properties dialogue looks like Figure 12.

Figure 12: The parameter properties

There are a few interesting items to note on the General page. For example, what is the difference between Name and Prompt? The Name refers to the actual name of the parameter that is used in the SQL query. The Prompt is what the user will see. So, you might want to change the “c” in color to uppercase make it more user-friendly.

You can change the Data Type if you must restrict the type of values entered, such as numbers or dates. In fact, if you switch to date, the report will display a date picker control for the parameter when you run the report. There are three other options (Allow blank value, Allow null value, and Allow multiple values) that will be covered later in the article. And, finally, there is the visibility property of the parameter. Here is what each option means:

Visible: The parameter is shown to the end-user who can change the value

Hidden: The end-user is not prompted for the parameter, but the value is typically passed in from a calling report

Internal: The end-user is not prompted and cannot change the value. This might be used for passing in the user id to the server.

There are three more pages to this dialogue. This article will cover Available Values and Default Values. Now, you’ll learn how to provide a list of values for the parameter.

Adding a Parameter List

It can be difficult for the user to remember the valid values for a report, so report developers often provide lists of values from which to choose. To provide a list of colors, follow these steps.

Switch to the parameter’s Available Values page. Currently, the option is set to None, as shown in Figure 13, which means that no list is provided.

Figure 13: The Available Values page

Switch to Specify values and click Add. You’ll now have a space to type in the first value, as shown in Figure 14.

Figure 14: Type in values

The Label is shown to the end-user, while the Value is passed to the SQL query. In this case, both values are the same. Enter the following list:

  • Black
  • Blue
  • Grey
  • Multi
  • Red
  • Silver
  • Silver/Black
  • White
  • Yellow

The screen should look like Figure 15 when you are done. Click OK to save the list.

Figure 15: The parameter list

Now when you preview the report, you’ll see a list of colors from which to choose, as shown in Figure 16.

Figure 16: The parameter with the list

Try running the report multiple times, each time with a different color to verify that the report works as expected.

If you are familiar with this data, you’ll know that there are several products with no color (NULL). How can you allow a user to see those products? You’ll learn that next.

Searching for NULL values

You may recall that there is a parameter option to allow NULL (see Figure 12), but to use this option, you must make a change to your query that causes other complications later. It gets messy quickly, so I suggest substituting the NULLs instead.

To get started, add another item to the available values in the Color parameter, N/A for both Value and Label. Double-click the ProductList dataset and change the query to this:

SELECT P.ProductID, P.Name AS ProductName, P.Color, P.Size, 
   P.ListPrice, PC.Name AS Category, PS.Name AS SubCategory
FROM Production.Product AS P 
JOIN Production.ProductSubcategory AS PS 
  ON PS.ProductSubcategoryID = P.ProductSubcategoryID
JOIN Production.ProductCategory AS PC
  ON PC.ProductCategoryID = PS.ProductCategoryID
WHERE COALESCE(P.Color,'N/A') = @color;

When you rerun the report and select N/A, you should see all the items with no color. So far, you are working with a static parameter list. Now, you’ll learn how to create a dynamic list. Note that using a function like COALESCE on a column in the WHERE clause can often cause performance issues.

Using a Query for a Parameter List

What happens if AdventureWorks gets in a new purple or orange product? You would have to manually add those colors to keep the parameter list up to date. Instead, you might want to maintain the list using a query. To do so, switch back to Design view add a new Dataset called Colors to the report with this query that causes the N/A row to show up first.

SELECT DISTINCT COALESCE(Color,'N/A') AS Color, 
        CASE WHEN Color IS NULL THEN 0 ELSE 1 END AS SortOrder
FROM Production.Product AS P 
ORDER BY SortOrder, Color;

Figure 17 shows how the dataset should look.

Figure 17: The Colors dataset

Click OK to create the dataset. Now open the parameter properties again and switch to the Available Values page. Select Get values from a query. Under Dataset, select Colors. In both the Values and Labels field, select Color. The properties should look like Figure 18.

Figure 18: Using a query for the parameter list

Click OK to save the change and be sure to test the report. If you don’t mind modifying a row of the Product table, run this update statement in SSMS or Azure Data Studio.

UPDATE Production.Product 
SET Color = 'Orange'
WHERE ProductID IN (802, 803);

If you rerun the report, you should see Orange in the parameter list and the orange items in the results. Figure 19 shows the report.

Figure 19: The orange items

You might want to give the ability to select multiple items at once. The next section will show you how to do that.

Selecting Multiple Values

The person running your report might want to see more than one color at a time, maybe even all of them. There is a setting on the General page of the parameter properties (see Figure 12) that allows you to select more than one item. If you do this, however, your query will error, and the report will not run. Figure 20 shows the error message:

Figure 20: The error message after setting Allow multiple values.

The query sent to SQL Server uses = (equal to), but the variable holds a comma-delimited list of values. To fix this issue, you’ll need to modify the ProductList query to this:

SELECT P.ProductID, P.Name AS ProductName, P.Color, P.Size, 
   P.ListPrice, PC.Name AS Category, PS.Name AS SubCategory
FROM Production.Product AS P 
JOIN Production.ProductSubcategory AS PS 
  ON PS.ProductSubcategoryID = P.ProductSubcategoryID
JOIN Production.ProductCategory AS PC
  ON PC.ProductCategoryID = PS.ProductCategoryID
WHERE COALESCE(P.Color,'N/A') IN (@color);

After running, the report should look something like Figure 21 when Multi and Orange are selected.

Figure 21: Selecting multiple values

So far, you have added just one parameter to the report. Many of the reports you run in the future will have more than that. Either the dataset will have multiple predicates in the WHERE clause, or you might also use parameters to control something about how the report looks. In the next section, you’ll learn how to control the value of a textbox in the report with a parameter.

Displaying Parameter Values on the Report

Parameters are the “workhorse” of SSRS. You can do so many things with them. In this section, you’ll learn that you can display the value or label of a parameter in a textbox.

Back in Design view, add a Textbox to the header section of the report. Drag it to the left of the page and expand the width. It should look like Figure 22.

Figure 22: The new Textbox

Right-click on the new Textbox and select Expression, as shown in Figure 23.

Figure 23: Select Expression

Just about any property in an SSRS report can be controlled with an Expression, i.e., a formula. You’ll learn much more about expressions throughout these articles, but this is a simple example to get you started. Once you select Expression in the menu, the Expression dialogue should pop up, as shown in Figure 24.

Figure 24: The Expression dialogue

Any expression begins with an equal to sign (=) similar to formulas in Excel. The Category area contains dozens of built-in fields and functions that you can use to build these expressions. Change the expression to

="Colors chosen: " +

Then, make sure your cursor is to the right of the plus sign (+), click Parameters and double-click color in the Values window, as shown in Figure 25.

Figure 25: The expression

The final expression should be:

="Colors chosen: " + Parameters!color.Value(0)

Click OK to save the expression. The Textbox will show <<Expr>> instead of a field name. Run the report but select only one color. The report should look like Figure 26 if you selected Orange. The value you chose is visible on the report.

Figure 26: The parameter value displayed

This works great, but it will only display one item. It’s possible that you are allowing multiple values to be selected. When you select more than one, only the first item is displayed. The reason is that the parameter values are held in an array of strings. Right now, the formula displays the first item in the array.

To display all the chosen values, go back to Design view and bring up the Expression dialogue again. Change the formula to this:

="Colors chosen: " + Join(Parameters!color.Value,", ")

Notice that the index of the array (0) was removed. The Join function builds a string from the array values. Now when you run the report, it will look something like Figure 27.

Figure 27: Displaying multiple values

In this example, the Values and Labels of the parameter are identical. In many cases, they are different. For example, the query might need an ID number while the person running the report might like to see the name. To get around this, change the formula so that the user-friendly label is used instead of the value:

="Colors chosen: " + Join(Parameters!color.Label,", ")

You can also use parameters to change the properties of objects on the report. You’ll learn how to do this next.

Using Parameters to Control Properties

Just about any property in SSRS can be controlled with an expression. If you take a look at the Text Box Properties dialogue of the Textbox you created in the last section, you’ll see the fx symbol next to two properties, as shown in Figure 28.

Figure 28: The fx symbol

Clicking this symbol anywhere you see it brings up the Expression box to control the associated property. Before adding in an expression, cancel out of this dialogue. Create a new parameter called Background by right-clicking the Parameters folder and selecting Add Parameter. Add these values/labels on the Available Values page.

  • Yellow
  • LightBlue
  • Plum

Once all the parameter properties are in place, click OK. You’ll then see the second parameter in the list of parameters. Remember that this one isn’t connected to a dataset query; it will be used to control the background, or fill, color of the Textbox.

The next step is to connect the parameter to the Textbox. Right-click and select Text Box Properties. Select the Fill page. Click the fx symbol, as shown in Figure 29.

Figure 29: The Fill property

The initial expression is “No Color.” Replace it with this formula:

=Parameters!Background.Value

The Expression dialogue should look like Figure 30.

Figure 30: The background expression

Click OK twice to save the property change. Now, try running the report. If you chose LightBlue, the report should look something like Figure 31.

Figure 31: The textbox with a blue background

This simple example demonstrated how powerful expressions and parameters are. Next, you’ll see how to set default values for parameters.

Using Default Parameters

In some cases, the user is likely to select a specific value for a parameter and only rarely change it. To learn how to set up a default value for the parameter, open the properties of the Background parameter. Select the Default Values page and Specify values, as shown in Figure 32.

Figure 32: The Default Values page

Click Add. Type in your favourite of the three colors, LightBlue, Plum, or Yellow. The property should look like Figure 33. Click OK to save the changes.

Figure 33: Filling in the default value

Now when you run the report, the background color will be automatically filled in. You can also get default values from a dataset. Open the Default Values properties of the color parameter. Select Get values from a query. Fill in the Colors Dataset and Color Value field. The properties should look like Figure 34.

Figure 34: The default values from a dataset

In this case, all colors will be selected when you run the report.

One of the most common requests is to make the selection of one parameter filter another one. You’ll learn how to do that next.

Creating Cascading Parameters

Each product belongs to a subcategory, and each subcategory belongs to a category. This is the type of hierarchical relationship that works well when parameters work together with what’s called Cascading Parameters. Figure 35 illustrates how this will work.

Figure 35: The product/category hierarchy

The first step is to modify the ProductList dataset query so that it prompts for the subcategory. Change the query to this:

SELECT P.ProductID, P.Name AS ProductName, P.Color, P.Size, 
   P.ListPrice, PC.Name AS Category, PS.Name AS SubCategory
FROM Production.Product AS P 
JOIN Production.ProductSubcategory AS PS 
  ON PS.ProductSubcategoryID = P.ProductSubcategoryID
JOIN Production.ProductCategory AS PC
  ON PC.ProductCategoryID = PS.ProductCategoryID
WHERE COALESCE(P.Color,'N/A') IN (@color)
  AND P.ProductSubcategoryID = @subcategory;

To make sure that the query works, add the SubCategory and Category fields to the report. Preview the report. Enter subcategory 31. The report should look something like Figure 36.

Figure 36: Filtering with subcategory

At this point, the products are being filtered by subcategory, but the ID must be typed in. To get around this issue, add a new dataset called Subcategory with this query:

SELECT PS.ProductSubcategoryID, PS.Name AS SubcategoryName
FROM Production.ProductSubcategory AS PS
ORDER BY SubcategoryName;

Connect the Subcategory dataset to the subcategory parameter. The Values field should be ProductSubcategoryID, and the Label field should be SubcategoryName. In this case, the query needs the ID while the user needs the name. The Available Values properties should look like Figure 37.

Figure 37: Connect the dataset to the parameter

If you review Figure 35, you’ll see that subcategories should be filtered by category. To do this, change the Subcategory dataset so that it’s filtered by category:

SELECT PS.ProductSubcategoryID, PS.Name AS SubcategoryName
FROM Production.ProductSubcategory AS PS
WHERE PS.ProductCategoryID = @category
ORDER BY SubcategoryName;

You now have four parameters in place. Notice that Category is listed before Subcategory in Figure 38. That’s because you must choose Category before Subcategory. In this parameter area, you can rearrange the parameters by dragging them around. The report will break if Category is not located before Subcategory!

Figure 38: The four parameters

The next logical step is to add a dataset for Category. Use this query:

SELECT PC.ProductCategoryID, PC.Name AS CategoryName
FROM Production.ProductCategory AS PC 
ORDER BY CategoryName;

Connect the dataset to the new Category parameter. You guessed it! The Value field is ProductCategoryID, and the Label field is CategoryName. The Available Values page should look like Figure 39.

Figure 39: The category Available Values

If you did everything correctly, the parameters should look like Figure 40 when you preview the report. Notice that the Subcategory parameter is greyed out until you select a Category.

Figure 40: The Subcategory parameter is not available

When you select a Category, the Subcategory parameter refreshes. For example, if you select Bikes, only the available bike subcategories show up. Figure 41 shows how this looks.

Figure 41: The filtered subcategory

Configuring Cascading Parameters is one of the most challenging things to understand in SSRS. Hopefully, I’ve shown that by breaking the steps down and completing them one at a time, it is doable.

Conclusion

Learning about parameters is critical for SSRS developers. In this article, you learned many ways in which parameters are used, including with a list of available values from a query, multiple selections, defaults, cascading, and more. In the next article, you’ll learn about more features that make SSRS reports dynamic.

 

The post Reporting Services Basics: Parameters appeared first on Simple Talk.



from Simple Talk https://ift.tt/2Kn1xgK
via

Wednesday, July 31, 2019

Cracking DAX – the EARLIER and RANKX Functions

The series so far:

  1. Creating Calculated Columns Using DAX
  2. Creating Measures Using DAX
  3. Using the DAX Calculate and Values Functions
  4. Using the FILTER Function in DAX

If you really want to impress people at DAX dinner parties (you know the sort: where people stand around discussing row and filter context over glasses of wine and vol-au-vents?), you’ll need to learn about the EARLIER function (and to a lesser extent about the RANKX function). This article explains what the EARLIER function is and also gives examples of how to use it. Above all, the article provides further insight into how row and filter context work and the difference between the two concepts.

Loading the Sample Data for this Article

As for the other articles in this series, the sample dataset consists of four simple tables which you can download from this Excel workbook:

After importing the data, you should see this model diagram (I’ve used Power BI, but the formulae in this article would work equally well in PowerPivot or SSAS Tabular):

One more thing to do – add a calculated column to the country table, giving the total sales for each country:

TotalSales = CALCULATE(Sumx(Sales,[Price]*[Quantity]))

This formula iterates over the Sales table, calculating the sales for each row (the quantity of goods sold, multiplied by the price) and summing the figures obtained. The CALCULATE function is needed because you must create a filter context for each row so that you’re only considering sales for that country – without it, you would get this:

Example 1: Ranking the Countries

The first use case is very simple. The aim is to rank the countries by the total sales for each:

DAX doesn’t have an equivalent of the SQL ORDER BY clause, but you can rank data either by using the RANKX function (covered later in this article) or by using the EARLIER function creatively. Here’s what the function needs to do, using country number 3 – India – as an example. Firstly, it creates a row context for this row:

The sales for India are 34.5. What it now must do is to count how many rows there are in the table which have countries whose sales are greater than or equal to India’s sales:

This shows the filtered table of countries, including only those whose sales are at least equal to India’s. There are four rows in this filtered table.

If you perform the same calculations for each of the other countries in the table, you’ll get the ranking order for each (that is, the number of countries whose sales match or exceed each country’s). For those who know SQL, this works in the same way as a correlated subquery. This would imply that it might run slowly, however, here’s what Microsoft have to say on the subject:

The problem: One Row Context Hides Another

Anyone who has driven much in France will have seen this sign at a level-crossing:

What it means is “one train can hide another” … and so it is with row contexts. The measure will open two row contexts, as the diagram below shows:

The problem is that when DAX gets to the inner row context for the FILTER function, it will no longer be able to see the outer row context (the country you’re currently considering) as this row context will be hidden unless you use the EARLIER function to refer to the first row context created in the formula.

What Would You Name this Function?

I’ve explained that the EARLIER function refers to the original row context created (nearly always for a calculated column). What would you have called this function? I’d be tempted by one of these names:

  • OUTERROWCONTEXT
  • PREVIOUSROWCONTEXT
  • INITIALROWCONTEXT

The multi-dimensional (cubes) version of Analysis Services gets it about right, using CURRENTMEMBER and PREVMEMBER depending on context. It’s interesting to see that you can’t use these words as names of variables in DAX as they are reserved words:

This is true even though they aren’t official DAX function names!

What I definitely wouldn’t use for the function name is something which implied the passage of time. To me, EARLIER means something which occurred chronologically before something else. I think this is one of the reasons it took me so long to understand the EARLIER function: it’s just got such an odd name.

The Final Formula Using EARLIER

Having got that off my chest, here’s the final formula:

SalesOrder = COUNTROWS(
    Filter(
        Country,
        [TotalSales] >= EARLIER([TotalSales])
   )
)

Here’s the English (!) translation of this …

“For each country in the countries table, create a row context (this happens automatically for any calculated column). For this row/country being considered, count the number of rows in a separate virtual copy of the table for which the total sales for the country are greater than or equal to the total sales for the country being considered in the original row context”.

What could possibly be confusing about that?

Other Forms of the EARLIER Function

Readers will be delighted to know that you don’t have to limit yourself to going back to the previous row context – you can specify how many previous row contexts to return to by varying the number used in the second argument to the EARLIER function:

You can even use the EARLIEST function to go to the earliest row context created for a formula. The formula could alternatively have been written like this:

SalesOrder = COUNTROWS(
    FILTER(
        Country,
        [TotalSales] >= EARLIEST([TotalSales])
    )
)

I find it very hard to believe that anyone would need this function! It could only be useful where you:

  1. Create a row context (typically by creating a calculated column).
  2. Within this, create a filter context.
  3. Within this, create a row context (typically by using an iterator function like FILTER or SUMX).
  4. Within this, create another filter context.
  5. Within this, create a third-row context.

In this complicated case, the EARLIER function would refer to the row context created at step 3, but the EARLIEST function would refer to the original row context created at step 1.

Avoiding the EARLIER Function by Using Variables

One of the surprising things about the EARLIER function is that you often don’t need it. For this example, you could store the total sales for each country in a variable, and reference this instead. The calculated column would read instead:

Sales order using variables = 
// create a variable to hold each country's sales
VAR TotalSalesThisCountry = [TotalSales]
// now count how many countries have sales 
// which match or exceed this
RETURN COUNTROWS(
    FILTER(
        Country,
        [TotalSales] >= TotalSalesThisCountry
    )
)

There’s not much doubt that this is easier to understand, but it won’t give you the same insight into how row context works!

Using the EARLIER function in a measure

The EARLIER function refers to the previous row context created in a DAX formula. But what happens if there isn’t a previous row context? This is why you will so rarely see the EARLIER function used in a measure. Here’s what you’ll get if you put the formula in a measure:

The yellow error message explains precisely what the problem is: measures use filter context, not row context, so no outer row context is created.

Example 2: Running Totals

Another common requirement is calculating the cumulative total sales for countries in alphabetical order:

The above screenshot shows that this calculates the answer separately for each country, but it looks more sensible when you view it in alphabetical order by country name:

The formula for this column calculates for each country the total sales for all countries coming on or before it in alphabetical order:

Running total = SUMX(
    FILTER(
        Country,
        Country[CountryName] <= EARLIER(Country[CountryName])
    ),
    [TotalSales]
)

Again, you could have alternatively used a variable to hold each country’s name:

Running total using variables = 
// store this row's country name
VAR ThisCountry = Country[CountryName]
// return the sum of sales for all countries up to or
// including this one
RETURN SUMX(
    FILTER(
        Country,
        Country[CountryName] <= ThisCountry
    ),
    [TotalSales]
)

Example 3: Group Totals

Here’s another use of the EARLIER function – to create group totals. To follow this example, first, add a calculated column in the Sales table to show the name of each product bought (you don’t have to do this, but it will make the example clearer if you use the product name rather than the product id to match sales rows to the product bought):

Product = RELATED(‘Product'[ProductName])

Here’s the column this should give:

You can now create a second calculated column:

Average product sales = AVERAGEX(
    
    // average over the table of sales records for the 
    // same product as this one ...
    FILTER(Sales,[Product] = EARLIER(Sales[Product])),
    
    // ... the total value of the sale
    [Price]*[Quantity]
)

Here’s what this will give for the first few roles in the SALES table. You may want to format the column as shown by modifying the decimal places on the Modeling tab.

The group average for Olly Owl products is 5.40. For this example, for each sales row, the calculated column formula is averaging the value of all sales where the product matches the one for the current row.

Example 4: Creating Bands

So far, you have seen three relatively simple uses of the EARLIER function – for the fourth example, I’ll demonstrate a more sophisticated one. Begin by adding a calculated column to the Sales table, giving the value of each transaction (which should equal the number of items bought, multiplied by the price paid for each):

It would be good to categorise the sales into different bands, to allow reporting on different customer bands separately. For example:

  • Any purchase with value up to £10 is assigned to “Low value”
  • Any purchase with value between £10 and £15 is assigned to “Medium value”
  • Any purchase with value between £15 and £20 is “High value”
  • Any purchase of more than £20 is “Premium customer”

One way to do this would be to create a calculated column using a SWITCH function like this:

Customer type = SWITCH(
    // try to find an expression which is true
    TRUE(),
    // first test - low value
    [SalesValue] <= 10, "Low value",
    // second test - medium value
    [SalesValue] <= 15, "Medium value",
    // third test - high value
    [SalesValue] <= 20, "High value",
    // otherwise, they are a premium customer
    "Premium customer"
)

This would allow reporting on the different customer types (for example, using this table):

However, this hard-codes the thresholds into the calculated column. What would be much more helpful is if you could import the thresholds from another table, to make a dynamic system (similar to a lookup table in Excel, for those who know these things).

Creating the Table of Bands (Thresholds)

To create a suitable table, in Power BI Desktop choose to enter data in a new table (you could also type it into Excel and load the resulting workbook):

Type in the thresholds that you want to create, and give your table the name Categories:

Note that in your model’s relationship diagram, you will now have a data island (a table not linked to any other). This is intentional:

Creating a Formula Assigning Each Sale Row to a Category

You can now go to the Sales table and create a calculated column assigning each row to the correct category:

For each row, what you want to do is find the set of rows in the Categories table where two conditions are true:

The lower band for the category is less than the sales for the row; and

The upper band for the category is greater than or equal to the sales for the row.

It should be reasonably obvious that this set of rows will always exist, and will always have exactly one row in it. Because of this, you can use the VALUES function to return the value of this single row, giving:

Category = CALCULATE(
    // return the only category which satisfies both of
    // the conditions given
    VALUES(Categories[CategoryName]),
    // this sales must be more than the lower band ...
    Categories[Low] < EARLIER(Sales[SalesValue]),
    // ... and less than or equal to the higher band
    Categories[High] >= EARLIER(Sales[SalesValue])
)

You might at this point wonder why you need the EARLIER function when you haven’t created a second row context. The answer is that the CALCULATE function creates a filter context, so you need to tell your formula to refer back to the original row context you first created in the formula.

Sorting the Categories

One problem remains: the categories aren’t in the right order (I’m well aware that one way to solve this would be to click on the column heading to change the sort order, but I’m after something more dynamic!):

To get around this, it may at first appear that all you need to do is to designate a sort column:

You could do this by selecting the CategoryName column in the Categories table as above, and on the Modeling tab, setting this to be sorted by the SortOrder column. This looks promising – but doesn’t work (it actually creates an error if you’ve typed in the data for the categories table, which you’ll need to refresh your model to clear). The reason this doesn’t work is that the alternative sort column needs to be in the same table as the Category column.

A solution is to create another calculated column in the Sales table:

Category SortOrder = CALCULATE(
    // return the sales order for the two conditons
    VALUES(Categories[SortOrder]),
    // this sales must be more than the lower band ...
    Categories[Low] < EARLIER(Sales[SalesValue]),
    // ... and less than or equal to the higher band
    Categories[High] >= EARLIER(Sales[SalesValue])
)

You now have two columns for each sale row – one giving the category, and one giving its corresponding sort order number. You can select the category column and choose to sort it using the sort order column instead (choosing the option shown below on the Power BI Modeling tab):

Bingo! The categories appear in the required order:

If after reading this far you’re still a bit fuzzy on the difference between row and filter context, practice makes perfect! I’ve found reading and re-reading articles like this helps, as each time you get closer to perfecting your understanding (for those in the UK, you could also consider booking onto one of Wise Owl’s Power BI courses).

Using the RANKX Function to Rank Data

Out of all the DAX functions, the one which trips me up most often is RANKX – which is odd, because what it does isn’t particularly complicated. Here’s the syntax of the function:

So the function ranks a table by a given expression. Here is what the arguments mean:

  • The Table argument gives the table you’re ranking over.
  • The Expression argument gives the expression you’re ranking by.
  • The Order column allows you to switch between ascending and descending order.
  • The Ties column lets you specify how you’ll deal with ties.

You’ll notice I’ve missed out the Value argument. This is for the good reason that it is a) bizarre and b) not useful. It allows you to rank by one expression, substituting in the value for another for each row in a table. If this sounds like a strange thing to want to do, then I’d agree with you.

To see how the RANKX function works, return to the Country table in which you created a calculated column at the beginning of this article:

Suppose you now want to order the countries by sales (clearly one way to do this would just be to click on the drop arrow next to the column and choose Sort ascending!). Here’s a calculated column which would do this:

What you should notice is the unusual default ranking order: unlike in SQL (and many other languages), the default order is descending, not ascending. To reverse this, you could specify ASC as a value for the fourth Order argument:

Sales order = RANKX(
    
    // rank the rows in the country table ...
    Country,
    
    //... by the total sales column ...
    [TotalSales],
    
    // omitting the third argument
    ,
    
    // and ranking in ascending order
    ASC
)

So far, so straightforward!

Using RANKX in a Measure

Where things get more complicated is when you use RANKX in a measure, rather than in a calculated column. Suppose that you have created a table visual like this in a Power BI report:

Suppose further that you want to create and display this measure to show the ranking order:

Sort order measure = RANKX(
    // order the countries by sales
    Country,
    SUMX(
        Sales,
        [Price]*[Quantity]
    )
)

However, when you add this measure to your table, you get this:

The reason for this is that Power BI evaluates the measure within the filter context of the table. So for the first row (Brazil), for example, here’s what Power BI does:

  • Applies the filter context to the Country table to pick out just sales for Brazil
  • Calculates the total sales for this country (14, as it happens)
  • Returns the position of this figure within the table of all of the figures for the current filter context (so the returned number 1 means that 14 is the first item in a table containing the single value 14)

To get around this, you first need to remove filter context before calculating the ranking order, so that you rank the total sales for each country against all of the other country’s total sales:

However, even this doesn’t solve the problem. The increasingly subtle problem is that the RANKX function – being an iterator function – creates a row context for each country, but then evaluates the sales to be the same for each country because it doesn’t create a filter context within this row context. To get around this, you need to add a CALCULATE function to perform context transition from row to filter context within the row context within the measure:

Sort order measure = RANKX(
    // order across ALL the countries ...
    ALL(Country),
    // by the total sales
    CALCULATE(
        SUMX(
            Sales,
            [Price]*[Quantity]
            )
        )
    )

This – finally – produces the correct ranking (note that there is a blank country at the top because some sales don’t have a matching country parent – although this isn’t important for this example):

It’s worth making two points about this. Firstly, this isn’t a formula you’ll often need to use; and secondly, this is about as complicated a DAX formula as you will ever see!

Dealing with Ties

If your ranking produces ties, the default is to SKIP numbers, but you can also use the DENSE keyword to override this. To see what each keyword means, add this calculated column to the Sales table:

QtyRanking = RANKX(Sales,[Quantity])

What it will do is to order the sales rows by the quantity sold. Here’s what you’ll get if you use Skip, or omit the Ties keyword altogether:

Here, by contrast, is what you’ll get if you use Dense (I’m not quite sure why you’d ever want to do this):

In the second screenshot, there are no gaps in the numbers.

Conclusion

You can apply the EARLIER function in various contexts to solve modelling problems in DAX, and it should be an essential part of every DAX programmer’s arsenal. The RANKX function, by contrast, solves a very specific problem – ranking data. What both functions have in common is that they are impossible to understand without a deep understanding of row and filter context, so if you’ve got this far, you can consider yourself a DAX guru!

The post Cracking DAX – the EARLIER and RANKX Functions appeared first on Simple Talk.



from Simple Talk https://ift.tt/2yoEKf7
via