Quantcast
Channel: Telerik Blogs | .NET
Viewing all 1954 articles
Browse latest View live

Integrating Blazor Components with ASP.NET Core Views

$
0
0

What developers really want is to use the Telerik UI for Blazor components in a Blazor SPA that’s integrated into Views (or Razor Pages) in existing ASP.NET Core projects. Here’s everything you need to make that happen.

Real-world web applications integrate multiple technologies. Here's how to integrate ASP.NET MVC, HTML, CSS, Blazor, and the Telerik UI for Blazor components. Hey! At least you don't need JavaScript.

As I said in an earlier blog post, the real power of using controls like Telerik UI for Blazor is how those controls work together and how they work with ASP.NET Core. Before you start assembling your UI, you're going to need to assemble a project that lets you combine ASP.NET Net Views and Razor Pages, which is what this post is about.

In this column, I'm going to integrate a Server-Side Blazor (SSB) component into an existing ASP.NET Core project. With SSB, the component's code executes on the server based on information from the browser. As a result, reporting on the status of the server-browser connection must also be integrated into the solution.

Integrating Blazor and ASP.NET Core with Views or Pages

Adding SSB to an existing ASP.NET Core project requires some changes to the project. Those steps are:

  1. Add the latest version of the NuGet package, Microsoft.AspNetCore.Blazor to your project
  2. Add two folders to your project: (1) Components to the project's root, and (2) Pages to the Components folder
  3. Startup.cs: In the ConfigureServices() method, add this line at the start of the method:
services.AddServerSideBlazor();

In the Configure() method, add this line at the end of the body of the lambda expression passed to the call to the app.UseEndpoints() method:

endpoints.MapBlazorHub();

While I'll eventually be creating a View that hosts a Blazor component that forms my SPA, some things don't change. A ControllerAction() method that, for example, retrieves a collection of Customer objects and passes them to the View that will host my SPA, looks very familiar:

public IActionResult Index()
{
  IEnumerable<Customer> custs;
  custs = CustomerRepo.GetAll();
  return View(custs);
}

Integrating a View or Page

One critical caveat: While I'll talk exclusively about views in this section, everything discussed here would work equally well in a Razor Page. I just got tired of typing View or Page.

