Monday, July 30, 2018

Patching a property from a json string in RavenDB

On this post, let's understand how to patch data using a json string in RavenDB

Because RavenDB is a NoSql database and because it stores its data internally as Json strings, sometimes when patching, we can simplify things immensely by using common JavaScript resources.

Up to Raven 3.5 the patch window accepted JavaScript (including running fancy lodash commands). So, being JavaScript, it's also valid to declare our own functions and/or use standard JavaScript functions including JSON.parse().

The Problem

My patch required to update one property (ContentName) from another (OriginalContent). Turns out that OriginalContent is a string that may or may not contain Json data and I need to access the property Name of that - if valid - Json object.

Sounds complicated? How do we do that?

The Solution

Take a look at the patch below to understand what I mean:


In this case my OriginalContent property stores the generic Json string that I pulled from an integration endpoint. That property is a string and can be anything: null, empty, a valid or invalid Json string, a simple string or a complex json data structure.

And what did I do on that patch?

I created a function to simply parse that property from a string to a Json object. If parsed, my code then tries to access its Name property. Then I set my ContentName property to, if available, the parsed Name from the Json string.

See Also

Monday, July 23, 2018

Patching RavenDB Metadata

On this post, let's understand how simple it is to patch the metadata of your documents using RavenDB Studio
On a previous post we talked about how to query metadata using RavenDB. Now, let's take a look at some ways to patch our metadata in RavenDB.

Patching Records with RavenDB

Patching records is RavenDB can be easy or less easy =). The easy way is doing it from RavenDB Studio. There you can do it by collection or index and write some JavaScript to it.

Patching using RavenDB Studio

Here's a simple example on how I can patch the Name and IsActivated fields in my Users collection:

Patching metadata using RavenDB Studio

But, you may be required to patch the metadata, how to do it? The answer is: Using the @metadata dictionary. Let's take a look.

Final Thoughts

In the example above, we're updating the document metadata property "Raven-Clr-Type" with "MyApp.Core.User, MyApp.Core":

this["@metadata"]["Raven-Clr-Type"] = "MyApp.Core.User, MyApp.Core";

You can obviously patch whatever you want in your metadata. In the previous example, I was patching the namespace of an entity that was refactored in my application.

Hope it helps!

See Also

Monday, July 16, 2018

Querying RavenDB Metadata

Need to query your RavenDB metadata? Read to understand.
We've been discussing RavenDB on this blog. On this post, I want to address a feature that's commonly asked: how to query metadata in RavenDB.
There are two ways to do this:
  • using an pre-defined index: adding metadata to an index and querying it;
  • using a dynamic: using dynamic indexes in the studio.

Querying Metadata in RavenDB using an Index

This should be your standard approach, basically resumed in:
  1. Access the document's metadata from your index;
  2. Query the indexes, using the metadata property as if it were a normal property.
 Here's what you should do to access a document's metadata from your index:

Once that set, here's how you would query it:

Simple enough, isn't it? This is the best option as your data will be always searched using the index causing minimum stress to your database.

Querying Metadata in RavenDB dynamically using the Studio

But sometimes is unavoidable: users will come to you and ask you to run some queries. What if you don't have that property indexed? You have to options:
  1. add that property to an index in rebuild the index - not recommended on production;
  2. run a query against the dynamic index in RavenDB. The dynamic index allows you to write your queries against the collection and RavenDB will, behind the scenes, create the index for you. Note that we shouldn't be doing this frequently because it adds some stress to the server as it will build an index to process that query but
In order to query for the metadata in the studio, here's how you should do it:

So, using the below Lucene query allows you to query a document's metadata using RavenDb. Just remember to select the dynamic index. In this case, I'm using the dynamic/Users index.

@metadata.Raven-Clr-Type:"HildenCo.User, HildenCo.Domain"

Querying metadata using Lucene in C#

If I wanted, we can also use the client api to query RavenDB Lucene from my C# application. The following example shows us how to do it:

Conclusion

On this post I tried to show a few ways to query metadata. Hope it helps.

See Also

Monday, July 9, 2018

Getting Enum descriptions using C#

Accessing Enum descriptions isn't complicated. Let's review an elegant solution using attributes, and extension methods.
Photo by Emre KarataÅŸ on Unsplash

One programming data type that developers use a lot are Enums. Enums are simple and when well utilized, simplify the development making your code cleaner. In .NET, all Enums derive from System.Enum. In this post we assume you know and work with enums already. if not, check this link out for a nice introduction.

A common question I see is: how to build and access enum descriptions? There's different answers for that question that depend on which context your code is running. In this post we'll examine how to do it elegantly in C# by using attributes and extension methods. We will also demo it using a console app but the same concept could be used on your backend, a windows service, a library, etc.

DescriptionAttribute

The secret do do this the right way is using the DescriptionAttribute class. For illustration, let's assume that we have a Status Enum in our code that determines the possible statuses invoices in our system may have:

As you can see, the above code also used Description attribute to decorate each entry with a description string. That's exactly what that attribute is for. But how do we access the attribute value?

Accessing the description

With the descriptions added to our enums, let's see how to access their descriptions. For clarity and simplicity, I'd like to propose an extension method so that access to that method is centralized in one place and can be reused throughout our application:

