Quantcast
Channel: Telerik Blogs
Viewing all 5320 articles
Browse latest View live

VueJs Amsterdam 2019 experience and talks summary (Part 2)

$
0
0

VueJs Amsterdam is one of the biggest Vue conferences. It comprises one day of FrontEndDeveloperLove and two days of Vue talks. In the second part of this series, get to know more about the event and what great speakers presented.

This is the second part of a series recapping the conference - see the first part of the recap here.

After Johannes’ great talk about the future of JavaScript bundlers (Ed Note: mentioned at the end of the last post), the next was Sean Larkin with the talk “New Features of Webpack 5.” This was one of the talks I wanted to see, as I am using webpack on a daily basis. To my disappointment, Sean’s talk was skipped and the next speaker was announced. Fortunately, Sean presented his talk, but just a bit later. Therefore, the next speaker after Johannes was Elena with “Elegance of Movement with Reactive Angular Animations.”

Elegance of Movement with Reactive Angular Animations – Elena Gancheva

Elena-Gancheva

Personally, I don’t use Angular, as Vue and React do the job well enough for me. However, I still found this talk quite interesting, as nice and useful animations can be great to improve user experience no matter the framework.

Why-Animate

Nevertheless, it is important not to overdo it and put too many animations that could distract and frustrate. Animations can enrich user experience when used for decoration, during micro interactions, showing loading progress, or clarifying steps or state in an application, but they should feel natural.

Examples-Cookbook

Elena showed a few examples of animations with use of Angular Material, SVG, RxJS and Angular Animations.

Love Button animation

https://stackblitz.com/edit/angular-love-button

LikeMe

The first animation is a decorative animation which reacts to micro interaction. We have a pair of eyes which with use of animation imitate looking around when moving a cursor. Animation as such shows immediate effect to an action performed by a user

Progress animation

https://stackblitz.com/edit/angular-progression-animation

The next example is a progression animation. It turns a button into a line, which shows progression state. It can be used to make user aware that something is happening in the background and how long it still might take for an action to complete.

Progress1Progress2

Reusable animation

https://stackblitz.com/edit/angular-james

Reusable

This example shows how easy it is to control animation state as well as how it can be reused for multiple elements.

BalerinaEffect

Elena ended her talk with underlining that animations and interactions should feel natural.

New Features of Webpack 5 – Sean Larkin

Sean-Larkin

Webpack is one of the most popular tools in the modern front-end development workflow. It is a module bundler which has much more to offer than just that, thanks to hundreds of plugins available. The current version of webpack is 4, and Sean Larkin’s talk was not only about new features of the next version – webpack 5 – but also explained how webpack works under the hood.

How-webpack-builds-the-graph

Faster Builds

Webpack is using a plugin system for extending functionality. As Sean explained, the next version will be a boring version update, as it will not involve any major breaking changes for users. Most of the changes are internal, but what is intriguing is the fact that build times will be up to 98% faster. This is an extreme improvement over webpack 4, especially for large projects. It is possible thanks to a new caching algorithm that will be introduced in the next version.

Deprecated Features

Other changes to webpack include removal of deprecated features in webpack 5. This change can affect plugin writers, and when upgrading to a newer version it is important to ensure deprecated features are not used.

As a developer who is using webpack in almost every project, I am looking forward to the next release as I can tell from experience that production builds can take quite some time.

Microfrontends – Luca Mezzalira & Max Gallo

The-beginning

Microfrontends are an interesting idea derived from the microservices architectural pattern. Architectural decisions have an impact on the future, as they affect developers, users and business. Bad decisions can result in loss of time and money. Therefore, it is important to take into consideration a lot of aspects when building software.

Impact-with-the-teams

Luca and Max talked about how they use microfrontends in their company, Dazn. They argued that using microfrontends makes project management easier across many teams. Just like in microservices, which are separate entities with their own languages and technologies, microfrontends are independent and can be managed by autonomous teams that can use their own technology stack. I thought that in a case of a big application, which could potentially use even a few frameworks and various versions of libraries, the JavaScript size would be enormous. This could be minimized by lazy loading different parts of the application on demand and heavily caching certain files. In addition, Service Workers could be used as well to improve caching. The way microfrontends are implemented in Dazn is by implementing a middleman between a user and microfrontends, which load required parts of application on demand.

To be honest, before this conference I only heard about microfrontends once, a few months earlier when going through my usual list of newsletters. It seems like an interesting idea, but I think that it needs a bit more time. Microfrontends is a new thing in the front-end development world and has not gotten high traction yet.

Web Components with Angular – Ana Cidre & Sherry List

Ana’s and Sherry’s talk involved explanation of Web Components and how they can be used in an Angular application. Web Components are very interesting features, as they allow creation of reusable and framework-agnostic custom elements that can be imported and used directly in HTML files.

Angular-web-components-compatibility

If you are interested in how compatible various frameworks are with Web Components, you can check out this link – https://custom-elements-everywhere.com/.

Web-components-technologies

Web Components comprise three main features – HTML template, Custom Elements, and Shadow DOM. These unfortunately are not supported in all browsers. Polyfills are available, but some features might not work exactly in the same way. More about Web Components support across browsers over here – https://caniuse.com/#search=web components.

Sherrys-Berries

After an introduction to Web Components, Ann and Sherry continued to showcase how Web Components can be created and implemented while using an example app called Sherry’s Berries.

That's all for now on VueJS Amsterdam. If you were there too, feel free to add your thoughts about the conference in the comments below.

For More Info on Vue

Want to learn about creating great user interfaces with Vue? Check out Kendo UI for Vue, our complete UI component library that allows you to quickly build high-quality, responsive apps. It includes all the components you’ll need, from grids and charts to schedulers and dials.


New ButtonTextBox and FontDropDownList Controls in Telerik UI for WinForms

$
0
0

Learn all about the new ButtonTextBox and FontDropDownList controls that shipped with the R1 2019 release of Telerik UI for WinForms.

With the latest release of the Telerik and Kendo UI product lines, we've included a variety of new controls and features across all toolkits, where in the case of Telerik UI for WinForms, we were happy to announce official support for .NET Core 3.0 and a bunch of new controls - FontDropDownList, ButtonTextBox, TabbedForm and TimeSpanPicker. In the next few paragraphs we are going to cover the first two in more detail.

ButtonTextBox

The new RadButtonTextBox control allows you to easily add buttons or other elements inside a regular textbox. Elements can be added in front or after the text. Another common case is creating a password textbox where the user can show the typed password  and then hide it. This is easily achievable by just adding a toggle button and setting its image dynamically:

RadButtonTextBox_FontDropDown_blog001

Another case where this control can be used is as buttons container and no text. This is controlled by the ShowTextBox property. Here is an example that shows how this can be used.

RadButtonTextBox_FontDropDown_blog002

Detailed information about this control is available here: RadButtonTextBox.

FontDropDownList

The RadFontDropDownList controls shows the fonts available on the system in a popup and allows the user to preview and select them. It aims to save time whenever you need to allow the end users to select a font in an application. It is already embedded in the RichTextEditorRibbonBar.

RadButtonTextBox_FontDropDown_blog003

Detailed information about this control is available here: RadFontDropDownList.

You can check a complete list of the released features here: New Splendid Release for Telerik UI for WinForms.

We would love to hear what you think, so should you have any questions and/or comments, please share them to our Feedback Portal or in the comment section below.

If you're new to Telerik UI for WinForms, you can start a free trial of the latest version today.

Dynamically Loading the KendoGrid in Blazor

$
0
0

For a preview, there's a surprising amount of functionality in the KendoGrid and KendoButton included in the Telerik UI for Blazor Early Preview. Here's how you can use them together to display data, support user editing and (almost) handle updating.

In a previous blog post I showed how to set up a Visual Studio 2019 project to use the KendoGrid control that comes with the Telerik UI for Blazor Early Preview. That post also demonstrated how easy it is to have the grid display objects retrieved from a web service. And, thanks to Blazor, it was all driven by C# code running in the client.

Note that the full project referenced in this article can be found on GitHub.

Getting Real

However, I simplified things a little in that post. For example, I fetched the data from the web service as soon as my Blazor-enabled page reached the browser. That's not always realistic. At the very least, the user will want to refresh the grid to get the latest data from the web service. Alternatively, the grid may contain data that shouldn't be displayed as soon as the page is loaded. For example, the user might need to enter some criteria to send to the web service to control what data is retrieved or the grid might be displaying “optional” data that should only be fetched when requested.

The Telerik UI for Blazor preview includes the KendoButton, which allows you to implement all those scenarios: When users are ready to see the grid populated with data, all they have to do is click the button. All that's required is to add the KendoButton to the .cshtml file along with the KendoGrid and specify the name of the method in the page that will fetch the data from the web service.

Assuming that method is called GetCustomersAsync, this markup would do the trick:

<KendoButton OnButtonClick='@GetCustomersAsync'>
  Get Customers
</KendoButton>

The declaration I used in my last post for the grid isn't affected at all. For example, I still bind the grid's Data property to a property in my Blazor code (I called the property, customers), and I still bind columns in the grid to properties on the Customer object I'm displaying. Here's that markup:

<KendoGrid Data="@customers">
  <KendoGridColumns>
    <KendoGridColumn Field="Id" Title="Customer Id" />
    <KendoGridColumn Field="FirstName" Title="First Name" />
    <KendoGridColumn Field="LastName" Title="Last Name" />
  </KendoGridColumns>
</KendoGrid>

The next step, of course, is to add the GetCustomers method to the functions block in the Blazor page. In that method, I need to do two things: fetch the data from the web service and update the property that the grid's Data property is bound to. Really, all I do is move the code I had in my startup method in my last blog post into the method that I bound to the button's click event. That code (along with the customers property) looks like this:

@functions
{
  private IEnumerable<Customer> customers = null;
  public async void GetCustomersAsync()
  {
    HttpClient hc = new HttpClient();
    HttpResponseMessage rm =
      await hc.GetAsync("https://localhost:5001/customers");
    customers =
      await rm.Content.ReadAsAsync<IEnumerable<Customer>>();
    StateHasChanged();
  }
}

What I like about Blazor is that this is just “plain old C# code.” The only thing that signals that this is client-side Blazor code is the call to the Blazor component's StateHasChanged method (that method notifies Blazor that the UI has been updated so that Blazor will redraw the affected areas of the page).

Handling Updates and State

In fact, the preview version of the KendoGrid is almost ready to handle simple updates. The grid already lets users change values in the grid just by double-clicking on a cell. What's missing is the ability to tell which rows in the grid have been changed. Ignoring that problem (for now), it's relatively easy to build some initial code that sends changed objects back to the web service for updating.

The first step is to add another button to let the user trigger updates. The markup for that would look something like this (this time I've tied the method to the button click's event using a lambda expression just to show that you have that option):

<KendoButton OnButtonClick='@(() => { SaveCustomers(); })'>
  Save Customers
</KendoButton>

Because I don't have a way to check to see what rows have changed (and am too lazy to compare the current state of the objects to their original state), in the SaveCustomers method I'll always assume that it's the first object in my collection that's changed. Here's the method that sends the first Customer object in the collection back to the web service's PUT method for updating:

public async void SaveCustomers()
{
  HttpClient hc = new HttpClient();
  HttpResponseMessage rm =
    await hc.PutAsJsonAsync("https://localhost:5001/customers",
                            customers.First());
}

Again, however, my code is a little too simple: I shouldn't allow the user to click the update button until some objects have been retrieved (and, really, not until the user has made a change, but I can't check for that with the preview grid). What I need to do is manage the update button based on my page's state.