A View that works with Blazor requires some special support (in addition to doing the typical thing of a accepting the Customer collection created in the Controller's Action() method). First, I need the JavaScript library that supports my Blazor component communicating with my code on the server. To support the Telerik components, I also need that JavaScript library:

@model IEnumerable<BlazorFromMVC.Models.Customer>
<script src="~/_framework/blazor.server.js"></script>
<script src="https://kendo.cdn.telerik.com/blazor/1.1.0/telerik-blazor.min.js" defer></script>

To ensure that my grid displays correctly, I also need a Telerik cascading stylesheet (the funny syntax below is required to handle the @ symbol in the middle of the Telerik URL). I've also included a stylesheet with styles that I'll use when displaying HTML that notifies the user when the connection to the server is lost:

<link rel="stylesheet" href="https://unpkg.com/@("@")progress/kendo-theme-default@latest/dist/all.css" />
<link href="~/css/BlazorConnection.css" rel="stylesheet" />

All of these link and script elements could, of course, be put in the site's Layout View rather than repeated in each View or Razor Page.

To handle notifying the user about the connection status, I need an element with an id of “components-reconnect-model.” Blazor assigns a CSS class to this element when the SignalR connection to the server is lost. If the connection can't be re-established, Blazor assigns a different style. The Blazor JavaScript library includes a reconnect method that you can call to try and re-establish connection if Blazor is unable to reconnect, which I want to take advantage of. Here's some simple HTML and a script to handle all of that:

<div id="components-reconnect-modal" class="reconnect-block">
  <div class="reconnect-wait">
    Connection lost -- please wait, attempting to reconnect
  </div>
  <div class="reconnect-button">
    Unable to reconnect. Click to attempt to reconnect:
    <input type="button" value="Reconnect" onclick="Reconnect()" />
  </div>
</div>
<script>
  function Reconnect() {
    window.Blazor.reconnect();
  }
</script>

This is the BlazorConnection.css stylesheet I created to work with Blazor to display status messages about the connection status. It defines the styles used by Blazor (components-reconnect-hide, components-reconnect-show, components-reconnect-failed), along with rules for displaying/hiding the div elements in my View:

.components-reconnect-hide {
  display: none;
}

.components-reconnect-show {
  display: block;
}

.components-reconnect-failed {
  display: block;
}

.components-reconnect-show .reconnect-wait {
  display: block;
}

.components-reconnect-failed .reconnect-wait {
  display: none;
}

.components-reconnect-show .reconnect-button {
  display: none;
}

.components-reconnect-failed .reconnect-button {
  display: block;
}

I realize this displays my almost complete ignorance of CSS.

Within the View, you're ready to call a Blazor component (Customers.razor), passing the data the component needs (in my code below, I pass the Model property of the View). While the code must be included inside some element, the name of the element is irrelevant:

<custs>
  @(await Html.RenderComponentAsync<TelerikUi.Components.Pages.Customers>(new { custs = Model }))
</custs>

Integrating the Telerik Components

Finally, it's time to create the component. To add a component, right click on the Pages folder you added earlier and select Razor View (currently there is no template for a Razor component). Enter the name of your component file (which will also be the name of your component) and give it a file extension of .razor (Customers.razor).

Your component doesn't need a page directive because it's being called from a View. The component does, however, need a property whose name matches the parameter used in the RenderComponentAsync() call to pass data to the component (cust in my case). That parameter also needs to be decorated with the Parameter attribute as in this example:

@using BlazorFromMVC.Models

@functions
{
  [Parameter]
  private IEnumerable<BlazorFromMVC.Models.Customer> custs { get; set; }
}

Within the component, the simplest way to display the collection of customers is to use a TelerikGrid. To use that, you'll need to download the Telerik UI for Blazor installation package. Once that's downloaded and installed, you'll need to follow these instructions to add the Telerik NuGet feed to your NuGet Manager. After that, you can use NuGet manager to add the Telerik.UI.for.Blazor package to your project.

Within your project, to add the necessary Telerik classes to your project's dependency injection container, you'll need this line of code in Startup.csConfigureServices() method:

services.AddTelerikBlazor();

The last step before adding the Telerik is to return to your component's Razor file and add a using directive for the grid's namespace:

@using Telerik.Blazor.Components.Grid

With that in place, you can add your grid to your Blazor component. To get the grid to display your collection, you need to:

  1. Set the grid's Data attribute to the property holding the collection
  2. Define a column for each property of the objects in the collection that you want to display

I covered this in detail in an another post.

Here's an example for my Customers collection:

<TelerikGrid Data="@custs">
  <TelerikGridColumns>
    <TelerikGridColumn Field="Id" Title="Customer Id"></TelerikGridColumn>
    <TelerikGridColumn Field="FirstName" Title="First Name"></TelerikGridColumn>
    <TelerikGridColumn Field="LastName" Title="Last Name"></TelerikGridColumn>
  </TelerikGridColumns>
</TelerikGrid>

But, of course, as powerful as the TelerikGrid is, it's just the simplest possible user interface for displaying a collection. Creating a truly useful UI requires combining several components, as I'll demonstrate in my next posts. Stay tuned.


Accessibility and the Law

$
0
0

The web continues to evolve into dynamic environment that effects all aspects of our society, from online commerce to government services. Let's explore the development of accessibility laws and how they interact with web application development.

This is the part where I issue the disclaimer that I am not a lawyer and this is not legal advice. This is a collection of information that I have found while working with accessibility. Please consult with an actual lawyer if you have any specific legal questions.

The web continues to evolve from merely providing useful but essentially static information to a place where dynamic applications are widely present. This shift has spread to all aspects of our society and we now have online commerce (Amazon… need I say more?), online banking, online education (from product training to actual degree programs), online government (services, communication, applications, and even voting), and more including the delivery of basic communications and services.

Global Awareness

Along with this evolution has come a general awareness of the need to structure these services in such a way that they can be used by those with various disabilities. Laws and guidelines have been put in place by world-wide organizations like the United Nations as well as individual governments and even industries.

In 1982 the General Assembly of the United Nations adopted the World Programme for Action (WPA) concerning Disabled Persons. This was a global strategy to enhance disability prevention, rehabilitation, and the equalization of opportunities. The key here is the “equalization of opportunities.”

The Standard Rules on the Equalization of Opportunities for Persons with Disabilities, adopted by the UN in 1993, specifically added that the member states’ action programmes should include:

“Support for the use of new technologies and the development and production of assistive devices, tools and equipment and measures to facilitate access to such devices and equipment for persons with disabilities to enable them to gain and maintain employment”

These actions both reflect and helped drive further awareness of the need to provide access to technology, although at that time the full range of opportunities with the internet was still in the future.

Country and State Accessibility

There have been a number of standards created that describe policies and procedures to use when making the web more accessible. Most of these were sponsored by various governments, but the most widely used came from the Web Accessibility Initiative (WAI) which is part of the World Wide Web Consortium (W3C). The W3C is an international organization dedicated to developing open standards for the web.

The W3C lists 40 countries that have adopted governmental policies related to web accessibility and this is not even a complete list. Many use standards that they have developed, but many also have standardized on the Web Content Accessibility Guidelines (WCAG) which is the standard developed by the WAI. The WCAG has been approved as an international standard by the International Organization for Standardization (ISO) and the International Electrotechnical Commission (IEC). The WCAG is currently at rev 2.1 which was released in June of 2018. The WCAG is, by itself, a voluntary standard, but it has been referenced by a number of laws on accessibility.

The United Kingdom, for example, passed the Equality Act of 2010, which is a non-discrimination law that applies to both the public and private sections and is similar to the American ADA. The law is a broad non-discrimination law that replaces a number of earlier individual non-discrimination laws. It covers discrimination based on age, gender, race, religion, sexual orientation, and, of course, disabilities. This law does not directly specify the WCAG (or any other standard), but the UK Government Service Manual’s section on accessibility and assisted digital does specifically require WCAG 2.1 compliance for all government web sites.

Web Accessibility in the United States

In 1990, the Americans with Disabilities Act (ADA) was enacted to prohibit discrimination based on disabilities. This was an extension to the Civil Rights Act of 1964 which outlawed discrimination based on race, religion, sex, national origin, and other characteristics. The ADA made it also illegal to discriminate based on disability. What’s more, it required employers to provide reasonable accommodations to employees with disabilities, and it places accessibility requirements on public accommodations. The bill was later amended in 2008 with those changes going into effect in 2009.

In addition to the ADA, there are a number of other laws in the US that cover accessibility in various circumstances, including several sections of the US Rehabilitation Act of 1973 as amended, Section 225 of the Communications Act, and the 21st Century Communications and Video Accessibility Act of 2010, and more. In addition to that, a number of states have passed laws concerning accessibility as well. If that all sounds confusing, that’s because it is. However, the WCAG, when not specifically adopted, is generally considered to meet or exceed all of these requirements. And this is a good time to remind you that this is not legal advice and you should seek legal counsel if you have questions.

The other standard that you might hear about is Section 508 of the Rehabilitation Act mentioned above. The Rehabilitation Act was amended in 1998 to require Federal agencies to make their electronic and information technology (EIT) accessible to people with disabilities and was further updated in 2018 to meet evolving standards. Section 508 is now based on the WCAG 2.0 guidelines.

The Law in Action

We’ve taken a quick look at some of the laws that have developed concerning accessibility and websites. This can be confusing and unless you really know what you are doing in this area, it’s a very good idea to engage the services of a company that does have accessibility expertise to at least help train you dev team and review your work. In general, conforming with the WCAG will be a good start. But do you really need to worry about it, especially if you are not doing business with the government? The answer is a very clear “yes,” as a number of recent legal cases have shown.

According to a search of court cases conducted by Minh N. Vu, Kristina M. Launey & Susan Ryan of the law firm Seyfarth & Shaw, the number of lawsuits about website accessibility nearly tripled from 2017 to 2018 and hit a total of 2258 cases.

Some of these cases have received public attention as well and highlight not only the growing need to adhere to accessibility standards, but also the ongoing work that needs to be done in establishing clear rules. A recent case involving Domino’s Pizza saw the Ninth Circuit Court of Appeals issue a ruling that overturned a district courts dismissal of a suite in the favor of accessibility. The Ninth Circuit held that the ADA applies to services of a place of public accommodation, not just services in a place of public accommodation. Their customers access the website away from the physical location (the pizza shop). The initial suit claimed that Dominos website did not work with the customer’s reader software and so he could not order a pizza from them. This was argued to be a violation of the ADA…

Dominos website was weak in accessibility, and that limited access to their pizza services. Note that this is not the end of the case, and the Ninth Circuit’s ruling simply means the suit can continue now. But it is still a victory for accessibility.

Combining Components, HTML, and C# to Create an Effective UI

$
0
0

Creating an effective UI doesn’t require a lot of code – just integrating and customizing the right set of Telerik components. In fact, the only code required is a single property.

Creating useful web pages involves integrating multiple components and technologies. Here's how to integrate Telerik UI for Blazor components to create a master/detail page with multiple tabs and an animated display that only shows the details when requested (and with only one new line of code).

In an earlier post, I walked through the process of combining ASP.NET Core Views (or Razor Pages) with a Blazor component containing a TelerikGrid. In that scenario, using C# on the server, I retrieved a set of Customer objects that I then passed, through the Model property of a View, to a Blazor component that displayed a list of customers in a TelerikGrid.

Using this process, the page (including my Blazor component) is rendered to HTML on the server before being sent to the browser. The net result is that the user gets a complete page without having to wait for an AJAX call to fetch the page's data after the page is displayed.

In my case, however, each customer that I'm displaying in the grid owns two collections: a set of payments and another set of purchases. When the user clicks on a customer in the grid, I want to display the two lists of payments and purchases in tabs beneath the grid of customers. I also want to highlight the selected customer so that the user gets some feedback on which customer the display payments and purchases belong to.

But, once the page is displayed in the browser, I don't want to go back to the server unless I have to (AJAX and SignalR calls excepted, of course). A combination of HTML, Telerik components, and a little bit of code delivers all of that. I can even add some animation to my UI.

Sizing the Grid with HTML and Component Attributes

By default, the TelerikGrid takes up the full page with each column in the grid dividing the space evenly. I can customize that behavior by enclosing the grid in a <div> element and setting the width on that <div> element to 75% of the page. The grid will automatically size itself to fill all of the <div> element instead of the whole page.

Within the grid, I can use the same strategy with the grid's columns to control their size (using percentages, rather than fixed widths, allows the grid to adjust its size based on the width of the browser). The result is something like this:

<div style="width:75%">
  <TelerikWindowContent>
    <TelerikGrid Data="@custs">
      <TelerikGridColumns>
        <TelerikGridColumn Field="Id"
                           Title="Customer Id"
                           Width="16%">
        </TelerikGridColumn>
        <TelerikGridColumn Field="FirstName"
                           Title="First Name"
                           Width="42%">
        </TelerikGridColumn>
        <TelerikGridColumn Field="LastName"
                           Title="Last Name"
                           Width="42%">
        </TelerikGridColumn>
      </TelerikGridColumns>
    </TelerikGrid>
  </TelerikWindowContent>
</div>

Adding a Button to Trigger Displaying Details

In order to display the purchases and payment information for a specific customer, I need to give the user the ability to select a row in the grid. In an earlier column I took advantage of the grid's native events to implement a “select row” button. However, that involved invoking and then suppressing the grid's edit functionality. There's nothing wrong with that, of course, but it makes more sense to me to use a Telerik button that doesn't require me to suppress any behavior.

Normally, each column in the grid generates its own HTML. However, by inserting a <Template> element inside a <TelerikGridColumn> element, I can include pretty much whatever I want inside the column (if you don't believe me, see Ed Charbeneau's justly named post “Why Blazor Grid Templates Will Make You Question Everything”). I can even integrate C# into the template by flagging the code with an @ symbol.

Putting all that together, I can add a column to my grid containing a <TelerikButton> element with a click event handler that stuffs the row's context into a property called currentCustomer:

<TelerikGridColumn>
  <Template>
    <TelerikButton OnClick="@(_=> currentCustomer = (Customer) context)">
      Select
    </TelerikButton>
  </Template>
</TelerikGridColumn>

By the way: Be careful when entering the <Template> element. Currently, Visual Studio will attempt to “correct” the element name to use a lower case “t” and give you <template>; you may need to restore the uppercase “T.”

Now, I need to set up the currentCustomer property to hold the selected customer:

@functions
{
  private Customer currentCustomer { get; set; }

  // ...
}

Before leaving the customer grid, though, I should provide some feedback to the user on which customer is currently selected. A little bit of extra code in my template will let me set the Icon property on the <TelerikButton> element to show a checkmark when the customer current row's context property matches the customer in the currentCustomer property:

<TelerikGridColumn>
  <Template>
    <TelerikButton Icon="@(currentCustomer == context ? "checkmark" : "")"
      OnClick="@(_ => currentCustomer = (Customer) context)">
      Select
    </TelerikButton>
  </Template>
</TelerikGridColumn>

Displaying Multiple Tabs

To handle displaying and revealing the two grids showing payments and processing, I could enclose those grids inside a <TelerikWindow> element (as I did in an another post). But where's the fun in that? Instead, I can use the <TelerikAnimiationContainer> element to have my payments and purchases slide in in some cool way whenever the currentCustomer property isn't null:

<TelerikAnimationContainer Visible="@(currentCustomer != null)"
                           AnimationType="AnimationType.ZoomOut"
                           Width="100%"
                           Height="500px">
  // ... purchases and payments
</TelerikAnimationContainer>

Because I have two sets of data to display, I'll nest a <TelerikTabStrip> element inside the animation container with two tabs: one for each of my payments and purchases:

<TelerikAnimationContainer Visible="@(currentCustomer != null)"
                           AnimationType="AnimationType.ZoomOut"
                           Width="100%"
                           Height="100%">
  <TelerikTabStrip>
    <TelerikTab Title="Purchases">
      // ... purchases grid
    </TelerikTab>
    <TelerikTab Title="Payments">
      // ... payment grid
    </TelerikTab>
  </TelerikTabStrip>
</TelerikAnimationContainer>

Within each <TelerikTab> element, I can just drop another <TelerikGrid> element bound to the appropriate property on the currentCustomer property (purchases or payments). Here's the grid entitled, “Purchases” inside its tab as an example:

<TelerikTab Title="Purchases">
  <TelerikGrid Data="@currentCustomer.Purchases">
    <TelerikGridColumns>
      <TelerikGridColumn Field="Description" Title="Description">
      </TelerikGridColumn>
      <TelerikGridColumn Field="Price" Title="Price">
      </TelerikGridColumn>
      <TelerikGridColumn Field="Quantity" Title="Quantity">
      </TelerikGridColumn>
    </TelerikGridColumns>
  </TelerikGrid>
</TelerikTab>

I'd be the first to admit that's a lot of markup. However, it's not much code (all I had to add was the currentCustomer property). But, by integrating multiple components, HTML, and some code, I've got an effective UI out of it:

Of course, this page isn't much good without giving the user the ability to update this information, so I'll look at that in my next post. Stay tuned!

Telerik UI for Blazor 1.3.0 Is Here!

$
0
0

The Telerik UI for Blazor 1.3.0 release is already here! With it comes the new TreeView component, updated filtering options for the Grid, as well as improvements to other components like the DropDownList and DatePicker.

We are very excited to kick off July the right way: with a brand new release of Telerik UI for Blazor! With this most recent release, 1.3.0, we are providing a new component along with updates across existing UI widgets, all based on feedback that our users have been providing us. This is all a part of our continuous release cycle (see here in case you missed the 1.2.0 release) with quicker releases to provide you with constant updates. Blink and you might miss a release.

Without dragging the intro section along any further, let’s jump straight in to the new bits!

New Components

TreeView Arrives for Blazor!

Sample of the Telerik UI for Blazor TreeView showcasing a mix of expanded and collapsed nodes with icons and text

We are very happy to be able to say that the Telerik UI for Blazor TreeView has arrived! Even though this is the first release we have quite a lot of features to highlight and the component is in a great spot already.

Templates

Need to provide more in an item than we offer configuration options for? Or, just want an alternate layout for your TreeView nodes? The TreeView template feature allows you to provide custom templates within every node of the TreeView. You even have the capability to define this on a level-by-level basis, like we highlight in our TreeView template demo.

Hierarchical or Flat Data

What is a TreeView without its data? A big part of what we focused on with this initial version of the TreeView is to make sure you can properly data bind to the component. So, the Telerik Blazor TreeView can be bound to both flat and hierarchical data, giving you plenty of options for how to bind to the component. As a quick reference, here is the flat data demo and here is the hierarchical data demo just so you can compare the two approaches.

Lazy Loading

Speaking of data, out of the box we support lazy loading the various levels of the TreeView. This means that for large data sets you do not have to worry about loading all of that data at once. On initial page load only the root level will be loaded (unless you configured a node to be expanded initially). A particular node’s children will not be loaded until the node has been expanded by the user, giving you a performance-friendly experience.

Bindings

Going along with the data (since we are on a roll here) we should also mention the flexibility that we have baked in when it comes to bindings. As this demo showcases, we have some default field names that will automatically be picked up by the TreeView component if they exist on your model. This includes Id, Text, Items, ParentId, Icon, IconClass, ImageUrl, and HasChildren. If you do not want to transform your existing data to fit with these naming conventions you can simply work without TreeView bindings and define which fields within your model correspond to these properties the TreeView is expecting.

Best part about all of this? You can define these bindings on a per-level basis, so depending on where you are in the TreeView hierarchy you can define different bindings!

Feature Updates

Grid Filtering Gets a List

The Data Grid from Telerik UI for Blazor has supported filtering for a while now. However, filtering has been limited to more of an on or off interaction on a predefined filter type. Well, no longer! With 1.3.0 the Telerik UI for Blazor Grid now offers a built-in list that pops up when you click on the filter icon, allowing you to select what type of filtering you’d like to do on a particular column.

Telerik UI for Blazor Grid with filter list expanded providing options like contains, starts with, and others to be applied to current filter of a column

There’s still more to come for the Grid (and filtering) and while we have marked feature requests like this one as completed we aren’t stopping here! This is part of a continuing effort to evolve the Grid and its feature set to ensure that we can fulfill all of the requirements that your Blazor applications may have from a data table.

Making DropDowns and Popups Better

While this may not have been something apparent for everyone, working with popups in Blazor and Telerik UI for Blazor has been tricky. Specifically, the dropdowns and popups have been rendering in the place of declaration, which means that their containing / parent elements control them quite a bit. As an example, we have not been able to use our DatePickers or DropDowns in the edit templates of the Telerik Grid because the popup / dropdown will be hidden “beneath” the surrounding cells. This feedback item has a few good examples on what this has looked like so far.

Well, after a bit of research and some feedback around our approach we can finally say that we have a great solution in place for dealing with popups across all of our components. We have properly detached these popups from the component which allows them to appear freely without worrying about where they may have been added to the page (not just within the Telerik Grid). Here are some scenarios we can think of where this becomes a bigger deal:

  • Using the Telerik Blazor Grid and any custom editor that involves a popup like DropDownList, ComboBox, DatePicker, etc.
  • Any scenario where you need a component using a popup like a DropDown or DatePicker within an element that has overflow:hidden set.
  • Conflicts around z-index within your layout and DropDowns that need to appear above other elements within your application.

All of this is probably something that is taken for granted, especially if you’re coming from other web-based frameworks. With this improvement in place this means that we can continue to build these components without worrying about odd clipping issues here and there.

We Want to Hear from You!

That’s it for the 1.3.0 release! We’re already hard at work on 1.4.0, but in the meantime we want to hear from you and what features you’d like to see in a future release. If you have any feedback, or are missing certain components or features, head on over to our public feedback portal and let us know!

Accessibility is Patriotic!

$
0
0

The 4th of July is a celebration of the independence of America. Today we face a challenge to independence for some people who struggle to access information and service on the web. You can help keep the spirit of independence alive by making sure that your web apps are accessible to all. Find out how in this post.

Over 200 years ago the colonists in American got tired of taxation without representation and got into a bit of a scrap with England. So was born the United States of America and we celebrate our independence this week on the 4th of July. We shoot off fireworks to remind us of the cannon fire in the battles. We grill hamburgers and hot dogs to remind us of… well... lunch I guess.

But in the midst of all the fun, let’s take a moment to pause and reflect on the values that America was founded on. Core to this was the belief that all men are created equal. It was based on the idea that people should not be put at a disadvantage, that everyone should have a voice, basic freedoms, and an equal voice in the government.  And yes, before someone points it out, the term “men” has been broadened a bit to mean “people” today but the basic concept remains the same. We are all equal, no one should be denied Life, Liberty, or the Pursuit of Happiness.

Good so far, but the world was a very different place in 1776. Money was actual physical money. Banking, if you did it at all, was conducted in person. You showed up at a bank and gave them money, or they gave you money. They physically handed it to you. If you needed to deal with the fledgling government for something, you went to them in person and talked to them in person. Possibly you wrote them a physical letter. Maybe. But no texting or emailing or surfing.

And I know this because I was there – see below? That’s me marching to Concord, MA in 1775 to help defend it from the British.

Picture of colonial re-enactors marching 

O.K. That picture isn’t really from the 1700s, but that is me in the picture. I used to play drums in a colonial re-enactment company and that was us marching to Concord, MA as part of our yearly re-enactment of the march to the Battle of Concord (Shout out to the Stow Minutemen)

But I digress.

Things are very different today. Today you email, or text, or surf the web to interact with a bank, or the government, or to order pizza. And this has given rise to another problem with guaranteeing equality: equal access to information and services. What if you can’t easily surf the web? Well, no banking for you! No government for you! And, maybe worst of all, no pizza for you! And that’s no good. So if we really care about equality, we need to care about equal accessibility for all. If you are denied access to basic services because you have trouble navigating the web, then you are not being treated equally.

Why does this really matter? Is it so important that people with disabilities can access websites? Actually yes. First of all, it’s just not nice to say that some group of people don’t matter so who cares if they can access your website. Second, they are prospective customers. Do you really want to ignore part of your audience? Most importantly, web access is not just a convenience. There are more and more things that can only be done online today.  There are an increasing number of activities that are critical to living your life and that can only be done online. If you can’t access the web it’s not just cat videos you are missing out on, it’s paying your utility bills, filing your taxes, and making appointments.

Unfortunately, our forefathers did not have the presence of mind to specifically include internet accessibility as part of the declaration of independence. I’m sure that was just an oversight. They probably assumed that well designed and developed apps would just be obviously part of the equality they talked about and they didn’t need to state it explicitly. Today, just to make sure that the founders' wishes were carried out we have legal rules like the Americans with Disabilities Act that does cover accessibility on the internet.  It’s not just about being a good person, it’s also about not ending up in court.

This is not a lot of work, nor is it brain surgery. Everyone can make their websites accessible. It just takes a little bit of knowledge and a little bit of attention. And you know what? Most of what you will do to make your app accessible will usually make it more usable for everyone. So don’t think of accessibility as something you “have to do,” think of it as another step in giving your users a great experience.

In honor of the 4th of July, make a resolution this year to celebrate the founding of America with a pledge to get better about accessibility. Help do your part to make sure that all people are not just created equal, but they are treated equally and have equal opportunities in life.

“But John,” I hear you say, “how can I do that?”

Well, I’m glad you asked that! The best place to start is with a comprehensive guide to accessibility that covers the laws you need to be aware of, what you need to do, and shows you how to do it. By an odd coincidence, we happen to have recently published one! We wrote it in partnership with the user experience experts at truematter, as well as a number of other accessibility consultants. You can get it here:

Download the whitepaper on Accessibility for Developers

Want a quick tip? One way to get a head start on making your app accessible is to use UI components that already have accessibility built into them. By another amazing coincidence, we also happen to have just such a set of awesome UI components called Kendo UI. It includes a large set of popular UI components from Grids and Charts to Drop-downs and Schedulers. They come in all your favorite flavors, including jQuery, Angular, React, Vue, and Peppermint. OK, I made that last one up although I’ll bet someone somewhere does have a Peppermint JavaScript library.

Take a look at Kendo UI – there is even a free 30 day trial (with full support) available!

Check out Kendo UI 

So this 4th of July be patriotic and make your apps accessible. And if you are not American, then just do it to help celebrate equality and independence on the internet. Because those are good things, whether it’s 1776 or 2019.

How to Make Working with PDFs in a Xamarin Application Easy

$
0
0

Learn how you can use PdfProcessing in your Xamarin or .NET Core application to easily manipulate PDF documents.

If you are familiar with our web and desktop suites, you most probably have heard about the Telerik Document Processing libraries we provide with the packages. During the last release, we worked hard to port the library enabling you to work with PDF documents – RadPdfProcessing– to .NET Standard. The new binaries are shipped for the first time with Telerik UI for Xamarin. You can now create, modify and export PDF files within your Xamarin application.

In case you still haven’t met the API of this component and haven’t worked with it, I will show you some of the basic and most used features and how you can utilize them.

Start from the Basics

To start working with a document, you will need to first instantiate the RadFixedDocument class. There are two approaches to achieve that, depending on whether you would like to create a document or edit an existing one. For the first scenario it's enough to just instantiate a RadFixedDocument:

RadFixedDocument document = new RadFixedDocument(); 

When you already have a PDF document and need to translate it to a RadFixedDocument, the PdfFormatProvider class comes to help you do that:

RadFixedDocument document;
using (var stream = File.OpenRead(pathToExistingDocument))
{
Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider provider = new Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider();
document = provider.Import(stream);
}

Have You Ever Seen a PDF Document without at Least a Page? No? Me Either

The RadFixedDocument class exposes the Pages collection allowing you to add, remove and iterate the pages inside the document. Here is how you can add an empty page to a document:

RadFixedPage page = document.Pages.AddPage(); 


And if you already have the pages, you can iterate them as you would do with any collection:

 foreach (var page in document.Pages)
{
// Modify the page...
}

Let’s Edit It

No matter if you create the document from scratch or just modify an existing one, in both cases you will need to interact with the content and most probably add something additional. Here comes the FixedDocumentEditor class which allows you to draw content and control its positions in the fixed document.

Let’s start by creating an editor. The constructor requires a parameter of type IContentRootElement, which will be our RadFixedPage:

FixedContentEditor editor = new FixedContentEditor(page); 

I am now going to define several fields so I can use them across the class for easier position tracking:

private static readonly double defaultLeftIndent = 50;
private static double currentTopOffset = 120;

Now we have everything defined to start drawing our content. In the following code snippet, I will introduce you the Block class. This class is responsible for making easy the basic layout of text. It might sound like something pretty simple but in the PDF document format only text fragments are supported. In other words, if you pass some long text, it will be just clipped by the boundaries of the page. When using the Block class, it can measure the content and arrange it on different lines so that all the content can be visible when rendering the page.

double currentXOffset = defaultLeftIndent;
editor.Position.Translate(currentXOffset, currentTopOffset);
Block block = new Block();
block.GraphicProperties.FillColor = RgbColors.Black;
block.HorizontalAlignment = HorizontalAlignment.Left;
block.TextProperties.FontSize = 14;
block.TextProperties.TrySetFont(new FontFamily("Helvetica"), FontStyles.Italic, FontWeights.Bold);
block.InsertText("RadPdfProcessing");
block.TextProperties.TrySetFont(new FontFamily("Helvetica"));
block.InsertText(" is a document processing library that enables your application to import and export files to and from PDF format. The document model is entirely independent from UI and allows you to generate sleek documents with differently formatted text, images, shapes and more.");
// Define a size in which you would like to accommodate the content
double maxWidth = page.Size.Width - defaultLeftIndent * 2;
Size contentMaxSize = new Size(maxWidth, double.PositiveInfinity);
editor.DrawBlock(block, contentMaxSize);
currentTopOffset += block.DesiredSize.Height;

Are you curious about what this content looks like? I will show you an image of the current result but in case you would like to test it, at the end of the post you will find how to save the file. 

RadPdfProcessing Content-1

Yeah, we have some content inside our document. But… it looks a bit… let’s say simple, doesn’t it? Here comes the time to introduce the logo of the library to you. And, of course, the API for inserting images:

editor.Position.Translate(300, 40);
ImageSource source = new ImageSource(File.OpenRead(@"../../pdfProcessing.jpg"));
editor.DrawImage(source);

It is simple like that – define the image source and draw it on the page. And voila! Now we have an image on the top of the page, like you would insert it in the header of a rich-text document.

RadPdfProcessing Content-2

The next shiny functionality I would like to show you is the drawing of tables. In the PDF format, there is no concept for similar elements – they are defined as a bunch of lines and text fragments. That is why generating a table using the PDF primitives is not a trivial task. PdfProcessing makes it easy, though. This is what the code would look like if you need to insert a table with several rows and columns:

Table table = new Table();
table.Margin = new Thickness(0, 20, 0, 0);
table.DefaultCellProperties.Padding = new Thickness(5);
Border border = new Border(1, RgbColors.Black);
table.DefaultCellProperties.Borders = new TableCellBorders(border, border, border, border);
for (int rowIndex = 0; rowIndex < 10; rowIndex++)
{
TableRow row = table.Rows.AddTableRow();
for (int columnIndex = 0; columnIndex < 5; columnIndex++)
{
TableCell cell = row.Cells.AddTableCell();
Block cellBlock = cell.Blocks.AddBlock();
cellBlock.InsertText($"Row {rowIndex}, Cell {columnIndex}");
}
}
editor.Position.Translate(currentXOffset, currentTopOffset);
editor.DrawTable(table);
// Keep the position up to date
currentTopOffset += table.DesiredSize.Height;

RadPdfProcessing Content-3

Do You Want to be Interactive?

At this point, we discussed the most recently used and basic elements in a PDF document. Are you curious about the more advanced options the PDF format provides? The Interactive Forms are one of the most used features of the format and are supported by our library as well. You can create a document from scratch and use the forms to allow the users enter their data or import an existing document and change the values of the forms inside. For a full list of the supported form fields and more details about the API, you can check our Interactive Forms Overview documentation article. If you would like to directly test the feature and dive into the code, our SDK examples are a good starting point to do so: Create Interactive Forms and Modify Forms.

And let’s see some code for inserting a Text Box field with an initial value in our sample document:

TextBoxField textField = document.AcroForm.FormFields.AddTextBox("SampleTextBox");

textField.MaxLengthOfInputCharacters = 500;
textField.IsMultiline = true;
textField.IsPassword = false;
textField.IsFileSelect = false;
textField.ShouldSpellCheck = true;
textField.AllowScroll = true;
textField.Value = "Sample content";

currentTopOffset += 20;
editor.Position.Translate(currentXOffset, currentTopOffset);

editor.DrawWidget(textField, new Size(200, 25));

Interactive text box form in a PDF document

Preserve Your Data

Once you are done with the generation and modification of the content, you will need to save it. This is achieved through the PdfFormatProvider class and its methods allowing you to export the document to a Stream instance or to a byte[].

using (Stream stream = File.OpenWrite("sample.pdf"))
{
Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider pdfFormatProvider = new Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.PdfFormatProvider();
// Save the document to a Stream
pdfFormatProvider.Export(document, stream);
}

That’s it! Now you have a PDF document using the most popular of the format’s functionalities.

Conclusion

Working with PDF documents is now easier with the functionalities and API provided by RadPdfProcessing. You can quickly generate or modify documents as well as fill their form fields or protect the data with a password.

In this post I showed only the most used functionalities. PdfProcessing, however, can cover many more cases. Check our documentation for a full list of the supported features and elements. And don’t forget that all of that is .NET Standard 2.0 compatible so you can run it on any platform supporting it.

If you have any questions for the team, feel free to post your comments here. In case you need more technical assistance, you can always open a support ticket or post in the forums. The same folks who build the components also answer the questions from our customers. As always, we will be more than happy to also hear your feedback for the components.

Still haven't tried Telerik UI for Xamarin? The free trial is right here waiting for you to give it a try and explore all the components provided in the suite.

C# 8: Static Local Functions and Using Declarations

$
0
0

The next major version release of the C# language (C# 8) comes with exciting new features. Let's look at two new features in C# 8, static local functions and the using declaration.

In this post, we'll explore the new static local functions and the using declaration. If you want to try out these features, you’ll need to install .NET Core 3 and set your project to use C# 8. I talked about how to do those in my previous post.

Static Local Functions

Local functions enable you to declare methods inside the context of another method. This makes it easier for readers of the class to know that the local method is only called from the context in which it is declared. This gives you a better place to write methods that are called from only one location and to write code that looks like this:

public string MethodWithLocalFunction()
{
  string firstname = "Hiccuo";
  string lastname = "Mauritius";
  return LocalFunction();
  string LocalFunction() => firstname + " - " + lastname;
}

Local functions automatically capture the context of the enclosing scope to make any variables from the containing method available inside them. This feature was added in C# 7.0, and in C# 8, you can declare a local function as static by adding the static modifier. By adding this, you ensure the local function doesn’t reference any variables from the enclosing scope. By adding this to the code snippet from before, you’ll hereby pass firstname and lastname as parameters.

public string MethodWithLocalFunction()
{
  string first = "Hiccuo";
  string last = "Mauritius";
  return LocalFunction(first, last);
  string LocalFunction(string firstname, string lastname) => firstname + " - " + lastname;
}

Using Declaration

The using statement in C# provides a convenient syntax that ensures the correct use of IDisposable objects. C# 8 gives you an alternative which is using declaration. A using declaration is a variable declaration preceded by the using keyword. When the variable goes out of scope (i.e. the containing block of code is exited), the Dispose method will automatically be called for that object. The following example reads a file and uses the using declaration.

void ReadFile(string path)
{
  using FileStream fs = File.OpenRead(path); // using declaration
  byte[] b = new byte[1024];
  UTF8Encoding temp = new UTF8Encoding(true);
  while (fs.Read(b,0,b.Length) > 0)
  {
    Console.WriteLine(temp.GetString(b));
  }
  // fs is disposed here
}

In this example, the variable fs is disposed when the closing brace of the method is reached.

Conclusion

C# 8 comes with interesting features, and, in this post, I wrote about using declaration and static local function. The using declaration allows you to declare variables preceded by the using keyword and the compiler will generate code to call Dispose() when the object gets out of scope. The static keyword can now be added to a local function declaration, making it such that any variable from the enclosing scope cannot be referenced inside the local function. These are interesting features coming in C# 8.

Types of Disabilities and User Experience

$
0
0

For technology to lower barriers for people with disabilities, accessibility must be built into the user experience. To understand accessibility, we'll discuss different types of disabilities, and how they can affect the user experience.

We all know that technology lowered many barriers for people all around the world. It enabled us to have superpowers our ancestors would have craved for. You probably booked a ride with your phone this month or talked with people living in another country through your favorite messaging app.

It is also true that technology helps to lower barriers for some people who have disabilities, but here is the catch: This is only the case when accessibility is built into the user experience.⚠️

Accessibility simply means that websites, tools, and technologies are designed and developed so that people with disabilities can perceive, understand, navigate, and interact with them but also contribute to them [1]. ‍

But in order to understand accessibility, a first important step is to discuss the different types of disabilities users might have. We will also try to understand what a person with a disability experiences when dealing with computers or web-based interfaces. ‍‍

Mobility or Physical Impairments ✋

Mobility or physical impairment refers to weakness, limited ability and inability to independently use one’s body or one or more of his/her extremities. It ranges from lower body impairments to upper body impairments, and includes:

  • Weak / limited muscular control (for instance, tremors, lack of coordination, paralysis, muscular dystrophy, tremor and spasms, repetitive stress injury)
  • Limited sensation
  • Joint disorders (such as arthritis)
  • Pain impeding movement (like fibromyalgia)
  • Missing limbs (such as from amputation)

We usually think of mobile impairments as permanent conditions only, but they can also be temporary – when a bone is broken, for example. Keep in mind that many seniors are also prone to mobility impairments.

NOT implementing accessibility impacts the experience of mobility impaired users in the following ways:

  • Inability to access full features and navigate interfaces when full keyword support is not provided
  • Not completing tasks because of time limits (like filling out online forms)
  • Getting stuck and not accessing the full features of an interface when navigation mechanisms are too complicated or not easily accessible
  • Making it painful to use a mouse for extended periods of time when keyboard commands are not enough to navigate

Hearing Impairments

Hearing impairments include:

  • Mild to moderate hearing loss (hard of hearing)
  • Substantial to uncorrectable hearing loss (deafness)

Something to keep in mind is that there isn’t one single sign language, but hundreds of sign languages used throughout the world. Interesting enough is the fact that not everyone who suffers from an auditory impairment knows sign language.

Today’s interfaces are increasingly relying on multimedia, so when captions (or transcripts) are not provided, content becomes simply inaccessible for people with hearing impairments.

Also, you should keep in mind that audio content with too much background noise is extremely challenging to understand for people with mild to moderate hearing impairment.

Visual Impairments ️

Visual impairment covers a wide range of conditions:

  • Low vision (short or long sightedness, blurred vision)
  • Total blindness
  • Colorblindness

For low-vision users, there are a few no-no’s that make their life really difficult when using a computer:

  • Text that cannot be resized.
  • Fonts that are too small or too hard to read. Some web fonts have been specifically designed for readability (like Inter UI), so make sure you choose the right one.
  • Insufficient color contrast (like text color versus background color for your buttons). (This can mean different things to different users – some users need high contrast, while others need low contrast. This is why it’s important to provide adequate markup, so users have multiple options for accessing content.)
  • Busy page backgrounds (be it patterns or even just too many ads on the page).
  • Solely relying on color to convey meaning.

Many people assume that blind people just aren’t able to use the internet. Well, there are ways that enable them to effectively use a computer. Namely, a screen reader or a braille display. The latter is more appropriate for deaf-blind users… but also more practical for our blind programming comrades.

# Refreshable braille display

However, the following things make it complicated to rely on the tools they have:

  • Not providing appropriate alternate text to images
  • Poorly marked-up pages
  • Relying on the use of Java or Flash functionalities
  • Being able to navigate only through a mouse (a mouse requires hand-eye coordination, so even if the person is using a screen reader it becomes useless when keyboard commands are not enough to navigate)

Most of us think that colorblindness means only seeing in black and white, but that is just another misconception. Note that there are different forms of color blindness that encompass the inability to:

  • Distinguish between red and green
  • Distinguish between yellow and blue
  • Perceive any color

Colorblind people do not require extraordinary accessibility functions, but there are two things (that they also share with low-vision users) which make it really hard for them to navigate the web:

  • Insufficient color contrast (like for text versus background color on buttons)
  • Solely relying on color to convey meaning

And by the way here is a fun fact: Do you know why Facebook is blue?

According to The New Yorker, Zuckerberg is red-green colorblind, which means the color he can see best is blue. That also happens to be the color that dominates the Facebook website and mobile app. “Blue is the richest color for me,” he told the magazine.
Source: Why does Facebook have a blue color scheme?

Cognitive, Learning, and Neurological Disabilities

Cognitive, learning, and neurological disabilities impact how a person:

  • Hears and/or understands information
  • Moves
  • Sees
  • Speaks

Some of these disabilities include:

  • Attention deficit hyperactivity disorder (ADHD)
  • Mental health impairments (anxiety, delirium, depression, paranoia, schizophrenia, to mention just a few)
  • Learning disabilities that impact reading (dyslexia), writing (dysgraphia), processing number (dyscalculia), or space-time orientation
  • Short or long-term memory (caused by dementia for instance)
  • Autism spectrum disorders (autism, Asperger’s, pervasive development)
  • Down syndrome (that causes learning impairment)
  • Seizure disorders (such as epilepsy and migraines)
  • Multiple sclerosis (causes nerve damage to the brain and spinal cord extending to other motor and sensory functions)

There is this strange assumption that people with cognitive, learning, or neurological disabilities are somehow less intelligent or do not need tech features like those without disabilities. For you, it may seem ludicrous to think like this, but in many communities this thinking is very common.

In an era in which technology is here to help people advance in life and bring value to one another, technology is a right, and inaccessibility is discriminatory. In certain circumstances, inaccessibility limits a person’s potential.

That being said, from mild to life-changing cognitive or neurological disorders, everyone’s needs should be accounted for. Things like the issues I’m citing below add additional barriers to those who have these disorders.

  • Uneven gaps between words, very small font, and pure white page backgrounds
  • Unstructured or verbose content
  • Unpredictable functionalities and inconsistent labeling
  • Poor navigation options or complex navigation mechanisms
  • Distracting content, overly stimulating visual flickering and audio signals at certain frequencies or patterns

My Take

Going through the different types of impairments and the number of barriers people face, you quickly get to understand that accessibility is not just essential for many people but actually useful for all of us. [2]

A lot of the challenges people with impairments encounter are actually unacceptable in a modern society like ours. That’s why I believe that, at the end of it all, accessibility has a lot to do with good and well-thought-through UX/UI design.

Cited Sources:

[1] Source: W3 - Introduction to Web Accessibility www.w3.org
[2] Source: W3 - Web Accessibility Perspectives www.w3.org

Additional Sources:

W3C Web Accessibility Initiative - Diverse Abilities and Barriers www.w3.org
Joe Clark - Building Accessible Website: How do disabled people use computers? www.joeclark.org
Disabilities, Opportunities, Internetworking, and Technology (DO-IT) www.washington.edu
Disabled World - Disabilities: Definition, Types and Models of Disability www.disabled-world.com
Coolfields Consulting - Web Accessibility: types of disability. www.coolfields.co.uk


To Learn More about Accessibility

We have created a comprehensive whitepaper on accessibility for developers that covers everything from laws to coding to testing. 

Download the whitepaper: Accessibility for Developers

Adding Accessibility to Your Apps

One easy way to make sure that you are creating accessible web apps is to start with components from the Kendo UI libraries. Our components are all WCAG compliant and  give you great functionality from grids and charts to schedulers and pickers. Get a head start on your apps UI and a head start on accessibility compliance at the same time. 

Learn more about: Kendo UI


The International Accessibility Standards You Need to Follow

$
0
0

American web accessibility standards are often top of mind for most developers, but the United Nations, European Union and many nations have their own laws and policies. Read more about how to develop international accessibility standards in this blog post.

As a web developer, you’re likely familiar with the concept of web accessibility: designing web services or environments for use by people who experience disabilities. Web accessibility allows everyone, including those with disabilities, access to web content and the internet as a whole. With the internet’s increasing importance in so many aspects of life, an accessible web helps people with disabilities participate more actively in society.

While American web accessibility standards are often top of mind for most developers, they aren’t the only standards. The United Nations has its laws and policies, as do the European Union and many of its member countries. Australia, New Zealand, Canada, Israel, and other nations have also passed comprehensive regulations. You can find a good list of policies organized by country on this page of the World Wide Web Consortium (W3C) website.

International Accessibility Standards

The most effective way for you as a developer to maximize compliance is to start by observing worldwide regulations, as individual countries tend to base their regulations on global agreements. After this, take into consideration local regulations where the majority of your user base resides. Complying with every single regulation is practically impossible, but it is important to understand and adhere to the most important regulations, both global and local.

Which regulations take priority? In a global context, the best strategy to increase your international accessibility compliance is to understand and follow the Web Content Accessibility Guidelines (WCAG) 2.0 and Articles9 and 21 of the Convention on the Rights of Persons with Disabilities (CPRD). Let’s go through these three specifications one by one.

The WCAG 2.0

First is the WCAG, a set of guidelines developed in cooperation with individuals and organizations around the world using the W3C’s process. Its goal is to provide a single common standard for web content accessibility. When properly implemented, the guidelines make your applications and content perceivable, operable, understandable, and robust for all demographics. Most other standards in use by the EU and its member countries already are or will soon be in line with the WCAG 2.0. The Laws and Policies page on the Web Accessibility Initiative website has a list of all countries where the national web accessibility regulations are based on the WCAG. This page has a list of EU countries where the web accessibility legislation has already been ratified. For more detailed information, read the EU directive on making the websites and mobile apps of public sector bodies more accessible.

Article 9 of the CPRD

The second standard that’s important to adhere to is Article 9 on Accessibility from the Convention on the Rights of Persons with Disabilities (CRPD). Most countries have signed, though not ratified, the CPRD. It comes after decades of work by the United Nations to change attitudes and approaches to persons with disabilities. The document is intended to be a human rights instrument that clarifies and details all the rights granted to persons with disabilities. It identifies situations where persons with disabilities would require allowances to effectively exercise their rights, where their rights have been infringed upon, and where the protection of their rights must be reinforced. Every signatory to the CPRD will eventually develop legislation to support the article’s action items and those of other articles in the convention. From Article 9 specifically, we can identify some action items that apply directly to software accessibility.

For one, it’s vital for your organization to learn about the specific issues that persons with disabilities may encounter when using your software. The article also mandates support for those with disabilities by training your staff on these needs and challenges, sharing this information within your organization, and adapting your product accordingly. Last but not least, Article 9 directs you to start considering accessibility in the early stages of developing your products.

Article 21 of the CPRD

You can further improve your compliance with international accessibility by following another article of the CPRD, this time Article 21 - Freedom of expression and opinion, and access to information. Specifically, this regulation mandates that you provide content in different formats promptly and at no extra charge. It also directs you to make your formats accessible by providing text alternatives to audio and visual content and by using open formats whenever possible. In so doing you ensure that persons with disabilities can exercise their right to “seek out, receive, and impart information and ideas on an equal basis with others.”

Country-Specific Standards and Legislation

Many countries have more specific web accessibility legislation. Most of the web accessibility laws around the world either reference the WCAG or are based on it. Here is the summary of the legislation in a few English-speaking countries.

Australia

The Disability Discrimination Act of 1992 has been most recently amended in 2016. The regulations apply both to the public sector and private companies. This law disallows the discrimination on the grounds of disability and applies to many parts of life, including education, employment, and access to information and services. In addition, the government agencies in Australia are now required by the procurement standards to only purchase services and products that comply with the accessibility standards that are used in the EU.

Canada

The Standard on Web Accessibility covers all government websites and requires them to comply with the WCAG level AA. The Canadian Human Rights act makes it illegal to deny services, facilities, and products to disabled persons on the grounds of disability. The act also applies to web-based services and products.

Ireland

Ireland prohibits discrimination on the grounds of disability when it comes to products and services in the Equal Status Act of 2000. The Disability Act of 2005 obliges the government bodies to make their services accessible to all.

The United Kingdom

The Equality Act of 2010 tasks the government agencies in the UK with eliminating discrimination in all parts of life, including access to information. The Disability Discrimination Act from 1995 makes it illegal to discriminate against disabled persons, both for public agencies and private companies in areas like education, employment, and access to facilities and services.

Investigate Local Regulations for the Top 5 Countries where Your Audience Resides

In addition to becoming familiar with these three documents that define international accessibility compliance, the WCAG 2.0 and Articles 9 and 21 of the CPRD, it’s also crucial to inform yourself about local regulations in the top 5 countries where your audience is located, because they may well include mandates not covered at the global level. So how can you go about researching these local regulations?

Start by checking local government websites, and keep an eye out for organizations or agencies whose charters involve technology and inclusivity. Specifically, consider standardization agencies and any ministry or department of technology in the primary countries where your users resides. It’s also a good idea to seek advice from a qualified accessibility consultant in the area in question; they’re bound to have deep, detailed, and accurate insight into the accessibility issues specific to their region.

Another approach is to seek out organizations and events that have a diverse development or design community with whom you can network and inquire about accessibility issues. Don’t forget the possibility of design schools and their course offerings; they might also have ongoing events or information sessions on the topic of accessibility in your own country or region.

Conclusion

Many websites and tools, even those developed recently, have barriers to accessibility that make them difficult or impossible for some people to use. For responsible web developers to lift these barriers, it’s important to consider not only American accessibility standards, which tend to loom largest for many, but also other regulations that exert a lot of influence over accessibility standards worldwide. The UN itself as well as the EU, its member countries, and many others across the world have their own regulations, comprehensive and wide-ranging. Although it’s not feasible to observe every regulation that exists, it’s possible and indeed practical to understand which ones to comply with first, on both global and local levels.


To Learn More about Accessibility

We have created a comprehensive whitepaper on accessibility for developers that covers everything from laws to coding to testing. 

Download the whitepaper: Accessibility for Developers

Adding Accessibility to Your Apps

One easy way to make sure that you are creating accessible web apps is to start with components from the Kendo UI libraries. Our components are all WCAG complaint and give you great functionality from grids and charts to schedulers and pickers. Get a head start on your apps UI and a head start on accessibility compliance at the same time. 

Learn more about: Kendo UI

C# 8: Indices and Range

$
0
0

The next major version release of the C# language (C# 8) has some exciting new capabilities. Let's look at the hat and range operators, two new features in C# 8.

C# 8 comes with interesting features, and, in this post, I'm going to talk about default interface implementation: the hat operator (^) and the range operator (..). I have previously written about some other top C# 8 features, so for more feel free to check out my posts on nullable reference types, static local functions, and the using declaration.

Introduction

The hat operator (^) and range operator (..) provide a different syntax for accessing elements in an array: Span, or ReadOnlySpan. The range operator is used to specify the start and end of a range for a sequence.

Let's look at some examples. Consider the following code where you have an array of strings and you want to get the first four elements:

static void Main(string[] args)
{
  var people = new string[] { "Jane", "Jean", "Grey", "Marcus", "Theophilus", "Keje" };
  var firstFour = GetFirstFourPersons(people);

  foreach (var person in firstFour)
  {
    Console.WriteLine(person);
  }
}

static string[] GetFirstFourPersons(string[] people)
{
  var result = new string[4];
  for (int i = 0; i < 4; i++)
  {
    result[i] = people[i];
  }
  return result;
}

// result:
// Jane
// Jean
// Grey
// Marcus

We can rewrite it using the range operator, passing the range operand inside [ and ].

static void Main(string[] args)
{
  var people = new string[] { "Jane", "Jean", "Grey", "Marcus", "Theophilus", "Keje" };
  var firstFour = people[0..4];

  foreach (var person in firstFour)
  {
    Console.WriteLine(person);
  }
}

This gives the same result as the previous example. Before and after the .. operator are the start index and end index from which to get a sequence of data. It doesn't include the element in the end index as part of the result.

The range can also be open-ended. That means you can omit the start index, end index or both.

var all = people[..]; // contains all the elements from the origin array
var firstFour = people[..4]; // contains "Jane", "Jean", "Grey", and "Marcus"
var lastTwo = people[4..]; // contains "Theophilus" and "Keje"

The all variable is open-ended on both ends and therefore returns all the elements. It can also be written as var all = people[0..people.Length]. If you omit the start index, it'll use 0 as the start index, and if it's the end index, it'll use the value sequence.Length to resolve the value.

You can also declare range variables:

Range firstFourRange = ..4
var firstFour = people[firstFourRange]; // contains "Jane", "Jean", "Grey", and "Marcus"

With C# 8, you can now specify that an index is relative to the end of the array. You do this using the ^ operator. Given the array people, we can get the last element in the sequence using people[^1]. The ^0 is the same as people.Length. So if you use people[^0] to get the last element of the sequence, you'll get an exception because it's outside the allowed range. We can use this with the range operator:

Range lastTwoElement = ^2..
var lastTwo = people[lastTwoElement] // contains "Theophilus" and "Keje"

This will give us the last two names. Omitting the end index translates to using ^0 (i.e. people.Length) as the end index. We can also assign the index to a variable:

Index lastIndex = ^1;
string value = people[lastIndex];

This language support is based on two new types, System.Index and System.Range. The Index type represents an index into a sequence, and the Range type specifies a sub-range of a sequence.

Wrap Up

So many exciting new features are coming to C# 8. They include features such as readonly members, nullable referencesstatic local functions, using declaration, and new operators for working with indices and range. I've written about some of these features, and you'll find the links above. In this post, I talked about indices and ranges. Working with the hat and range operators. I used a basic example to show how you can use the hat operator to specify indices relative to the end of the sequence, as well as using the range operator to get a sub-range of a sequence.

The WCAG: Accessibility Regulations You Need to Know

$
0
0

In this era ruled by digital information, it’s vital to make sure that the internet’s vast wealth of knowledge is accessible to as many people as possible. This article explains how adherence to the Web Content Accessibility Guidelines, or WCAG, helps you get closer to that goal.

What is the WCAG?

The WCAG offers a foundation for the legal standards that nations all around the world use to enforce accessibility requirements. It’s the basis for many laws, acts and national standards across the globe. For example, the US policy regarding web accessibility, the Section 508 Standards, relies on the WCAG version 2.0. The EU accessibility directive also references the WCAG and applies to all 28 EU countries. For a full list of policies anchored by the WCAG, visit the W3C website.

The goal of these guidelines is to provide a single shared standard for web content accessibility that meets the needs of individuals, organizations, and governments across the globe. The WCAG addresses accessibility for all material that appears on a web page or in an application, including text, images, sounds, code, and markup.

In short, the WCAG exists to ensure that as wide an audience as possible can access and consume your online content, irrespective of ability.

Why Comply with WCAG?

The W3C policies page lists 25 different regulations that rely on WCAG. In addition to the Section 508 standards and the EU accessibility directive, national laws in 19 different countries are based on the WCAG and, therefore, require you to comply with the WCAG to comply with the law.

For example, these are some of the laws, regulations, and policies that rely on the WCAG:

All these regulations apply to both the public and private sectors. Breaking these and other laws can lead to fines, administrative charges, and even criminal charges in some countries. For example, a company in Ontario, Canada, might be fined up to CAD $100,000 per day for not complying with the accessibility standards. In Israel, discriminating against a person with a disability is a ground for criminal proceedings.

With accessibility legislation evolving, not complying with the accessibility laws is not an option anymore. Many businesses and public bodies are already working toward compliance with the accessibility standards, and others are planning the necessary work.

Complying with the WCAG won’t automatically make you compliant with all of the accessibility laws in every country, but it brings you closer to that goal. Let’s dive in and take a look into how to achieve WCAG compliance.

How to Follow the WCAG

The requirements for WCAG compliance are prescriptive and clearly laid out. You can find a list of every WCAG requirement in this W3C quick reference, broken down into easily understandable sections with action items, tests, and more.

At first look, the list may seem a little overwhelming. Where to begin? Does every line item on the page apply? Let’s walk through some of the terminology and the various ways to approach the information on the WCAG website, beginning with WCAG conformance levels.

The WCAG breaks down its requirements into three different levels of conformance: A, AA, and AAA. The minimum requirements for compliance constitute level A. Level AA includes all of A’s requirements and adds more, and in turn level AAA starts with and elaborates on the requirements for AA. The criteria for each level define how easy it is to comply with each requirement, the extent to which assistive technology can work around the issues caused by non-compliance, and so forth. The W3C goes into more detail here on the levels of conformance.

Level A standards are generally easier to meet than AA or AAA standards, and the level A standards alone provide immediate benefits for a large proportion of users. It’s best to start with meeting all the level A standards, then move up to the higher levels. This link to the aforementioned WCAG tool filters out the AA and AAA regulations from the list, allowing you to focus on just the A regulations when modifying your content. Although actual conformance only comes when you meet all of each level’s requirements, the WCAG encourages you to claim any progress made toward the next level directly on your website.

Once you have the WCAG tool ready, you can begin going down the list of requirements, covering topics that range from video and audio content to color, animations, and even user input. The process may seem time-consuming, but once you get started, you’ll find the tool simple to navigate, and the results well worth the effort.

An Alternative Approach to the WCAG

In a perfect world, every web page and application would be 100% accessible to everyone. Unfortunately, it’s not always easy to get there. If you design or manage a site that can’t meet the requirements for conformance, there’s good news: the WCAG considers pages like yours to be conformant if an alternate version exists that does meet the requirements.

To conform to the requirements, an alternate version must meet several conditions. Specifically, to quote the W3C site, such an alternate version must:

  1. Conform at the designated level, and
  2. Provide all of the same information and functionality in the same human language, and
  3. Be as up to date as the non-conforming content, and
  4. Meet at least one of the following requirements:
    1. the conforming version can be reached from the non-conforming page via an accessibility-supported mechanism, or
    2. the non-conforming version can only be reached from the conforming version, or
    3. the non-conforming version can only be reached from a conforming page that also provides a mechanism to reach the conforming version

You can find more details about alternate versions at the W3C site.

While creating an alternate version is an excellent solution for pages and apps that are difficult to conform, it’s important to regard it as only a temporary solution for the time it takes to implement a permanent fix. When you have a conforming alternate version, you’re forced to continually update the same information in two different locations so that both versions’ audiences are getting the same content, which creates a lot more work for the content creator.

Conclusion

Congratulations—you’ve taken your first steps toward meeting the WCAG’s accessibility requirements. Where you go from here is up to you: you can dive in deeper and read more about the WCAG on the W3C’s comprehensive website or jump right into the tool and begin improving your web page.

Adherence to the WCAG is crucial, not only because the law requires it, but also because it’s beneficial to everyone when as many people as possible can visit and navigate your site. Accessibility should be seen not as a hurdle to clear when building your website but an integral step in creating successful content. Technical compliance with the WCAG is only part of the goal; the other equally important part is training your staff to think about accessibility in every stage of their work cycle. When you consider accessibility before the project starts, in its early stages, and during production, it becomes easy to build accessible products and services that everyone can use and enjoy.


To Learn More about Accessibility

We have created a comprehensive whitepaper on accessibility for developers that covers everything from laws to coding to testing. 

Download the whitepaper: Accessibility for Developers

Adding Accessibility to Your Apps

One easy way to make sure that you are creating accessible web apps is to start with components from the Kendo UI libraries. Our components are all WCAG complaint and give you great functionality from grids and charts to schedulers and pickers. Get a head start on your apps UI and a head start on accessibility compliance at the same time. 

Learn more about: Kendo UI

Integrating the TelerikCalendar Component

$
0
0

In my previous post, I combined several Telerik Blazor UI components to create a rich form with minimal effort. In the page I created, I used the DateInput component to handle displaying and accepting the date a customer signed up to our company's loyalty program. That's not very graphical (but it was easy). In this post, I'm going to upgrade to the TelerikCalendar component.

Caveats

Before I begin looking at my options, though: If you (a) followed those previous posts, and (b) upgraded to Preview 6 of Blazor… well, there have been some changes. Most of the changes are the result of Microsoft standardizing the names of Blazor directives that appear as attributes on the elements that represent Blazor components. Those attribute names are all prefixed with an @ sign (i.e. ref becomes @ref, onclick becomes @onclick, ondblclick becomes @ondblclick, and so on). These changes are just part of a move on the Blazor team's move to standardize attribute names, reduce some redundancy in how these are used, and support some additional functionality to be added in the future.

The native attributes on the components' elements (the attributes defined by Telerik) do not, however, get an @ prefix. However, if you are setting those attributes to some code or binding them to a field or property, the value for the attribute does need to be prefixed with an @ symbol. If this sounds confusing… well, I have lots of examples in this post. But there's also an easy way to tell as you're typing in code: If you type in an attribute name and it doesn't appear in boldface, prefix it with an @ symbol; if the attribute name doesn't require an @ symbol, prefix the value you're binding the attribute to (except for those occasions where you really are just setting the attribute to some string value).

In addition, if you want to appear hip and happening, in your .razor file you can change @functions to @code (my code worked equally well with either). The announcement of Preview 6 describes some additional changes, not all of which I was able to get to work.

You should also make sure that you're using the latest version of the Telerik UI for Blazor components (I'm using 1.2). This version, among other changes, takes advantage of some bug fixes to Blazor that enable the ValueChanged event on the TelerikCalendar component.

