Saturday, November 2, 2013

SignalR 2.0 VB.NET Push Notification

Many readers have had difficulty with the post SignalR VB.NET Push Notification as they have installed the latest version 2.0. We will require some changes to the old post to make it work.

"..No more RouteTable.Routes.MapConnection but the new Owin MapSignalR..."
Let us review the steps...


Step 1


Install gituhub Package from Package Manager Console

PM> Install-Package Microsoft.AspNet.SignalR

Step 2


Add a new Class to project and create a PersistantConnection:

Imports System.Web
Imports System.Threading.Tasks
Imports Microsoft.AspNet.SignalR

Public Class NotificationConnection
  Inherits PersistentConnection
   Protected Overrides Function OnConnected(request As IRequest, connectionId As String) As System.Threading.Tasks.Task
      Return MyBase.OnConnected(request, connectionId)
   End Function
End Class

Step 3

Add our class for notifications (for simplicity we create note with a value and a time)

Imports Microsoft.AspNet.SignalR

Public Class Notification
   Private _ExamValue As Int32
   Private _Data As String
   Public Property ExamValue As Int32
      Get
         Return _ExamValue
      End Get
      Set(value As Int32)
         _ExamValue = value
      End Set
   End Property
   Public Property Data As String
      Get
         Return _Data
      End Get
      Set(value As String)
         _Data = value
      End Set
   End Property
End Class



Step 4 (Here is the update!!!)

No longer use the file Global.asax.vb. We add a new class for mapping connection. 
No more RouteTable.Routes.MapConnection but the new Owin MapSignalR

Imports Owin
Imports Microsoft.AspNet.SignalR
Imports Microsoft.AspNet.SignalR.Infrastructure
Imports System.Threading
Imports System.Threading.Tasks

<Assembly: Microsoft.Owin.OwinStartup(GetType(SignalR.Startup))> 

Public Class Startup
   Public Sub Configuration(app As IAppBuilder)
      app.MapSignalR(Of NotificationConnection)("/NotificationConnection")
      Task.Factory.StartNew(Function()
                               Dim connectonManager As IConnectionManager = GlobalHost.DependencyResolver.Resolve(Of IConnectionManager)()
                               Dim connection = connectonManager.GetConnectionContext(Of NotificationConnection)()



                               While True
                                  Dim item = New Notification() With { _
                                 .Data = DateTime.Now.ToString("hh:mm:ss"), _
                                 .ExamValue = CInt(Math.Ceiling(Rnd() * 100))
                              }

                                  connection.Connection.Broadcast(item)

                                  Thread.Sleep(1000)
                               End While
                            End Function)
   End Sub
End Class


Step 5 (also here a small change !!!)

In html page we have to change the reference to the old script with the new one for SignalR.

<script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="scripts/json2.js" type="text/javascript"></script>
<!--<script src="scripts/jquery.signalR-1.1.1.js" type="text/javascript"></script>-->
<script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
<script type="text/javascript">
    var output;
    $(document).ready(function () {

        output = $("#output");

    });

    var data;
    var options;
    connection = $.connection('/NotificationConnection');
    connection.received(function (dataItem) {
        var newItem = dataItem;
        output.text("Received exam value: " + newItem.Data + "," + newItem.ExamValue);
    });

    connection.start();
</script>
<body>
    <h2>Laboratory Exams Monitoring</h2>
    <div id="output"></div>
</body>

Monday, May 27, 2013

Runtime change JQuery mobile Collapsible theme

This morning one of my colleagues had the need to change the theme of a  JQuery Mobile collapsible panel at runtime.
It is not a particularly difficult thing but not so trivial.

Here is the link:

http://jsfiddle.net/wonderboycb/JsPnH/3/

Thursday, May 23, 2013

SignalR VB.NET Push Notification


SignalR is a Microsoft library  still in pre release.

https://github.com/SignalR/SignalR

With SignalR we can implement the HTML5 WebSocket without worrying that the web server or the browser supports it. We can do this because the library itself will use long polling or classic polling as an alternative.