The page's initial state is “no data retrieved.” After the user clicks the Get Customers button, the state changes to “data is retrieved.” I'll manage that state by adding a field to my page that holds the state (I'll call that field “status”). To represent my page's two states, I'll include an enumerated value (called pageState) that holds two values: NoDataRetrieved and DataRetrieved. I'll also initialize my state property to my first state of NoDataRetrieved. Finally, primarily to support debugging, I'll display the value of the state field at the bottom of my page, just above the functions block.

Putting all that together, the code following my grid and button markup looks like this:

Status: @status.ToString()
@functions {
  private enum pageState
  {
    NoDataRetrieved,
    DataRetrieved
  }

  private KendoGrid<Customer> grid { get; set; }
  private pageState status = pageState.NoDataRetrieved;
}

Because, currently, only the GetCustomers method changes the state of my page, it's the only method I'll enhance it to update the status field (I'll also have it deal with errors to make it a little more realistic):

public async void GetCustomers()
{
  HttpClient hc = new HttpClient();
  HttpResponseMessage rm =
    await hc.GetAsync("https://localhost:5001/customers");
  customers =
    await rm.Content.ReadAsAsync<IEnumerable<Customer>>();

  status = rm.IsSuccessStatusCode ? pageState.DataRetrieved
                                  : pageState.NoDataRetrieved;

  StateHasChanged();
}

All that's left to do is disable the UpdateCustomers button when the page isn't displaying data. I can do that by adding some code to the Enable attribute on the KendoButton and have that code check the value in my status field. My new, enhanced button looks like this:

<KendoButton Enable='@(status==pageState.DataRetrieved)'
             OnButtonClick='@(() => { SaveCustomers(); })'>
  Save Customers
</KendoButton>

And there you have it: A relatively functional page that, like any good AJAX application, offloads all the UI processing to the user's computer. The page only demands CPU cycles from your servers (a shared resource) when it's absolutely necessary. Unlike other AJAX pages, though, this page is written in C#.

For More on Telerik UI for Blazor

To learn more about Telerik UI for Blazor and download the preview, don't forget to check out this introductory blog post or visit the product page here.

How to Use a Vue Line Chart UI Component in Your Web App

$
0
0

Learn how to easily use line charts in your apps to plot data that changes over time. Line charts can visually display patterns like uptrends and downtrends.

In this post, you will learn how to use the LineChart component of Kendo UI for Vue. Line charts are used to plot data that changes over time. We will be using a line chart to graph cryptocurrency data. We chose cryptocurrencies because graphing financial data is a good use case for a line chart. Line charts allow you to detect patterns in data like uptrends and downtrends. The price of cryptocurrencies rise and fall regularly, so plotting the data on a line chart can help you determine which way the trend is going.

Of course, a line chart can also be used for other types of data like weather and health. You could compare temperature over time or a person’s blood pressure over time.

Up next, we will demonstrate how to create a line chart showing the weekly price of Bitcoin using a local data source. Then, we will create a line chart showing the daily volume for the currency Dash using a remote data source.

Getting Started

To initialize our project we use the Vue webpack-simple template. Inside our project, we install the dependencies which are Kendo UI, the default theme, the Charts wrapper, and the DataSource wrapper. The following commands install the packages.

npminstall --save @progress/kendo-ui
npminstall --save @progress/kendo-theme-default
npminstall --save @progress/kendo-charts-vue-wrapper
npminstall --save @progress/kendo-datasource-vue-wrapper

Inside the main.js file, we import Kendo UI, the theme, the Chart, and the DataSource. We register the Chart and Datasource globally using the ChartInstaller and DataSourceInstaller respectively and add them to the component list.

import Vue from'vue'import App from'./App.vue'import'@progress/kendo-ui'import'@progress/kendo-theme-default/dist/all.css'import{ Chart, ChartInstaller }from'@progress/kendo-charts-vue-wrapper'import{ DataSource, DataSourceInstaller }from'@progress/kendo-datasource-vue-wrapper'

Vue.use(ChartInstaller)
Vue.use(DataSourceInstaller)newVue({
  el:'#app',
  components:{
  Chart,
  DataSource
  },
  render: h =>h(App)})

Binding to Local Data

The data we will be using comes from the site CoinMarketCap. The site contains information on over 2,000 cryptocurrencies including market capitalization, price, supply, and volume. It was chosen because they keep historical snapshots of all the cryptocurrencies by the week. This gives us the information we need to build a chart so we can compare how the price of Bitcoin has changed over time. We will be looking at 10 data points from the time period October 14, 2018, to December 16, 2018.

We will add a chart component to the template in the App.vue file. Inside the component, we will set the title of the chart to “Bitcoin Prices,” position the legend on the bottom of the chart, and add tooltips when hovering over the markers. The series, categories, and value axis will be defined in our data. The following is the updated template:

<template><divid="app"><kendo-chart:title-text="'Bitcoin Prices'":legend-position="'bottom'":tooltip-visible="true":tooltip-template="'$#: value #'":series="series":category-axis-categories="categories":value-axis="valueAxis"></kendo-chart></div></template>

For the series, we will specify the type, name, and data. The series type will be a line. By default, it is a bar. The name is used in the legend to identify a series. If our chart had multiple series, they would be colored differently and we would rely on the name to distinguish one series from another. The data is the values that will be graphed. This is our Bitcoin prices. The categories are the dates. They are listed in order from earliest to latest and correspond to each value in the data. The value axis was configured in order to customize the appearance of the labels. The following is the updated script:

<script>exportdefault{
  name:'app',data(){return{
      series:[{
        type:'line',
        name:'Price',
        data:[6316.77,6513.70,6477.32,6367.24,6402.62,5594.97,3768.79,4191.90,3493.53,3272.31],}],
      categories:['10/14/2018','10/21/2018','10/28/2018','11/04/2018','11/11/2018','11/18/2018','11/25/2018','12/02/2018','12/09/2018','12/16/2018'],
      valueAxis:[{
        labels:{
          format:"${0}"}}]}}}</script>

And here are the updated styles:

<style>#app{font-family:'Avenir', Helvetica, Arial, sans-serif;margin-top:60px;}</style>

Vue

Binding to Remote Data

The data for our next example comes from the Kraken API. Kraken is an exchange where you can buy and sell cryptocurrencies. We will be making a request to their API to get data for the currency pair Dash/USD since December 1, 2018. The interval will be daily and we are interested in getting the volume and the date. The volume will be graphed on the value axis and date will be graphed on the category axis. This is the URL to fetch the data:

https://api.kraken.com/0/public/OHLC?pair=dashusd&interval=1440&since=1543622400

We will save the data to a file and specify a relative URL as the transport-read-url. The data type is JSON. Since the data isn’t formatted exactly the way we need it, we will also have to parse the response. This is the DataSource component added to the template:

<kendo-datasourceref="dataSource":transport-read-url="'./src/OHLC.json'":transport-read-data-type="'json'":schema-parse="schemaParse"></kendo-datasource>

In the chart component, we add a reference to the datasource. We change the title to “Dash Prices”. We remove the category-axis-categories attribute and replace it with the category-axis attribute. The following is the updated component:

<kendo-chart:data-source-ref="'dataSource'":title-text="'Dash Prices'":legend-position="'bottom'":tooltip-visible="true":tooltip-template="'$#: value #'":series="series":category-axis="categoryAxis":value-axis="valueAxis"></kendo-chart>

For the series data, instead of defining the data, we define the field to use from the data source. This is is the Volume field. The same goes for the category axis. We set the field to use from the data source. This will be the Date field. Last, we add a method, schemaParse, to handle parsing the data. This is the updated script:

<script>exportdefault{
  name:'app',data(){return{
      series:[{
        type:'line',
        name:'Price',
        field:'Volume'}],
      categoryAxis:{
        field:'Date'},
      valueAxis:{
        labels:{
          format:'${0}'}}}},
  methods:{
    schemaParse:function(response){return response.result.DASHUSD.map(function(arr){let utcSeconds = arr[0];let date =newDate(0);
        date.setUTCSeconds(utcSeconds);return{
          Date: date,
          Volume: arr[6]}})}}}</script>

Vue

Here is the link to the final project: https://github.com/albertaw/kendoui-linechart

Summary

A chart consists of a series, a category axis, and a value axis. Optionally, a chart can have a title, legend, and tooltips. The series attribute is the values being graphed. When binding our chart to a local data source we added an array of values to the series. When binding to a remote data source we specified the field in the series. The category axis shows the time periods in our examples. It is the axis that runs horizontally on the chart. When using a local data source the categories were defined using the category-axis-categories attribute. With a remote data source, the field was defined in the category-axis attribute. The value axis shows the values of the data points. It runs vertically on the chart.

In our next post, we will continue working with charts - stay tuned.

Resources

Try out Kendo UI for Yourself

Want to start taking advantage of the more than 70+ ready-made Kendo UI components, like the Grid or Scheduler? You can begin a free trial of Kendo UI for Vue today and start developing your apps faster.

Start My Kendo UI Trial

Angular, React, and jQuery Versions

Looking for UI component to support specific frameworks? Check out Kendo UI for Angular, Kendo UI for React, or Kendo UI for jQuery.

Resources

Authentication in Frontend Applications

$
0
0

No matter the scope of your application - even if it's a single page app - protecting the user's data is critical. Learn the best ways to keep user data secure.

The web has changed a lot. Many processes that are usually done on the server have moved to the client side. One of these is authentication.

In the past, we’ve had servers manage and store user sessions, which makes most of the authentication process secure.

Now that most of these operations have moved to the client side, where information can be easily accessed and leveraged on stateless APIs, it is important that we continue to adopt best practices and avoid vulnerabilities to ensure our application remains secure.

How Does Website Authentication Work?

Protecting the user’s information should always be top priority, regardless of the scope or size of the application.

Single Page Apps (SPAs) are often tied to APIs, and these APIs, in the form of endpoints, help provide data that can be manipulated in the logic of these apps. Some of these data the APIs provide are sensitive, so before they can be accessed some form of authentication needs to be in place.

The server housing all the data receives submitted user credentials from the frontend application, authenticates it, and returns the appropriate response.

The best known solutions to authentication problems are the OAuth 2.0 and JSON Web Token (JWTs) specifications. JWTs give you a structured way to declare who a user is and what they can access. They can also be encrypted and signed for verification. JWTs take the following form: header.payload.signature

Authentication vs. Authorization

Authentication is sometimes mistaken for Authorization, but they are quite different. With Authentication, you are trying to identify the user with credentials you have received, while Authorization is determining if this identified user should have access to a particular resource or not.

Common Security Issues with Frontend Applications

  1. Vulnerabilities in APIs used: Sometimes the vulnerabilities come from the way the APIs are built to process and return data. APIs that you specifically built for your application can be improved and proper authentication carried out, but more often than not, the use of third-party APIs is required. With less control of how secure these public APIs can be, your application may be left vulnerable.
  2. Cross Site Scripting (XSS) Attacks: This usually occurs when a vulnerable application allows external or unwanted JavaScript code to be injected and executed on the page. This vulnerability is common through forms.
  3. Cross-Site Request Forgery (CSRF): This usually occurs when a malicious website causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated (i.e. a malicious website carrying out operations you have not authorized it to do).

Things to Do

When building frontend applications, a lot of things are considered as best practices to make your applications as secure as possible. Not all these completely eliminate the problem, but they take a huge step in ensuring a more secure application.

1. Everything HTTPS with SSL

SSL stands for Secure Sockets Layer and is used to encrypt data that is transferred over the internet. This encryption allows your visitors to browse your website within a secure connection. SSL protects personal information, like phone numbers, addresses, name and credit card information when transferred.

This used to be an expensive feature to implement, but we now have providers that offer free SSL Certificates like Let’s Encrypt.

Aside from the securing of your website, an SSL certificate makes your site trustworthy: any visitor that sees that your site is protected with the “https” will have full faith in sending you their information and using your application.

2. Keep Tokens Safe

By using JWT, you have a token returned to you from the server that can be used to make subsequent requests. The challenge with this is how best to store this token.

The browser offers different approaches to storing the data but each comes with its own vulnerabilities.

Web Storage: It’s common practice to store a token in window.localStorage so that it can be easily retrieved when making an API request, but it was never designed to be secure.

window.localStorage.setItem('token', tokenReturned)

Although it is immune to CSRF, it is vulnerable to XSS. Since JWT payload/claims can actually be read without the private key (secret), it’s not secure to store it in localStorage.

HTTP Cookies: An HTTP cookie is a small piece of data, usually no more than 4kb that a server sends to the user’s web browser. Data can be stored more securely here, specifically in Secure and HttpOnly mode.

HTTP Cookies are immune to XSS but vulnerable to CSRF.

set-cookie: Expires=sun, 16 Sep 2018 17:43:00 GMT; Secure; HttpOnly

The Secure flag ensures that the browser sends the cookie only over a HTTP connection.

The httpOnly flag prevents any JavaScript code to be read from it.

3. Use Security Headers

As mentioned above, Cross-Site Scripting (XSS) is one of the major vulnerabilities for web applications. Fortunately, browsers offer and implement many features to help prevent it. This involves using security headers such as CSP, SRI, HSTS, or HPKP.

Content Security Policy (CSP): A CSP describes a series of rules that instruct the browser to allow or block resources from being loaded and executed by specifying the domains that the browser should consider to be valid sources of executable scripts.

Subresource Integrity (SRI): Using SRI enables browsers to verify that files they fetch (for example, from a CDN) are delivered without unexpected manipulation.

HTTP Strict Transport Security (HSTS): The HTTP Strict Transport Security is another HTTP response header that tells the browser that it should only allow HTTPS requests on all subsequent requests.

HTTP Public Key Pinning (HPKP): The header provides the ability to instruct the browser to verify a set of given cryptographic public keys against the requesting website.

HTTP Cookies: Already talked about this, but it’s weird to leave this empty

4. Use Access Controls

As mentioned above, a more secure way of storing tokens is using HTTP Cookies, but it also opens you up to CSRF. A CSRF attack can be prevented by using Non-Simple Requests.

To understand this, we’d look into CORS.

CORS stands for Cross-Origin Resource Sharing and is a mechanism that uses additional HTTP headers to defend against one origin (domain) from accessing data of another origin. A Non-Simple Request triggers a “CORS-Preflight” and prevents accessing of data.

Conclusion

It’s very important for every developer, especially when building single-page frontend applications, to be aware of the possible security vulnerabilities and how to minimize the risk of attack.

Authentication in different apps varies, as different apps have different flows and requirements, but the need to be security conscious is universal.

Introducing Diagram Ribbon and Smart Routing for WPF Diagram

$
0
0

In this post we take a deeper look at a new update in the Telerik UI for WPF Diagram Framework, the Diagram Ribbon and its new and improved ability to avoid overlapping connections. 

With the latest release of Telerik UI for WPF, we introduced .NET Core 3.0 support, two new controls (NavigationView & HyperlinkButton), as well as a variety of new features and improvements to the toolkitk including the Diagram Ribbon.

In the next few paragraphs, we will go over the newest features and functionalities of the WPF Diagram framework by focusing on the Diagram Ribbon and Smart Routing.

DiagramRibbon Component

Ever wonder how cool it would be to have a ribbon control which exposes the different functionalities of the Diagram Framework, like: save/load, printing, setting the selection mode, adding bridges to the connections etc. Search no more!

In the latest version of Telerik UI for WPF we introduced the RadDiagramRibbon. This control is a predefined, fully customizable and ready-to-use RibbonView, providing UI for the most common features and settings of RadDiagram. The control can be easily configured and wired to RadDiagram using a design-time wizard. With a click of a button, now you can have different kind of settings of the RadDiagram Framework combined in one control.

RadDiagramRibbon Main Tab

The DiagramRibbon contains three tabs which hold the most used features of the Diagram.

  • Home: The first tab holds functionalities like save/load, undo/redo, exporting to an image etc. I need to point out the special design Shape tool (similar to the shape tool inside Microsoft Visio) which was added to the Tools section. The new tool provides three types of shapes: Rectangle, Circle and Triangle. So, using your mouse you can add one of these shapes to the diagram surface and set their size accordingly.

DiagramRibbon_ShapeTool

  • Settings: The second tab delivers options to set more specific settings to the diagram and its items. Customizing the background grid, changing the size of the shapes or setting the zoom level are a few of the options which can be set out of the box.

DiagramRibbon_SettingsTab

You can plug three other components of the Diagram framework (RadDiagramToolBox, RadNavigationPane, RadDiagramRuler). Using the checkbox in the View section, you can set which extensions to show or hide.

DiagramRibbon_SettingsTab_Extensions

  • Design: The last tab's purpose is to give the user control over shapes layout, connection types and AStar connection routing algorithm. The diagram provides several Layouts out of the box which can be set from the Re-Layout dropdown button: Sugiyama Layout, Tree Layout, Mind Map, Radial, Tip Over. Changing the connection type or adding bridges has never been so easy. If a connection overlap appears, you could turn on the routing mechanism by just checking the Enable Routing checkbox.

DiagramRibbon_DesignTab

Cool, isn't it?

  • Extensibility: In case these built-in tabs do not include your desired functionality, or you have your own magic which you want to add for quick access, the RadDiagramRibbon can be extended to fit your needs. The AdditionalTabs and AdditionalGroups collection properties can be used to add new RadRibbonTab and RadRibbonGroup.
<telerik:RadDiagramx:Name="diagram"/>
<telerik:RadDiagramRibbonDiagram="{Binding ElementName=diagram}">
    <telerik:RadRibbonTabHeader="Custom Tab">
        <telerik:RadRibbonGroupHeader="Extend Clipboard">
            <telerik:RadRibbonSplitButtonText="Paste">
                <telerik:RadRibbonSplitButton.DropDownContent>
                    <telerik:RadMenu>
                        <telerik:RadMenuItemHeader="Paste"/>
                        <telerik:RadMenuItemHeader="Paste from"/>
                    </telerik:RadMenu>
                </telerik:RadRibbonSplitButton.DropDownContent>
            </telerik:RadRibbonSplitButton>
        </telerik:RadRibbonGroup>
    </telerik:RadRibbonTab>
</telerik:RadDiagramRibbon>

Using the above code snippet, you will get the following visualization.

DiagramRibbon_CustomTab

For more information, please refer to the Overview help article of Diagram Ribbon.

Wait, there is more!

Avoid Connections Overlap in RadDiagram

In a complex scenario where a large number of shapes and connections are used, it is hard to understand the relation between the shapes when connections overlap. Our team struggled to reduce these overlaps, but yes, we did it. Improvements were made to the AStarRouter algorithm implementation to cut down on such cases. The new AvoidConnectionOverlap property will enable the AStar algorithm to add a penalty for connection segments overlapping, thus trying to minimize the total number of such 'hard-to-follow' connections.

AvoidConnectionOverlap

For better configuration of the algorithm we added three more properties to the AStarRouter: ShapeCrossPenalty, SegmentOverlapPenalty, and SegmentOverlapDistance:

  • SegmentOverlapPenalty is a property of type double that indicates a penalty assigned to the cost of a given path when it overlaps an existing diagram connection. By default, it is 0.75. By increasing the value of this property, connections might start to cross a given shape (avoiding a connection will become a higher priority than avoiding a shape) to reduce connection segments overlap.
  • ShapeCrossPenalty is a property of type double that indicates a penalty assigned to the cost of a given path when connections cross a shape. Its default value is 1. Which means that the shortest path between two shapes is multiplied by 1. The AStarRouter will try to draw the connection in a way so that no shape is crossed. Increasing this property to 2 for example, will allow this path to be twice as long, thus reducing the chance of crossing a shape. By setting a higher value, connections may start to overlap each other as avoiding crossing shapes will have a higher priority.

ShapeCrossPenalty_Property

  • SegmentOverlapDistance is a property of type double which sets the distance around a segment in which overlap is detected. The default value is 3px. The algorithm creates a bounding box for every connection segment and considers an overlap if there are intersecting boxes from different connections.

More information about the routing mechanism of the RadDiagram can be found in the Routing help article in our documentation.

Share Your Feedback

Feel free to drop us a comment below sharing your thoughts about the new goodies in the Diagram Framework. Or visit our Feedback portal for Telerik UI for WPF and let us know if you have any suggestions or if you need any particular features/controls which you expect our RadDiagram to have.

And if you haven’t already had a chance to try our UI toolkits, simply download a trial version from the button below:

Telerik UI for WPF 

In case you missed it, here are some of the updates from our last release.

Razor Pages: the Natural Successor to Web Forms

$
0
0

ASP.NET Core Razor Pages is the natural successor to the traditional Web Forms development framework. Mike Brind attempts to demonstrate this with a high-level orientation of comparable features, showing how one maps to the other.

Is Web Forms Dead?

Well, yes and no. ASP.NET Web Forms is not completely dead, but it has pretty much had its day. There are a lot of existing Web Forms applications out there still being supported, maintained and developed further, and a lot of developers are still working with Web Forms. But web development is moving on. Frameworks need to be agile and lightweight. They need to evolve quickly. And they need to support a wide choice of platforms. They also need to include loose coupling as a feature.

Web Forms was never designed to support a loosely coupled approach to web development. The framework was primarily designed to emulate the desktop development experience as much as possible. The entire UI for each page is encapsulated in a <form> element, whether it is needed or not. The tooling promotes a drag-and-drop design experience, at the expense of building any knowledge of the underlying technologies upon which the web is built - HTTP, HTML, CSS. Dependency injection, a technique that underpins loose coupling, was difficult to implement. Extensibility points are rare. You can’t easily swap out the default HTML generation system with something of your choosing.

Over the years, improvements have been added to the Web Forms framework that effectively try to peel back its layers of abstraction. You have more control over the output that server controls generate and how view state is used. Features such as model binding have been transplanted from the more recently introduced MVC framework. And in the latest update, support for dependency injection was introduced.

But the last time that Web Forms was updated was almost a year ago. It still only works with Internet Information Services web server on Windows, and it requires an installation of the full .NET Framework. Developers new to ASP.NET are not learning Web Forms.

How Do You Move on from Web Forms?

For years, the only alternative to Web Forms for existing ASP.NET developers was the MVC (Model-View-Controller) framework. One of the biggest stumbling blocks with MVC is the architecture itself. Page-Controller-based development is pretty easy to understand. Each page has its own controller, which might be the page itself, or in a separate corresponding object such as a “code-behind”.

MVC adds what some would says is needless complexity to the development process. There is no longer a one-to-one mapping between URLs and files on disk. If you want to do anything, you have to add files in several different places. You need to understand the interaction between the various parts of the architecture. Compared to page-centric development models, MVC adds a lot of ceremony to the business of building a web site.

The ASP.NET Web Pages framework was introduced in 2010 as part of the “WebMatrix Stack,” partly to reduce the concept count associated with MVC. While Web Pages provided a return to page controller-based development, it was not without its problems. It was primarily designed to ease beginners into web development and to wean existing PHP developers over to using the Microsoft stack. As such, it provided nothing for the professional developer looking to build robust, testable and scalable web applications. The development model encouraged the mixing of processing logic and HTML markup in the same file, making it very easy for developers to reintroduce the problems associated with “spaghetti code” - difficulties in testing and maintenance. Web Pages also made heavy use of the dynamic type (introduced in .NET 4.0) as part of its data access technology, which is pretty difficult to debug.

It wasn’t long before two of the key pillars supporting the WebMatrix Stack were deprecated - the WebMatrix IDE itself, and the file-based database product, SQL Server Compact Edition, effectively killing Web Pages as a standalone development model. But it left a legacy - the Razor templating syntax upon which Web Pages was built. And the underpinnings of the Web Pages framework still exist today as the Web Pages View Engine, which supplanted the Web Forms View Engine from MVC 3.0 onward.

.NET Core

Then, Microsoft launched .NET Core in 2016, a lighter weight framework designed to have no dependencies on Windows, so that it can work on other platforms. .NET Core is also designed to solve other problems. It is modular in design, enabling the developer to choose the components that they need, rather than being saddled with the overhead of everything in one bucket. It has been designed to support much more in the way of extensibility. Dependency injection is a first-class feature, supporting loose coupling. And it is performs considerably better than traditional ASP.NET.

When it was launched, .NET Core only offered the MVC model for web developers. Version 2.0 of ASP.NET Core included a new page-centric development model called Razor Pages. This paradigm makes use of the (easy-to-learn) Razor templating syntax, and it also sits on top of the MVC framework. But you don’t need to know anything about MVC in order to work with Razor Pages. Razor Pages is the natural successor to Web Forms.

Mapping Web Forms Features to the Razor Pages Model

The remainder of this article explores the key features of the Web Forms development model, and describes how they are mapped to the Razor Pages model. I’ll describe the characteristics of each of the features, without necessarily going too deep into the technicalities. Code is included where it helps to illustrate the basic shape of the feature under discussion.

Request Processing: Code Behind

The controller for each web form is its code-behind file, a separate class file that corresponds with a template - the .aspx file. The class file derives from System.Web.UI.Page. General logic for processing the request is placed typically in the Page_Load method. The verb used to make a request is determined by examining the page’s IsPostBack property:

public class Index : Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (IsPostBack)
    {
      // process the POST request
    }
    else
    {
      // process the GET request
    }
  }
}