Editor's Note: Since the time of writing, Telerik UI for Blazor 1.3 has been released, with new features and no breaking changes. You can see everything that's new here.

Displaying Dates

The TelerikCalendar provides a full graphical calendar that allows the user to select dates and, by default, page through months to find the date they want. The component has Max and Min attributes that let you control how far the user can page into the future and the past (the calendar also automatically disables dates outside the Min and Max range in displayed months). By default, only one month is displayed at a time, but you can override that by setting the Views attribute to the number of months you want to display on the screen at a time.

Of course, I want to display the user's sign up date when the calendar is first displayed. For that, I can use the component's Value attribute. This means that displaying a date in the TelerikCalendar can be as simple as adding this markup to your page:

<TelerikCalendar Min="@DateTime.Now.AddMonths(-1)"
                 Max="@DateTime.Now"
                 Value="@currentCustomer.SignUp" />

And that would be fine if all I wanted to do was display the customer's signup date. But I want to give the user the ability to select a new date.

Retrieving Dates

You have two (2) options when it comes to retrieving a date the user has selected. If you don't intend to edit the date, then you can bind the component to a field or property using Blazor's @bind-Value attribute. While the Value attribute binds the data in one direction, @bind-Value implements two-way databinding, allowing you to pick up the date the user has selected.

