Insert bulk Records and View it using WPF and REDIS Cache

Rajnilari2015
Posted by in NoSql category on for Beginner level | Points: 250 | Views : 230 red flag

In this article we will look into how to Insert bulk Records and View the same in a WPF Grid with Redis as the backbone.


 Download source code for Insert bulk Records and View it using WPF and REDIS Cache

Introduction

Redis is an advance Key-Value store, open source, NoSQL database which is primarily use for building highly scalable web applications. Redis holds its database entirely in memory and use the disk only for persistence. It has a rich set of data types like String, List, Hashes, Sets and Sorted Sets with range queries and bitmaps, hyperloglogs and geospatial indexes with radius queries. It finds is use where very high write and read speed is in demand. It also includes other notable features like -

  1. LRU (Less Recently Used) Eviction
  2. Messaging broker implementation via Publisher-Subscriber Support
  3. Disk Persistence
  4. Automatic Fail over
  5. Transaction
  6. Redis HyperLogLog
  7. Redis Lua Scripting
  8. Act as database
  9. Act as a cache
  10. Provides high availability via Redis Sentinel
  11. Provides Automatic partitioning with Redis Cluster
  12. Provides different levels of on-disk persistence

Windows Presentation Foundation (or WPF) is a graphical subsystem by Microsoft for rendering user interfaces in Windows-based applications.

In this article we will look into how to Insert bulk Records and View the same in a WPF Grid with Redis as the backbone.

Redis installation in Windows

First of all download the Redis-x64-3.2.100.zip file from here. Extract the zip to some location (say C:\Redis-x64-3.2.100). Then run redis-server.exe.

In order to verify if our Redis Server is working or not , run redis-cli.exe and type

127.0.0.1:6379> ping "Say Hello to Redis from RNA Team"
"Say Hello to Redis from RNA Team"
127.0.0.1:6379>

Create a WPF application

Now open VS 2015 and create a WPF application.

Design the "MainWindow.xaml" as under

<window x:class="RedisWPF_CRUD.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:RedisWPF_CRUD" mc:ignorable="d" title="MainWindow" height="350" width="525">
     <grid>
        <grid.rowdefinitions>
            <rowdefinition height="0.939*">
            <rowdefinition height="Auto">
        </rowdefinition></rowdefinition></grid.rowdefinitions>
        
        <groupbox header="Student Record" horizontalalignment="Center" verticalalignment="Center" height="383">
            <grid>
                <grid.rowdefinitions>
                    <rowdefinition>
                    <rowdefinition height="Auto">
                </rowdefinition></rowdefinition></grid.rowdefinitions>
                
                <scrollviewer verticalscrollbarvisibility="Auto">
                    <stackpanel>
                        <stackpanel orientation="Horizontal">
                            <datagrid x:name="dgStudent" autogeneratecolumns="False">
                                <datagrid.columns>
                                    <datagridtextcolumn header="Student ID"></datagridtextcolumn>
                                    <datagridtextcolumn header="Student Name"></datagridtextcolumn>
                                    <datagridtextcolumn header="Gender"></datagridtextcolumn>
                                    <datagridtextcolumn header="DOB"></datagridtextcolumn> 
                                </datagrid.columns>
                            </datagrid>                            
                        </stackpanel>
                    </stackpanel>
                </scrollviewer>                
            </grid>
        </groupbox>
    </grid>
</window>

Running the application at this point yields

Install the Redis client

From NuGet Package Manager Console, execute the below command.

PM >Install-Package StackExchange.Redis.StrongName

After a successful installation, we will receive

Create the Student Model

Create a folder say "Model" and add a "Student" class to it with the below properties.

namespace RedisWPF_CRUD.Model
{
    public class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public string Gender { get; set; }
        public string DOB { get; set; }
    }
}

Create the Redis DB Operations

Create a folder say "RedisDBOperations" and add a "RedisConnector" class file to it with the following implementation.

using StackExchange.Redis;

namespace RedisWPF_CRUD.RedisDBOperations
{
    public class RedisConnector
    {
        static IDatabase GetRedisInstance()
        {
            return 
                ConnectionMultiplexer
                .Connect("localhost")
                .GetDatabase();
        }        
    }
}

The connection to Redis is handled by the ConnectionMultiplexer class which is the central object in the StackExchange.Redis namespace. The ConnectionMultiplexer is designed to be shared and reused between callers. The GetDatabase() of the ConnectionMultiplexer sealed class obtains an interactive connection to a database inside redis.