This technology finds its expression in chat rooms or online games, but we can think about health information systems, such as notifications to clients of alarms related to the results of laboratories (ok, I did not fancy, it's only my job :-) )

In this post we realize a system of push notifications in VB.Net updated to the latest release of SignalR, at least for now.


Step 1


First open visual studio 2012 and select new project: ASP.NET Empty web application.
Install gituhub Package from Package Manager Console

PM> Install-Package Microsoft.AspNet.SignalR


Step 2

Add a new Class to project and create a PersistantConnection:

Imports System.Threading.Tasks

Imports Microsoft.AspNet.SignalR
Public Class NotificationConnection
    Inherits PersistentConnection
    Protected Overrides Function OnConnected(request As IRequest, connectionId As String) As System.Threading.Tasks.Task
        Return MyBase.OnConnected(request, connectionId)
    End Function
End Class

Step 3

Add our class for notifications (for simplicity we create the note with a value and a time):
Imports Microsoft.AspNet.SignalR

Public Class Notification
    Private _ExamValue As Int32
    Private _Data As String
    Public Property ExamValue As Int32
        Get
            Return _ExamValue
        End Get
        Set(value As Int32)
            _ExamValue = value
        End Set
    End Property
    Public Property Data As String
        Get
            Return _Data
        End Get
        Set(value As String)
            _Data = value
        End Set
    End Property
End Class

Step 4


Critical step, the addition of the file Global.asax.vb, it specializes our router, which will do the job right at the time when the client creates a connection to the server

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
 RouteTable.Routes.MapConnection(Of NotificationConnection("NotificationConnection","/NotificationConnection")

Task.Factory.StartNew(Function()
Dim connectonManager As IConnectionManager =GlobalHost.DependencyResolver.Resolve(Of IConnectionManager()
Dim connection = connectonManager.GetConnectionContext(Of NotificationConnection)()
 While True
                Dim item = New Notification() With { _
                          .Data = DateTime.Now.ToString("hh:mm:ss"), _
                          .ExamValue= CInt(Math.Ceiling(Rnd() * 100)) 
                          '/* For simplicity we simulate the result of examination with a randomic value 
                        }

               connection.Connection.Broadcast(item)

               Thread.Sleep(1000)
  End While

   End Function)
End Sub

Step 5


Now we move on the client and build our html page:

<script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="scripts/json2.js" type="text/javascript"></script>
<script src="scripts/jquery.signalR-1.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
    var output;
    $(document).ready(function () {

        output = $("#output");

    });


    var data;
    var options;
  connection = $.connection('/NotificationConnection');
    connection.received(function (dataItem) {
        var newItem = dataItem;
        output.text("Received exam value: " + newItem.Data + "," + newItem.ExamValue);
    });

    connection.start();
</script>
<body>
<h2>Laboratory Exams Monitoring</h2>
<div id="output"></div>
</body>

That's it, from now our good server will update us every second with the value of the exam to be observed, we can think to plot the trend or change the Application_Start() to retrieve values ​​from the laboratory and just update us in case of alert.


Wednesday, May 8, 2013

Call a Windows Communication Foundation Service with Jquery

I found myself in need to call WCF services from html pages with Jquery,
is not difficult but if you know what to check, you can save a lot of time.

The call 

Is the same as a WebService, WebMethod, with the exception of the extension ".svc"
unnecessary to write yet another Jquery Ajax tutorial:


// Function to call WCF  Service      

        function CallService() {
            $.ajax({
                type:   // GET or POST
                url: // http://..../MyService.svc/GetData
                data: // Data sent to server
                contentType: // content type sent to server (ie: "application/json; charset=utf-8")
                dataType: // Expected data format from server (ie: "json")
                processdata: // True or False
                success: function (msg) {
                   //When service call success
                    ServiceSucceeded(msg);
                },
                error: ServiceFailed // When Service call fails
            });
        }


What about the contract ??


First of all, why "Interface" is called Contract in WCF ? No...is not important,
what is really important, is specify in the contract that you want to operate
with WebInvoke, the type of verb (GET /POST) and the expected data format (Json)


<ServiceContract()>
Public Interface IDataService
    <OperationContract()> _
    <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)>
    Function GetData() As String

     .... yessss VB.Net, why not ?

End Interface

What about the implementation of Interface?

Nothing but remember to specify the AspNet Compatibility before starting to write your Class

Imports System.ServiceModel.Activation

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class DataService
    Implements IDataService  
   
    Public Function GetData() As String Implements IDataService.GetData

    End Function
End Class


That's all....ops no no, just one last thing:

EndPoint

You have to set your endpoint in the Web.config file:

<endpoint address="" binding="webHttpBinding" bindingConfiguration="WHB" contract="HelloWCF.IDataService" behaviorConfiguration="EndpBehavior" />

where binding is:
<bindings>
<webHttpBinding>
<binding name="WHB" crossDomainScriptAccessEnabled="true">
<security mode="None" />
</binding>
</webHttpBinding>
 </bindings>

and behaviorConfiguration is:
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>

Enjoy your service from Jquery html page!


Create a simple slider with CSS3 and JavaScript

To begin with, we need a nice container (the image of an iphone is perfect), with a hole in the center. We put a wrapper around the hole and then the content in the wrapper.


Live demo


The CSS:


/* phone: put it some where in the page */

#phone {
width: 750px;
height: 400px;
background:url(./iphone_4G.png);
position:absolute;
margin:50px 250px;
}

/* wrapper: as big as the hole in the iPhone */

#wrapper {
width: 499px;
height: 283px;
position: relative;
margin: 59px 126px;
overflow: hidden;
border: 2px solid
}