Switching to @bind-Value gives this HTML (notice that, when using Blazor attributes as opposed to the Telerik component's attributes, the @ sign moves out from between the double quotes and onto the attribute name):

<TelerikCalendar Min="@DateTime.Now.AddMonths(-1)"
                 Max="@DateTime.Now"
                 @bind-Value="currentCustomer.SignUp" />

However, if you'd prefer to take some action as soon as the user selects a date, you'll want to use Telerik's ValueChanged event and tie the event to some method in your code. Your method will automatically be passed the new, selected value date the user clicks on it. Your markup would look like this:

<TelerikCalendar Min="@DateTime.Now.AddMonths(-1)"
                 Max="@DateTime.Now"
                 ValueChanged="@SignUpDateChanged" />

And the code to catch the new value would look like this:

private void SignUpDateChanged(DateTime newDate)
{
  DateTime d =  newDate;
}

As attractive as this option is, it does have one drawback: You can't combine the ValueChanged attribute with the @bind-Value or Value attributes. Using @bind-Value with ValueChanged generates a compile-time error; using Value with ValueChanged (at least in my testing) seems to prevent the calendar component from highlighting the date the user selects (an issue that, assuming it doesn't just reflect a problem with my testing, will probably be addressed in a later release of either Blazor or the Telerik components).