Install Json.NET from NuGet Package Manager Console as

PM >Install-Package Newtonsoft.Json -Version 9.0.1

Now let us add a "DBOperation" class to the "RedisDBOperations" folder with the below implementation.

using Newtonsoft.Json;
using RedisWPF_CRUD.Model;
using System;
using System.Collections.Generic;

namespace RedisWPF_CRUD.RedisDBOperations
{
    public class DBOperation
    {
        /// 
        /// Insert bulk students
        /// 
        private void InsertBulkStudent()
        {
            var numberOfRecords = 10;

            var cache = RedisConnector.GetRedisInstance();

            for (int i=1;i<= numberOfRecords;i++)
            {
                cache.StringSet(
                        "Student" + i
                        ,JsonConvert.SerializeObject(
                                new Student() {  StudentID = i
                                                , StudentName ="Student" + i
                                                , Gender = i%2 ==0 ? "Male":"Female"
                                                , DOB = DateTime.Now.AddYears(i).ToString()
                                              }                                
                                ));
            }
        }

        /// 
        /// Fetch the students
        /// 
        /// 
        public List GetStudentRecords()
        {
            //Insert Student Records
            InsertBulkStudent();

            var studentList = new List();
            var cache = RedisConnector.GetRedisInstance();
            var numberOfRecords = 10;
           
            for (int i = 1; i <= numberOfRecords; i++)
            {
                studentList.Add(JsonConvert.DeserializeObject(cache.StringGet("Student" + i)));                
            }
            return studentList;
        }
    }
}

The StringSet method sets key to hold the string value. If key already holds a value, it is overwritten regardless of its type. The StringGet method get the value of a key or nil if the key does no exist.

Create the View Model

Create a class say "StudentVM.cs" file that will inherit from INotifyPropertyChanged. This is the ViewModel. The implementation is as under

using RedisWPF_CRUD.Model;
using RedisWPF_CRUD.RedisDBOperations;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace RedisWPF_CRUD
{
    public class StudentVM : INotifyPropertyChanged
    { 

        DBOperation _objDataSource = new DBOperation();

        public ObservableCollection StudentList
        {
            get { return new ObservableCollection(_objDataSource.GetStudentRecords()); }

        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyOfPropertyChange(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}

We are using the ObservableCollection which is dynamic collection of objects of a given type (Student in our case). The StudentList is a read-only property since we are only interested to display the record. The INotifyPropertyChanged interface of the System.Component namespace provides a way to notify binding clients of a property value change.

Bind the ViewModel property to the View

Now we need to bind the StudentList property to our view as under.

 

<grid>
        <grid.rowdefinitions>
            <rowdefinition height="0.939*">
            <rowdefinition height="Auto">
        </rowdefinition></rowdefinition></grid.rowdefinitions>
        
        <groupbox header="Student Record" horizontalalignment="Center" verticalalignment="Center" height="383">
            <grid>
                <grid.rowdefinitions>
                    <rowdefinition>
                    <rowdefinition height="Auto">
                </rowdefinition></rowdefinition></grid.rowdefinitions>
                
                <scrollviewer verticalscrollbarvisibility="Auto">
                    <stackpanel>
                        <stackpanel orientation="Horizontal">
                            <datagrid x:name="dgStudent" itemssource="{Binding StudentList}" autogeneratecolumns="False">
                                <datagrid.columns>
                                    <datagridtextcolumn header="Student ID" binding="{Binding StudentID}"></datagridtextcolumn>
                                    <datagridtextcolumn header="Student Name" binding="{Binding StudentName}"></datagridtextcolumn>
                                    <datagridtextcolumn header="Gender" binding="{Binding Gender}"></datagridtextcolumn>
                                    <datagridtextcolumn header="DOB" binding="{Binding DOB}"></datagridtextcolumn> 
                                </datagrid.columns>
                            </datagrid>                            
                        </stackpanel>
                    </stackpanel>
                </scrollviewer>                
            </grid>
        </groupbox>
    </grid>

Set the Data Context

Now open the "MainWindow.xaml.cs" file for setting the data context

using System.Windows;

namespace RedisWPF_CRUD
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = new StudentVM();           
        }
    }
}

Run the application

Reference

Redis

Conclusion

Redis is a very popular open-source , in-memory, key-value NoSQL data store. It is promoted by Microsoft to replace AppFabric. In this article we have seen the Read and Write operation to and from Redis Server from a WPF application. Hope this will be helpful. Thanks for reading. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)