Saturday, May 9, 2015

SignalR - Damien Edwards' MoveShape sample . Getting it to work with latest SignalR + Sample Project

Introduction

I had a good learning experience with SignalR. I started by watching Damien Edwards Video on YouTube. Now I am officially the SignalR newbie and I am hoping to keep climbing this ladder in upward direction :)

In this post I would like to share my experience with the Move Shape example that Damien showed in his video. I initially followed all the instructions as he demonstrated, but I failed to get it to work. I then read through the SignalR documentation and found that the latest version has a few changes since that video was filmed. I corrected the example and this post contains all the things that are different and of course the sample project source code for you to download. So lets get started.

Screenshot


As you may have noticed in the video, this was how the example worked. You drag and move the box in one browser, the box in other browser will follow the movements.




Changes

First thing you would need to change is in the Hub definition file. Or the MoveShapeHub class. There are a couple of changes in the class code.

  1. Hub methods have to be attributed using HubMethodNameAttribute
  2. Instead of calling the client method on Clients object, you have to call it on Clients.All property.

So the new code looks like this (notice the highlights)

    [HubName("moveShape")]
    public class MoveShapeHub : Hub
    {

        [HubMethodName("moveShape")]
        public void MoveShape(int x, int y)
        {
            Clients.All.shapeMoved(Context.ConnectionId, x, y);
        }
    }


The next thing that is changed is the way hub was extended. If you remember the video, he used the $.connection.extend method. But now you just have to define it like a regular prototype

    hub.client.shapeMoved = function (cid, x, y) {
        if ($.connection.hub.id != cid) {
            console.log("Yes");
            $shape.css({ left: x, top: y });
        }
    };

Also notice that instead of hub.shapeMoved, it is now called hub.client.shapeMoved. Next change goes inside the drag handler. Instead of calling hub.moveShape, you have to call hub.server.moveShape.

so the Hub's start-done handler looks like this

    $.connection.hub.start().done(function() {
        $shape.draggable({
            drag: function () {
                hub.server.moveShape(this.offsetLeft, this.offsetTop || 0);
            }
        });
    });


And you're done. Happy coding!

Downloading the sample project

You can download the full-blown VS2013 Solution Here.



Sunday, April 5, 2015

Is the technology really making us better?


This blog post discusses my thoughts about technology that I use on daily basis, what I love about it, what I don't love, and how I feel about technology’s effect on our cognizance. I have given a few examples to support my claims


Technology today has advanced so much that we depend on it and it will not be unfair to say that we cannot survive without it. There have been emergencies declared in places where technology was out temporarily in the past. We use technology everyday while at home or driving on the road, this has become so transparent in many places that we use technology not knowing we are using it. For Instance, it was only very recently when I found out the traffic lights were controlled by a technology that is sensitive to the traffic activity and they were not using the timers anymore.
What I really love about technology that I use on daily basis is; first, it has made my life a whole lot easier, I can do things a lot faster than I used to do without technology, and it has helped with my productivity. The famous "do less achieve more" comes to my mind. For example, my earlier travels to New York City was very time and effort consuming and at the end of the day made me real tired leaving me with only so little sense of accomplishment. I had to keep a lot of maps for riding Subways and Buses, keep track of schedules and if something doesn't go the happy path, it would take a whole lot of extra time to correct what I missed. But now I just keep my smartphone in my pocket, I just tell Siri what I would like to do. She would suggest me places to choose from and once I have picked a place she would also tell me which way to walk towards to get what bus or train, where to make connections, and what time I should expect myself to arrive by.
Another Example of technological things I enjoy is my DVR at home, I don’t have to worry about missing my favorite TV show episodes anymore, I can watch it at my schedule. It also allows me to pause when I have to answer the door or take a bathroom break. I can also rewind to watch my favorite scenes again, and it also allows me to watch wherever I am over internet; not just at home.
Now coming to what I don't love so much about technology. There are many ways the technology does not make me happy. The biggest one is, when it stops working as it does a lot of times; it brings your world to a grinding halt. Take that New York City mass transit example, when you find out that the cellular data service is not available in the area you are in; you are on your own with no plan B. Another thing I hate about technology is that it is expensive. You have more bills to pay when depending on technology than when you live without it.