There's a great deal more to say about the calendar (it supports, for example, multiple views at the year, month, and day level) which I'll discuss in my next blog post.

Controlling the Display & Selection in the Calendar Component

$
0
0

The TelerikCalendar component in Telerik UI for Blazor gives the user lots of navigation options – and you don’t have to do anything. But, if you do want to write some code, you can make it a lot easier for your users to find the date they want.

In my previous post, I showed how I would use the TelerikCalendar component in a rich UI, created by integrating multiple Telerik components. However, there’s some additional functionality around picking dates that I need for my case study (which is displaying detailed information about a customer) that this post will cover.

By default, the calendar control displays a single month – you pick that month through the Value attribute of the <TelerikCalendar> element. Displaying a date in the calendar can be as simple as adding this element to your page:

<TelerikCalendar Value="@currentCustomer.SignUpDate" />

In my case study, however, the date I’m binding to is the date that the customer joined the company’s loyalty program – which could be some time in the distant past. Forcing the user to page through multiple months to get to the date they want would be cruel.

Fortunately, the TelerikCalendar component handles this. If the user clicks on the month and year displayed in the calendar’s upper left corner, the TelerikCalendar automatically switches into a view that displays the months in the year (and the date shown in the upper left-hand corner switches to showing just the year). The user can then click on the “month of their choosing” to get back to the display of the days in the month. Alternatively, the user can click on the year in the upper left corner and get a display of years, allowing them to move quickly into the distant path or future.

But wait, there’s more!

Selecting the Month or Year You Want

The calendar element also has a BottomView attribute that allows you to control the user’s selection. If you set the BottomView to CalendarView.Month then, in the view listing all the months, clicking on a month name doesn’t display the dates for the month. Instead it allows the user to select that month. Similarly, if you set the BottomView to CalendarView.Year then, when the calendar is displaying a list of years, the user can select a year.

As that discussion implies, if you want to take advantage of the BottomView attribute, you also need to control what view the calendar is currently using: day, month, or year. You can control that display through the View attribute. Putting both of those attributes together, this element would display a list of months in the year and allow the user to select a month:

<TelerikCalendar View="CalendarView.Year"
                 BottomView="CalendarView.Year"
                 Value="@currentCustomer.SignUpDate" />

So, by managing the View and BottomView attributes, you could create a UI with multiple, linked calendar components that would allow the user to select:

  1. a year in the first component
  2. a month in the second component for that year
  3. a specific date in a third component for that year and month

The best part is that you don’t even need three copies of the component: using the component’s Navigate() method, you can set the View in one line of code and use another line of code to set the BottomView, giving the user the ability to set the selection level they want.

To do that, you first need to access the calendar component from code so you can call its Navigate() method. That requires you to rewrite your element to bind it to a field or property in your code with Blazor’s ref attribute. You also need to bind the BottomView to a field or property.

The resulting element that displays the initial list of years would look something like this:

<TelerikCalendar @ref="calendar"
                 View="CalendarView.Decade"
                 BottomView="@selectionMode"
                 Date="@currentCustomer.SignUpDate" />

Next, you need three buttons to let the user pick between selecting years, months, or days:

<TelerikButton OnClick="@SetViewToShowYears">Select Year</TelerikButton>
<TelerikButton OnClick="@SetViewToShowMonths">Select Month</TelerikButton>
<TelerikButton OnClick="@SetViewToShowDaysInMonth">Select Day</TelerikButton>

In your code section, you need to set up the fields or properties to hold the references you use in your calendar (including initializing the field or property that drives the BottomView). In my case, I decided to use fields so my code looks like this:

@code {
  private TelerikCalendar calendar;
  private CalendarView selectionMode = CalendarView.Decade;

  // ...
}

The three methods called from my buttons all look very much alike: They use the Navigate() method to change the current view and then set the BottomView to that level. The only interesting issue is that the Navigate() method requires that you pass a date that will become the calendar’s currently selected date. In my scenario, I don’t want to override any date the user has selected, so I just pass the date in the calendar’s Value property, which will be the last date the user selected.

The three methods look like this (and are sufficiently similar that they should probably be collapsed into a single method that accepts a parameter):

private void SetViewToShowYears()
{
  calendar.Navigate(calendar.Value, Telerik.Blazor.CalendarView.Decade);
  selectionLevel = CalendarView.Decade;
}

private void SetViewToShowMonths()
{
  calendar.Navigate(calendar.Value, Telerik.Blazor.CalendarView.Year);
  selectionLevel = CalendarView.Year;
}

private void SetViewToShowDays()
{
  calendar.Navigate(calendar.Value, Telerik.Blazor.CalendarView.Month);
  selectionLevel = CalendarView.Month;
}

By the way, as I mentioned in my earlier post, the TelerikCalendar component has Min and Max attributes that let you control how far in the past or into the future the user is allowed to select dates. All these views honor those limits by not letting the user page past the limits and disabling dates outside the range if the view displays them.

One caveat, though: This column is written with one of the Blazor previews so (as with any preview technology) things may be “quirky” and they’ll almost certainly change before they get into production. Personally, I can’t wait.

What You Need to Know about Section 508

$
0
0

Section 508 addresses people with disabilities and their access to and use of information and data related to electronic and information technology. Here's what you need to know.

Those of us who were alive in 1973 may have been watching the premier of American Graffiti or pulling on a pair of groovy bell bottoms, but President Richard Nixon was busy signing The Rehabilitation Act of 1973. This enduring Act requires that people with disabilities be able to access programs and activities that are funded by federal agencies and federal employment.

There have been several amendments to the Act since you put on those bell bottoms, including the Section 508 amendment, which was added in 1986 (by which time you were tuning in to the very first episodes of the Oprah Winfrey Show and had traded in the bell bottoms for a Members Only jacket). Section 508 was amended again in 1998.

