RavenDB – Exporting and Importing using Smuggler

Tags

, ,

badge1Smuggler is a tool for RavenDB which is used for exporting and importing data – today at work I was shown a nice way to use it to take production data out and import it locally for just one collection of documents – something which might be useful and I know I will forget the syntax I the future for so blogging about it helps me know remember it and I can always read here again in the future if and more likely when I do forget it.

The syntax for exporting a collection called Categories would be as follows:-

smuggler

What are we doing here, well we are saying use Smuggler to export from the Catalogue Tenants database a dump file – we are also using metadata so that we are only exporting a collection of documents called Categories and then only the latest version so no revisions, and lastly only export the Documents so no Indexes or any other types of documents.

I wanted to then import this into my local instance of RavenDB so the following command does just that:-

smuggler2

This will import the Categories and override any existing Categories in my local RavenDB instance.

You can read more about smuggler here.

Hope someone finds that useful.

ElmahR – monitor errors in your app using a dashboard

Tags

, , ,

If your unfamiliar with Elmah and/or ElmahR then please take a quick look here.

If you’re using Elmah but haven’t taken advantage of ElmahR then read on.

If you have one or more application(s) which currently use Elmah then you can very easily add in ElmahR which gives you a superb dashboard from where you can monitor either one or all of you applications which log errors.

The dashboard is basically one webpage which makes very nice use of SignalR to display information regarding errors thrown by your application(s), so if you deploy something and you monitor this page and see the error count for your application counting up quickly then you know you have a problem. You can use the dashboard to monitor a number of applications on different environments for example.


Existing/New Web Application

  • Either create a brand new test web application or you can use an existing web application – add ElmahR to this application using the Nuget package as below:-
    ElmahR
  • Ok now that we have added ElmahR to a web application we need to configure it accordingly, open up the web.config and look for the elmah section, should look something like this:-
  • elmah1

  • Important – The sourceId setting needs to match the sourceId setting in our dashboard application’s web.config

DashBoard

  • Now lets create our dashboard, so create a new MVC or Web application, then add the Nuget package as below:-
    ElamhrDash
  • Now we need to edit the dashboard’s web.config so that the sourceId’s match, shown below:-
    elmahr3

Testing ElmahR is working

  • Within your web application we want to test that ElmahR is set up and working correctly, to do this we need to have an error generated, so deliberately add an exception, such as a throw new NotImplementedException() or similar into an area you can test quickly (e.g. index actionresult within the home controller in MVC)
  • Run the dashboard application, which should look something like this:-

    elmahr5

  • Then run your web application and browse to the page which will generate an error so we can see if it logs as we expect.
  • If you have everything configured correctly then you will see the error count change in the dashboard application, like so:-
    elmahr6

TroubleShooting

  • If you don’t see your application logging errors on the dashboard it’s usually the sourceId element or the targetUrl element within your web.config

Hope you find this of use and start using ElmahR.

If you get stuck or something isn’t working add a comment.

Code coverage results for your JavaScript

I wanted to find out if there were any tools that can display code coverage results for JavaScript code (without the need for Java on the server or having to use Node), I experimented with a few different frameworks, test runners and what not and have spent a couple of hours looking in to this, in the end I opted for the following:-

jasmine_logo At work we currently use Jasmine which is a behaviour-driven development framework for testing JavaScript code along with PhantomJS which we use to run the tests using a specrunner (there are several ways to do it but this works for now)

I have installed the Visual Studio Extension called Chutzpah which is a JavaScript Test Runner which gives you a few nice things such as integration with TeamCity and the ability to right-click and then select Run Tests similarly to unit testing your C# code with your favourite unit testing framework.

chutzpah

Ok so back to code coverage for our JavaScript code – Matthew the guy who created Chutzpah is working on integrating code coverage into the next release so in the mean time here is how you get it to work – enter one further library called Blanket.js – Blanket.js is used to give us the code coverage results and currently supports Qunit, Mocha and Jasmine. An adapter API exists for supporting other test runners.