The equivalent to the code-behind in Razor Pages is the PageModel class, which has a one-to-one mapping with its content page (which is analogous to the .aspx file). Request processing logic is placed in handler methods. These are named, by convention, after the verb used for the request that they process: OnGet and OnPost (along with their asynchronous equivalents):

public class IndexModel : PageModel
{
  public List<Product> Products { get; set; } = new List<Product>();
  public string Title { get; set; }

  public void OnGet()
  {
    // process the GET request 
  }

  public void OnPost()
  {
    // process the POST request 
  }
}

Ad-hoc public properties can be added to the PageModel class representing items that might be used in the content page.

Presentation: Generating UI

Content Pages

The Razor Pages content page contains a mixture of HTML and server-side logic, which is included in the page using Razor syntax. Server-side logic is usually restricted to that needed-to-control output, such as loops, conditionals, perhaps some formatting strings.

Just like Web Forms, Razor content pages have a page directive, which is required and placed at the top of the file. This is followed by a model directive, which specifies the type of the data that the page is expected to work with (the Model). By default, this is the data type of the corresponding PageModel class:

@page
@model IndexModel
...

Public properties and methods of the PageModel class are exposed to the content page via its Model property:

@page
@model IndexModel

<h1>@Model.Title</h1>
<ul>
@if(Model.Products.Any())
{
  foreach(var product in Model.Products)
  {
    <li>@product.ProductName</li>
  }
}

Master Pages

The master page file in Web Forms is used to centralize control of the layout of all pages that implement it. It is typically declared as part of the Page directive in the template file:

<%@ Page Title="Home"
         Language="C#"
         AutoEventWireup="true"
         CodeBehind="Index.aspx.cs"
         Inherits="Index"
         MasterPageFile="~/Site.Master" %>

Razor’s equivalent to the master page file is the layout file. You can specify the layout file that a Razor page should use by setting the Razor page’s Layout property to the relative path of the specified file:

@{
  Layout = "/shared/_Layout.cshtml";
}

Razor provides an additional convenience in the shape of the ViewImports file - a file that affects all the pages in the folder in which it is placed, and those in all sub-folders. You can specify the layout file to be used by all of these pages in the ViewImports file instead.

In a Web Forms master page, the location of page content is defined by positioning one or more ContentPlaceHolder controls. Content controls that correspond to the placeholders are populated with content in the web form. The usual pattern is to provide a main content placeholder representing the bulk of the web form’s output, and some ancillary placeholders for page-specific meta tags, scripts, style sheets, etc.

A Razor layout page must have one call to the RenderBody method, which is the equivalent to the main content placeholder in a master page. Ancillary placeholders are represented by calls to the RenderSection method in the Razor layout. The following example shows a very simple Razor layout page that illustrates both the RenderBody and RenderSection calls:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <link href="/css/site.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="main-content">
      @RenderBody()
    </div>
    @RenderSection("scripts", false)
  </body>
</html>

The main content is rendered in the <div> element, and a separate section is defined in the RenderSection method call. In this example, the name of the section is “scripts”, and the second parameter to the method call specifies that the section is optional. It does not have to be populated in every Razor page that makes use of this particular layout page.

Server Controls

Server controls are exclusive to Web Forms. There is no direct equivalent when working with Razor-based templates. The closest thing that Razor Pages offers are Tag Helpers - reusable components for automating the generation of HTML. A tag helper targets specific HTML or custom tags in the Razor template. Through the addition of special attributes, usually prefixed with asp-, server-side code gets involved in the generation of the rendered HTML.

There are tag helpers for form inputs, for example. Mostly, they are designed to facilitate the two-way binding of data. There are also tag helpers for displaying images and hyperlinks. The following example of an anchor tag helper illustrates some of the more commonly used attributes to generat a link to a page called Edit, passing a route value of 1:

<a asp-page="edit" asp-route-id="1">Edit</a>

The more complex data bound server controls, such as the GridView and DataList, don’t have equivalent tag helpers as part of ASP.NET Core, but there are commercial controls available (including some from the owners of this blog). However, there is an equivalent to the DropDownList control - the select tag helper.

The following example binds the selected value to the ProductId property of the PageModel, and specifies that the options should be generated from the items within the ProductOptions property, which will either be an instance of a SelectList, or a collection of SelectListItem:

<select asp-for="ProductId" asp-items="Model.ProductOptions">
  <option value="">Pick one</option>
</select>

User Controls

User Controls in Web Forms represent reusable snippets of HTML which may or may not require some form of server-side processing. The closest Razor Page equivalent to the user control is a View Component. Like a user control, a View Component consists of two parts - a template file and a “code behind” file (or controller) that derives from the ViewComponent class and implements a method called InvokeAsync.

The template file features an @model directive, which dictates the data type of the data that the template is expected to work with:

@model List<Product>