I don’t think technology has made us any smarter, it has actually the reverse effect in many cases. It is cutting our connection to the knowledge of how things used to be done without it and has convinced us up to some extent that we are not going to need to learn about the ways our ancestors lived their lives.
For example, according to Environmental Protection Agency (EPA) census survey of 2007, only 1% of the Americans reported farming as their occupation. Which concludes that 1% of the population is growing food for the whole population. How is it possible? Technology. Agriculture workers are using airplanes to spray fertilizers, or pesticides over the crop; they are using big harvesting machines that does the wonders most of us are completely oblivious to. But this also concludes that most of 99% of the us may not know how the food is grown and will not be able to if required for our own survival.
Technology is keeping people away from reading books and do research to invoke the healthy brain activity. People rely too much on technology to just grab the exact piece of information with little to no effort of searching through the books and magazines. This has gone so far out of the hands that the word Google is added to Oxford dictionary as a verb which means to search using Google.com.


Conclusion

Technology comes with pros and cons, on one side it makes our life easy but on the other side it comes with requiring you to plan the usage of it. It does amazing things for us and takes care of a lot of things for us. While using it for our own good, we should never stop the process of the human learning process that is being passed down to descendants for ages. This helps us determine how things have evolved and also help us invent new ideas of how to make technology even better.

Thursday, June 26, 2014

F# example: Getting live stock ticks through Google Finance API

NOTE: This article demonstrates how F# in conjunction with Reactive Extensions can be used to connect to live data streaming. The full project with example client can be found at This Github link.

Disclaimer

I do not  take any responsibility of the code and any damages caused by it. Code which is provided AS IS is only for demonstration purposes and in no way encourages anyone to use Google Finance API for business. 

Introduction

It has been a week learning F# and I have finally converted my C# code that uses Google Finance API to F#

Here is what my code does. In simple words, it gives you back the IObservable<Tick> for one security (or symbol)

Here is the screenshot of how it looks like


Here is how you use it as a library in C#
 DataMachine machine = new DataMachine();  
 IObservable<Tick> appleTicker = machine.GetStockQuote("AAPL"); // Get Apple's stock prices  
 appleTicker.Subscribe(tick => {  
        // Everytime price changes, this piece of code will be called and an   
       // An object of Tick will be supplied as tick  
       // You can either add them to your Graph series to plot live chart  
       // Or save them to CSV  
       });  

Google Finance API

The simple finance API by Google is just a URL that takes symbol in 'q' GET parameter (or query string parameter). The following will give you the current price data for Yahoo in Json format.


How it works ?

It creates a thread using TaskFactory which queries Google Finance every 1 second, fetches the price and if there is a change in price produces the output into the Observable. Google Finance API gives back Json object. I am using Json.Net library by James-Newton King to parse that.

Here is the type definition of Tick
 type Tick() =   
     [<JsonProperty(PropertyName = "t")>]   
     member val Symbol = Unchecked.defaultof<string> with get, set  
     [<JsonProperty(PropertyName = "l")>]  
     member val Price = Unchecked.defaultof<float> with get, set  
     [<JsonProperty(PropertyName = "lt_dts")>]  
     member val LastUpdated = Unchecked.defaultof<DateTime> with 