At this point you might be thinking its a fair amount of work to get this going but I will simplify the steps required to get your JavaScript code outputting code coverage results.

  • Download Blanket.js and look for the file called blanket-jasmine.js, add this to your Scripts folder inside your web application. This file is blanket version that works with Jasmine.
  • Add the Nuget package jasmine.js jasminenuget
  • Add some JavaScript code as below for example this is code.js
  • var stringLib = {
        vowels: function (a) {
            count = 0;
            for (var i = 0; i < a.length; i++) {
                if ("aeiou".indexOf(a[i]) > -1) {
                    count++;
                }
            }
            return count;
        }
    }
    var mathLib = {
        add5: function (a) {
            return a + 5;
        },
        mult5: function (a) {
            return a * 5;
        }
    }
    
  • Add a JavaScript file with your Jasmine tests for the code above like so :-
    describe("general", function () {
        it("A basic test", function () {
            expect(true).toBeTruthy();
            var value = "hello";
            expect("hello").toEqual(value);
        });
    });
    
    describe("stringLib", function () {
        it("will get vowel count", function () {
            var count = stringLib.vowels("hello");
            expect(count).toEqual(2);
        });
    });
    
    describe("mathLib", function () {
        it("will add 5 to number", function () {
            var res = mathLib.add5(10);
            expect(res).toEqual(15);
        });
    
        it("will multiply 5 to number", function () {
            var res = mathLib.mult5(10);
            expect(res).toEqual(50);
        });
    });
    
  • Ok so we have some JavaScript code and Jasmine tests for the code, lets add some required links to our Jasmine specrunner page so we can see the code coverage
    results output to the screen, edit the spec runner like so:-

    specrunner2

    The above screen shot shows that we have added a reference to both our JavaScript code file and the file containing the Jasmine tests.

  • Now if we browse to the specrunner page for Jasmine we will see the results of the test – green for passed and red for failed (no code coverage results yet).

    jasmineresults1

  • Now lets show the JavaScript code coverage results – which is as simple as adding in the line to reference Blanket for Jasmine:-

    specrunner3

  • Refresh the specrunner page and you will now see your JavaScript code coverage results like so:-

    specrunner4

    The screen shot above shows us 100% code coverage, so no lines of JavaScript are coloured red (not covered)

  • If I comment out one of the tests we can see the difference below:-
    specrunner5
  • And there we have it code coverage results of your JavaScript, brief post but enough to get you started I hope, next time I will add this to TeamCity and see what that gives us.

KoLite – dirty flag and more

Tags

,

KoLite its written by John Papa and Hans Fjällemark and has helpers which add some extra very nice functionality to KnockoutJS.

I was working on a project which uses KnockoutJS and had the need to implement the idea of setting a dirty flag if a user made a change to a form, this would in turn enable a save button and allow the changes to be saved.

KoLite makes this very easy indeed, I decided to put together some quick code demonstrating the features I mention – at work jsfiddle.net doesn’t work too well so I have added the code to a sample app and uploaded it to GitHub.

The original samples and more information can be found here, I thought they could do with being expanded upon a little.

The ViewModel I used for the demo code is as follows:-

code2

Dirty Flag and how to use it

  • The code on line 10 is creating the dirtyflag by using KoLite’s DirtyFlag – I pass in which observable’s I want to monitor to see if they become dirty when they’re value changes.
  • The code on line 27 is setting up a computed observable which will return true if the observables have theyre values changed, otherwise it will return false.

So by having some observables updated we can track for dirty changes and then decide what we want to do on our form, an example would be to enable the clear form button as well as enable the save button on when we have the dirty flag set to true.

Grey out button when Ajax request is in progress

  • The code on lines 29-33 is making use of the KoLite asyncCommand
  • If you then add the code below, to the html then we have the functionality were after.
<button data-bind="command: saveCommand">Save</button>

Grey out button when Ajax request is in progress and show activity icon

  • If you add in the extra binding like so:-
  • <button data-bind="command: saveCommand, activity: saveCommand.isExecuting">Save</button>
    

KoLite will now add in an activity icon within the button, and that’s it – in the example code I am using an Ajax post to call the MVC Controller and whilst this is off doing work the activity icon spins.

save

  • My demo code can be found here
  • You can download the code for KoLite here

Leave a comment after the beep.

My DotNetCurry Magazine Articles

Tags

, ,

Over the last couple of months I have been privileged to write a couple of articles for the free .Net Developer Magazine brought to you by
DotNetCurry.

Its been my first attempt at writing for a magazine and has been a lot of fun, maybe in the future I can write more articles.

Please enjoy and give them a read – and sign up for the magazine – its FREE!

dnc-nov-thumb
Create a Snappy UI with KnockoutJS -> Issue 3
This article explores KnockoutJS and what KnockoutJS gives you as a developer.

dnc-jan-thumb
Web Essentials for Visual Studio 2012 -> Issue 4
This article explores the Visual Studio 2012 Web Essential add-on.

dnc-mar

What’s New in RavenDB 2.0 -> Issue 5
This article explores RavenDB 2.0

Take a look at these articles and hopefully you will learn something new – Gregor.

Book Review: C# Smorgasbord by Filip Ekberg

smorgasbord

Book Review: C# Smorgasbord by Filip Ekberg