Now to access your description, we just have to call the GetDescription extension method to get that attribute as a string. Note that on the example below, I'm also doing two interesting things:
  1. Overriding the ToString method so we can simply call (line 8)
  2. Using String Interpolation to simplify the formatting instead of String.Format (lines 8-11)

Building a sample tool

To finish off, let's build a simple .NET Core tool to practice the above code. Oh, and because we're using .NET Core, let's run it on Windows and on my beloved Fedora Linux.

Running on Windows

Here's it our code running on Windows:

Running on Linux

And, as a nice exercise, let's run it on Linux too. First, we need to run the dotnet publish command to build it:
Then, just run it on your Linux with dotnet EnumDescription.dll.

Conclusion

On this post we reviewed how to combine the use the DescriptionAttribute class and a C# extension method to decorate/access your enums with nice contextual descriptions. You also learned how to extend your entities to use it in a simple demo console application on Windows and Linux. Remember that this technique can be used everywhere. Use your creativity!

Source Code

As always, the source code is available on GitHub.

See Also

Monday, July 2, 2018

Building a dynamic table with Vue.Js and Bootstrap 4

Vue.js makes it easy to manipulate the DOM and build dynamic elements. Read to understand.

You probably had that requirement to build tables where the user can Edit/Remove/Add items to it dynamically. With jQuery that required handling a lot of events usually leading to bugs and wasted time. Turns out that with Vue.Js, if modeled correctly, that's extremely easy. Let's take a look.

Adding Bootstrap 4

First, to make it look cool and save us some time prepping html, css and layout stuff, let's use Bootstrap's starter template to save us some dev time building the base html page.

Save that file and add Vue's dev version from the cdn on the bottom of the file with:

    <!-- Vue development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

With Bootstrap and Vue loaded, let's do some code.

Building the Vue Instance

My agenda class below will be responsible for rendering the dynamic table. Its syntax looks like this:
        const agenda = new Vue({
            el: '#agenda',
            data: {
                topics: [
                    new Topic({ title: 'Item 1' }),
                    new Topic({ title: 'Item 2' }),
                    new Topic({ title: 'Item 3' }),
                ]
            },
            computed: {

            },
            methods: {
                add() {
                    this.topics.push(new Topic({ editing: true }))
                },
                save() {
                    alert("todo :: submit to server");
                },
                cancelEdits() {
                    this.topics.forEach(el => el.editing = false );
                }
            }
        });

That represents our Vue instance, the start point of our Vue app. See how simple it is? That's the beauty of Vue. Now let's revise our Topic class. Our agenda app consists of a table of a list of topics in which each row is an instance of the Topic class described below:

        const Topic = function(model){
            var self = this;
            var m = model || {};
            
            self.oTitle = m.title || "";
            self.title = m.title;
            self.required = m.required || false;
            self.orequired = self.required;
            self.editing = m.editing;

            self.update = function(i){
                if ((self.title || "").length < 3){
                    alert('At least 3 chars are required to save');
                    return;
                }

                agenda.topics[i].title = self.title;
                self.editing = false;
            }

            self.edit = function(){
                agenda.cancelEdits();
                self.editing = true;
            }

            self.cancel = function(i){
                if (!self.oTitle){
                    agenda.topics.splice(i,1);
                    return;
                }

                self.title = self.oTitle;
                self.required = self.orequired;
                self.editing = false;
            }

            self.remove = function(i){
                if (confirm('Are you sure you want to remove this topic?')){
                    agenda.topics.splice(i,1);
                }
            }
            
            return self;
        }

Reviewing the HTML

The part of the HTML that deserves some comment is how we dynamically list the records using Vue's v-for directive binding. The code below shows how this is accomplished elegantly using Vue:
    <tr v-for="(t, i) in topics">

So, for each element in agenda.topics, Vue will render a tr for us with this piece of code:

<tr v-for="(t, i) in topics">
                    <th scope="row">{{ i + 1 }}</th>
                    <td>
                        <span v-if="t.editing">
                            <input v-model="t.title" @@keyup.enter="t.update(i)"/>
                        </span>
                        <span v-else>
                            {{ t.title }}
                        </span>
                    </td>
                    <td class="text-center">
                        <span v-if="t.editing">
                            <input type="radio" value="true" v-model="t.required"> Yes
                            <input type="radio" value="false" v-model="t.required"> No
                        </span>
                        <span v-else>
                            {{ t.required == "true" ? 'Yes' : 'No' }}
                        </span>
                    </td>
                    <td class="text-center">
                        <span v-if="t.editing">
                            <button class="btn btn-outline-info btn-sm" v-on:click="t.update(i)">Update</button>
                            <button class="btn btn-outline-danger btn-sm" v-on:click="t.cancel(i)">Cancel</button>
                        </span>
                        <span v-else>
                            <button class="btn btn-outline-info btn-sm" v-on:click="t.edit(i)">Edit</button>
                            <button class="btn btn-outline-danger btn-sm" v-on:click="t.remove(i)">Remove</button>
                        </span>
                    </td>
                </tr>

The source code for this page is available on my GitHub repo

Conclusion

The objective of this post is to demo how simple things become when using the right tools. Vue in my experience has matured and deserves a lot of praise in how it handles reactivity, simplifies, organizes and accelerates development.

See Also

About the Author

Bruno Hildenbrand      
Principal Architect, HildenCo Solutions.