So, what is this Section 508 amendment, and more importantly what does is mean to business today when the bell bottoms and Members Only jackets have been replaced by… well… an avatar? Believe it or not, it has only grown in significance. And, as long as electronic and information technology continues to grow, so will the significance of Section 508. With the proliferation of the web and its impact on business today, it is more important than ever to understand. To keep things simple, this is where we’ll focus our look at 508 – the World Wide Web.

Simply put, Section 508 addresses people with disabilities and their access to and use of information and data related to electronic and information technology. Some key points:

  • It applies to individuals with disabilities who are:
    • federal employees
    • members of the public seeking information or services from a federal department or agency
  • It requires that access to information and data by individuals with disabilities be comparable to those without disabilities unless undue burden would be imposed on the department or agency.

In terms of websites, this means that federal government websites must be accessible to people with disabilities. In reality, this extends to all sorts of “browser-based” experiences and, of course, beyond the web to all things electronic and information technology related.

What Does Section 508 Mean to My Organization?

How does this affect your organization? Well, if you’re a federal agency, I think you probably already get it. But, what if you’re a private company? It doesn’t affect you, right…? Great! You can stop reading now and go back to surfing the web!

Nope!

Not until you ask yourself two things:

  1. Do I want to do business with the federal government?
  2. Does anyone I do business with do business with the federal government?

If you have a product or service that falls into the electronic and information technology bucket and you want to sell those products or services to the U.S. federal government or to a vendor that sells to the government, understanding and following 508 is imperative for you.

Now that you know why it’s important, let’s look at what you need. We can break it out into two simple things:

  1. Make your website or product accessible
  2. Demonstrate that in an accessibility report in the format of a Voluntary Product Accessibility Template (VPAT)

Accessibility Guidelines and Section 508

Good news – there are guidelines for accessibility. Section 508 is very clear on what guidelines you should follow. This can, however, get a bit tricky given some changes that have happened along the way, but I’m going to make it easy for you – Section 508 maps to the WCAG 2.0 Level A and AA guidelines.

Up until January of 2017 (we’re not going to get into what you were doing 2017 – you were probably still wearing those pants), Section 508 and the WCAG 2.0 guidelines were separate. Now Section 508 maps directly to WCAG 2.0 Level A and AA as the guidelines to follow to meet the requirements. Moreover, following the January 2017 refresh, the VPAT format was amended later that year to accept the WCAG 2.0 and now also WCAG 2.1 Guidelines, so it remains the method by which to demonstrate level of conformance.

Getting that VPAT You’ve Always Wanted

If you’re that person who can’t wait to do their own taxes every year, then you may want to tackle your own VPAT. However, even then, you’re likely to become pretty frustrated because it takes substantial knowledge to just properly fill out the VPAT, nevermind evaluate your website for conformance to the guidelines.

This is where a third-party expert comes in. An expert can evaluate your site, tell you where you don’t meet the guidelines and what to do about it. Then, once you’ve addressed the issues, tell you how you did. It will look something like this:

  • Perform a Manual Review of a representative sample of the site
  • Report the findings and give advice on remediating the issues
  • Support you through the remediation by answering questions and providing clarification to the advice
  • Review the site to verify the issues have been properly addressed
  • Draft an accessibility report in the VPAT format

Assuming everything has gone well, right after that second review (when everything has been verified) is the magic moment in time when your website will substantially conform to the guidelines. The trick from here is to maintain that the best you can. Again, a good third-party expert can help create a strategy that works for you.

Beyond the VPAT

What we have covered here, from the inception of the Rehabilitation Act of 1973, through the integrations of the Section 508 amendment, to the adoption of the WCAG 2.0 Level A and AA guidelines, and, finally, obtaining a VPAT are the base fundamentals you should understand. There is, however, a lot more to think about when it comes to accessibility, Section 508, and what your organization should consider to manage accessibility efficiently over time. Some of the key things to look into are:

  • Supplemental and ongoing accessibility education
  • Consistent access to third-party support
  • Ongoing monitoring
  • Regular Manual Reviews
  • Regularly refreshing your VPAT

The exact strategy your organization adopts will be unique to your needs and the way your organization operates will likely morph over time. It’s okay to think about all these things, but don’t get too wrapped up in the details. Start at the beginning and have your site or product assessed, then work with your team and the experts to build the best strategy from there. Before you know it, you will be meeting the requirements and operating in the federal space like the expert you are.


Learn More about Accessibility

We have created a comprehensive whitepaper on accessibility for developers that covers everything from laws to coding to testing.

Download the whitepaper:Accessibility for Developers

Adding Accessibility to Your Apps

One easy way to make sure that you are creating accessible web apps is to start with components from the Kendo UI libraries. Our components are all WCAG complaint and give you great functionality from grids and charts to schedulers and pickers. Get a head start on your app's UI and a head start on accessibility compliance at the same time.

Learn more about: Kendo UI

Fitting It All In: Keeping the Grid Small with a Custom Update Panel

$
0
0

You want to spend your time adding functionality, not getting the basics of your UI to work. Here's how, in Blazor, the right combination of HTML, code, and components can create a custom editing experience for a Telerik Grid that takes up the minimum space on the screen.

In a previous post, I combined an ASP.NET MVC View, a Blazor component, and about a half-dozen Telerik UI for Blazor components to create a page that displayed a grid of customers with a tabbed interface that allowed the user to view related information for any selected customer. What I hadn't done was allow the user to update any of that information, which is what this column is all about.

In many ways this post is unnecessary: The TelerikGrid implements update, delete, and save functionality out of the box. However, taking advantage of that built-in functionality requires that you add at least two more columns to the grid to hold the buttons that implement adding and deleting rows. On a mobile device you might not want to give up that screen space: In small format screens, ‘taller/longer' is OK, but ‘wider' is evil (though fitting everything on a single screen is ideal, of course). And it doesn't help that I've already added a column to my grid to allow the user to select a row

Reducing Columns with Click and Double-Click

So I'm going to redesign my grid to eliminate the HTML button by replacing it with a smaller image that the user can click on (or tap) to select a customer when viewing the customer's "related data." As my image, I used the favicon.ico icon that comes with the default ASP.NET Core project temple. To activate the display of the related data, I just leverage the click event for the <img> element. In that event, I use the grid's Context property (which holds the object displayed in the current row of the grid) to capture the current customer and shove it into a property defined in my component's code (currentCustomer).

This lets me support updates without adding a new column: I put the code to activate my update panel in the <img> element's dblclick event. In that code, I open a TelerikWindow to display the current customer's data and let the user update that customer (I put that code in a method I called EditItem).

To incorporate that HTML into a TelerikGrid, all I have to do is define a column with a <Template> element inside of it and then put my HTML in there. Initially, therefore, my grid looks like this:

<TelerikGrid Data="@custs">
  <TelerikGridColumns>
    <TelerikGridColumn Title="Select"
                       Width="10%"
                       Context="customer">
      <Template>
        <td>
          <img src="/favicon.ico"
               height="25"
               width="25"
               onclick="@(a =>currentCustomer = ((Customer) customer))"
               ondblclick="@(a =>EditItem(a))" />
        </td>
      </Template>
    </TelerikGridColumn>
  <TelerikGridColumn Field="Id" Title="Id" Width="10%" />
  <!-- more columns -->
</TelerikGrid>

And here's the related code:

@functions
{
  [Parameter]
  private IEnumerable<Customer> custs { get; set; }
  private Customer currentCustomer { get; set; }
  private void EditItem(UIMouseEventArgs args)
  {
    // ...
  }

When the user single clicks, I'd also like to give the user some feedback on which customer is selected by updating the background color for the <td> element that the <img> element is nested inside of. To support that I set up a field called backcolor and switch its value depending on whether or not the customer for the current row matches the customer in the currentCustomer property.

My enhanced <Template> element now looks like this:

<Template>
  @if (customer == currentCustomer)
  {
    backcolor = "red";
  }
  else
  {
    backcolor = "light-gray";
  }
  <td style="background-color: @backcolor">
    <img src="/favicon.ico"
         height="25"
         width="25"
         onclick="@(a =>currentCustomer = ((Customer) customer))"
         ondblclick="@(a =>EditItem(a))" />
  </td>
</Template>

The supporting code for this change is pretty simple since all I have to do is add a field to hold the current background color:

@functions
{
  private string backcolor = "white";
  // ...
}

Defining the Update Window

My next step is to define the window that will pop up to display the data and let the user change the current customer's data.

One note, however: In HTML when a user double clicks, the element actually fires a click event, followed by a dblclick event. This can force you to write some ugly code to prevent the click event code from executing before the "real" double-click event. Fortunately for me, having the click event fire before any double-click event doesn't cause me any problems: It just causes the related data for the current customer to be displayed before I open the update panel.

I used a TelerikWindow to create my update panel. The "frame" for my window is easy to define: I include a title section to display the current customer's name (so the user knows who's being edited) and two buttons to support update and cancel. I also made the window modal (which also centers the window in the page). Finally, I used the ref attribute to tie my window to a field in my code (EditWindow). I use that reference in my code to call the window's Open() method to display the window (later, I'll use the reference to call the window's Close() method to hide the window).

Here's all the required markup to create that frame:

<TelerikWindow ref="EditWindow" Modal="true">
  <TelerikWindowTitle>
    Edit @currentCustomer.FirstName @currentCustomer.LastName
  </TelerikWindowTitle>
  <TelerikWindowContent>
    <TelerikButton OnClick="@Update">Update</TelerikButton>
    <TelerikButton OnClick="@Close">Cancel</TelerikButton>
  </TelerikWindowContent>
</TelerikWindow>

In my @functions block, I have to create the field that ties to my window's ref attribute and add the code to open the window in the EditItem method called from my dblclick event. I also added the methods I'll call from the click events of the two buttons in the window (though all these methods do right now is close the window):

@functions
{
  private TelerikWindow EditWindow;

  private void EditItem(UIMouseEventArgs args)
  {
    EditWindow.Open();
  }

  private void Update()
  {
    EditWindow.Close();
  }

  private void Close()
  {
    EditWindow.Close();
  }

  // ...
}

Accepting Inputs and Handling Updates

Now, it's just a matter of adding the necessary components to my window that will let the user update the Customer object in the currentCustomer property. The Customer object has four properties that I'll let the user update:

  • FirstName and LastName: I'll use TelerikTextBox components for them
  • Signup: I'll use a TelerikDateInput component
  • CreditScore: A TelerikNumericTextBox

Just a reminder: To get many of these Telerik controls to work, you'll also need to include the Telerik JavaScript support file (there are some things Blazor can't do… yet). That means you'll need to add this <script> element to the View (or Razor Page) that's hosting your component:

<script src="https://kendo.cdn.telerik.com/blazor/1.1.0/telerik-blazor.min.js" defer></script>

But with that taken care of, I can just add the input components to my window with the appropriate labels. To tie a component to a property on the Customer in the currentCustomer property, I just need to set the component's bind-Value attribute to the property the component is supposed to work with. Setting the bind-Value attribute ensures that any change to the property's value will be displayed in the <TelerikTextBox> element; similarly, any changes the user makes in the <TelerikTextBox> element will be automatically passed to my property.

Here's an example of a <TelerikTextBox> element tied to the Customer's FirstName property:

<TelerikTextBox bind-Value="@currentCustomer.FirstName">
</TelerikTextBox>

In addition to tying the component to a Customer property, where it makes sense I take advantage of the various attributes on the component to control what the user is allowed to enter. After all of those changes, here's all the markup for the window:

<TelerikWindow ref="EditWindow" Modal="true">
  <TelerikWindowTitle>
    Edit @currentCustomer.FirstName @currentCustomer.LastName
  </TelerikWindowTitle>
  <TelerikWindowContent>
    Signup Date:<br />
    <TelerikDateInput bind-Value="@currentCustomer.SignUp"
                      Format="yy-MMM-dd">
    </TelerikDateInput><br />
    First Name:<br />
    <TelerikTextBox bind-Value="@currentCustomer.FirstName"
                    MaxLength="20"
                    MinLength="2">
    </TelerikTextBox><br />
    Last Name:<br />
    <TelerikTextBox bind-Value="@currentCustomer.LastName"
                    MaxLength="20"
                    MinLength="2">
    </TelerikTextBox><br />
    Credit Score:<br />
    <TelerikNumericTextBox bind-Value="@currentCustomer.CreditScore"
                           Max="5"
                           Min="1"
                           Step="1">
    </TelerikNumericTextBox><br />
    <br />
    <TelerikButton OnClick="@Update">Update</TelerikButton>
    <TelerikButton OnClick="@Close">Cancel</TelerikButton>
  </TelerikWindowContent>
</TelerikWindow>

As this picture shows, it doesn't look half bad even without any special styling applied:

What's left, of course, is to handle updating the Customer after the user finishes. Since this is server-side Blazor, I can call local resources to handle that – my customer repository, for example. With client-side Blazor, I'd want to call a Web Service. Since changes to my UI components are automatically reflected in the currentCustomer properties, all I have to do is access the currentCustomer property from my update method.

Putting that all together, my update method can be as simple as this:

private void Update()
{
  CustomerRepo.Update(currentCustomer);
  EditWindow.Close();
}

And this is the point I'm trying to make: The right combination of components, HTML, and code can give you the UI you want with very little code required (a half-dozen lines, in this case). Of course, a real application will require more code than what I have here, but all that additional code will be all about adding functionality rather than just "making it work."


Vision Disabilities and What You Need for Accessibility

$
0
0

In this article, we'll define vision disabilities and talk about web development strategies for improving accessibility for users with visual impairments.

For people with vision disabilities, the advent of the internet has done more than transform the way they access information, and it has enabled them to participate in a global system of communication. Unlike many print products, online articles and applications offer quick and low-cost options to people who need additional tools to access their content.

Most web applications have a long way to go before they can truly welcome users with vision disabilities. This article explores the strategies web developers can use to maximize the accessibility of their products to these users.

What Are Vision Disabilities?

Vision disabilities generally fall into one of three broad categories:

  1. Blindness. The extreme end of the spectrum of vision disability is total blindness, where a person has no access to visual information from the outside world. Most people considered legally blind do have some vision, but not enough to enable them to move around without assistive technologies. The threshold for legal blindness in the United States is 20/200 vision or a field of vision that covers 20 degrees or less.
  2. Low vision. A person with low vision can often rely on glasses or contact lenses to access written material and navigate the world. Low vision is common among the elderly and also in younger populations due to genetic predisposition, illness, or traumatic injury.
  3. Color blindness. People who are color-blind generally have a normal range of visual acuity but perceive color differently, to a limited degree, or not at all. Though not generally considered a disability, color blindness can impact the way a user interacts with a web application, and accessibility to color-blind users is an essential consideration for developers.