@foreach(var product in Model){
<div>@product.ProductName</div>
...

The InvokeAsync method in the controller class is used to prepare the data and to pass it to the template:

public async Task<IViewComponentResult> InvokeAsync()
{
  List<Product> products = await productService.GetProductsAsync();
  return View(products);
}

Model Binding

Web Forms model binding works by associating an entity type with a databound control. The framework tries to extract values from the control’s inputs and then construct an instance of the specified entity from the submitted values:

<asp:FormView runat="server"
              ID="addStudentForm"
              ItemType="ContosoUniversity.Models.Student" 
              InsertMethod="addStudentForm_InsertItem"
              DefaultMode="Insert"
              RenderOuterTable="false"
              OnItemInserted="addStudentForm_ItemInserted">
  <InsertItemTemplate>
    <fieldset>
      <ol>
        <asp:DynamicEntity runat="server"
                           ID="DynamicEntity1"
                           runat="server"
                           Mode="Insert" />
      </ol>
      <asp:Button runat="server"
                  ID="Button1"
                  Text="Insert"
                  CommandName="Insert" />
      <asp:Button runat="server"
                  ID="Button2"
                  Text="Cancel"
                  CausesValidation="false"
                  OnClick="cancelButton_Click" />
    </fieldset>
  </InsertItemTemplate>
</asp:FormView>

In Razor Pages, the bindable object is added as a public property to the PageModel, and then decorated with the BindProperty attribute:

public class IndexModel : PageModel
{
  [BindProperty]    
  public Student Student { get; set; }

  public IActionResult OnPost()
  {
    if (ModelState.IsValid)
    {
      // save to database
    }
  }
}

Form-based tag helpers are used to bind the property values of the entity both ways in the content page:

<form method="post">
  <label asp-for="Student.FirstName"></label>
  <input asp-for="Student.FirstName" /><br />
  <label asp-for="Student.LastName"></label>
  <input asp-for="Student.LastName" /><br />
  <!-- ... -->
  <input type="submit" />
</form>

When the form is posted, the model binding system takes care of constructing a Student instance from the submitted form values.

Summary

Razor Pages is the natural successor to Web Forms. It continues a long line of page-centric web development frameworks. In fact, with the introduction of Razor Pages, MVC is no longer “king.” The default web application project in Visual Studio is Razor Pages, and the Razor Pages framework is Microsoft’s recommended approach to server-side HTML generation. As this high-level orientation is intended to demonstrate, moving from Web Forms to Razor Pages should not be a daunting experience.


For More Info on Building Great Apps with ASP.NET Core

Want to learn more about creating great web apps with ASP.NET Core? Don't forget to check out Telerik UI for ASP.NET Core, the complete UI component library that allows you to quickly build high-quality, responsive apps. It includes everything you need, from grids and charts to dropdowns and gauges.

Learn More about Telerik UI for ASP.NET Core

Get a Free Trial of Telerik UI for ASP.NET Core

Decongest Your Codebase with Logpoints in Chrome DevTools

$
0
0

Learn how you can leverage a new Chrome DevTools feature to clean up your codebase and get rid of many console.log() calls.

As developers, we always have the need to log certain parts of our code to the console. The reasons for which we log are endless; hence, it is a process we can’t get rid of easily. Therefore, if we must log, we’ll have to find a better way to do it. In this post, we’ll explain and demonstrate how you can leverage a new Chrome DevTools feature to clean up your codebase by getting rid of many console.log() calls.

What Are Logpoints?

Simply put, Logpoints is a new feature in Chrome DevTools that helps you log messages to the console without congesting your code with numerous console.log() calls. Logpoint doesn’t replace console.log(), it is just a new smarter way to log messages to the console.

How It Works

To log something to the console using the Logpoint feature, you right-click on the line number where you want to log the message.

add a logpoint

Here we right-clicked or control-clicked on line number 174 and the following options are displayed for selection. Click the highlighted Add Logpoint option to load up the breakpoint editor.

define log message

In the breakpoint editor, you define your log message. The log editor takes in data of any type so you’re not limited to logging string and integers. You can log objects and arrays and basically everything you log with the console.log() pattern.

log todo app

Here, we are logging all the entire TodoApp variable. You may have noticed we wrapped the variable in curly braces as an object, that way, we can log out its name and value in the Console. You can check out Log Objects and Object Property Value Shorthand to learn more about this syntax.

Click Enter on your keyboard to save the Logpoint.

logpoint badge

Here the orange color badge on line 74 represents a Logpoint. That way, when next the line executes, DevTools will log the result of the expression to the console. Here’s the output:

output

Conclusion

In this post, we have demonstrated how you can decongest your code by replacing all the console.log() calls with Logpoints on the browser. This makes your code a lot cleaner and reduces the tasks involved in logging data for your application. This article was inspired by the recent Google developers announcement on Logpoint. Feel free to read up the documentation for more information.

Customizing Your Console Logs Further

Interested in other ways you can improve the way you use logs in DevTools? Read these posts next:


For More Info on Building Great Web apps

Want to learn more about creating great user interfaces? Check out Kendo UI - our complete UI component library that allows you to quickly build high-quality, responsive apps. It includes all the components you’ll need, from grids and charts to schedulers and dials.


Why Blazor Grid Templates Will Make You Question Everything

$
0
0

With native components, the Telerik UI for Blazor Grid templates can fully utilize the the best features of Blazor to highly customize the user experience.

Using a template in an application implies that you're creating a custom experience for your user by leveraging a component or framework you're working with. Because the Telerik UI for Blazor components are native, built from the ground up using the Blazor framework, it can tap directly in to Blazor's best features. Grid component templates can fully utilize the HTML, Razor, and components to completely customize the user experience.

In this article we'll see an overview of what templates are available and simple use cases. We'll use these as building blocks to see just how dynamic a Blazor grid can be when using templates for advanced ideas like custom editors and master-detail views.

Template Types

There are currently three types of templates available for the Blazor grid: column Template, Editor Template, and Row Template. Each has very specific uses and are powerful tools for adapting the grid to your specific needs. Let's start with a quick introduction to each template type.

Column Template

By default, the grid renders the value of the field in the column exactly as it's provided from the data source. We can override this behavior by using a column Template which allows us to take control over the rendering of the object within the column. The Template provides the entire object currently bound to the row in which the column exists, and this object is the template's context. Through the Template we can apply custom formatting, insert additional HTML and images, and display Razor Components using any value from the context.

<TelerikGridColumn Field="@(nameof(SampleData.Name))" Title="Employee Name">
    <Template>
       Employee name is: @((context as SampleData).Name)
    </Template>
</TelerikGridColumn>

The column Template is visible when the current row is not in edit mode. To customize the grid's editing experience we'll use the EditorTemplate.

Editor Template

The EditorTemplate is a template that bound to the editing context. The EditorTemplate defines the inline template or component that will be rendered when the user is editing the field. Although the EditorTemplate acts much like the column Template, it is only shown when the given row is in edit mode.

<TelerikGridColumn Field=@nameof(Employee.VacationDays) Title="Position">
    <EditorTemplate>
        @{
            var employeeToUpdate = context as Employee;
<KendoNumericTextBox Decimals="1" Format="#.0 days" Max="15" Min="0" Step="0.5m" Value="@employeeToUpdate.VacationDays" />
        }
    </EditorTemplate>
</TelerikGridColumn>

The column and editor templates give excellent control over column rendering in the grid. For even more control we can choose to use a row template and completely customize the grid.

Row Template

Unlike the previously mentioned templates, the RowTemplate spans the entire grid for all columns. The row template allows you to define custom rendering for the entire <tr> element for each record. It can be convenient if you want to use templates for most or all of the columns, as it requires less markup than setting individual templates for many columns.

Since the template isn't bound to a specific column, it can use the Context attribute of the RowTemplate to set the name of the context variable. Its type is the model type to which the grid is bound.

<RowTemplate Context="employee">
    <td>
        <span>@employee.Id</span>
    </td>
    <td>
        Hired on: @(String.Format("{0:dd MMM yyyy}", employee.HireDate))
    </td>
</RowTemplate>
<TelerikGridColumns>
    <TelerikGridColumn Field=@nameof(SampleData.Name) Title="Employee Name" />
    <TelerikGridColumn Field=@nameof(SampleData.HireDate) Title="Hire Date" />
</TelerikGridColumns>

Using the three template types we can tackle a wide variety of requirements. Let's look at how flexible the Telerik UI for Blazor Grid can be - what we can accomplish might just surprise you.

Image Template

We'll begin with a simple yet common scenario, embedding an image in a grid column. Let's assume we have a list of users that we need to manage a broad range of details for. It be nice to associate a face with a name, and with a column template we can do just that. Using a column template we can use one or many values from the currently bound item's properties to generate an image element and display an image directly in the column. In this example we'll assume that our product's images are stored on the server with a relative path of /images/, and each image file name corresponds to the productId.

Let's begin without a template to see how the grid is structured without customization.

<TelerikGrid Data=@GridData Height="500">
    <TelerikGridColumns>
        <TelerikGridColumn Field=@nameof(Product.ProductName) Title="Product Name"/>
        <TelerikGridColumn Field=@nameof(Product.UnitPrice) Title="Unit Price"/>
    </TelerikGridColumns>
</TelerikGrid> 


@functions {
    public IEnumerable<Product> GridData { get; set; }
    
    protected override void OnInit() => GridData = ... //fetch data;
}

grid-plain

Here we have a basic two column grid with just a text display of each Product Name and Unit Price. Using a template we can transform the Product Name column to display an image alongside the product name.

To access the template, the Product Name column needs to have a TelerikGridColumn component with matching begin/end tags. Inside the component we'll add a Template component which will define our custom rendering. Inside of the template we have access to the context object, this is the current Product in scope. A simple cast of context as Product will give us access to the proper type.

<TelerikGridColumn Field=@nameof(Product.ProductName) Title="Product Name">
    <Template>
        @{
            var product = context as Product;
        }
    </Template>
</TelerikGridColumn>

Now that we have our current Product we can render it how we see fit within the column. Let's add an HTML <img tag and create a path from the ProductId property. We can apply CSS to the image using standard HTML markup class="rounded-circle". Also, since this is Razor, C# string literals are a valid way of formating the path src="@($"/images/{product.ProductId}.jpg")". We'll also display the Product Name property along side the image using simple markup.

<TelerikGrid Data=@GridData Height="500">
    <TelerikGridColumns>
        <TelerikGridColumn Field=@nameof(Product.ProductName) Title="Product Name">
            <Template>
                @{
                    var product = context as Product;
                    <img class="rounded-circle" src="@($"/images/{product.ProductId}.jpg")" />
                    <span>@product.ProductName</span>
                }
            </Template>
        </TelerikGridColumn>
        <TelerikGridColumn Field=@nameof(Product.UnitPrice) Title="Unit Price"/>
    </TelerikGridColumns>
</TelerikGrid> 

@functions ...

image-template

Because the underlying Razor Components framework supports templates and the Telerik UI for Blazor Grid is built using the framework's native architecture, the grid is a fully capable solution to many problems.

Custom Form

With templates we can fully utilize Blazor's framework features. Inside the template we can add components, logic, and even trigger events. In addition, templates aren't just scoped to the component they're contained in - we can access events and values outside of the template as well. This opens up new possibilities for creating a custom experience.

Let's assume we want to create a custom edit experience versus using one of the built in grid editors. This will give us full control over every aspect of the form. The challenge is getting the form to interact with the grid. To make a custom editor we'll need to select an item, place its properties on a form, and save/cancel changes. On the surface this might seem like a complex task, however the framework has extremely flexible data binding mechanics.

Identifying the currently selected object would provide most of what we need to accomplish the task since we can bind its properties directly to form elements. The grid's template gives us access to items that are bound to a grid row, all we'll need is a method of selecting the value and creating a reference to the object. Let's start by creating a placeholder for our object reference using a field named selectedProduct. To create an easy way of selecting a product, a column template with a button will suffice. When the button is clicked, we'll invoke an in-line function to set selectedProduct to the current context.

<TelerikGridColumn Field=@nameof(Product.ProductId) Title="Id">
    <Template>
        <TelerikButton Icon="edit" OnClick="@(_=> selectedProduct = (Product)context)">Edit</TelerikButton>
    </Template>
</TelerikGridColumn>

With the data referenced we can now add a form to display the information and provide save and cancel actions. The form will exist outside of the grid, since the object reference is now scoped to the page we can place the form anywhere outside the grid. The form can be hidden or shown based on if an item is selected using a standard Razor @if block.

@if (selectedProduct != null) {
...form
}

Saving and canceling the edit are also straightforward tasks now. We just need to create buttons with corresponding OnClick events. To cancel the edit, the selectedProduct reference is simply reset to null.

<TelerikGrid Data=@GridData Height=@Height Pageable="true" PageSize=@PageSize>
    <TelerikGridColumns>
        <TelerikGridColumn Field=@nameof(Product.ProductId) Title="Id">
            <Template>
                <TelerikButton Icon="edit" OnClick="@(_=> selectedProduct = (Product)context)">Edit</TelerikButton>
            </Template>
        </TelerikGridColumn>
        <TelerikGridColumn Field=@nameof(Product.ProductName) Title="Product Name" />
        <TelerikGridColumn Field=@nameof(Product.UnitPrice) Title="Unit Price" />
    </TelerikGridColumns>
</TelerikGrid>
<hr />
@if (selectedProduct != null)
{
    <div class="form-group ">
        <label class="control-label" for="productName">
            Product Name
        </label>
        <input class="form-control" bind="@selectedProduct.ProductName" id="name" name="name" type="text" />
    </div>
    <div class="form-group ">
        <label class="control-label" for="unitPrice">
            Unit Price
        </label>
        <input class="form-control" bind="@selectedProduct.UnitPrice" id="unitPrice" name="unitPrice" type="number" />
    </div>
    <div class="form-group">
        <div>
            <TelerikButton Icon="save" Class="k-primary" OnClick="@Save">Save</TelerikButton>
            <TelerikButton Icon="cancel" OnClick="@(_=> selectedProduct = null)">Cancel</TelerikButton>
        </div>
    </div>
}
@functions {
    ...
    Product selectedProduct;

    void Save()
    {
// save logic
        selectedProduct = null;
    }
}

CustomEditor

With the ability to share state with other components on the page, the opportunities for template driven experiences are unlimited.

Master-Detail View

Using templates we can completely transform an entire grid row with custom HTML, Razor, and even components. In this next example we'll look at just how advanced we can get with templates by adding a Master-Detail view to a grid.

A likely scenario for any application is one where a data point has many properties with varying importance. Some of those properties should always be front and center, while others might be helpful to have just within reach. This is where a master-detail view can be quite handy. This type of view helps keep extended data out of view until it is requested by the user, while keeping critical data up front all of the time.

Using the RowTemplate we can define two different states for our row which can easily be toggled by a simple button click. We'll start with the default state which only displays two columns of data. This view is nicely tucked away in a custom component called ProductMasterTemplate and takes a parameter of Product to be displayed in a two column format.

<ProductMasterTemplate Product="@product" />

In addition, we'll use a more complex view to reveal all of the data for a given product in a list view. Once again, we'll encapsulate the view in custom component called ProductDetailTemplate.

<ProductDetailTemplate Product="@product"/>

Within each of these custom components are table data cells <td> that contain Razor code for displaying the properties of a given Product. The contents of the row template must be <td> elements and their number (or total colspan) must match the number of columns defined in the grid. Internally both templates contain markup similar to the following example.

<td>@Product.property</td>
<td colspan="2">
... some view logic
</td>

With the two states clearly defined as components we can focus on switching between the two. Let's begin by defining which item is selected by creating a variable where we can hold a reference to the selected product. As such, we'll name it SelectedProduct. To enable the user to toggle between views, we'll need a set of buttons to display for the user. To show the details we'll simply check the SelectedProduct to see if it matches the current item in the row. Since we're using Blazor, we can easily set the state of SelectedProduct directly in the event handler with an in-line function, OnClick="@(_=> SelectedProduct = ...)".

<RowTemplate Context="product">
        @if (SelectedProduct != product)
        {
            <td>
                <TelerikButton Icon="@IconName.Window" OnClick="@(_=> SelectedProduct = product)">Details</TelerikButton>
            </td>
            <ProductMasterTemplate Product="@product" />
        }
        else
        {
            <td>
                <TelerikButton  Icon="@IconName.Close" OnClick="@(_=> SelectedProduct = null)">Close</TelerikButton>
            </td>
            <ProductDetailTemplate Product="@product"/>
        }
    </RowTemplate>

The completed code below is actually quite simple due to the combination of template and component architecture.

<TelerikGrid Data=@GridData Height="@Height">
    <RowTemplate Context="product">
        @if (SelectedProduct != product)
        {
            <td>
                <TelerikButton Icon="@IconName.Window" OnClick="@(_=> SelectedProduct = product)">Details</TelerikButton>
            </td>
            <ProductMasterTemplate Product="@product" />
        }
        else
        {
            <td>
                <TelerikButton  Icon="@IconName.Close" OnClick="@(_=> SelectedProduct = null)">Close</TelerikButton>
            </td>
            <ProductDetailTemplate Product="@product"/>
        }
    </RowTemplate>
    <TelerikGridColumns>
        <TelerikGridColumn Width="100" Field=@nameof(Product.ProductName) Title="Product" />
        <TelerikGridColumn Field=@nameof(Product.ProductName) Title="Product Name" />
        <TelerikGridColumn Field=@nameof(Product.UnitsInStock) Title="Unit Price" />
    </TelerikGridColumns>
</TelerikGrid>

@functions {
    Product SelectedProduct;
}

Clicking the Details button gives us a slick UI that allows us to drill into grid data.

MasterDetail

Conclusion

Because the Telerik UI for Blazor components are native, built from the ground up using the Blazor framework, it can tap directly in to Blazor's best features. Grid component templates can fully utilize the HTML, Razor, and components to completely customize the user experience. Simple templates are useful for formatting or displaying images, while more extensive templates can transform the user interface completely adding entirely new functionality to the grid.

In this post we focused on the grid, however other components like the DropDownList already feature template fields as well. Make sure you download the latest release and try the templates for yourself using our demo repository on GitHub.

Try Telerik UI for Blazor

A Look Back at React Amsterdam 2019

$
0
0

React Amsterdam took place last week in Amsterdam Noord at De Kromhouthal organized by GitNation an amazing group of folks who do an amazing job at running developer conferences like JS Nation another Netherlands based JS community project and now conference, React Day Berlin a first of its kind, a full day conference in Berlin Germany, and others. This year's React Amsterdam conference was attended by more than 1500 React developers. I attended the conference, volunteered for both days of workshops and ran a booth for my company Progress to show off our suite of KendoReact UI components.

An Amazing Conference Location

The Kromhouthal used to be a major marine engine manufacturing plant. I showed up the day before and got to see the hall before most of the conference setup was complete. Alone it's a cold dark hall, a scene that in the past would have been a labor intense atmosphere with massive machines, today it's used for major events and can hold thousands of people with its long hall and massively tall ceilings. The venue was easily accessible using the ferry from Central Station to the IJplein terminal but I also could have come from the Noordpark Metro station and in either situation just had a short 5 minute walk to the venue through a bustling creative area having a mix of local resident housing and soon to be a hotel and packing district. This area will continue to be a great location especially with plans to extend a bridge from the city center over the IJ (river). Check out these well-produced videos from the organizers to get an idea of the venue, atmosphere and moods from React Amsterdam past events.

Amazing Workshops Teaching Valuable Principles and Patterns

Although not at the infamous Kromhouthal, part of React Amsterdam (the workshops) took place nearby, in the shadow of A'DAM Lookout at the Tolhuistuin a restaurant also fronting the IJ with amazing views for the workshop attendees. This is where I volunteered for two days and had a great opportunity to work with the workshop instructors and attendees. I love helping out wherever I can, I figure that if I'm in Amsterdam for the conference, I can only do so much sightseeing, I like to work in the city to a certain capacity, feel what it's like to be there with deadlines, requirements and work to get done. There are many others like this and I met a lot of them, I worked with a few amazing volunteers and organizers like Olena, Daria, Sara, Ravi, Nicholas, Maksym, and Aleksandra directly and others that had given up their time in this amazing city to serve the community and I want to thank them for being so awesome. You may not know these people but I want you to know that the success of this conference is greatly affected by their hard work.

Speakers like Kent C Dodds did two workshops (Advanced React& Testing React), one each day and he also spoke at the conference. His workshops were exactly the kind I would have gotten so much value attending, I was able to be a fly on the wall, but I hear that you can visit his sites and get some of this same training. There were also speakers like Andrey Okonetchnikov & Artem Sapegin who gave an amazing workshop on Design Systems for React Developers showing how to design systems offer a systematic approach to the process of product creation. Their view of the IJ was amazing, which in my horrible pictures you can't see.

React Amsterdam workshop

Maybe I got one of the river, ... Here we go!

React Amsterdam workshop river view

In this same venue, we had Michel Weststrate's TypeScript for React Devs and React Native Workshop by Alex Lobera & Horacio Herrera, all of these workshops in three different rooms at the Tolhuistuin.

Across the river closer to the Amsterdam City Center, there was another set of workshops that I'm sure provides as unique of a location as the one I was volunteering at. It was at the Royal Industrieele Groote Club which I walked past several times admiring and not knowing it was actually where the other workshops had taken place. Such a beautiful building like so many others in Amsterdam the City. At that location there were talks from Kitze on two different days (GraphQL Workshop& Advanced React). They also had another interesting fundamentals workshop on [Max Stoiber Modern React.

I could not be in two places at once, but I am very interested in the differences between Kitze' and Kent's workshops. Would love if these workshops were recorded adn given access later on like the talks are done. I know that it would have gaps where the class is working, but the instructors could get clever during this time and maybe live code the exercise on the broadcast. I don't know many ways to make this conference experience more immersive, but this sounds like something they should explore. maybe they already are!

Conference Kickoff


React Amsterdam Registration

Helping at the registration was so much fun getting to meet everyone even if it was just for a minute to get them a badge and some swag. As an attendee, I got to walk away with a bag and I love my new coffee mug! There were a lot of people to process and I felt we did a good job of getting those people who showed up at the beginning, into the event on time for the kickoff, although hectic with 1500 people coming through the doors over a few hour period. It felt like a success and the conference got underway. I headed to my booth to check in with my tam where I switched hats one last time at React Amsterdam. Working our booth and meeting people that were interested in installing our components and playing with KendoReact. I love talking about the library and getting others excited about it.

KendoReact Booth

Conference Talk Highlights

There were so many great presentations and Lightening talks, I want to take some time to highlight what I think were the most valuable ones that I attended. Being someone who works with a lot of UI, layout, and presentation in React, I am a big proponent of the fundamentals and general knowledge. I start to get lost when it comes to the advanced and deep dive topics outside of UI and basic React, and what's great about this conference is that they have something for everybody. Let's look at some of those talks and review them here:

Requisite React (Kent C Dodds)

The conference started off strong with Kent C Dodds on the main stage with a talk called "Requisite React". In his own words, this talk is about: "Taking a few steps back and thinking about the usefulness of the fundamentals". We learn how to fix a droopy faucet head (with pics), and learn how understanding abstractions help us to be more effective when using them, not only in real life ?? but also in our code. This means being mindful of our abstractions and understanding that each one ultimately has some type of cost. My favorite abstraction that he dives into is that of JSX and I won't ruin the talk, but getting a look at how we can easily convert our Babel into raw JS, we are able to see under the hood and understand this abstraction better. I felt a lot of the talk was mostly about how to level up as a React developer and if you were a boss or manager who sent several of your developers out to React Amsterdam, this is exactly the type of information you want out of the gate!

Refactoring React (Siddarth Kshetrapal)

No time is wasted getting into another very valuable fundamentals based talk around refactoring in React, again we are definitely getting our value right out of the gate with many helpful tips this time from Siddarth Kshetrapel an independent developer from India who does an amazing job refactoring a login and authentication form. Starting with class components and constructors with a fair amount of prop drilling involved, we refactor this code quickly into something more manageable and future proof. Some of the techniques that he talks about are spreading props, using methods passed down in props the proper way and how to ensure that we are not overriding prop values for methods or applying them due to not managing our props correctly. He touches on principles like "Single Responsibility" and "Separation of Concerns". I really like most the parts where he talks about understanding about mixing of controlled vs uncontrolled state and how to avoid this. Pick one, he likes uncontrolled components, and this gives us the chance to get into higher order components or better yet, React Hooks. useSmartness() FTW!

So those talks were very code heavy and I was already in the mood for some straight up slide talk! My favorite kind fo talks! I don't have to strain my eyes and I still learn some new stuff I didn't know before.

A Common Design Language (Andrey Okonetchnikov)

Andrey who also did an amazing workshop on the same topic of Design Systems in React, puts all the pertinent info into a very clean and easy to understand talk on building a common design language and reducing the choices of options between typography, spacing and color to create a design language system. Using a common design language systems allows for reusability of design choices across multiple products and logos. This can be something as simple as he points out as the design of the German government logos vs Austrian government logos. One has a clear design system and language the other although creative lacks distinguishable characteristics that would show a clear alignment of all of its properties through a common design language.

Andrey's presentation had many strong visuals like above that helped to show us how a design system language can help not only your developers and designers talk, but also help your organization speak to its clients and customers clearly and with great meaning and commonality. The presentation leads into design languages for digital products and this is where we tie in the component-oriented capabilities of React that make it easy to define a common language with your UI achieving similar results as discussed before but now within digital products. Truly amazing talk and I really suggest taking the time to watch. I also want to note that React Amsterdam has an amazing design language and have continued year over year to capitalize on this using a similar set of logos, typography, and design.

Designing with React (Mark Dalgleish)

Following the previous design language presentation, we nicely transition into a talk from Mark Dalgleish on designing in React. Using design systems paired with React Mark is able to design in the final medium. Because React is so component oriented, it allows us to build our own domain specific language. I have seen first hand at companies I have worked at like Tesla capitalize on the ability to do this in React and other web technologies. Mark has some other examples of this idea spreading throughout our industry as many companies build their own design systems. Mark's major points back up the ability to capture the design intent from our design systems and applying them to the web and native apps. Seek style-guide is something that Mark's company has created and is a great resource and example of a design system for React executed remarkably.

Another amazing resource that Mark shows off is the React Sketch.app which renders React components to Sketch helping to design with real data, in react with real component code and manage your design system implemented in React. Watch the video for information on an amazing npm package they created called html-sketchapp. I will let you discover that amazing gem on your own.

Server Side Rendering Talks

So far I'm 4 talks in, and I have watched the majority of the talks running back to our booth each break to interact with the attendees and talk components. For someone like me who just likes to be totally immersed in technology and talking about it, this event allows you to get into your element. It's great to have the support of a company like mine that gives us the opportunity to do these events in an organic way and let the people representing their product come here and just geek out on React. Aside from questions I had to field about our own component library, most of the talk at the conference was around fundamentals, bleeding edge features and the React roadmap, what's coming next. just an amazing conference to really get knee deep in JavaScript and React more specifically.

The next four talks are all on Server Side Rendering (SSR) using frameworks like Next JS for pre-rendering, Crystalize for the backend to create lightning-fast scalable SSR React apps, the upsides and downsides of creating apps that use SSR, topics like rehydration, time to interactive and other things related to how our larger e-commerce sites render. In the e-commerce world, shaving milliseconds or maybe even full seconds off of load time can be very valuable. These 4 talks take you on a journey through the benefits and gotchas of SSR.

Lightning Round... One .. Start! (Read Rapidly and Fast)

OK, really fast, let me tell you about the amazing lightning round talks, read this section really fast to get an idea of what lightning rounds are like. There were four amazing lightning talks, I caught two of them in person and watched the other two from home today and I have to say that I walked away from all of them with golden nuggets from each topic that I could use to explore that topic more on my own. below are the talks and a link to them on YouTube.

I'm a huge fan of the library showcased in that last talk called Git-history and after being reminded of its awesomeness as React Amsterdam, I will be playing with this package and using it in some of my upcoming talks and demos to show the change when refactoring class based components to functional components with Hooks, I think this will provide a great visual aid in teaching on this subject. It's easy to use, I can show you right here.

Take any file in any repo of your on GitHub. Like for instance, this article I am writing now:

https://github.com/httpJunkie/telerik-blogs/blob/master/react-amsterdam-a-look-back.md

Replace http://github.com with http://github.githistory.xyz resulting in the following string: https://github.githistory.xyz/httpJunkie/telerik-blogs/blob/master/react-amsterdam-a-look-back.md

Here is a look at what Git History has done with my file from my repo:

If you are not instantly in love with this, you don't exist. I showed my son and he was mesmerized, we noted that if I were to have saved more often, I would have a much more granular step through. This is my nomination for the next years GitNation Open Source Awards (which means nothing, because I'm in no way affiliated with GitNation lol). I just think it is people like Rodrigo who will be highlighted for their contributions to open source. Truly amazing, have I said that enough?

Tech Regrets at Spectrum (Max Stoiber)

I admit that the SSR talks were a little bit over my head, but next up was Max Stoiber to talk about his Tech Regrets at Spectrum which was acquired by GitHub. Another great talk and I don't want to spoil the regrets that Max goes over and I suggest taking a listen to this talk on your own to get the value of lessons learned from hindsight and his experience building a real-world product and shipping it to users.

Scaling Applications with Microfrontends (Max Gallo)

Every once in a while there are talks at a conference where I think the guys on stage are on another level than me. TO be honest I have never built any micro frontends and if I did, I would have no idea how to scale them. When he asked for us to raise our hands if we had even heard of them, I was under strict contract to keep my hand down as I had never even heard of this. Once he started explaining the idea, I understood from a very high level. I like how his talk sets up three main tracks for understanding this micro frontends thing. Why do we need them? What is it? and how do they work under the hood? I was going to need all the hand holding I could get for this talk.

Microfrontends are like a mix between microservices and the actual frontend single page application. Microfrontends are a way of splitting up the codebase of the frontend over many teams, obviously using some type of design system to keep them all similar in style and branding, we have already heard how to do this with extra benefit from React.

Women of React Amsterdam

There was no better way to end the General React Track and the conference than to have three amazing talks by pioneering women in the React space. My absolute favorite talk from React Amsterdam was from Elizabet Oliveira. As well, I was truly inspired by both Peggy and Ashi because I'm slowly getting into GraphQL and to see WebGL and Hooks used together painting pixels has to be one of my runners up for second most inspiring talks at React Amsterdam.

An SVG's Tale (Elizabet Oliveira)

An SVG's Tale like I said is my favorite talk. She is a senior UX designer at Optum in Ireland. If I could give an award for the most inspiring talk at React Amsterdam and the most likely to get me started playing with an old but amazingly robust technology that been given a new lease thanks to React, it's SVG. I have always been a huge fan of SVG, but after her talk, I have so many ideas of how I can use SVG's properly and dynamically in my React applications using inline methods or with JSX and components. It's possible with React JS to create animations and styling that under the React hood may be complex but can allow developers not as well versed in SVG to easily use them through your components. Beyond SVG and React, Elizabet showcases a few of her side projects over the years. One of them is an app that you can record your own vocals over dank hip-hop beats which Elizabet demo's for us with some amazing lyrical skills. This speaker definitely blew my mind and I wish I could have spotted her after the talk to give her a big thank you. Truly amazing presentation, she had everyone out of their seat cheering including myself and at other times fighting back tears because her (fictional) story was so amazing and warm and her performance was pure dope!

The GraphQL Developer Experience (Peggy Rayzis)

