Thursday, June 26, 2014

How to make Alerts fade in and fade out with Bootstrap 3.0

I wanted to make the alerts work a little nicer by using fade in and fade out. I know there are classes in the CSS to handle the fade in, but they don't work in all browsers. So I wanted to implement some Javascript to make it work

Create a div for your alerts

<div id="alerts">

</div>

We need to create unique Ids, I have used this function to do so

   function createUUID() {
        // http://www.ietf.org/rfc/rfc4122.txt
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }

Make a function to show the alert, by adding it dynamically

    function addAlert(message) {
        var id = createUUID();
        var JQueryId = "#" + id;

        $('#alerts').append(
            '');

        $(JQueryId).fadeIn(5000);
        window.setTimeout(function () {

            // closing the popup
            $(JQueryId).fadeTo(300, 0.5).slideUp(2000, function () {
                $(JQueryId).alert('close');
            });


        }, 10000);
    }

Notice that when adding the alert, it is hidden. The JQuery fadeIn API will create the fade effect when the alert is showing. Using setTimeout, we start fading out, and then closing the alert. You can play with the numbers to have the effect you want, but this seems to work nice and make alerts popup nice, and close on their own

Testing the Alerts

    $(document).ready(function () {

        addAlert("test");

        window.setTimeout(function () {
            addAlert("test1");
        }, 1000);

        window.setTimeout(function () {
            addAlert("test2");
        }, 10000);

        window.setTimeout(function () {
            addAlert("test3");
        }, 20000);

        window.setTimeout(function () {
            addAlert("test4");
        }, 20000);


        
    });

The code

You can see the code and the full effect here http://www.bootply.com/Sfn68ySAnB

Wednesday, June 18, 2014

Membership and roles as a WCF service

In case you want to have your membership and roles exposed as a service

Click here for more information

How to create a web thumbnail

I found a lot of tools that do this but I think the one I am going to really give a try is this one

webthumbnail.org

And I am going to try to add a link to CNN here:

Generated by WebThumbnail.org

Wednesday, June 4, 2014

How to make technical demos better

If you are showing code, a power point and then switching to a view of the application it can be challenging so here are some tips to improve your technical demo

I don’t want to see your dog

You should not show your family or dog in your background, it is better to keep your background black or with a logo of your demo or company. You should also consider that it takes longer to render images when people view your demo in a remote location.

I don't want to see e-mail popups

I don’t want to see an e-mail pop from your wife telling you to pick up milk on the way home during a demo. For the demo, consider sharing your secondary monitor and not the main monitor. This way you don’t need to close all these items on the task bar, you don’t want to show what you have open to everyone. It also solves the issues of notifications from e-mail. Normally these e-mails notifications can pop during the demo and normally they are on the main screen. Putting your demo on the secondary screen will make sure no one sees these notifications. Of course, you can also just close your e-mail program before the demo.

I can’t see that! Can you make it bigger?

Well, there is an app for that. Download the application ZoomIt and it will allow you to zoom into parts of the screen you want to explain. ZoomIt has cool features that allows you to draw arrows and boxes around items on your screen. The best part is that it’s free!

Hold on let me find that code…

Nothing is more annoying than a developer looking for the code he wants to show in the solution. The solution to this is actually simple. In Visual Studio use Bookmarks, using bookmarks you can mark the parts of the code you want to go to. Bookmarks can be enabled from the Edit Menu. You can see all your bookmarks in a bookmark view window (in the View menu).

Oh no! Not another slide

Don’t make too many slides full of text – no matter what you are showing you are likely to put your audience to sleep. Keep your slide short, put more graphics and diagrams into them. The reason is simply because the human brain works better with visuals. However, keep most of your demo interactive as much as possible. Best demos can be when you code with the audience and explain what you are doing. Which brings me to my next point...

How do I code without errors during my demo?

If you choose to be brave and code during the demo, you better make sure your code will work. The best way to know your code will work, is to code everything and test everything before the demo. If you have a working version of your code, launch it on the main screen, and share your secondary screen with the audience (running a second version of Visual Studio). You can also have notepad with code snippets on the main as a reference. Copy pasting is another technique, however, don’t use copy past too much, you may lose the audience with large snippets. Best thing is to type it as you go… this way you keep everyone watching…

The cool thing is that your audience doesn't know you have a working reference on the first screen, and they can't see your task bar (showing 2 version of Visual Studio), so to everyone it looks like you are doing it from memory and on the fly. Making you look like a true Master Jedi.