Why Is it Important to Make Your Site Accessible to People with Vision Disabilities?

People with blindness, low vision, and color blindness make up approximately 1.3 billion people worldwide. Catering to this broad demographic is a respectful way to interact with others, but it’s also a smart business practice. Despite the wealth of assistive technologies available to people who need them, a web application not designed with accessibility in mind can present frustrating problems for users with visual impairments.

Improving the Accessibility of Your Website for Visually Impaired Users

Improving accessibility in your applications starts with considering how visually impaired users navigate the web. The strategies employed by people with visual disabilities vary by the type and extent of their disability, as well as by the preferences of the individual user, but the following tools cover most of the crucial ways that visually impaired people use the web.

For Users with Blindness

People who are blind often read the web with screen readers, which speak written text aloud or convert it into Braille with the help of Braille displays. They often navigate web pages using their keyboards - e.g., by using the Tab key to jump between sections. A blind user may not use a mouse to navigate a page nor to access information that is presented exclusively through visuals.

First and foremost, to improve accessibility for people who use screen readers and keyboard navigation, make sure your site’s markup works well with a screen reader. The W3C’s WAI-ARIA standard provides complete guidance for creating accessible rich web applications. For specific tips for making your website accessible to those using screen readers, read the WAI-ARIA implementation practices, which cover elements such as keyboard navigation, accessible design patterns, and defining landmark regions to allow screen readers to identify the structure of the page for visually impaired readers.

Other strategies include providing text alternatives for visual content by writing alternative descriptions for each of your images and summaries for charts, graphs, and other visual content, and adding column and row headers to tables, as well as descriptions of their contents.

For Low-Vision Users

Zoom apps enlarge sections of the page so that people with low vision can distinguish the letters in a block of text. Although most operating systems can render fonts’ glyphs at a sufficiently high resolution for these apps, they cannot boost the resolution of images. An alternative technique, enlarging font size in the text, also cannot be used on text within images.

To improve accessibility for people who use zoom apps and enlarged font sizes, use text instead of image embedding whenever possible. True text responds well to zooming, while text embedded in images loses resolution as it expands. Ensure that your site’s users can change the font size of your content by using the following strategies:

  • Avoidlimiting changes to font size when setting the HTML meta attributes, such as maximum-scale=1.0 or user-scalable=0.
  • In your CSS, use relative measures (percent of a whole) rather than absolute measures (precise number of pixels) to give users flexibility in their font sizes.
  • Make sure your webpage is responsive and that the relevant content is visible at different font sizes and screen sizes by running usability tests on each page.
  • Use correct markup so that tools like iOS Reader Mode and Safari Reader, which allow users to customize the text to their needs, work normally.
  • Wrap your content blocks in elements like <article> to signal to a screen reader to engage with the text. Any wrapper other than <body> or <p> will work for most readers, but be sure to test unusually formatted pages to make sure the screen reader can access their content.

For Users with Color Blindness

The most common type of color blindness is red-green deficiency, in which these and similar colors are difficult to distinguish. For a user with this type of color blindness, reds and greens may appear as yellows, beiges, or oranges, making all colors in these families unreliable indicators of the true colors of emitted light. Many people with red-green color blindness can tell the difference between dark and light shades, and colors in the blue family are usually unaffected.

Another type of color blindness is “achromacy,” or complete color blindness, where the world is rendered in blacks, grays, and whites. People with achromatic color blindness make up a small percentage of the color-blind, but their needs are worth considering for developers interested in accessibility improvements for those who are color-blind.

Keep in mind that all those who are blind are, in a sense, also color-blind; any improvements removing reliance on color to convey information may also increase accessibility for users who are blind.

To improve accessibility for users with color blindness, don’t rely on color alone to convey the meaning of controls. Instead, include text or alternative text descriptions of navigation buttons and other controls. Also, ensure that all the visual information is conveyed not just with color, but also using different visual textures—see WebAIM’s metro lines example.

Finally, keep in mind that just as users who are blind benefit from accommodations made with color-blind users in mind, accessibility measures designed for blind users can also help those who are color-blind.

Conclusion

Though the above techniques describe some approaches to improving accessibility for users with visual impairments, they don’t express the full potential of true accessibility. Developers committed to making their content more accessible should take these goals into account as early as possible when planning a project. Tweaks like switching to relative measures in your CSS markup can be applied after project development is complete, but not everything required for accessibility is a simple technical change.

Because interactive web pages are much more complex than simple blocks of text, one of the greatest challenges of accessibility is in creating navigable pages without relying exclusively on visual controls. Measures intended to make content accessible to users with visual impairments should also include changes to the project’s content structure itself. The clarity in content, as well as in markup, can make a big difference for users with vision disabilities as they move through the content of your project.


Learn More about Accessibility

We have created a comprehensive whitepaper on accessibility for developers that covers everything from laws to coding to testing.

Download the whitepaper:Accessibility for Developers

Adding Accessibility to Your Apps

One easy way to make sure that you are creating accessible web apps is to start with components from the Kendo UI libraries. Our components are all WCAG complaint and give you great functionality from grids and charts to schedulers and pickers. Get a head start on your app's UI and a head start on accessibility compliance at the same time.

Learn more about: Kendo UI

Uncovering TypeScript for C# Developers

$
0
0

This post gets C# developers started building applications with TypeScript, which allows static typing combined with the enormous ecosystem of JavaScript.

If you ever worked on a JavaScript application in the old days and have never had a chance to do the same with modern tooling and ecosystem, you would be surprised by how both the development and the production experiences are different and immensely improved. This is especially the case if you are coming from a .NET and C# background. C# is a very productive, general purpose programming language. Today, you can build games, web, desktop and mobile applications with C# running on .NET Core, Mono and various other available runtimes. JavaScript mostly offers the same, but the biggest gap is missing the comfort and safety of static typing.

Static typing allows us to catch many typical programming errors and mistakes during compilation time instead of noticing these in runtime. When you combine this fact with great tooling and code editor support, you achieve a much faster feedback loop which then gives you a higher chance to build more robust applications in a much quicker way.

TypeScript gives you just that, and it does it without taking the best of JavaScript from you: the enormous ecosystem! All the packages available on npm, for instance, are available for you to tap into even if they are not implemented in TypeScript. This is huge, and it's possible due to one of the core principles of TypeScript: it starts and ends with JavaScript. We will shortly see an example of how this is actually made possible in practice.

The main aim of this post is to get you started on building applications with TypeScript and also to give you a sense of how this process looks from the development perspective. It's highly encouraged that you first have a look at “TypeScript in 5 Minutes” if you don't have prior experience with TypeScript and how it functions at a high level.

Code is Read More Than Written

My experience proves Uncle Bob's quote on the ratio of code reading versus writing being over 10-to-1. So, it's only fair to evaluate and see the power of TypeScript in terms of code reading aspect.

Let's clone one of the biggest open-source TypeScript projects: Visual Studio Code. What I am after here is to learn how we should be implementing a command in order to execute it through the Visual Studio Code command palette. A quick search on GitHub got me the blockCommentCommand.ts file, and it revealed a class which implemented an interface: editorCommon.ICommand. Let's get the tooling help from Visual Studio Code (meta!) and find out about the interface definition:

Visual Studio Code: Peek Definition

Visual Studio Code: Peek Definition Interface

We are directly inside the interface, and the most important part here is the explicitness, how apparent the extensibility point is. I want to understand this interface further though. So, let's look into the getEditOperations() function of the interface and find out all of its implementations:

Visual Studio Code: Find All References

Visual Studio Code: Find All References Results

This is really nice, and what's really good here is that it's not a string find. It's actually finding all the interface function implementations. sortLinesCommand seems interesting to me and I want to dive into it. Let's go into it and start changing it. The first thing I am noticing is the help I get from the code editor.

Visual Studio Code: public getEditOperations

You can see that all of this tooling help, which comes from the power of static analysis abilities of the language itself, makes it super easy for me to explore an unfamiliar and fairly large codebase. This is the core value proposition of TypeScript.

Now that we understand the main value of the language, let's look at some of its aspects by going through a sample.

A Sample Application

Let's look at a sample application to understand how we can structure the codebase with TypeScript. In this sample, we will see:

  • How to work with TypeScript primitives such as Classes
  • Consuming NPM packages implemented in pure JavaScript
  • Running the application on Node.js

The core logic of the application is around voting for particular topics that have some options. I have structured the code logic of this application inside the domain.ts file, which has the below content.

import { v4 as uuid } from 'uuid';

export class TopicOption {
  readonly name: string;
  readonly id: string;

  constructor(name: string) {
    this.name = name
    this.id = uuid()
  }
}

interface Winner {
  readonly option: TopicOption;
  readonly votes: number;
}

export class Topic {
  readonly name: string;
  readonly options: TopicOption[];
  private readonly _votes: Map<string, number>;

  constructor(name: string, options: TopicOption[]) {
    this.name = name
    this.options = options;
    this._votes = new Map<string, number>();
    options.forEach(option => {
      this._votes.set(option.id, 0);
    })
  }

  vote(optionId: string) {
    const votesCount = this._votes.get(optionId);
    if (votesCount != undefined) {
      this._votes.set(optionId, votesCount + 1);
    }
  }

  getWinner(): Winner {
    const winner = [...this._votes.entries()].sort((a, b) => a[1] > b[1] ? 1 : -1)[0];
    const option = this.options.find(x => x.id == winner[0]);

    if (option == undefined) {
      throw "option has no chance to be undefined here";
    }

    return {
      option: option,
      votes: winner[1]
    };
  }
}

If you have a C# background, this code should be mostly self-explanatory. However, it's worth specifically touching on some of its aspects to understand how TypeScript lets us structure our code.

Say “Hello” to Classes

The Class construct sits at the heart of the C# programming language and it's mostly how we model our applications and domain concepts. TypeScript has the same modeling concept, which is close to classes in ECMAScript 6 (ES6) but with some key additional “safety nets.”

Assume the following:

export class Topic {
  readonly name: string;
  readonly options: TopicOption[];
  private readonly _votes: Map<string, number>;

  constructor(name: string, options: TopicOption[]) {
    this.name = name
    this.options = options;
    this._votes = new Map<string, number>();

    options.forEach(option => {
      this._votes.set(option.id, 0);
    })
  }

  // ...
}

A few things to note here:

  • We are able to have readonly and private fields, just like we can in C#. That's big! Especially for cases where we start passing around an instance of a class, we want to be confident that it will stay intact and won't get any unintended modifications. private and readonly access modifiers allow us to express this intent in code and allow the compiler to protect against these unintended modifications.
  • We have the notion of a constructor as well. This is again a big win, allowing us to express what makes up a class instance in order to enforce a certain level of state integrity for the instance.

Structural Typing

The TypeScript type system is based on structural typing. This essentially means that it's possible to match the types based on their signatures. As we have seen with the getWinner() method implementation above, the signature requires us to return the Winner interface. However, we didn't need to create a class which explicitly implemented the Winner interface. Instead, it was enough for us to new up an object which matched the interface definition:

getWinner(): Winner {
  // ...

  return {
    option: option,
    votes: winner[1]
  };
}

This is really efficient when implementing logic, as you don't need to explicitly implement an interface. This aspect of the language also protects us in case of potential changes to the signature of the Winner interface. Let's take the following change to the signature of the Winner interface by adding a new property called margin.

interface Winner {
  readonly option: TopicOption;
  readonly votes: number;
  readonly margin: number;
}

As soon as making this change, Visual Studio Code highlights a problem:

Visual Studio Code: Property 'margin' is missing but required in type 'Winner'

No More Billion Dollar Mistakes: Protection Against null and undefined

Don't you love NullReferenceException when working with C#? I can hear you! Not so much, right? Well, you are not alone. In fact, null references have been identified as a billion dollar mistake. TypeScript helps us on this problem as well. By setting the compiler flag --strictNullChecks, TypeScript doesn't allow you to use null or undefined as values unless stated explicitly.

In our example of returning a winner from the getWinner() method, we would see an error if we were to assign null to the option property.

Visual Studio Code: error for assigning null to option

TypeScript provides the same level of compiler safety across the board for all relevant members. For example, we can see that we are unable to pass null or undefined as a parameter to a method which accepts a string:

Visual Studio Code: unable to pass null or undefined as a parameter to a method which accepts a string

However, there are sometimes legitimate cases for us to represent a value as null or undefined. In these circumstances, we have several ways to explicitly signal this. For example, one way is to mark the type as nullable by adding ? at the end of the member name:

interface Winner {
  readonly option?: TopicOption;
  readonly votes: number;
}

This allows us to pass undefined as a legitimate value to this or entirely omit the assignment. For example, both the below representations are correct to match the object to Winner interface:

return {
  option: undefined,
  votes: winner[1]
};

// ...

return {
  votes: winner[1]
};

TypeScript doesn't stop here. It also helps you when you are consuming a member which can be null or undefined. For example, we would see an error like below if we were to try to reach out to the members of the TopicOption value returned from the getWinner() method:

Visual Studio Code: object is possibly undefined

This behaviour of TypeScript forces us to guard against null and undefined. Once we perform the check, the compiler will then be happy for us to access the members of TopicOption:

Visual Studio Code: TopicOption id

Visual Studio Code: TopicOption name

Consuming a JavaScript npm Package

As you can see in the below code, we are able to import a package called uuid which we installed through npm install uuid --save.

import { v4 as uuid } from 'uuid';

This package is implemented in JavaScript but we are still able to consume it and get the tooling and type safety support as we get for pure TypeScript code. This is possible thanks to the notion of TypeScript declaration files. It's a very deep topic to get into here, but the best piece of advice I can give here is to check TypeScript type search, where you can find and install the declaration files.

typesearch

Executing on Node.js

TypeScript compiles down to JavaScript, and this means that we can run our applications anywhere we are able to execute JavaScript, as long as we compile our source code in a way that the executing platform knows how to interpret. This mostly means targeting the correct ECMAScript version through the –target compiler flag and specifying the relevant module code generation through the --module compiler flag.

Let's look at how we can compile this small voting logic to be executed on Node.js. The below is the content of index.ts:

import { Topic, TopicOption } from './domain';

const topics: Topic[] =[
  new Topic("Dogs or cats?", [
    new TopicOption("Dogs"),
    new TopicOption("Cats")
  ]),
  new Topic("C# or TypeScript?", [
    new TopicOption("C#"),
    new TopicOption("TypeScript"),
    new TopicOption("Both are awesomse!")
  ])
];