About the Author:
Filip is a Software Engineer working with various techniques such as C#, WPF, WCF, ASP.NET MVC, ASP.NET and much more. Currently working at Star Republic in Sweden as a Software Engineer working with both newer and older technologies in a Windows environment, mainly focusing on ASP.NET MVC development.

During his years of Programming, Filip has managed to accomplish some of the following:
• Software Engineering Degree @ Blekinge Institute of Technology
• Managing the Software Development Company SmartIT eSolutions Sweden which focused mainly on developing software and web solutions.
• Working as an Amanuensis ( Teacher ) @ Blekinge Institute of Technology teaching Java, C++, Sql and Network-programming.

You can read more on his blog here.

I saw a tweet from @daniellangnet who said this book was fantastic and if your looking for something to read over the holidays then give this a go, I actually ordered the book without even reading anything about it, unusual but glad i did!

Chapter 1: Introduction to Parallel Extensions :- Learn the basics of paralleization, use basic Linq, and how to optimize code by introducing parallelization.
Chapter 2: Productivity and Quality with Unit Testing :- Understand why tests are import, create a test project and improve code quality.
Chapter 3: Is upgrading your code a productive step? :- How to find bugs faster, How to use Resharper to get a more manageable project and to get things done faster.
Chapter 4: Creating a challenge out of the trivial tasks :- Challenge yourself to create understandable and higher quality software.
Chapter 5: Asynchronous programming with async and await :- Identify where yo might need asynchronous processing, refactor a synchronous app into becoming more responsive.
Chapter 6: Dynamic program :- Create and extend a dynamic object by using the ExpandObject, also understand why introducing dynamic objects might cause problems long-term.
Chapter 7: Increase readability with anonymous types and methods :identify where you might have single purpose methods that you can replace with anonymous methods for increased readability and lucidity.
Chapter 8: Exploring Reflection :- User reflection to get information about types at runtime and understand more about properties and methods.
Chapter 9: Creating things at runtime :- Create your own method at runtime using Reflection, be able to read IL and understand portions of it.
Chapter 10: Introducing Roslyn :- Create a basic code analysis that suggest issues in your code, run code snippets on entire code files.
Chapter 11: Adapting to Inversion of Control :- Understand the basics of Inversion of Control, introduce a Dependency Injector into your application.
Chapter 12: Are you Mocking me? :- Create a mock of any interface and write tests that introduce

This book as you can see has something for everyone, i have thoroughly enjoyed reading it from cover to cover and will be reading a good few of the chapters again, it’s a very handy reference book and covers a number of topics that as a developer can help you explore, improve and be inspired – just as it says on the front cover.

I picked this book up on Amazon for £19 and its well worth it – recommended reading for 2013.

Choosing what Technologies/Frameworks to use

TechnologyBasics I have seen a few of my good friends on twitter discussing what technologies/frameworks they use and why they chose them.

I have also seen people saying why they should use this technology/framework over that technology all with really good arguments, as well as people asking which technologies/frameworks/libraries they should look at.

Note:- This is from the perspective of a company and not an individual developers stand point.

It comes down to a number of things and twitter isn’t really the best place to discuss this as it’s too small to get your point across hence this blog post.

I have worked in a few different places over time and there really is no single answer, some financial place I was in you were told which technology you were going to be using and it wasnt even up for debate, software architects who you would never even see had made the decisions already whether that be a good idea or not.

I would say choose the technology/framework that fits your current criteria as well as the technology/framework that matches your teams skill sets.

There has been a few posts about MVC or Nancy, in the end who cares what you choose? – if it gets the job done right?

Perhaps if you’re in a small team then its easier to choose say Nancy over MVC perhaps? – but if you walked into a team of 50-100 developers in a company im betting more people know MVC than know Nancy, that’s not to say MVC is better than Nancy, I havent even looked at Nancy, why not? – for a couple of reasons, why do I want to look at Nancy when MVC is used through our solutions, do I want to spend time learning another tool that does the same job? – no I don’t have time, don’t get me wrong I love to look at new ways of doing things, but I want to spend time learning something else like KnockoutJS or RavenDB and expand on my skill set, id rather do that port perfectly fine code bases which use a number of tools that run on MVC to Nancy and then have to check everything still works as expected including tests, build scripts, all sorts of other tools we use like chirpy and T4MVC.

People wonder why companies choose Microsoft products over other similar products and from experience it’s usually for either the option of MSDN licence support if required, or that more developers out there know and understand the product therefore there is more chance of help/finding a solution to a nasty bug – sort of strength in numbers it’s also easier for a manager to say to their boss look we will use SQL Server instead of CouchDB because of the products past history and thy can sleep safe in the knowledge its proven – I am not saying that other products are brand new and not to be trusted far from it, but I hope you get the point.