Peggy Rayzis has to be the most compelling speaker on the topic of GraphQL especially for beginners like myself. It was one of the talks I was most amped up to hear and as happens in most conferences I got sidetracked and missed it ??. But listening back today I was not surprised at all when Peggy told us that she lived in Amsterdam for a month last year and that it is her favorite city in the world. I think most of us who came out for our first time to Amsterdam has the same feeling. I cannot think of a better backdrop for this event. It was my introduction to Europe proper! I enjoyed taking in all of the knowledge that Peggy brings to us on the subject of GraphQL and she has a great perspective as an employee for Apollo where she works as an Engineering Manager. This company builds the most amazing implementation of GraphQL. Apollo helps us bridge the gap between application and API and I don't want to spoil her talk so I simply suggest checking this one out if you are interested in learning about GraphQL.

Painting Pixels With WebGL And Hooks (Ashi Krishnan)

Ashi Krishnan is a seasoned speaker on so many different topics beyond React. She has been on my radar because of amazing talks like Deep Learning in React and Learning from machines. She works with GitHub in the UK and at React Amsterdam she closes out the General React track at React Amsterdam taking us on a journey into WebGL and how to leverage this journey with Hooks. This talk reminds me of the many things we can do in React that challenge the way we think about what a React application is and what it can do. I first started realizing all the amazing things we could do with React and rendering from Ken Wheeler's talk on building a drum machine or rendering web pages with canvas. Ashi continues to challenge our thinking about React with an amazing live demo using WebGL to paint pixels in React. If I was able to select one talk that I believed mostly encompassed creativity and thinking outside of the box it would be this one. Without giving too much away, she runs through many demos truly artistic in nature that achieve different styles and approaches to painting the screen using WebGL in React.

The React Native Track

Although I have "et, slept and breth'd" the General track at React Amsterdam I was not able to get over to the React Native track that often. But I did make a conscious effort to watch some of it. I have never used React Native but I have heard so many great things about it and did catch a few bits and pieces while I was at React Amsterdam. If I could point to one talk specifically that I think helped me understand React native better it would be the presentation given by the React Native core team member Parashuram which just so happens to also be the first talk of this React native track: Building React Native.

The React Native track can be viewed in its entirety on YouTube. Below is a complete list of all of the talks you might want to hear! If you're more of a web developer and less of a native developer, I would suggest also checking out Native Web Apps by Florian Rival.

On the React native track, we saw strong talks on Practical Perfomrance by Anna Doubková and Making React Applications Accessible by Ankita Kulkarni and Demystifying The Complex Animations Creation Process with Vladimir Novick. All were talks I was able to easily follow along not being a React Native developer.

Open Source Awards

Since React Amsterdam at heart is a JavaScript conference, a love for open source is at the heart of every conference run by GitNation, they really do a great job of highlighting and recognizing great open source projects. This year they had several categories and you can watch the awards ceremony for more context.

Breakthrough of The Year

Taken home by Michel Weststrate a Nederlander and main contributor of Immer the popular open source library used to create the next mutatable state by mutating the current state. I have just barely scraped the surface of what this library can help with, but I have used it to make returning state from my reducers in React used to mutate (while keeping immutable) my local component state. I'm sure there are many other great uses for this library and I think it was well deserving of the award. Nominees for this award were Linaria, Formik and React-navigation.

Most Exciting Technology

This award was given to the VX open source library that makes it easy to combine D3 charts into React to build amazing visual components. A demo can be seen on vx-demo.now.sh and shows how easy it is to make both your own reusable chart library or your own slick custom one-off charts. A representative was not available to take t his award home, but many props go out to the VX team for making such an amazing contribution to JS open source.

Fun Side Project of The Year

The title of the award says it all, this is just an open source contribution that GitNation believed to be fun, light-hearted and amazing in its own right. The nominees for this category were React95 (a play on Windows 95) is a React component library with Windows95 style UI. This would have also been my pick although I think both projects are absolutely fantastic. The next nominee was React-insta-stories A React component for Instagram like stories. The component responds to actions like a tap on the right side for the next story, on left for previous and tap and hold for pause. The custom time duration for each story can be provided. The winner for this award was React95. Gabriel Daltoso and Alysson Dos Santos (São Paulo - Brazil) both came up on stage to accept this very well deserved award!

Most Impactful Contribution to The Community

The winner of this award was React-testing-library. Other nominees for this award were Detox and React-navigation, and Downshift and are all very impactful in our JS community. It should be and is noted by the announcers on stage that two of these libraries have the main contributor in common with Kent C Dodds. And if he wasn't given an award himself for most impactful and influential person to React Amsterdam, he should as well with a few other speakers who did both workshops and speaking at the conference, it just so happens that kent was able to pull off a trifecta in also winning an open source award, but there were many people wearing many hats speaking, volunteering, teaching workshops and overall just living and breathing this conference.

Productivity Booster

The final award category is all about being productive as a developer. The winner is near and dear to my heart as someone who loves to write in Markdown, I'm writing this article now in markdown using VS Code and I use Git to record my progress and iterations of each and every article I write for this blog. As well, I write many presentations and slide decks and love using markdown for those as well. As you can guess, the winner of this award went to MDX Deck and was accepted by Time Neutkens and delivered to Brent jackson. Other nominees for this category were Formik, React-cosmos, and React-table.

React is Amsterdam

Talk about how Amsterdam is a perfect city for JavaScript and more importantly React developers. Some of the sponsors at the vents were based in or had offices in Amsterdam or Netherlands. The city offers so much in historical, artistic, tech and shopping, so it's obviously a great place to bring the React community and is very relaxed yet highly invigorated at the same time. Given enough time and the ability to travel throughout the city and learn the Metro, Dutch national rail company NS (Nederlandse Spoorwegen) and the various other ferry and tram systems, you can easily move around to the areas that you want to visit and crank up the energy or turn it down by traveling just out of the city's center.

I stayed in the Wilbautstraat area just 4 stops off the metro from Central Station at a wonderful hotel that I talk about more in my Developers Guide to React Amsterdam.

React 2020

If you are planning on attending the React Amsterdam 2020 event, mark your calendars now, it will be April 16th and 17th. I know I'm missing other amazing things that happened, but hopefully, this can serve as a guide if you were not able to attend or maybe a tool you can use to convince your boss to go next year. If you do, stop by our booth and talk to me, I will definitely be going back in April of next year!

Meet Telerik UI for WPF's New Family Member—HyperlinkButton

$
0
0

Buttons are everywhere and represent the most fundamental part of any WPF application, serving a variety of use cases. Let's learn all about the new hyperlink button control in Telerik UI for WPF.

The Telerik UI for WPF suite provides a variety of buttons for developers to use in building their desktop applications, yet something was missing - a way to easily add a hyperlink to a button. The good news is, the RadButtons family just got a new member – the HyperlinkButton. No, it's not the stork that is responsible - it's the Telerik UI for WPF R1 2019 Release that brought this finishing touch to your WPF apps.

Buttons Everywhere!

Where is the Hyperlink Button in WPF?

In short - there is no such control in the WPF framework.

If you are one of those people, searching for this "missing link", well I recently did some digging into that myself and followed the below research process:

  • Sources: the best-known communities for computer programmers
  • Topic: where is the link button in WPF
  • Answers Found: a tremendous volume and variety!

There were tons of people looking for such a small, yet it turns out essential, part to put the finishing touches on their WPF applications. They wondered what the control's name was, how to style the existing Button to display it as a hyperlink, and so on.

One commenter even wrote something like Did you try googling it? You would have gotten thousands of hits. P.S. to make his point, “gotten” was written with a larger font size and bolded!

It may sound funny, but the problem exists. There isn’t a straightforward, quick and easy way to have a hyperlink button in your WPF application.

Well, there wasn’t.

Discover the Brand New RadHyperlinkButton

RadButtons - a well-known part of Telerik UI for WPF - define a set of fully customizable button controls, which are feature rich and modern. Most of all, they are a strong weapon that helps in building complex and flawless user interfaces.

RadButtons Family

Cheers to that! No more need to lookup custom control templates for Button’s style, or to create a custom one, then use a bunch of other controls, plus complex bindings and triggers to get to the desired point.

WPF’s Hyperlink element (defined in System.Windows.Documents namespace) is an inline-level content element that is used to add a hyperlink to FlowDocument content. Until now, you were able to add hyperlink support to any Inline element.

If you want to have the awesome RadButton functionality and extend it with Hyperlink capabilities, well you hit the jackpot.

There are several things that you need to know about the brand new link button.

Hosting & Getting Started

One of the main advantages of HyperlinkButton is that it inherits from RadButton class, which simply means that it:

  • Supports all features of RadButton
  • Can be hosted in any UI element depending on your needs and imagination
  • Can become a part of your app in a single line of XAML code

    <telerik:RadHyperlinkButtonContent="Link"NavigateUri="http://www.telerik.com"TargetName="_blank"/>

Navigation

One of the most common properties for utilizing the control is the NavigateUri property, which is intended to be used for navigating to the needed Uri when the control is clicked.

One thing that is worth noticing is that the RadHyperlinkButton saves you the trouble of handling navigation yourself, while navigation can only occur for Hyperlink if either its direct or indirect parent is a navigation host.

Content

Another essential part of the control is the Content property, which sets the content that will be visualized by the control. The sky is the limit here. Literally.

The Content can be set to an Image, for example. In such a setup the link will be opened when the user clicks on the Image. It can be set to Glyph as well, by setting the ContentTemplate property of the control to, for example:

<DataTemplatex:Key="hbContentTemplate">
<telerik:RadGlyphGlyph="&#xe300;"FontSize="32"Margin="5"/>
</DataTemplate>

... and then you can swap it with another glyph when the link is visited, like so:

<DataTemplatex:Key="hbVisitedContentTemplate">
<telerik:RadGlyphGlyph="&#xe301;"FontSize="32"Margin="5"Foreground="White"/>
</DataTemplate>

And the result is:

Telerik UI for WPF GIF

Visual States

The RadHyperlinkButton comes with the full variety of Telerik UI for WPF’s themes (and all their different color variations) which you can apply to your application.

When Hovered or Visited, the control will be underlined, and when disabled – it will have the theme’s specific opacity value to deliver a consistent look and feel for your WPF app.

HyperlinButton Visual States

A great advantage here is that the control implements a VisitedForeground property with the help of which you are in total control of the foreground that the control will have when the link is visited. Information on whether the link is visited is also available through its IsVisited Boolean property, which might be useful.

Try the Latest Telerik UI for WPF Yourself

If you are looking for great flexibility and flawless theme-aware UI, you may want to take advantage of the latest awesome additions to the more than 130+ ready-made Telerik UI for WPF components, like RadNavigationView.

Get yourself a free trial of Telerik UI for WPF today and start developing your apps easier, better, faster.

Check Out Telerik UI for WPF

Share Your Feedback

Let’s continue to build the future of Telerik UI for WPF together, a.k.a. don’t forget to share your thoughts as a comment below or let us know if you have any suggestions and/or need any features/controls by visiting our revamped Feedback portals about UI for WPF/Silverlight and Document Processing Libraries.

How to Use a Vue Button UI Component in Your Web App

$
0
0

In this article, you will learn how to use the Kendo UI Button component with Vue. To illustrate how the button works, we will be building pagination for a list of cat pictures. Each page will have a title and an image as well as a next and previous button. Clicking the buttons will move you forward and backward through the pages respectively. When you reach the end of the posts, the next button will become disabled. When you reach the beginning post, the previous button will be disabled.

First, we will initialize our project with the data for our pages. Then we will add the buttons and implement their click handlers.

Getting Started

We will install Vue by adding a link to the CDN to the head of our HTML file. Because we are using the Vue CDN, we will need to link to the Kendo UI CDN for Vue. Kendo UI Vue Components are packaged together in different files. The following is the link to the file we will use to load the button component.

<scriptsrc="https://unpkg.com/@progress/kendo-buttons-vue-wrapper/dist/cdn/kendo-buttons-vue-wrapper.js"></script>

In the body of our page, we will create an element to mount the Vue instance on. Inside this element is a header for the title and an image element that will be bound with data from our Vue instance. The data will be an array of post objects that have a title and src attribute. To get started, we will create a Vue instance that points to the ID of our root element, initializes the data with post data and has an index to keep track of the current post selected. Then, we will add the computed property post to retrieve a post from the list. The following code shows the first post.

Vue

<!DOCTYPE html><html><head><metacharset="utf-8"><title>Button Vue</title><linkrel="stylesheet"href="https://kendo.cdn.telerik.com/2018.3.1017/styles/kendo.common.min.css"><linkrel="stylesheet"href="https://kendo.cdn.telerik.com/2018.3.1017/styles/kendo.default.min.css"><scriptsrc="https://code.jquery.com/jquery-1.12.3.min.js"></script><scriptsrc="https://kendo.cdn.telerik.com/2018.3.1017/js/kendo.all.min.js"></script><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script><scriptsrc="https://unpkg.com/@progress/kendo-buttons-vue-wrapper/dist/cdn/kendo-buttons-vue-wrapper.js"></script><style>#app{margin-top:10%;font-family: helvetica;}img {width:75%;}.text-center{text-align: center;}</style></head><body><divid="app"class="text-center"><div><h1>{{ post.title }}</h1><img:src="post.src"alt="cats"/></div></div><script>var posts =[{
        title:'Twilight', 
        src:'https://images.unsplash.com/photo-1503431128871-cd250803fa41?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80'},{
        title:'Whiskers', 
        src:'https://images.unsplash.com/photo-1448222993383-a2fff2914d27?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1510&q=80'},{
        title:'Smokey', 
        src:'https://images.unsplash.com/photo-1511275539165-cc46b1ee89bf?ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80'}];newVue({
        el:'#app',
        data:{
          posts: posts,
          index:0},
        computed:{
          post:function(){returnthis.posts[this.index];}}});</script></body></html>

Adding the Buttons

To toggle the disabling and enabling of the buttons, they are given a disabled attribute that will be equal to a boolean property in our Vue instance. For the previous button, we will add the property hasPrevious to our data and initialize it to false. Since the index is initialized to zero, the previous button needs to be disabled. For the next button, the hasNext property will be added to the data and initialized to true. The next button will be disabled when the last element is selected. This is the updated code:

<divid="app"class="text-center">
  ...
  <kendo-button:disabled="!hasPrevious"@click="onPrevious"icon="arrow-chevron-left"></kendo-button><kendo-button:disabled="!hasNext"@click="onNext"icon="arrow-chevron-right"></kendo-button></div>
newVue({...
  data:{
    posts: posts,
    index:0,
    hasPrevious:false,
    hasNext:true},});

Next, we will walk through the implementation for both buttons’ click handlers. The onPrevious method decrements the index property. The hasNext property is set to true because if the next button were disabled, it should now be enabled. Then we will check if the current index is zero. If it is, the hasPrevious property will be set to false to disable the previous button. The following code creates the onPrevious method:

methods:{
  onPrevious:function(){this.index -=1;this.hasNext =true;if(this.index ==0){this.hasPrevious =false;}}}