How to make sure people are not falling asleep

Try to keep the subject interesting, pop a few jokes and get your audience to participate. A few tips to get the audience involved is to simply ask them questions. Take breaks in the demo, and let the audience have a chance to ask questions and go into more details.

So there it is – have a great demo and good luck not getting that blue screen.

Tuesday, June 3, 2014

How to do Control-Alt-Delete on Remote Desktop

I am tiered of looking this up all the time, so here it is:

Press: CONTROL-ALT-END

Sunday, June 1, 2014

Knockout, Mapping plug-in, Typescript and ASP.NET MVC playing nice.

MVVM

In this article I will show how you can use the MVVM pattern to the fullest using the Knockout.JS framework, with the mapping plug-in add-on. The goal of this article is to show that you can define your view model at the back-end only, and have it "mapped" dynamically at the client side without the need to code it by hand. To make the coding simpler I have decided to use Typescript and test it with JQuery, and Knockout. You can learn more about the mapping plug-in here.

Typescript

To learn more about typescript I recommend you visit this site.

Lets get the environment setup

You will need to get a few Nuget packages to get going... here are some of them:

"

Next you will create a new TypeScript file and add the following dependencies:

The ViewModel

Notice that I only define the view model properties at the back-end. You will not see the fields of the ViewModel on the client side

    public class DomainItem
    {
        public string Name { get; set; }
        public string Description { get; set; }
    }

    public class DomainViewModel
    {
        public DomainViewModel()
        {
            Items = new List();
            Status = "Loaded";
        }
        public string Name { get; set; }
        public List Items { get; set; }
        public string Status { get; set; }
    }