Here is the code for DataMachine type
 type DataMachine() =   
   member this.GetLiveGoogleApiTicks(symbol : string) =  
     //google_api queries Google APi every second and produces the string output  
     let google_api (symbol : string) =  
       // When operation is cancelled by the caller, this variable will be modified  
       let cancelled = ref false  
       let operation(o : IObserver<string>) =  
         //Time to wait before fetching again through the API  
         let timeToSleep = TimeSpan.FromSeconds(1.0)  
         //Google Finance API , notice q is the query string parameter for symbol  
         let urlBuilder = new StringBuilder("""http://www.google.com/finance/info?q=""")  
         urlBuilder.Append symbol  
         let url = urlBuilder.ToString()  
         let client = new WebClient()  
         let cancelToken = Task.Factory.CancellationToken  
         client.BaseAddress = url  
         let task() =  
               try  
                 while not cancelToken.IsCancellationRequested && not !cancelled do  
                   let data = client.DownloadString url  
                   //Produce the item in observable  
                   o.OnNext data  
                   Thread.Sleep timeToSleep  
                   while client.IsBusy do  
                     Thread.Sleep 100  
               finally  
                   ignore  
         Task.Factory.StartNew task       
         let a = new Action(fun () -> (cancelled := true))  
         a |> Disposable.Create  
       Observable.Create(operation)  
     let strings = (google_api symbol)  
     // Eliminate unparseable characters for Json.Net library  
     let trimmed = strings.Select (fun (l:string) -> l.Substring(l.IndexOf("[") + 1, l.LastIndexOf("]") - 2 - l.IndexOf("[") + 1))  
     //Parse into object and return the IObservable<Tick>  
     trimmed.Select(fun (l:string) -> JsonConvert.DeserializeObject(l)).DistinctUntilChanged(fun (a:Tick) -> a.Price)
     

Remember to add Rx-Main and Json.Net from Nuget in your project and add appropriate 'open' declarations for namespaces.


Download the code


The fully functional project with sample client for this project can be found at This Github link.

Let me know your comments in the section below. If there is anything that I should have done differently, I would love to hear about that.

Happy coding!

Wednesday, November 20, 2013

Solved: Misleading link errors with gcc on linux

Solution Summary: LDFLAGS come in last

Background
I have been monkeying around with an issue of linking my code with xerces-c++ and xalan-c++ library for hours. Wondering what was I doing wrong.

I was issuing the following command for compiling

g++ -o file.out -lxalan-c -lxerces-c program.cpp

I was getting the following errors

program.cpp:(.text+0x75): undefined reference to `xercesc_3_1::XMLUni::fgXercescDefaultLocale'
program.cpp:(.text+0x7a): undefined reference to `xercesc_3_1::XMLPlatformUtils::Initialize(char const*, char const*, xercesc_3_1::PanicHandler*, xercesc_3_1::MemoryManager*)'
program.cpp:(.text+0x7f): undefined reference to `xalanc_1_11::XalanMemMgrs::getDefaultXercesMemMgr()'
program.cpp:(.text+0x87): undefined reference to `xalanc_1_11::XPathEvaluator::initialize(xercesc_3_1::MemoryManager&)'
program.cpp:(.text+0x8c): undefined reference to `xalanc_1_11::XalanMemMgrs::getDefaultXercesMemMgr()'
program.cpp:(.text+0x9e): undefined reference to `xalanc_1_11::XalanSourceTreeInit::XalanSourceTreeInit(xercesc_3_1::MemoryManager&)'
program.cpp:(.text+0xac): undefined reference to `xalanc_1_11::XalanSourceTreeDOMSupport::XalanSourceTreeDOMSupport()'
program.cpp:(.text+0xb1): undefined reference to `xalanc_1_11::XalanMemMgrs::getDefaultXercesMemMgr()'
program.cpp:(.text+0xcd): undefined reference to `xalanc_1_11::XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison(xalanc_1_11::XalanSourceTreeDOMSupport&, xercesc_3_1::MemoryManager&)'
program.cpp:(.text+0xea): undefined reference to `xalanc_1_11::XalanMemMgrs::getDefaultXercesMemMgr()'
program.cpp:(.text+0x112): undefined reference to `xalanc_1_11::XalanDOMString::XalanDOMString(char const*, xercesc_3_1::MemoryManager&, unsigned int)'
program.cpp:(.text+0x118): undefined reference to `xercesc_3_1::XMLPlatformUtils::fgMemoryManager'



Thanks to this Stackoverflow Discussion. I found out what I was doing wrong. Although the discussion was about compiling in windows but it gave me the clue.

So basically, while it did work on suse, the actual syntax is (LDFLAGS come in last)

g++ -o exectuable <object files> <ld flags>

So I changed my command to the following and got my issue fixed.

g++ -o file.out  program.cpp -lxalan-c -lxerces-c