/* the trick is in content: very long, will contain all photos. 
wrapper overflow hidden, so it is visible only the current photo */

#content {
height: 283px;
background-color: #000000;
position: relative;
margin: 0 0;
transition: all 1s; /* here CSS3 Animation !!! (like iPhone) */
-moz-transition: all 1s;
-ms-transition: all 1s;
-webkit-transition: all 1s;
-o-transition: all 1s;
}

I forgot ... the style of the photos:

photoslide {
position: relative;
width: 499px; /* same size as the wrapper */
height: 283px;
margin: auto;
text-align: center;
display: inline;
float: left;
background-size: contain; /* CSS3 adjusts the picture by itself !!! */
background-repeat: no-repeat;
background-position: center;
}


just below to the iPhone, the arrows to try scroll:


#keyboard {
position: absolute;
margin: 450px 600px;
}

The Html:


<div id="phone"> 
<div id="wrapper">
       <div id="content">
        // static in the example, three wired photos :-( 
        // but you can inject your photo div
        // from the server just with an ajax call
        <div class="photoslide" style="background-image: url(./uno.jpg);">&nbsp;</div>
        <div class="photoslide" style="background-image: url(./due.jpg);">&nbsp;</div>
        <div class="photoslide" style="background-image: url(./tre.jpg);">&nbsp;</div>
      </div>
    </div>
</div>
<p id="key">
<a href="#" onclick="left()">&lt;- indietro</a>
<a href="#" onclick="right()">avanti -&gt;</a>
</p>


The script:


<script type="text/javascript">
        var _width = 499, nrfoto = 3, r = 0, l = 0, dstart, dend

        function init() {  // to be executed onbody load
            x = document.getElementById("content")
            x.style.width = _width * nrfoto + "px";
        }

        // store the number of trips left and right not to come out from the iPhone :-)
        function left() {
            l += 1;
            var m = (-_width * r) + (_width * l)
            if (m != _width) {
                x = document.getElementById("content")
                x.style.transform = "translate(" + m + "px)"                     // magic css3!!!
                x.style.webkitTransform = "translate(" + m + "px)"
                x.style.OTransform = "translate(" + m + "px)"
                x.style.MozTransform = "translate(" + m + "px)"
            }
            else
                l -= 1;
        }

        function right() {
            r += 1;
            var m = (-_width * r) + (_width * l)
            if (m != -_width * nrfoto) {
                x = document.getElementById("content")
                x.style.transform = "translate(" + m + "px)"
                x.style.webkitTransform = "translate(" + m + "px)"
                x.style.OTransform = "translate(" + m + "px)"
                x.style.MozTransform = "translate(" + m + "px)"
            }
            else
                r -= 1;
        }
</script>