The Controller

    public class HomeController : Controller
    {
        //
        // GET: /Configuration/
        public ActionResult Index()
        {

            return View();
        }

        //
        // GET: /Configuration/Details/5
        public ActionResult List()
        {
            DomainViewModel vm = new DomainViewModel();
            vm.Name = "Name1";

            var list = new List();
            vm.Items.Add(new DomainItem { Name = "item 1", Description = "This is item 1" });
            vm.Items.Add(new DomainItem { Name = "item 2", Description = "This is item 2" });
            vm.Items.Add(new DomainItem { Name = "item 3", Description = "This is item 3" });

            return Json(vm, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Refresh()
        {
            Random random = new Random();
            int number = random.Next(1, 50);
                        
            DomainViewModel vm = new DomainViewModel();
            vm.Name = "Name" + number;
            var list = new List();                       
            
            for (int i = 0; i < number; i++ )
            {
                vm.Items.Add(new DomainItem { Name = "item " + i, Description = "This is item " + i });
            }           

            return Json(vm, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult SubmitViewModel(DomainViewModel viewModel)
        {
            viewModel.Status = "Saved...";
            return Json(viewModel);
        }
     }
  • List returns list of items, this data will be converted into a view model on the client
  • Refresh simulates a data update on the back-end and sending the updated the data to the client
  • SubmitViewModelSimulates a save operation on the view model, and updating the status field to "Saved..."

The Dynamic ViewModel base class (in Typescript)

This is the base class that holds the necessary operations to dynamically map the view model from the server into the client. It also contains some re-usable flags to indicates if we are in the process of getting data from the back-end, I use this data to notify the user when communication with the back-end occurs.

class DynamicViewModel {

    // set to the true when the data is loaded from the back-end
    isLoaded = ko.observable(false);
    
    // set to true while the data is loading from the back-end
    isLoading = ko.observable(false);

    constructor() {

    }


    // show a hidden html id
    show(id: string) {
        $(id).show();               
    }

    // does an http get to the server, take a url returns the viewmodel. Once the request
    // is done, the view model is added to this class
    httpGet(url: string, callback?: (vm) => void) {

        // keep a pointer to this view model
        var self = this;

        // update flags
        self.isLoaded(false);
        self.isLoading(true);


        // make the REST call using GET
        $.ajax(url, {
            type: "GET",
            cache: false,
        }).done((vm) =>
        {
            // map the view model data we got from the server into this viewmodel
            ko.mapping.fromJS(vm, {}, self);

            // update flags
            self.isLoaded(true);
            self.isLoading(false);

            // if there is a callback, then call it.
            if (callback !== undefined)
                return callback(vm)
        });
    }

    // makes a post call to the server, and updates the viewmodel response
    httpPost(url: string, onSuccess?: (vm) => void) {
        
        // keep a pointer to this viewmodel
        var self = this;

        // update flags
        self.isLoaded(false);
        self.isLoading(true);
        
        // make a POST call to the server
        $.ajax({
            url: url,
            type: 'post',
            // pass this viewmodel
            data: ko.mapping.toJSON(self), 
            contentType: 'application/json',
            success: function (vm) {
                // update flags
                self.isLoaded(true);
                self.isLoading(false);

                // update the view model 
                ko.mapping.fromJS(vm, {}, self);

                // if there is a callback, call it
                if (onSuccess !== undefined)
                    return onSuccess(vm);
            }
        });
    }
}
  • ko.mapping.fromJS(vm, {}, self); this is the code that dynamically expends the view model, and adds the observable items based on the JSON coming back from the back-end
  • ko.mapping.toJSON(self) is used to serialize the view model to JSON so it can be sent to the back-end (it is used on the post)
  • Making making a post to the server, to send the view model, the code ko.mapping.toJSON(self) the magic
  • Notice that I had to use self, that's because the this keyword changes scope even with Typescript
  • the url will be passed from the child class

Child ViewModel

class DomainViewModel extends DynamicViewModel {
    initUrl: string;
    postUrl: string;
    refreshUrl: string;


    constructor(initUrl: string, refreshUrl: string, postUrl: string) { 
        super();  
        this.initUrl = initUrl;
        this.postUrl = postUrl;
        this.refreshUrl = refreshUrl;        
    }

    // Initialize the view model for the first time.
    initializeAction() {

        super.httpGet(this.initUrl, (data) =>
        {
            // apply the binding
            ko.applyBindings(this);
            
            // show the window
            super.show("#Main");
        });
    }


    // Update the data on the UI
    updateAction() {

        super.httpGet(this.refreshUrl);
    }

    submitAction() {

        super.httpPost(this.postUrl);
    }
}

Notice that the DomainViewModel deals mostly with commands and doesn't actually define the data in the view model. This is because the base class will handle injecting the data in when doing a GET or a Post

The View


@{
    ViewBag.Title = "Index";
}

@section scripts
{
    
    <script type="text/javascript">
        $(document).ready(function () {

            // get some url configuration for the view model to do its work
            var initializeUrl = "@Url.Action("List")";
            var refreshUrl = "@Url.Action("Refresh")";
            var submitUrl = "@Url.Action("SubmitViewModel")";

            var domainViewModel = new DomainViewModel(initializeUrl, refreshUrl, submitUrl);

            // initialize the view model
            domainViewModel.initializeAction();
        });

    </script>

    @*typed scripted geneated*@
    <script src="~/Scripts/TypeScript/ViewModel.js"></script>
}

<h2>Configuration Controller</h2>
<div id="Main" class="part" style="display : none">
    <div class="part">
        <h3>Binding to a selection box</h3>
        <select data-bind="options: Items,
                       optionsText: 'Name',
                       optionsCaption: 'Choose...'" size="5" multiple="true"></select>
    </div>

    <div class="part">
        <h3>Binding to a text box</h3>
        <input type="text" data-bind="value: Name" />
    </div>

    <div class="part scrollDiv">
        <h3>Binding to a table</h3>
        <table class="table">
            <thead>
                <tr><th>First name</th><th>Last name</th></tr>
            </thead>
            <tbody data-bind="foreach: Items">
                <tr>
                    <td data-bind="text: Name"></td>
                    <td data-bind="text: Description"></td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="part">
        <label data-bind="text: Status"></label>
    </div>
    <div class="part">
        <button data-bind="click: updateAction">Refresh data</button>
    </div>

    <div class="part">
        <button data-bind="click: submitAction">Submit data</button>
    </div>


    <div class="part">
        <label data-bind="if:isLoading">Loading from server...</label>
        <label data-bind="if:isLoaded"> Loading from server... done</label>        
    </div>

</div>

No need to code the ViewModel by hand in Javascript anymore

So thanks to the mapping plug-in for knockout, you don't need to worry about typing all the view model observable by hand anymore. You can use the base class view model and use it to do most of the work for you. This code is not production quality code, and only used to show the use of a dynamic view model using the knockout mapper plug-in

.

The full code

Click here for the full source code (compiled with Visual Studio 2013 Update 2)

Wednesday, May 28, 2014