I am sharing this so the next guy who has similar issues will hopefully find this post and save him some trouble.

Happy coding!

Friday, August 30, 2013

Here is one more thing you can do when you're bored - Thanks to Illinois Tollway

Illinois just gave you a new prank idea. The Illinois Tollway recently published a list of Top Violators who owe big money to Illinois in Toll Violations and are not paying. Somehow they justified this.
Image copyright: http://www.hntb.com

So here is what you can do,

Disclaimer: Always check local state laws of origin and destination states of the call as well as federal law when communicating over the phone. Federal law prohibits anyone from recording a phone conversation without the other party's knowledge and consent. Do not repeat the call to same party if they have told you that they do not wish to receive any call from you.

Step 1  - Click the following link to access the list of violators
Super Scofflaws

Step 2 - Pick one from the list, copy their names, city and state.

Step 3 - Google the name of entry with City and State to find their phone number.

Step 4 - Call them during their regular business hours, tell them you are their wanna-be customer; you just have a very small concern before you give them your business and that is When are they planning on paying off their balance to Illinois Tollway. 

You will likely to hear some funny answers. Good luck!


Friday, May 10, 2013

5 Things I learned about email-marketers


1. Last chance is never a last chance.
This one time I searched my Gmail folder where I kept all the marketing emails I got for “Last chance” or “You must upgrade by midnight”, I was surprised to see repeating emails. So never take those emails seriously, in fact this attitude shows that they are missing their monthly or quarterly sale target. So you could call their customer support and get a good bargain.

2. N% off is most likely N% more the price you can get elsewhere.
Whenever you see the price for something that says that it is after some percentage off, they are not basing their information on the right List price of that product. They are making up a “List price”. Always search for the same product through either the part-number or short-description on other websites and search engines.

3. Unsubscribe sometimes results into more emails from different vendors.
I have always wondered why I am getting emails from a company who want to sell me the prescription medicines for cheap, who gave them my email address. Until I read in a PCMag article that many small businesses; when they learn that you are cutting them loose, they still keep a list of people like you including your email address, name and other information and sell them out. The article suggested to “block” future emails from that business than unsubscribe. Unsubscribing actually lets them know that your email is a legit email which is checked frequently.

4. Offer that is only for you is sometimes not true.
Sometimes those small business owners who are desperately trying to reach their sales goals without having to invest money on billboards and TV ads. They not only lower the price, but to make it sound even better, they tell you that this offer is only for you and everybody else is having to pay the actual price.

5. Never fall for Message from CEO
Do you think a legitimate business’ CEO would have nothing better to do than emailing you to sell a thirty-dollar membership ? To have some fun, call that business and tell them you are replying CEO’s email through phone and you need to speak with him about membership. Tell them you cannot speak with anybody else.


I would love to hear your comments in the comment box below.

Saturday, May 4, 2013

Diomede Islands, a practically possible time-travel scenario?

For those who don't know what and where Diomede Islands are. They are small Islands, located on the Bering sea. One called Little Diomede Island fall in Alaska, USA and other one called Big Diomede Island falls in Siberia, Russia. The shortest distance between those two are roughly two miles


Picture taken from North of the islands, On the left is Little Island which is in USA and right is the big island in Russia.


Here is a small fun fact
On the west edge of Little Diomede Island in Alaska, there is a small town called Diomede, AK which has a population of about 125. In winter time, the Bering waters around that area get frozen, and some residents of Diomede, AK like to take a short walk on the frozen sea waters to Russia. Off course, Russia does not like it, but they know that the island in Siberia is remote and no one lives there so people walking into Russia to feel good about themselves is not a concern for Russian authorities.


Here is the actual fun part
The Big Diomede Island is 23 hours ahead of Little Diomede Island. Which means whatever time it is right now in Little Diomede Island in Alaska, its about the same time next day in Big Diomede Island in Siberia, Russia. So right now as of me writing this post, its 10:30 PM in Diomede, AK Saturday. It is 9:30 PM Sunday in Big Island.

Can travelling from Big island to Little island be considered as a "Back to the future" travel?