for (let i = 0; i < 100; i++) {
  const randomTopic = topics[Math.floor(Math.random() * topics.length)];
  const randomOption = randomTopic.options[Math.floor(Math.random() * randomTopic.options.length)];
  randomTopic.vote(randomOption.id);
}

topics.forEach(topic => {
  const winner = topic.getWinner();
  console.log(`Winner for '${topic.name}' is: '${winner.option.name}'!!!`);
})

You can think of this file scope as the Main() method of your .NET Console application. This is where you will be bringing all of your application together and execute appropriately.

Executing the application

Conclusion

I have shown you the tip of the iceberg here. The truth is that TypeScript actually gives you way more than this with handful of advanced type features such as Discriminated Unions and String Literal Types, which makes it possible to model complex scenarios in much more expressive and safe ways.

More on TypeScript

Want to read more about getting started with TypeScript? Check out these related posts:

Telerik UI for Blazor 1.4.0 is Here!

$
0
0

We're excited to release version 1.4.0 of Telerik UI for Blazor, with enhancements to the native Grid and TreeView components, ASP.NET Core 3.0 Preview 7 compatibility, and new API reference documentation!

The Telerik UI Blazor team is happy to announce the release of version 1.4.0 of the Telerik UI for Blazor components. This release includes several component enhancements, ASP.NET Core 3.0 Preview 7 compatibility, and brand new API reference documentation. Read on to learn about everything that's new.

API Reference

In July we published our Blazor API reference which is one of the foundational elements to any documentation for UI components. This has been requested by our Blazor developers in the past and this is yet another step in our commitment to offer best-of-breed resources along our excellent UI components. The API reference will give you the opportunity to further develop, expand and customize the components state and behavior, and build up your applications.

The Telerik Blazor components API reference can be accessed here and contains a list and descriptions of all public available classes, methods and properties of the Telerik UI for Blazor product.

We aimed at building it with an intuitive structure (just search for the <ComponentName>Base class where the actual properties and methods reside) and easy navigation. It will always be up to date with the latest version of Telerik UI for Blazor, so any additions to our Blazor suite of components will appear simultaneously in the API reference as well.

Again, We are Lightning Fast with Preview 7 Compatibility!

Just two days after the official release of ASP.NET Core 3.0 Preview 7 we are fully compatible with all changes by Microsoft.

Component Enhancements

Grid

With the previous versions of our native Blazor grid component, we exposed the filtering row and filter list options. With the current release we have added the grid filter menu in each of the column headers. To use a filter menu, you simply need to set the FilterMode property of the grid to FilterMode="Telerik.Blazor.FilterMode.FilterMenu", and the grid will render a button in the column header that you click to get a popup with filtering options. The popup lets you choose filter operator, filter criteria, to apply and clear the filter.

Telerik UI for Blazor Grid Filter Menu

Figure 1 Telerik UI for Blazor Native Grid Component Filter Menu

TreeView

Another essential component that we have enriched is the TreeView and its navigation, where we added the option to render links pointing to URLs. Now there are a couple of ways to achieve this:

  1. As mentioned in our previous post for Blazor 1.3.0 version: by using a template to generate the desired links
  2. By using the new built-in UrlField in the data bindings to populate the URLs in the anchors, the TreeView will generate links for you

Beyond this we have also introduced an improved TreeView user experience with sleek reveal for expand and collapse animation movements.

Blazor TreeView Animation Figure 2 Telerik UI for Blazor Native TreeView Animation

You’ve seen this with previous releases along with this 1.4.0 release, but this is worth stating again. Looking ahead to the official release of ASP.NET Core 3.0 we are ready to continuously provide you with interim version of Blazor components compatible with each official preview by Microsoft. So, keep an eye out for the ASP.NET Core 3.0 preview release schedule and rest assured that we will closely follow each release.

Experience Telerik UI for Blazor 1.4.0

With our 1.4.0 release we encourage everyone who hasn’t already tried out the components to head over to the Telerik UI for Blazor overview page and sign up for a trial experience - it’s as easy as a single button click!

Try Telerik UI for Blazor

As Always, We are Continuously Looking for Your Feedback

And for our early adopters and fans we want to continue to hear your feedback! If there are features you are missing, or components you need, please do not hesitate to reach out! We have the official Telerik UI for Blazor feedback portal for this exact reason. Submit your ideas for new components and features, or vote and comment on existing feature requests to have a direct impact on our roadmap!

Happy Blazor Coding!

Combining Components, HTML, and C# to Create an Effective UI

$
0
0

Creating an effective UI doesn’t require a lot of code – just integrating and customizing the right set of Telerik components. In fact, the only code required is a single property.

Creating useful web pages involves integrating multiple components and technologies. Here's how to integrate Telerik UI for Blazor components to create a master/detail page with multiple tabs and an animated display that only shows the details when requested (and with only one new line of code).

In an earlier post, I walked through the process of combining ASP.NET Core Views (or Razor Pages) with a Blazor component containing a TelerikGrid. In that scenario, using C# on the server, I retrieved a set of Customer objects that I then passed, through the Model property of a View, to a Blazor component that displayed a list of customers in a TelerikGrid.

Using this process, the page (including my Blazor component) is rendered to HTML on the server before being sent to the browser. The net result is that the user gets a complete page without having to wait for an AJAX call to fetch the page's data after the page is displayed.

In my case, however, each customer that I'm displaying in the grid owns two collections: a set of payments and another set of purchases. When the user clicks on a customer in the grid, I want to display the two lists of payments and purchases in tabs beneath the grid of customers. I also want to highlight the selected customer so that the user gets some feedback on which customer the display payments and purchases belong to.

But, once the page is displayed in the browser, I don't want to go back to the server unless I have to (AJAX and SignalR calls excepted, of course). A combination of HTML, Telerik components, and a little bit of code delivers all of that. I can even add some animation to my UI.

Sizing the Grid with HTML and Component Attributes

By default, the TelerikGrid takes up the full page with each column in the grid dividing the space evenly. I can customize that behavior by enclosing the grid in a <div> element and setting the width on that <div> element to 75% of the page. The grid will automatically size itself to fill all of the <div> element instead of the whole page.

Within the grid, I can use the same strategy with the grid's columns to control their size (using percentages, rather than fixed widths, allows the grid to adjust its size based on the width of the browser). The result is something like this:

<div style="width:75%">
  <TelerikWindowContent>
    <TelerikGrid Data="@custs">
      <TelerikGridColumns>
        <TelerikGridColumn Field="Id"
                           Title="Customer Id"
                           Width="16%">
        </TelerikGridColumn>
        <TelerikGridColumn Field="FirstName"
                           Title="First Name"
                           Width="42%">
        </TelerikGridColumn>
        <TelerikGridColumn Field="LastName"
                           Title="Last Name"
                           Width="42%">
        </TelerikGridColumn>
      </TelerikGridColumns>
    </TelerikGrid>
  </TelerikWindowContent>
</div>

Adding a Button to Trigger Displaying Details

In order to display the purchases and payment information for a specific customer, I need to give the user the ability to select a row in the grid. In an earlier column I took advantage of the grid's native events to implement a “select row” button. However, that involved invoking and then suppressing the grid's edit functionality. There's nothing wrong with that, of course, but it makes more sense to me to use a Telerik button that doesn't require me to suppress any behavior.

Normally, each column in the grid generates its own HTML. However, by inserting a <Template> element inside a <TelerikGridColumn> element, I can include pretty much whatever I want inside the column (if you don't believe me, see Ed Charbeneau's justly named post “Why Blazor Grid Templates Will Make You Question Everything”). I can even integrate C# into the template by flagging the code with an @ symbol.

Putting all that together, I can add a column to my grid containing a <TelerikButton> element with a click event handler that stuffs the row's context into a property called currentCustomer:

<TelerikGridColumn>
  <Template>
    <TelerikButton OnClick="@(_=> currentCustomer = (Customer) context)">
      Select
    </TelerikButton>
  </Template>
</TelerikGridColumn>

By the way: Be careful when entering the <Template> element. Currently, Visual Studio will attempt to “correct” the element name to use a lower case “t” and give you <template>; you may need to restore the uppercase “T.”

Now, I need to set up the currentCustomer property to hold the selected customer:

@functions
{
  private Customer currentCustomer { get; set; }

  // ...
}

Before leaving the customer grid, though, I should provide some feedback to the user on which customer is currently selected. A little bit of extra code in my template will let me set the Icon property on the <TelerikButton> element to show a checkmark when the customer current row's context property matches the customer in the currentCustomer property:

<TelerikGridColumn>
  <Template>
    <TelerikButton Icon="@(currentCustomer == context ? "checkmark" : "")"
      OnClick="@(_ => currentCustomer = (Customer) context)">
      Select
    </TelerikButton>
  </Template>
</TelerikGridColumn>

Displaying Multiple Tabs

To handle displaying and revealing the two grids showing payments and processing, I could enclose those grids inside a <TelerikWindow> element (as I did in an another post). But where's the fun in that? Instead, I can use the <TelerikAnimiationContainer> element to have my payments and purchases slide in in some cool way whenever the currentCustomer property isn't null:

<TelerikAnimationContainer Visible="@(currentCustomer != null)"
                           AnimationType="AnimationType.ZoomOut"
                           Width="100%"
                           Height="500px">
  // ... purchases and payments
</TelerikAnimationContainer>

Because I have two sets of data to display, I'll nest a <TelerikTabStrip> element inside the animation container with two tabs: one for each of my payments and purchases:

<TelerikAnimationContainer Visible="@(currentCustomer != null)"
                           AnimationType="AnimationType.ZoomOut"
                           Width="100%"
                           Height="100%">
  <TelerikTabStrip>
    <TelerikTab Title="Purchases">
      // ... purchases grid
    </TelerikTab>
    <TelerikTab Title="Payments">
      // ... payment grid
    </TelerikTab>
  </TelerikTabStrip>
</TelerikAnimationContainer>

Within each <TelerikTab> element, I can just drop another <TelerikGrid> element bound to the appropriate property on the currentCustomer property (purchases or payments). Here's the grid entitled, “Purchases” inside its tab as an example:

<TelerikTab Title="Purchases">
  <TelerikGrid Data="@currentCustomer.Purchases">
    <TelerikGridColumns>
      <TelerikGridColumn Field="Description" Title="Description">
      </TelerikGridColumn>
      <TelerikGridColumn Field="Price" Title="Price">
      </TelerikGridColumn>
      <TelerikGridColumn Field="Quantity" Title="Quantity">
      </TelerikGridColumn>
    </TelerikGridColumns>
  </TelerikGrid>
</TelerikTab>

I'd be the first to admit that's a lot of markup. However, it's not much code (all I had to add was the currentCustomer property). But, by integrating multiple components, HTML, and some code, I've got an effective UI out of it:

Of course, this page isn't much good without giving the user the ability to update this information, so I'll look at that in my next post. Stay tuned!

Telerik UI for Blazor 1.4.0 is Here!

$
0
0

We're excited to release version 1.4.0 of Telerik UI for Blazor, with enhancements to the native Grid and TreeView components, ASP.NET Core 3.0 Preview 7 compatibility, and new API reference documentation!

The Telerik UI Blazor team is happy to announce the release of version 1.4.0 of the Telerik UI for Blazor components. This release includes several component enhancements, ASP.NET Core 3.0 Preview 7 compatibility, and brand new API reference documentation. Read on to learn about everything that's new.

API Reference

In July we published our Blazor API reference which is one of the foundational elements to any documentation for UI components. This has been requested by our Blazor developers in the past and this is yet another step in our commitment to offer best-of-breed resources along our excellent UI components. The API reference will give you the opportunity to further develop, expand and customize the components state and behavior, and build up your applications.

The Telerik Blazor components API reference can be accessed here and contains a list and descriptions of all public available classes, methods and properties of the Telerik UI for Blazor product.

We aimed at building it with an intuitive structure (just search for the <ComponentName>Base class where the actual properties and methods reside) and easy navigation. It will always be up to date with the latest version of Telerik UI for Blazor, so any additions to our Blazor suite of components will appear simultaneously in the API reference as well.

Again, We are Lightning Fast with Preview 7 Compatibility!

Just three days after the official release of ASP.NET Core 3.0 Preview 7 we are fully compatible with all changes by Microsoft.

Component Enhancements

Grid

With the previous versions of our native Blazor grid component, we exposed the filtering row and filter list options. With the current release we have added the grid filter menu in each of the column headers. To use a filter menu, you simply need to set the FilterMode property of the grid to FilterMode="Telerik.Blazor.FilterMode.FilterMenu", and the grid will render a button in the column header that you click to get a popup with filtering options. The popup lets you choose filter operator, filter criteria, to apply and clear the filter.

Telerik UI for Blazor Grid Filter Menu

Figure 1 Telerik UI for Blazor Native Grid Component Filter Menu

TreeView

Another essential component that we have enriched is the TreeView and its navigation, where we added the option to render links pointing to URLs. Now there are a couple of ways to achieve this:

  1. As mentioned in our previous post for Blazor 1.3.0 version: by using a template to generate the desired links
  2. By using the new built-in UrlField in the data bindings to populate the URLs in the anchors, the TreeView will generate links for you

Beyond this we have also introduced an improved TreeView user experience with sleek reveal for expand and collapse animation movements.

Blazor TreeView Animation Figure 2 Telerik UI for Blazor Native TreeView Animation
 

Inputs

The inputs now expose two events you can use:

  • OnChange– fired when the user presses Enter in the input, or when the input loses focus
  • ValueChanged– the standard part of the Value property, now you can use it because this bug in the framework is fixed

Head over the documentation to see examples (Date Input, Date Picker, Numeric Textbox, Textbox).

Experience Telerik UI for Blazor 1.4.0

With our 1.4.0 release we encourage everyone who hasn’t already tried out the components to head over to the Telerik UI for Blazor overview page and sign up for a trial experience - it’s as easy as a single button click!

Try Telerik UI for Blazor

You’ve seen this with previous releases along with this 1.4.0 release, but this is worth stating again. Looking ahead to the official release of ASP.NET Core 3.0 we are ready to continuously provide you with interim version of Blazor components compatible with each official preview by Microsoft. So, keep an eye out for the ASP.NET Core 3.0 preview release schedule and rest assured that we will closely follow each release.

As Always, We are Continuously Looking for Your Feedback

And for our early adopters and fans we want to continue to hear your feedback! If there are features you are missing, or components you need, please do not hesitate to reach out! We have the official Telerik UI for Blazor feedback portal for this exact reason. Submit your ideas for new components and features, or vote and comment on existing feature requests to have a direct impact on our roadmap!

Happy Blazor Coding!

Viewing all 1954 articles
Browse latest View live