The onNext method increments the index and sets the hasPrevious property to true. IfhasPreviouswerefalse, clicking the next button should make it true and enable the previous button. Then we will check if the current index is two, the last index of our post data. If it is,hasNext` will be set to false, disabling the next button. This is the additional code and what the final project looks like:

methods:{...
  onNext:function(){this.index +=1;this.hasPrevious =true;if(this.index ==2){this.hasNext =false;}}}

vue


vue


vue

You can see the code for the final project here: https://dojo.telerik.com/oBEqItIZ

Summary

We created pagination for our cat pictures with a previous and next button to page through the posts. You saw how to disable the buttons and attach event listeners. You also learned the basics of how to create a Vue app, including creating a Vue instance and specifying the el and data properties at a minimum. We used the computed property to get the selected post. And we used the methods property to define our click handlers. In the next post, we will create a mini app using the Kendo UI ButtonGroup Vue component.

Try Out Kendo UI for Yourself

Want to start taking advantage of the 70+ ready-made Kendo UI components, like the Grid or Scheduler? You can begin a free trial of Kendo UI today and start developing your apps faster.

Start My Kendo UI Trial

Angular, React and jQuery Versions

Looking for UI components to support specific frameworks? Check out Kendo UI for Angular, Kendo UI for React or Kendo UI for jQuery.

Resources

Ubiquitous: a funny word that unearths some PowerShell trivia

$
0
0
Do you think that the word "ubiquitous" can be hard on a non-native English speaker's ears. It is hard for Bulgarians, that I am sure. I picked it for the title because I really like its the strangeness and because it has a nice allusion to the software development best practice of automating everything that you get your hands on: tests, build procedures, and deployment. You need that to gain predictability in your project and ensure rapid and often delivery of new features.

What surprised me was Jeffrey Snover's (yes, the architect behind PowerShell) comment about the original use of the word with regard to the PowerShell cmdlets (emphasis mine):

=================
I'll buy any book that has the word PowerShell or Ubiquitious in it.

FYI - our "common" parameters are called "common" because the doc people thought we would confuse people by calling them "ubiquitous" parameters. I had been calling them that for years prior to the switch. It's such a wonderful word.

Best of luck with the book. It sounds like it will be a good addition to the pool. It feels like it is going to be in that 2nd generations of books that focuses in on HOW TO USE PowerShell to accomplish a goal vs WHAT IS PowerShell. Both are super important.

Cheers!
Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
[Ed Note: The ScriptCenter link has since changed, find it here]
=================

By the way, if you are not aggregating the Windows PowerShell Team blog, please do it now and start getting your daily dose of useful tips and techniques.

UI for Xamarin Deep Dive: Starting Strong

$
0
0

The promise of Xamarin.Forms is that developers get to target major platforms like iOS, Android and UWP from a single shared code base and leverage their existing skills using C#/XAML in Visual Studio for Windows or MacOS. While Xamarin provides the frameworks, IDEs and integrations, most professional Xamarin.Forms apps need polished UX. Developers may be better served grabbing well-engineered performant UI controls out of the box to ship their apps faster. Think of a polished UI as the must-have wow factor. Seriously.

Telerik UI for Xamarin is a collection of Xamarin.Forms controls and Xamarin bindings built on top of the native Telerik UI for iOS and UI for Android suites. The Xamarin.Forms controls also utilize controls and features from the Telerik UI for UWP, providing a common API that allows the developer to use the native Telerik components on all three mobile platforms (iOS / Android / Windows) using a single shared code base. UI for Xamarin provides complex, rich and performant UI controls out-of-the-box so that you can focus on delivering your app functionality.

Today begins a series of articles that celebrate UI for Xamarin, unapologetically. No more fluffy overviews - we're taking a deep dive into each of the controls, their features and usage tactics. By developers, for developers. Here's what you can expect each day of this week - we'll update links as articles go live:

  1. UI for Xamarin Deep Dive: Starting Strong (this article)
  2. UI for Xamarin Deep Dive: Must-have Interactivity with ListView
  3. UI for Xamarin Deep Dive: Solid Organization with SideDrawer
  4. Recurring Appointments and Buid-in Sceduling Dialogs in Calendar
  5. View PDF Documents with PdfViewer for Xamarin.Forms
  6. New AutoCompleteView for Xamarin.Forms

Show Me the Money

Sure we can tell you that UI for Xamarin provides polished UI controls and makes a developer's life easier. But why take our word for it? Why not play around with the UI suite yourself and see if it fits your need? Check out the performance and interactivity of each of the controls, before deciding for yourself if you see the potential for your Xamarin app.

There are beautiful showcase apps that highlight UI for Xamarin controls for each mobile platform and show developers the simple sample code to achieve the results. If you're on iOS, head to the iOS Store and search for the Telerik UI for Xamarin Samples - install and play with the UI.

Telerik Xamarin Samples for iOS

Same story for Android - simply search for the Telerik UI for Xamarin Samples in the Google Play Store. Did we mention you should play around with the controls showcased in the app? Allow us to prove our worth.


Telerik Xamarin Samples for Android 

If you want to check the demos on UWP you can search in the Microsoft Store for Telerik UI for Xamarin Demo

Telerik Xamarin Demos for UWP

Supported Mobile Platforms

First, let's get the Platform support question out of the way - what can you target? You can use UI for Xamarin.Forms for applications running on the following operating systems and supported versions:

  1. Android - 4.0.3 (API 15) or higher
  2. iOS - 7.0 or higher
  3. Windows - Windows 10

That should cover most of your mobile app user base.

Getting Started with the Bits

Next up, let's talk about how you get started with the bits to use UI for Xamarin in your apps. You have several choices here, based on your OS and how you want the integration within your Xamarin project.

MSI Installation

If you're on Windows, an easy option is to download UI for Xamarin MSI Installer, if you already have a Telerik subscription to the product. Simply log in to your account on telerik.com, head to Product Downloads and find Telerik UI for Xamarin - download and fire up the MSI. It will install all the UI for Xamarin bits, provide Visual Studio integration and pull in Telerik Xamarin.Forms template integration.

Your Account Downloads 

Telerik Control Panel

Another convenient option for developers on Windows is the Telerik Control Panel - the one app that manages all your Telerik products in one place. Find UI for Xamarin, if your subscription has it, download it and install it to get the same MSI experience.

Telerik Control Panel 

NuGet

Be it on Windows or Mac, one of the easiest way for developers to integrate UI for Xamarin in their Xamarin projects is the Telerik NuGet Server.
For Windows - the first step is to configure your IDE's Package Manager to point to the Telerik NuGet feed - this is in your Tools menu/Nuget Package Manager /Package Manager Settings. Simply set up a new NuGet source to point to the Telerik gallery at https://nuget.telerik.com/nuget, authenticate yourself for the first time - and done!

On MacOS you should first add the Telerik NuGet Server in the packages source list. For more details please check our help article.

One big advantage of the NuGet route is that, not only do you get an easy way to pull in UI for Xamarin references into your existing project, you also get easy updates too. Any time we update UI for Xamarin bits, NuGet would let you know that package updates are available - you simply need to update to get the latest.

Here's how you use NuGet to pull in UI for Xamarin bits into an existing project - shown for here Visual Studio for Mac. Once you pull in the Telerik UI for Xamarin package, NuGet does the rest of the magic - you'll have the required UI for Xamarin references in your Shared project as well as all the platform specific projects.

 Add Telerik NuGet References
Telerik NuGet Packages

 Add telerik nuget for iOS project

Add Telerik Nuget for Android project

Download & Manual Integration

While NuGet may provide the easiest way to integrate UI for Xamarin in your projects, there is a more basic option in case NuGet isn't quite your cup of tea. To use UI for Xamarin controls, you essentially need the right DLLs referenced properly in your projects, and there is nothing stopping you from doing everything manually. Control freaks rejoice!

Simply get to the product page and hit the big red Download free trial button

Telerik Xamarin Free Trial
 

Once downloaded, unzip the package and take a peak inside.

Telerik UI for Xamarin Binaries iOS 

You get binaries for each supported mobile platform, as well as example apps and project templates. You may choose to add only the DLLs for the UI controls you are using from UI for Xamarin - and the required assemblies can be totally added manually.

Head to the UI for Xamarin docs and check out "Adding the required Telerik References" section inside the Getting Started article for each of the controls. The docs tell you how to integrate UI for Xamarin in both your Shared/ .NET Standard and platform-specific projects one at a time. Drop the DLLs into the specified locations in your project, add references in code and you are golden.

Starting off Right with Templates

It is not often that we developers get to start working on greenfield projects. But, if and when you do, we want to help you out a little with some polished Project Wizards - the goal is to get you to a nice starting point with UI for Xamarin.

Amidst the downloaded bits for UI for Xamarin, you'll find a Project Templates folder that contains .VSIX extension files for Visual Studio for Windows and .MPACK add-in files for Visual Studio for Mac.

If you installed UI for Xamarin from the MSI Installer, the Visual Studio Extension will be automatically added to your IDE. If you're on a Mac, you'll simply need to open up your Addin Manager and point to the .MPACK file - if successfully installed, the project wizard should show up in the IDE Extensions list, like so:

Install mpack file on VS for Mac Telerik Xamarin Add-in 

These extensions include easy project templates to aid in your getting started experience. They work in Visual Studio 2017 on Windows and Visual Studio for Mac. You'll get to pick the Telerik Xamarin UI Application template in Visual Studio and the Project Wizard steps you through your choice target platforms/API levels - the end result is a project customized to your needs and ready with UI for Xamarin bits.

Here is how to pick the template in Visual Studio for Windows:

Telerik Xamarin UI App Project Wizard 

Here's the same project wizard experience - this time on a Mac:

Telerik Xamarin Template for VS for Mac Create New Telerik UI project on Mac 

The end result is a Xamarin project with the correct UI for Xamarin bits added as references in the Portable project and platform-specific projects. Everything is all set for you to start coding up your app. 

App Solution

Conclusion

With Xamarin.Forms democratizing cross-platform mobile development for .NET developers, you should be proud of choosing the Xamarin technology stack. Just don't go reinventing the wheel with complex UI.

Telerik UI for Xamarin is here to help - our engineering efforts behind each control shows up in the performance and polish. Today was the just the beginning to get you started off on the right foot. But we know you are smart and have likely already moved past the starting experience. Come back to the Telerik Developer Network each day this week and we'll showcase a different UI control and how it can augment your app with smart features.

Also, want a rundown of common roadblocks encountered by Xamarin.Forms developers and how to solve them? Grab our new whitepaper for real-world strategies, coding samples and smart UI.

Happy coding!

UI for Xamarin Deep Dive: User Productivity with Calendar

$
0
0
Update: Check out the follow-up blog containing some of the latest new features and functionalities in the Xamarin Calendar control.

This article was co-authored by Rossitza Fakalieva and Sam Basu.

Welcome to Day 4 of our UI for Xamarin article series. Calendars keep our lives organized and productive. Everyone uses them, usually in a digital form. So it is no surprise that your mobile apps may need to display calendars and manage events on them. Turns out, however, that the calendar UI is tricky business - the little details matter.

The Telerik Calendar in UI for Xamarin is designed so you can offer your users ultimate productivity in your apps by implementing various calendar scenarios. And yes, these are truly native calendars on every mobile platform - just rendered through the Xamarin.Forms abstraction.

The Telerik Calendar capitalizes on all the innate benefits of a native UI, but exposes properties/events in C#, allowing developers full customization and flexibility. This article dives head first into leveraging the Telerik Xamarin Calendar and explores all the customization options for developers.

Visual Structure

The Telerik Calendar control offers a lot of customization options and caters to the unique UI paradigms of each mobile platform. Before we start tweaking things, it helps to see the overall big-picture control - the simple rendering of the Telerik Calendar with all visual elements explained.The labels should be self-explanatory.

You get some control to show and hide specific details to suit your needs. For example, by default, the day names show up and the week numbers don't. But here's some code to flip both along with the resulting calendar on each mobile platform:

var calendar = new RadCalendar();
calendar.WeekNumbersDisplayMode = DisplayMode.Show;
calendar.DayNamesDisplayMode = DisplayMode.Hide;

ViewMode

The Telerik Calendar has several supported View Modes that control how the calendar is initially rendered, namely:

  • Month
  • Week
  • Year
  • MonthNames
  • YearNumbers
  • Flow

Not every view mode is supported on all mobile platforms, with only iOS having the distinction of sporting them all. There are some methods exposed for changing up view modes programmatically. Each of these return true if there is support or if navigation is possible, or else they return false:

  • TrySetViewMode: Sets the Calendar to a specific view mode.
  • TryNavigateToUpperView: Navigates calendar to upper view if possible.
  • TryNavigateToLowerView: Navigates calendar to lower view if possible.

The hierarchy of navigation among the view levels is mobile platform dependent, like so:

  • iOS - YearNumbers > Year > MonthNames > Month > Week
  • Android - Year > Month > Week

Here's some simplistic code to instantiate a calendar and set the view mode to year - all programmatically:

var calendar = new RadCalendar();
calendar.NativeControlLoaded += CalendarLoaded;
    
private void CalendarLoaded(object sender, EventArgs args)
{
    (sender as RadCalendar).TrySetViewMode(CalendarViewMode.Year);
}

Date Management

The Telerik Calendar exposes properties that allow the developer programmatic flexibility to manipulate the calendar user experience:

  • DisplayDate: A date in the current view.
  • MinDate: Gets/Sets the minimum date that could be displayed or selected.
  • MaxDate: Gets/Sets the maximum date that could be displayed or selected.

Each of the date properties can be set explicitly or relative to current date, like so:

// XAML Markup
<xmlns:TelerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input" />
    
<TelerikInput:RadCalendar x:Name="MyCalendar" />
// Code Behind
MyCalendar.MinDate = DateTime.Today.AddMonths(-1);
MyCalendar.MaxDate = DateTime.Today.AddMonths(5);
MyCalendar.DisplayDate = DateTime.Today.AddMonths(2);

What do users want to do most with a Calendar? They want to select dates, of course. The Telerik Calendar sports a simple date selection functionality - both through user interaction and programmatically. And date selections can be single, multiple or a range of dates. Two key things make this possible:

  • SelectedDate: Gets/Sets currently selected date.
  • SelectionChanged: Event raised when the selected date is changed.

Here's some basic code that sets up the calendar to display the default month view mode and selects a date programmatically:

RadCalendar calendar = new RadCalendar();
calendar.SelectedDate = new DateTime(2016, 12, 14);

And here's the result - notice the style differences in the calendar controls rendered across different mobile platforms.

Appointments

Any calendar UI needs to display appointments - that's how you keep your users engaged and productive. Appointment support in the Telerik Calendar begins with the Telerik.XamarinForms.IAppointment interface which sports three basic members - StartDate, EndDate and Title. You should definitely consider adding more descriptors to your appointments as needed - a sample Appointment class implementing the interface is below:

public class Appointment : IAppointment
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate {  get; set; }
    public string Title { get; set; }
    
    public bool IsAllDay { get; set; }
    public Color Color { get; set; }
}

A collection of appointments, all stemming from an IAppointment interface implementation, can be fed to the Telerik Calendar control directly. Simply use the AppointmentSource property, which can also be data bound.

Here are some sample appointments being bound to the calendar and the corresponding results in each platform:

calendar.AppointmentsSource = new List<Appointment>() {
new Appointment() { 
    StartDate = DateTime.Today.AddDays(1), 
    EndDate = DateTime.Today.AddDays(2).AddTicks(-1), 
    Title = "Mom's Birthday",
    Color = Color.Red },
new Appointment() { 
    StartDate = DateTime.Today.AddDays(3).AddHours(17), 
    EndDate = DateTime.Today.AddDays(3).AddHours(22), 
    Title = "Big Game",
    Color = Color.Green },
new Appointment() {
    StartDate = DateTime.Today.AddDays(11).AddHours(20), 
    EndDate = DateTime.Today.AddDays(12).AddHours(4), 
    Title = "Progress Party",
    Color = Color.Red }
};

Here's a quick look at how professional Telerik Calendar appointments can look like through the Telerik UI for Xamarin Examples app - find the app in your respective App Stores.

Custom Cell Styling

Sure the Telerik Calendar has a polished UI, but there are times when you may want to customize its look and feel and manipulate the tiniest details. And in true developer-friendly form, the Telerik Calendar allows you to have custom styles for each cell.

You can set a property called SetStyleForCell to a custom function that can style individual Calendar cells. All cells share a common base class - the CalendarCell, with the following properties:

  • Text: Gets the text displayed in the cell.
  • Type (CalendarCellType): Gets the type of the cell. The possible values are:
    1. Date: All cells that correspond to actual dates have this type
    2. WeekNumber: Cells that hold week numbers
    3. DayName: Cells that hold the days of the week

And each cell can be styled using the CalendarCellStyle class, which has the following options:

  • BackgroundColor
  • BorderColor
  • BorderThickness
  • FontSize
  • FontWeight
  • ForegroundColor

Armed with cell styling flexibility, let's say you want to color the first day of spring to be a green cell in the Calendar - here's how:

var calendar = new RadCalendar();
calendar.SetStyleForCell = this.EvaluateCellStyle;
    
private CalendarCellStyle EvaluateCellStyle(CalendarCell cell)
{
    var springStyle = new CalendarCellStyle { BackgroundColor = Color.Green, FontSize = Device.OnPlatform(14, 30, 17), FontWeight = FontWeight.Normal, ForegroundColor = Color.FromRgb(139, 209, 0)};
    var dayCell = cell as CalendarDayCell;
    
    if (dayCell != null && dayCell.Date.Day == 22 && dayCell.Date.Month == 3)
    {
        return springStyle;
    }
    return null;
}

And the result:

Another common customization opportunity may arise with appointments - you may have a need to custom style appointments on a busy calendar. With the Telerik Calendar, you get an AppointmentStyle property which is of the type CalendarAppointmentsStyle. This allows for complete, color-coded customization of appointments with text and shapes.

Here's the visual structure of appointment styling in calendar cells. You can use text or shape or both.

Some of the styling opportunities with CalendarAppointmentsStyle have the following properties:

  • DisplayMode: Defines how appointments are visualized. Values can be
    1. Text
    2. TextWithShape
    3. TextWithBackground
    4. Shape
  • Padding: Defines the padding of the rectangle that holds the events.
  • Spacing: Defines the empty space between two appointments in the same date.
  • ShapeType: Defines the shape representing an appointment. Values can be
    1. Rectangle
    2. Ellipse
    3. TriangleUp
    4. TriangleDown
    5. Rhombus
  • AllDayIndicatorLocation: Defines the location where the all day indicators are visualized.

Some examples of how shapes representing appointments can be visualized are shown below:

An example of an all-day appointment indicator is below - you get to control the location, width and padding of how the indicator is rendered in the calendar cell:

Conclusion

Telerik Xamarin Calendar is a complex piece of UI with lots of features. Just know that when you need to support any type of calendars and events in your cross-platform mobile app, the Telerik Calendar stands ready out of the box - with a myriad of customization options. Look through the detailed docs when you are ready. Keep your users productive with the right calendar support. Cheers!

Other articles in this series:


UI for Xamarin Deep Dive: Typing Efficiency with AutoComplete

$
0
0
Update: Check out the follow-up blog containing some of the latest new features and functionalities in the Xamarin AutoComplete control.

Welcome to Day 5 of our UI for Xamarin article series. You survived the long reads! On the plus side, hopefully your mobile app is coming together nicely using specialized polished UI controls. Let's finish off the week with something lightweight, but important - the icing on the cake so to speak.

Let's face it - other than teenage kids, very few people enjoy typing on their mobile devices. Although keyboards, both physical and digital, have come a long way, mobile device typing is fraught with typos and frustrating auto-corrections. If and when the users of your mobile app have to type, you as a developer should try to ease the pain and aim to make it a pleasurable experience if possible.

The maxim of less is more holds true - offer suggestions and allow the user to type as little as feasible. This is true for any mobile platform, but puts the onus on developers. It turns out that pattern matching and offering suggestions with customizable UI during typing is tricky business.

The Telerik AutoComplete in UI for Xamarin is a simple, yet nifty control - it provides customizable suggestions as the user is typing. With robust data-binding options, the AutoComplete control makes it easy for developers to ease the users' pain by allowing them to choose one or multiple matching items from a list. The corresponding UI is customizable and caters to the nuances of individual mobile platforms.

This article takes an under-the-covers look at the Telerik AutoComplete control and what it can do for developers building Xamarin.Forms apps.

Show Me the Money

Since seeing is believing, here's a quick first look at a working AutoComplete control - allowing multiple selections from a pattern-matched list, along with a custom-colored look.

The Basics

First, let us get started with the AutoComplete control in its most simple form - here's some code showing the XAML markup and essentially feeding the AutoComplete control a list of strings. As the user starts typing, it does default pattern matching and aids in completing user input by offering suggestions.

// XAML Markup
.. xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input" ..
<telerikInput:RadAutoComplete BackgroundColor="White" x:Name="autoComplete" Watermark="Search here..." />
// Code Behind
this.autoComplete.ItemsSource = new List<string>()
{
    "Freda Curtis",
    "Jeffery Francis",
    "Eva Lawson",
    "Emmett Santos",
    "Theresa Bryan",
    "Jenny Fuller",
    "Terrell Norris",
    "Eric Wheeler",
    "Eduardo Thomas",
    "Jarvis Victorine",
    "Dane Gabor"
};

And here's the result - notice the nuanced differences across mobile platforms.

True Data Binding

In reality, AutoComplete usage will need more advanced and controlled data-binding to a data source against which pattern-matching will be performed at runtime. You may have a collection of objects and want the AutoComplete control to treat one text property on each object as the combined data source.

For example, when building my Aviation app that shows various planes and their top speeds, I started with a simple POCO class, like so:

public class JetData
{
    public string JetName { get; set; }
    public int JetMaxSpeed { get; set; }

    public JetData(string Name, int MaxSpeed)
    {
        this.JetName = Name;
        this.JetMaxSpeed = MaxSpeed;
    }
}

Next, here's a faux ViewModel class to hold a collection of jets - sample data being made up in line, like below:

public class SpeedViewModel
{
    public List<JetData> JetDataSource;

    public SpeedViewModel()
    {
        InitializeJetData();
    }

    private void InitializeJetData()
    {
        JetDataSource = new List<JetData>()
        {
            new JetData("Boeing Business Jet",890),
            new JetData("Gulfstream V",965),
            new JetData("Citation X",1125),
            new JetData("Bombardier Challenger 604",882),
            new JetData("Embraer Legacy",834),
            new JetData("Bombardier Learjet 60",839),
            new JetData("Beech Jet 400A",866),
            new JetData("Hawker 800XP",829),
            new JetData("Citation V",932)
        };
    }
}

With a data source in place, now I can proceed to bind the Telerik AutoComplete appropriately, like so:

// XAML Markup
<TelerikInput:RadAutoComplete x:Name="autoCompleteSearchBox" TextSearchPath="JetName"  />
// Code Behind
SpeedViewModel SVM = new SpeedViewModel();
this.autoCompleteSearchBox.ItemsSource = SVM.JetDataSource;

Notice how the ItemSource property of the AutoComplete control is being fed the data collection off the ViewModel, but the TextSearchPath is being set to a specific property of each object.

Flexibility

The Telerik AutoComplete control exposes a few properties that are aimed at providing flexibility to developers as they use the control in their apps. We developers love customization options, right?

  • BackgroundColor: The text background color as the user is typing the text.
  • TextSearchPath: Defines the object property name the search function will be executed against.
  • ImagePath: Defines the object property name holding a path to an image.
  • CompletionMode: Defines pattern matching mode against user-entered text | Values - Contains/StartsWith
  • DisplayMode: Defines whether Autocomplete allows single/multiple selections | Values - Text/Tokens

Back in the aviation app example, the XAML markup could be updated to use some of these properties, as below (the corresponding result follows):

<TelerikInput:RadAutoComplete BackgroundColor="Silver" x:Name="autoCompleteSearchBox" Margin="0,15,0,0" 
    TextSearchPath="JetName" CompletionMode="Contains"  DisplayMode="Tokens" />

Suggestion Templating

Like the pattern-matching capabilities of the Telerik AutoComplete control, but want to customize the user experience further? Sure - developers can have fine-grained control over the way the suggested items list shows up as the user is typing. This is controlled through the SuggestionItemTemplate - a customizable data template that defines how each of the suggestion items should look like.

Let's take a look at customizing the suggestion templates through an example. Say you are using the AutoComplete control in a chat application and want to show the connectivity status of each person, in addition to their name, in the suggestions list - here's a sample business object:

public class BusinessObject
{
    public BusinessObject(string name, string imageSource)
    {
        this.Name = name;
        this.ImageSource = imageSource;
    }
    
    public string Name { get; set; }
    
    public string ImageSource { get; set; }
}

And here's a sample View Model filling in a faux collection of business objects that can act as a data source for the AutoComplete control:

public class ViewModel
{
    public ViewModel()
    {
        this.Source = new List<BusinessObject>()
        {
            new BusinessObject("Freda Curtis", "available.png"),
            new BusinessObject("Jeffery Francis", "away.png"),
            new BusinessObject("Eva Lawson", "available.png"),
            new BusinessObject("Emmett Santos", "away.png"),
            new BusinessObject("Eric Wheeler", "busy.png"),
            new BusinessObject("Eduardo Thomas", "away.png"),
            new BusinessObject("Lauretta Pozo", "busy.png"),
            new BusinessObject("Jarvis Victorine", "away.png"),
            new BusinessObject("Dane Gabor", "busy.png")
        };
    }
    
    public List<BusinessObject> Source { get; set; }
}

Now, here's the XAML markup for the AutoComplete control where we can do the binding to the local View Model - notice the use of the SuggestionItemTemplate that puts the person's name and status side by side:

.. xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input" ..
<telerikInput:RadAutoComplete BackgroundColor="White" ItemsSource="{Binding Source}" TextSearchPath="Name" VerticalOptions="Start" Watermark="Search here...">
  <telerikInput:RadAutoComplete.BindingContext>
    <local:ViewModel />
  </telerikInput:RadAutoComplete.BindingContext>
  <telerikInput:RadAutoComplete.SuggestionViewHeight>
    <OnPlatform x:TypeArguments="x:Double" iOS="400" Android="200" WinPhone="400" />
  </telerikInput:RadAutoComplete.SuggestionViewHeight>
  <telerikInput:RadAutoComplete.SuggestionItemTemplate>
    <DataTemplate>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*" />
          <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Label TextColor="Black" Text="{Binding Item.Name}" FontSize="24" Margin="5" />
        <Image Grid.Column="1" HeightRequest="20" WidthRequest="20" Source="{Binding Item.ImageSource}" Margin="5" />
      </Grid>
    </DataTemplate>
  </telerikInput:RadAutoComplete.SuggestionItemTemplate>
</telerikInput:RadAutoComplete>

And now the result, with a customized suggestion template catering to the nuances of each mobile platform:

Conclusion

The Telerik AutoComplete control looks simple - but is doing a lot of heavy lifting behind the scenes. The performant pattern-matching is powered by sophisticated algorithms, but your productivity can be boosted in not having to think about implementations. Simply drop in the AutoComplete control and customize it for your needs. You will make typing a better experience on your mobile apps. Happy users make for increased app usage and, in turn, happier developers.

This concludes our weeklong UI for Xamarin deep dive articles, showcasing individual controls and their usage. The goal is simple - make Xamarin developers more productive and successful with polished performant UI controls out of the box. We've only scratched the surface though - there are lot more controls in the UI for Xamarin suite. Look for another article series coming up soon. Until then, stay classy developers!

Other articles in this series:

Why Xamarin

$
0
0

While there are many ways to build for mobile form factors, let's explore what's in it for developers if they choose the Xamarin technology stack.

Even after years of building for mobile, developers still heavily debate the choice of technology stack. Perhaps there isn't a silver bullet and mobile strategy really depends - on app, developer expertise, code base maintenance and a variety of other factors. If developers want to write .NET however, Xamarin has essentially democratized cross-platform mobile development with polished tools and service integrations. Why are we then second guessing ourselves?

Turns out, mobile development does not happen in silos and all mobile-facing technology platforms have evolved a lot. It always makes sense to look around at what other development is happening around your app - does the chosen stack lend itself to code sharing? Are the tools of the trade welcoming to developers irrespective of their OS platform? Do the underlying pillars of chosen technology inspire confidence?

Let's take a deeper look and justify the Xamarin technology stack. Spoiler - you won't be disappointed.

This article is a part of a long content series on Chasing Success with Xamarin Apps - we explore the Xamarin technology stack, tools and services that help developers build successful mobile apps.

Mobile Strategies

While there are variety of ways to build for mobile, the following are the broad categories:

UpdatedMobileStrategy

Thankfully, whichever technology stack mobile developers choose, there's mature tooling and easy access to mobile platform APIs. Let's discuss some pros and cons of each approach however:

  • Native: The most straightforward way of building for mobile is native apps for iOS, Android and Windows. Native apps run closest to the metal and developers get to use platform-specific SDKs/languages/tools. While fast and beautiful, native apps are rather expensive, requiring maintenance of platform-specific code bases.

  • Mobile Web/PWAs: The lowest hanging fruit to go cross-platform with mobile is often mobile web - there are plenty of frameworks that help web applications work nicely on mobile browsers. Mobile web apps can be taken to extreme smartness through Progressive Web Apps - where web apps start behaving as legitimate citizens in the mobile app world. Users can pin web apps to their home screens, have service workers run in the background and get push notifications. There is a lot of tooling help when building mobile web and mature JavaScript SPA frameworks for building PWAs.

  • Hybrid: Cordova popularized the idea of building cross-platform mobile apps with web technologies - HTML, CSS and JS bundled together to make a mobile app. Such hybrid apps ran within the browser shell and the user would not notice if done well. While hybrid apps enjoy good tooling, mature frameworks like Ionic and app store presence, the browser sandbox does hamper their runtime speed a little.

  • JS Native: The last few years have been witness to the rise of cross-platform mobile apps written in JavaScript/Typescript - the point is, why go hybrid when you can go native with the same technologies? JS Native apps enjoy complete native platform access and render native UI - all from a single code base. JS Native apps enjoy wonderful frameworks like NativeScript, NativeScript with Angular/Vue integration and React Native.

  • X-Compiled: If you would rather write .NET code and use familiar tooling like Visual Studio, the cross-compiled mobile app solution is rather enticing. The trick is compiling higher level .NET language code into binary bits for each mobile platform, all the while rendering native UI. Xamarin has largely democratized the X-compiled space for .NET developers, with the Uno platform lending a helping hand of late. If you are ok writing Dart, Flutter offers another enticing approach to writing native mobile apps for iOS/Android with fast dev-reload cycles.

While you'll find this article advocating for the Xamarin technology stack, the point of this mobile strategy discussion is that you don't have to always do Xamarin to reach cross-platform mobile. If you are invested in the web stack and happy writing JS/TS, the web route of getting to mobile form factors will yield rich dividends and lend itself better to code sharing.

All the .NETs

As one dives into the Xamarin technology stack, it is often beneficial to taka a step back and understand the .NET ecosystem - where does Xamarin fit? Here's the big picture story with .NET:

DotNets

As developers know, the .NET stack has evolved a lot in the past couple of years. There are multiple .NETs for different types of apps - to be read as multiple Base Class Libraries (BCLs). The three most popular ones are:

  • .NET Framework: This is the full .NET Framework that has the been the darling of developers on the Microsoft stack for 17 years now. The .NET Framework provides as rich an ecosystem as you can get - top notch tools, community support, extensibility and runtime for hosting variety of .NET applications. Over the years however, the .NET Framework has shown obvious bloat and the monolithic nature of the framework invites brittleness, as well as upgrade headaches. Make no mistake, the .NET Framework isn't dying and remains a core part of Windows. However, it may not see serious innovations going forward - existing apps would continue to run fine, but any greenfield development should look ahead at other .NETs.

  • .NET Core: This is the new .NET, built from ground up to address some of the concerns of .NET Framework. .NET Core is lean, modular and for the first time, boasts a cross-platform runtime taking .NET apps to MacOS/Linux. While new, .NET Core has seen rapid innovations and sports near-par API features compared to the .NET Framework. The lightweight nature of .NET Core lends itself naturally for building high performance web applications, while the command line/cross-platform tooling provides developers with liberties. The benefits of side-by-side .NET runtimes are stretching back to desktop with .NET Core 3, while .NET Core itself pushes the envelope with technologies like ML.NET.

  • Mono: Since the inception of .NET, there has been a desire to take .NET apps outside of Windows. Meet Mono - the port of .NET APIs to other platforms that is as old as the .NET Framework itself. Mono is the runtime for all Xamarin applications and remains an incredibly versatile way of supporting .NET on an increasing number of non-Windows platforms.

It is not hard to see how this variety of .NETs in the ecosystem provides flexibility - developers get to choose which .NET works best for their apps. Xamarin running on Mono is a very important piece of the puzzle for Microsoft - it is what gives .NET the extensive platform reach. With all the .NETs, there are very few devices/platforms that modern .NET developers cannot reach.

Mono or .NET Core

Mono has always been a great natural fit as a runtime for Xamarin apps. Developers write .NET code which is compiled down to generic Intermediate Language (IL) code, and then the Mono bridge/virtual machine translates .NET IL to native assembly code for iOS/Android or other platforms. It is only recently that much of .NET became open source - prior to that, Mono painstakingly made .NET code portable and executable on other platforms.

However, there is .NET Core now, which is modern, versatile and cross-platform. Developers in the Xamarin ecosystem have wondered of late - could .NET Core actually replace Mono as the runtime for Xamarin apps?

MonoNetCore

While it is enticing to expect everything out of the new polished runtime, the realities dictate otherwise. Turns out, age does make you wise and Mono, to this day, sports a bigger API surface area than .NET Core. Mono is also very performant for .NET apps running on iOS/Android - both through IL interpretation or statically compiled. Mono is also way ahead of the game in .NET implementations on future-facing platforms, like the all-important WebAssembly. So, it is safe to say that Mono is here to stay and power .NET apps across a wide variety of platforms.

The other question to consider is fragmentation of .NET. While having various .NET BCLs optimized for different platforms is nice, is the present state of the ecosystem inviting confusion for developers? Does it make sense for Microsoft or the open source community to maintain so many .NET? Perhaps a unification of the various runtimes is called for - only time will tell.

How to Xamarin

Developers choosing the Xamarin technology stack to build for mobile can be assured of a solid performant runtime and a plethora of rich tooling. This frees up developers from having to worry about the logistics of building an app, and lets them just focus on the app itself. As one gets started with Xamarin, there are two broad choices:

Xamarin iOS/Android

From the early days of Xamarin, the goal was to write .NET code that could be shared across mobile platforms, and this is traditionally what is called Xamarin.iOS/Android. Often dubbed Xamarin Native, the goal is to have a shared code layer written in .NET and platform-specific projects for the UI part of the mobile apps.

XamarinNative

The goal with Xamarin.iOS/Android is to abstract out as much of the app feature set as possible into a .NET code library - this is shared across all platforms. While a great step in the right direction, Xamarin Native does require developers to build the UI layer of each supported mobile platform on its own. This means developers do need to know how to build app UI for iOS, Android and Windows natively - all pulled together into a single project and referencing the shared library.

So when should developers choose to build with Xamarin iOS/Android? Xamarin Native is a good choice in general when mobile apps tend to cater heavily to a certain platform - where lots of native behaviors and custom UI are called for. Mobile games are also served well with Xamarin Native - essentially, Xamarin.iOS/Android is a good choice anywhere developers want to run as close to the metal as they can. Xamarin Native still benefits from a shared .NET code layer, but the UI is written natively for each mobile platform. Additionally, Xamarin.Forms (see below) can now be embedded inside of Xamarin Native, thus getting the best of both worlds.

Xamarin.Forms

What started out as a prototyping tool for cross-platform abstractions has grown into what we call Xamarin.Forms today. In addition to the shared .NET code, there is a layer of shared UI that stretches across platforms and renders corresponding native UI. This shared UI layer is an abstraction allowing developers to write .NET code/markup, which gets translated to native UI on each platform at/before runtime. Xamarin.Forms has the huge benefit of .NET developers not having to know the intricacies of building iOS/Android UI by hand.

XamarinForms

Keep in mind though, Xamarin.Forms is trying to solve an incredibly hard problem - a consistent UI abstraction layer that renders native UI on platforms that are uniquely different. While Xamarin.Forms has a large breadth of control coverage, the developer community and partner ecosystems fill in the gaps with cross-platform UI. If developers are up for it and app demands it, developers can always jump down to native UI land from Xamarin.Forms by writing custom renderers for platform-specific behaviors or rendering native UI controls on a per platform basis.

So Why Xamarin Again?

The bottom line is, it is 2019 and hopefully mobile isn't an afterthought. A legitimate mobile strategy reduces developer frustration and allows for code reusability. If you are invested in web technologies, modern mobile web, hybrid or JS native apps are the way to go - you have rich tooling and plethora of native API access.

If however you want to go with the .NET option, Xamarin is an easy choice. Here are some indicators that will help you make up your mind that you want to choose the Xamarin technology stack:

  1. You want to write C#/F# code
  2. You are comfortable with XAML as a markup language
  3. You care for maximum code reusability with other .NET projects
  4. You want to stay within the comforts of Visual Studio
  5. You expect a solid runtime, polished tools and a rich ecosystem

Convinced about Xamarin? Your code is in good hands and the future looks awesome.

Constraining Generics in C#

$
0
0

When working with generic classes or methods, it can be useful to constrain the types that can be used with them. There are many constraints we can apply. Learn what they are and how to use them.

Generics make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. Generic classes can be constrained to be used only on certain data types. This increases the number of allowable operations and method calls to those supported by the constraining type and all types in its inheritance hierarchy. I’ll introduce you to the various ways you can constrain generic types in C#.

Constrain by Value Type

You can constrain a generic type to a value type by setting the constraint of the type as follows.

class ConstrainByValueType<T> where T : struct { }

Here the struct keyword is used to constrain T to a value type. The object can then be instantiated like new ConstrainByValueType<double>, and you can specify any value type as you want. Be aware that you can’t use a nullable value type, so this will fail, new ConstrainByValueType<double?>.

Constraint to Allow Only Reference Types

You can also constrain the type to allow only reference types. Similar to how you would do it for value types, you would use the class keyword to constrain the type to a reference type.

class ConstrainByReferenceType<T> where T : class { }

Interface Type Constraint

You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.

interface IAnimal { }
class Snake : IAnimal { }
interface IMammal : IAnimal { }
class Lion : IMammal { }
class CuteLion : Lion { }

class ConstrainByInterface<T> where T : IMammal { }

The type T above is constrained to the IMammal interface, which allows only classes that implements this interface (or classes that inherit from a class that implements the interface) to access the generic type. Even if the IMammal inherits from the IAnimal interface, you can’t use Snake as the type for T. You can only use Lion or CuteLion type.

Constrain by Class

We can restrict a generic type to only allow type parameters of a specific class, or classes that inherit from that specific base class. Following the example of the previous section, let’s create a generic class which is restricted to the Lion class.

class ConstrainByClass<T> where T : Lion { }

In this scenario, only the Lion class or a class that inherits from Lion can be used to instantiate this generic type.

Another constraint we can apply is to ensure that the class that’ll be used as the type parameter has a public, parameterless constructor. We do this by using the keyword new() as the constraint for the generic type.

class ConstrainByParameterlessCtor<T> where T : new() { }

With the constraint above, the ConstrainByParameterlessCtor class is restricted to use classes which have a public parameterless constructor.

Using Enum as Constraint

Beginning in C# 7.3, you can specify the System.Enum type as a constraint. The code below is an example of how to use enums as constraint for generics.

class Program
{
  class ConstrainByEnum<T> where T : System.Enum
  {
    public void PrintValues()
    {
      var values = Enum.GetValues(typeof(T));
      foreach (int item in values)
        Console.WriteLine(Enum.GetName(typeof(T), item));
    }
  }

  enum Rainbow
  {
    Red,
    Orange,
    Yellow,
    Green,
    Blue,
    Indigo,
    Violet
  }

  static void Main(string[] args)
  {
    var enumGeneric = new ConstrainByEnum<Rainbow>();
    enumGeneric.PrintValues();
    Console.Read();
  }
}

The type T as you see is restricted to enums, and the class has a PrintValues method prints the enum type values to the console. Running the code should print out the following:

Red
Orange
Yellow
Green
Blue
Indigo
Violet

Microsoft Documentation also shows an example that used to make use of reflection, but with this feature allowed, it no longer uses reflection and has improved performance.

Beginning with C# 7.3, we can use the unmanaged constraint to specify that the type parameter must be an unmanaged type, and System.Delegate or System.MulticastDelegate as a base class constraint. The documentation provide an example and details on using the unmanaged constraint and delegate constraint.

Combining Constraints

You’ve seen how we can apply a single constraint to generic types. While that is valuable, we can also use these constraints in combination.

class Program
{
  interface IMammal { }

  class CuteLion : IMammal
  {
    private CuteLion() { }
  }

  class RainbowLion : IMammal { }

  class ConstrainByCombination<T> where T : IMammal, new() { }

  static void Main(string[] args)
  {
    new ConstrainByCombination<RainbowLion>(); // Valid
    new ConstrainByCombination<CuteLion>(); // Invalid
    Console.Read();
  }
}

In the example you see above, we’re constraining T to use IMammal interface and must have a public parameterless constructor. We have two classes which implement the IMammal interface. The CuteLion class implements this interface but has a private parameterless constructor, and this doesn’t satisfy the condition to use it the type for the generic class. The RainbowLion class satisfies this condition, therefore, can be used as the type parameter for the generic class.

Conclusion

When working with generic classes or methods, it’s sometimes useful to constrain the types that can be used with them. There’s a number of constraints that we can apply and this article sums up those constraints and how we can use them. We also looked at new constraints that are allowed starting from C# 7.3 and how to combine multiple constraints to enforce stronger rules on generics.

Top 5 JavaScript Online IDEs to Use in 2019

$
0
0

Using online JavaScript editors can help you edit and compile your code directly into your browser. Here, we look at the top 5 IDEs to help you achieve this fit.

The lack of mobility and other features in our local integrated development environments (IDE) has given rise to a number of other online development environments. Also as a result of these limitations, programming on the go has proven to be tough, especially for JavaScript since it is built for the web.

To this effect and to bridge this mobility gap, the web in return has provided JavaScript with amazing online editors that you can use to program on the go. Using online JavaScript editors can help you edit and compile your code directly into your browser. The code editors also offer you a LIVE preview, as it is all on the web! In this post, we’ll look at five of these online IDEs.

Codenvy

Codenvy is a cloud-based development environment for web developers and for distributed development teams. The strength of the Codenvy’s IDE lies in its ability to manage development teams and develop code with portable Docker runtimes.

Codenvy

Codenvy has three major packages specifically designed for Developers, Teams and Enterprises. This way, Codenvy supports any of your needs, whether you’re a developer, a team manager or an enterprise.

Developer

As a developer, Codenvy helps you overcome the stress involved with setting up local code editors to support different languages across all the systems you work with. With Codenvy, you take your work anywhere and set up on any computer without having to install and configure your editor.

Teams

Distributed teams leverage the collaborative power of Codenvy to work together on common projects to better manage project workflows. Codenvy offers more team focused features like custom runtimes, user permissions and of course consistent collaboration. The team features of Codenvy makes it possible for team members to collaborate dev-to-dev and equally interact with stakeholders before committing code.

Enterprise

When it comes to developing on the fly, enterprises need it all in one place — one-click developer environments, team onboarding and collaboration, and a secured DevOps workspace platform. As a result, Codenvy provides all these and more for enterprises as it integrates seamlessly with issue management, version control, and CI tools to generate ready-to-code workspaces with the right branch and runtime.

Codeanywhere

Codeanywhere is a cloud-based cross-platform development environment for web developers. It can connect with FTP and SFTP. What’s more, it offers connections to other cloud storage services like Dropbox, Google Drive, etc.

codeanywhere

Custom Dev Environment and Language Support
Codeanywhere gives you the flexibility to customize your development environment with your personal preferences as you set it up for your project. It supports over 70 different programming languages including JavaScript, Python, and HTML.

Console Support
Codeanywhere ships with a built-in terminal console that allows developers to run bash commands on their server and containers. The built-in console makes it possible for developers to SSH directly from their browser to a different server. As a result, you can compile your code without leaving the comfort of your browser.

Collaboration
With Codeanywhere, you can share and collaborate on projects with colleagues in different locations. Security-wise, Codeanywhere lets you share individual bits of your project if you wish; you can share files, folders, or an entire project, and each share comes with its own set of permissions. This is only a handful of its features. You can have a look at the documentation page for more.

Koding

Koding is a cloud-based platform that lets you (or your team) create and share fully automated development environments on any infrastructure for modern distributed applications, micro-services, and containers.

koding

Elaborate UI and Open Source
Koding has an intuitive and elaborate user interface that is welcoming and easy to navigate for all experience levels. And what’s best? It is open source and free.

What is Koding
Koding is not a typical online development environment. It is a bit more than just that, as is described in this short introductory video to further familiarize you with Koding.

Integration
Besides Koding’s amazing collaborations and sharing features, it has an amazing configuration manager that can integrate any service with a few lines of code. Whether you use Heroku with MongoDB and Node.js, or AWS with Ruby and MySQL, Koding will handle all the required integrations such that all you’ll need to do is add the service you need to Koding’s stack script, and that’s it! Find out more about Koding here.

SourceLair

SourceLair is a cloud-based platform that instantly provisions an isolated development environment for every project you create. Each provisioned environment is tailored around the needs of the project’s stack and ships it with all the tools needed to develop your project pre-installed.

sourcelair

Powerful IDE
SourceLair provides users a powerful in-browser IDE with all the basic features of your normal local development environment. With SourceLair, you’ll get features like realtime error reporting, auto completion, text key bindings, etc.

Github Integration
With SourceLair, you can clone a project repository with a single click. Writing more code, committing written work, pushing to a remote repository and pulling external changes into your repo can all be done within your SourceLair seamlessly.

Cross-Platform
One added advantage to using SourceLair is its cross-platform support. You can use a computer, a Chromebook, or even an iPad to work on SourceLair. This is a unique feature that only a handful of editors offer. With SourceLair, all you need is internet access and a web browser. Learn more about SourceLair’s super powers on its docs page.

Pricing
Basically there are two pricing plans in SourceLair, the basic plan and the pro plan.

sourelair-pricing

The basic plan offers 1 project for a fee of $5 per month, while the pro plan offers as many as 5 projects for a fee of $8 per month. That is not all — there are so many add-ons and extra features that are entitled to each plan, as you will find on their pricing page.

Cloud9

Cloud9 is a cloud-based development environment that provides developers all the equivalence of local IDEs on the browser. With Cloud9, you have the ability to write code, run the written code, and debug it all in the comfort of your browser.

cloud9

Cloud9 comes equipped with a dedicated code editor, a robust debugger, and a terminal console to help you run application commands and aid your debugging process. More so, it comes pre-loaded with all the essential tools needed for the supported languages, including JavaScript, Python, PHP, etc. This way, you don’t need to install any external packages or configure the dev environment when starting new projects.

Smart Editor
Coupled with the fact that Cloud9 is entirely based on the browser, giving you the flexibility to write your code on any machine anywhere and any time, the editor comes with smart features that help in development. It has an integrated debugger and other helpful, time-saving features such as code hinting, code completion, and step-through debugging.

Collaboration
Just like many other IDEs we’ve already discussed, Cloud9 has a pair programming feature that allows you to share your development environment with your colleagues and work together on the same codebase. What’s more? It happens in real time, such that you can see what everyone on your team is doing when they are doing it.

AWS Terminal Access
The Cloud9 terminal has sudo privileges to the managed Amazon EC2 instance that is hosting your development environment, and a pre-authenticated AWS Command Line Interface.

Conclusion

In this post we have discussed five top online JavaScript IDEs you can use in 2019. Each development environment has its unique abilities, so it’s difficult to choose a “best” one amongst them. We can, however, choose the one whose features best solve our needs.

Disclaimer: The five online IDEs discussed here are entirely my choice based on my own experience with them. There are other amazing online IDEs we haven’t discussed here. If you have other ones in mind, please do share them with us in the comments below. Hopefully this post helps you pick the most suitable one for your needs.

For More Info on Building Great Web Apps

Want to learn more about creating great web apps? It all starts out with Kendo UI  - the complete UI component library that allows you to quickly build high-quality, responsive apps. It includes everything you need, from grids and charts to dropdowns and gauges.

Learn More about Kendo UI

Get a Free Trial of Kendo UI

DIY IoT for Azure

$
0
0

Learn how to build and program a custom Internet of Things (IoT) sensor device for an Azure IoT Hub, and how to consume and visualize this data in an ASP.NET Core MVC application.

For software developers, working with the Internet of things (IoT) usually means focusing exclusively on the server side. Typical questions and problems are first and foremost the selection of cloud providers or methods for efficient data storage and analysis. However, taking a closer look at the actual "things" - building and programming them - is just as fascinating.

An IoT End-to-End Scenario in Three Acts

In this blog post, we create a basic IoT scenario and look at it from an end-to-end perspective. With just a little bit of tinkering and programming, we can even build a custom IoT sensor device that posts data into an Azure IoT Hub. That data will later be consumed and visualized in an ASP.NET Core MVC application. This whole end-to-end scenario is structured into three acts.

  • Act 1: preparation and configuration of the Azure IoT Hub
  • Act 2: building and programming an IoT sensor device that provides data for the Azure IoT Hub
  • Act 3: processing and visualizing data from Azure IoT Hub in an ASP.NET Core MVC application

Act 1: Preparations

Before we can start building and programming an actual IoT device, a couple of preparation steps need to be made inside the Microsoft Azure Portal.

Creating an IoT Hub

  • First of all, an Azure IoT Hub must be created by selecting Create a resource - Internet of Things - IoT Hub.

Create a new IoT Hub

In the next step, a few mandatory settings have to be configured:

  • Subscription: in case multiple subscriptions are available, one must be picked that is associated with the IoT Hub
  • Resource Group: if no resource group exists, a new one must be created here
  • Region: the geographic location where the IoT Hub will be hosted
  • IoT Hub Name: this can be chosen arbitrarily as long as it is still available

Basic configuration of the IoT Hub

Then, size and scale of the IoT hub must be configured. For a demo purpose like this, Free Tier should definitely be enough.

Determining size and scale of the IoT Hub

Now that the IoT Hub has successfully been created, an actual IoT device (our later sensor) must be registered with it.

Registering an IoT Device

On the newly created IoT hub, select IoT devices and then click Add to register a new device.

Register a new IoT device

In the following step, this new device must be given a name (here: DIY_IoT_Sensor), and after clicking Save it will be registered and associated with the IoT Hub.

Configure the new IoT device

By selecting the device, its property page opens, which provides the information (among others) about this device's connection string. This connection string will be required later for associating an actual physical device with it. So now is a good time to copy this connecting string and save it for later use.

The device's connection string will be needed later

Download the Source Code

As a last preparation step, we will clone the sample application for the whole end-to-end scenario.

$ git clone https://github.com/z1c0/diy-iot-sample.git

This repository consists of two folders/projects:

  • sensor: An Arduino project that contains the code for programming a NodeMCU microcontroller, which acts as a Microsoft Azure IoT sensor.
  • webapp: An ASP.NET Core MVC application, which will consume and visualize the IoT sensor data.

Act 2: The IoT Sensor

Now that everything is in place and all preparation steps have been finished successfully, we can start developing and programming the actual IoT sensor.

Sensor Hardware

Creating a physical sensor device usually requires wiring up pieces of hardware. In this case, the following components have been used:

  • NodeMCU Microcontroller: The NodeMCU is a very popular choice among microcontrollers, since it comes with built-in WIFI, has a Micro-USB connector and can be programmed using the Arduino platform. It's also really cheap with prices starting as low as $3.
  • DHT11 Temperature and Humidity Sensor: This sensor is also frequently used in hobbyist and demo projects. It provides decent accuracy and is available for less then $1.

The following schematic shows how the sensor and the microcontroller need to be wired up.

Schematic of the DHT temperature and humidity sensor connected to the NodeMCU

This is the actual circuit wired up on a breadboard.

Schematic of the DHT temperature and humidity sensor connected to the NodeMCU

Sensor Software

The NodeMCU microcontroller can be programmed using the Arduino IDE. This is a free development environment that can be downloaded from the Arduino website and supports a whole variety of different boards and microcontrollers in a standardized way.

The Arduino IDE

Since the NodeMCU microcontroller is not supported out of the box, an additional software package has to be installed first. For that, the Preferences dialog must be opened through the Tools menu, and this URL http://arduino.esp8266.com/stable/package_esp8266com_index.json must be added to the textbox labelled Additional Boards Manager URLs.

Include support for additional hardware

To download the actual addon package, open Tools - Board: - Board Manager, enter "esp8266" (ESP8266 is the chip used for NodeMCU and other microcontrollers) into the search box and install version 2.4.2 of that package.

Download support for ESP8266 boards

Note: The current latest version of the esp8266 package is 2.5.0. However, this version has compatibility problems with the Microsoft Azure IoT Arduino SDK, so we use version 2.4.2.

Now, the NodeMCU board should be available under the Tools - Board: menu and must be selected there.

NodeMCU support is now available

The last thing to do before we can successfully compile the code from the previously cloned repository, is to install a couple of libraries needed in the sample code.

Arduino libraries can be downloaded opening the Libary Manager through Sketch - Include Library - Manage Libraries….

Installation of new libraries in the Arduino IDE

Those are the libraries which are required in order to use the Microsoft Azure IoT Arduino SDK and collect data from the temperature and humidity sensor:

  • AzureIoTHub
  • AzureIoTUtility
  • AzureIoTProtocol_HTTP
  • DHT sensor library
  • Adafruit Unified Sensor

Now if we open the Arduino sketch sensor/Azure_IoT_Sensor/Azure_IoT_Sensor.ino from the diy-iot-sample repository, it should compile without errors.

Before finally uploading the sketch to the device, a last configuration step is required. Since the NodeMCU has no user interface and the sketch does not provide any interaction mechanism, connection settings for WIFI and the Azure IoT connection string (which we copied for later use in Act 1) are hard-coded.

// TODO: set these values before uploading the sketch
#define IOT_CONFIG_WIFI_SSID ""
#define IOT_CONFIG_WIFI_PASSWORD ""
#define IOT_CONFIG_CONNECTION_STRING ""
Note: For reasons of simplicity, these settings are managed as code constants. Make sure you don’t accidentally commit those into GitHub or any public source control system!

After having configured those settings, the sketch is ready to upload and our brand-new DIY IoT device should already be publishing data into the Azure IoT hub.

Sensor Test

A quick way to check whether the sensor is actually working correctly and publishing data is using a tool called Azure IoT Device Explorer. This is a small (Windows) test application that can be downloaded here and provides quick troubleshooting inside into Azure IoT Hub.

Azure IoT Device Explorer

In case a different operating system than Windows is used, we can still verify whether our sensor works correctly by using the Azure CLI (az command).

After installing and download the Azure CLI, we have to log in initially:

$ az login

Then, we can connect to our IoT Hub by simply specifying its name and monitor incoming events.

$ az iot hub monitor-events --hub-name <IOT_HUB_NAME>

If everything was set up correctly, the command's output should look similar to this:

Starting event monitor, use ctrl-c to stop...
{
  "event": {
    "origin": "DIY_IoT_Sensor",
    "payload": "{ 'humidity': 24.00,'temperature':22.00 }"
  }
}
{
  "event": {
    "origin": "DIY_IoT_Sensor",
    "payload": "{ 'humidity': 32.00,'temperature':22.00 }"
  }
}

Act 3: Visualizing the IoT Sensor Data

Now that we know our custom-developed sensor is actually providing IoT data, we want to visualize this data using an ASP.NET Core MVC application. The source code for this application can be found in the webapp folder of the previously cloned diy-iot-sample repository.

The application uses:

  • The Microsoft.Azure.EventHubsNuGet package to connect to the Azure IoT Hub.
  • ASP NET CoreSignalR is used to provide the collected sensor data to the web browser.
  • Chart.js is used for rendering the actual sensor visualization data on the web page.

Before the web application can be run, a couple of constants need to be set to be able to successfully connect to the IoT Hub:

// Event Hub-compatible endpoint
private const string EventHubsCompatibleEndpoint = "...";

// Event Hub-compatible name
private const string EventHubsCompatiblePath = "...";

// SharedAccessKeyName
private const string IotHubSasKey = "...";

The easiest way to retrieve the correct values for these constants is using the Azure CLI (az command) again.

EventHubsCompatibleEndpoint:

$ az iot hub show \
  --query properties.eventHubEndpoints.events.endpoint \
  --name <IOT_HUB_NAME>

EventHubsCompatiblePath:

$ az iot hub show \
  --query properties.eventHubEndpoints.events.path \
  --name <IOT_HUB_NAME>

IotHubSasKey:

$ az iot hub policy show \
  --name iothubowner \
  --query primaryKey \
  --hub-name <IOT_HUB_NAME>
Note: For reasons of simplicity, these settings are managed as code constants. Make sure you don’t accidentally commit those into GitHub or any public source control system!

Ideally, use ASP.NET Core's built-in mechanisms for properly handling secrets.

After that the application should start up, connect to our IoT Hub and display charts for the incoming sensor device data.

The IoT data visualized in an ASP.NET MVC application

IoT for Everyone!

IoT is an exciting topic since it can be approached from more than one direction. Personal focus and interest may lie on the client side, building hardware and sensor devices. Or it can be processing incoming IoT data inside an IoT Hub, applying machine learning and AI techniques to it. It may also be on the visualization side of things, where the challenge is to condense all that data into easily understandable graphs and charts. Wherever your main area of interest lies, there's probably at least one IoT scenario waiting exactly for your skill set and problem solving capabilities.

Viewing all 5320 articles
Browse latest View live