Recently we started using CoffeeScript for our latest project and to be honest I have never liked it, it was good for organising code in a better structured manner and I will leave it at that – we are looking to move to TypeScript and this isn’t because it’s a Microsoft product, its open source and I just think it’s so much nicer due to the tooling. It’s a better too for the job in my opinion and in summary there is no magic answer to what the best technology is, decide upon the variables in play and go from there is what I would suggest.

Not everyone will agree so feel free to add a comment.

KnockoutJS – what I’ve learned so far

Tags

,

I have been using KnockoutJS at work for the last few weeks and thought it might be an idea to blog about my findings whilst using KnockoutJS within an MVC 4 project, so here goes: –

  • With KnockoutJS you can get a really slick user experience if you show discipline in structuring your code, you can separate out your concerns using unobtrusive JavaScript – i.e. don’t put your JavaScript in the HTML, yes add data-bind attributes but that should be all you need, your JavaScript can be referenced from a file within a JS folder or similar keeping your HTML clean and free from being polluted by lots of inline JavaScript.

  • If you’re wondering how you go about going from your MVC model and working with this in KnockoutJS then look no further than KnockoutJS mapping. This plugin will take your existing Model from c# and convert it into what you will use within KnockoutJS, for example if in your model you have a string[] defined like so:-

    public string[] EmailAddresses { get; set; }
    

    then the mapping plugin converts this to an observableArray, and if you have a simple string property such as: -

    public string Email { get; set; }
    

    then the plugin will map this to a knockout observable for you.

  • When using ObservableArrays note that the number of items in the array is tracked – not the actual values within the array – this is important if, if the front end requires updated to the values within the array then you need to make the items within the ObservableArray observable also.

  • Take a look at the ko.utils code mentioned here for some hidden gems when working with KnockoutJS.

  • Dont store a lot of information in observables if you don’t have to, it’s not a good idea to store 10,000 records in an observable array and then bind that to a grid (Only store what you need in observables)

  • It can be a good idea to display on your page the contents of your viewmodel whilst you’re debugging so you can see what the observable and observable arrays you’re using contain

    <div id="debug" style="clear: both">
        <hr />
        <h2>Debug</h2>
        <div data-bind="text: ko.toJSON($data)" />
    </div>
    

  • More soon as I use it more and more, hope that helps.

Create CoffeeScript using Visual Studio and the Web Essentials Add-On

Tags

, ,


“CoffeeScript is a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way”

If your writing JavaScript in your web application, and the chances are these days you will be, then CoffeeScript is well worth a look – if your like me and you don’t particularly like writing JavaScript then bare with me you might learn some new tricks – CoffeeScript attempts to make your life easier when writing JavaScript and for the most part does a good job, it’s not all plain sailing as you might expect if you have worked with JavaScript much in the past.

Ok lets crack on, if you have Visual Studio handy make sure you have installed the Web Essentials Extension. This is a beauty of an add-on and has a nice little add-on for CoffeeScript included.

  1. Open up a new web solution either MVC app or a Web app
  2. Right click on your solution and then click Add in the next menu look for CoffeeScript, click this and we have a new CoffeeScript file added to your solution.
  3. On the left hand pane of the split is where you type your CoffeeScript and this is converted into JavaScript on the right hand side.
  4. Each time you save your changes the JavaScript file is updated for you – if you make any syntactical changes incorrectly then the preview tab on the right hand side will show you which line the error is on.

Some CoffeeScript basics are as follows:-

  • Semicolons are not required -> ;
  • Parenthesis are usually not required -> ()
  • Curly braces are usually not required -> {}
  • Commas are sometimes not required -> ,
  • Indent your code by tabbing for the start of a code block
  • Decrease indentation – end of a code block
  • The following screen shot shows you Visual Studio 2012 using the Web Essentials extension and I have added some CoffeeScript on the left and Web Essentials does the rest for me turning this into JavaScript.

  • To learn more about CoffeeScript check out the official website here.

Summary
CoffeeScript can be useful when your using something like KnockoutJS and you want to structure your code nicely using JavaScript classes and namespaces – I have been suing it recently and it has good points and bad points.

The good: – It allows you to structure your JavaScript easily and you can use namespaces as you would within C# classes. Less code is always good in my opinion and with CoffeeScript its easier to write less code to create your JavaScript files.

The bad: - Tabbing indents your code and this is how you create functions and loops and so on, miss one tab out and you can be left scratching your head but with some care this should be easily fixed.

Learn anything useful? – please let me know by leaving a comment after the beep.

Follow

Get every new post delivered to your Inbox.