SignalR Database update notifications in ASP.NET MVC using SQL Dependency

In this we will learn how to display real time updates from the  SQL Server  by using SignalR  and SQL Dependency in ASP.NET MVC. You can download the source from the Github The following are the steps that we need to enable in the SQL Server first. Step 1: Enable Service Broker on the database The

In this we will learn how to display real time updates from the  SQL Server  by using SignalR  and SQL Dependency in ASP.NET MVC.

You can download the source from the Github

The following are the steps that we need to enable in the SQL Server first.

Step 1: Enable Service Broker on the database

The following is the query that need to enable the service broker

ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;

Step 2: Add Connection string to the Web.Config file

<add name=&rdquo;DefaultConnection&rdquo; connectionString=&rdquo;Server=servername;Database=databasename;User Id=userid;Password=password;&rdquo; providerName=&rdquo;System.Data.SqlClient&rdquo; />

Step 3: Enable SQL Dependency

In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event

public class MvcApplication : System.Web.HttpApplication
    {
        string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //Start SqlDependency with application initialization
            SqlDependency.Start(connString);
        }

        protected void Application_End()
        {
            //Stop SQL dependency
            SqlDependency.Stop(connString);
        }
    }

Step 4: Install SignalR from the nuget

Run the following command in the Package Manager Console

Install-Package Microsoft.AspNet.SignalR

Step 5: Create SignalR Hub Class

Create MessagesHub class in the Hubs folder

public class MessagesHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        public void Hello()
        {
            Clients.All.hello();
        }

        [HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            context.Clients.All.updateMessages();
        }

        
    }

 Step 6: Get the  Data from the Repository

Create MessagesRepository to get the messages from the database when data is updated.

public class MessagesRepository
    {
        readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                {
                    command.Notification = null;

                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }
              
            }
            return messages;
           
            
        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub.SendMessages();
            }
        }
    }

Step 7:  Register SignalR at startup class

Add the following code

app.MapSignalR();

Step 8:  View Page

Create div messagesTable that will append the table data from the database

<div class="row">
    <div class="col-md-12">
       <div id="messagesTable"></div>
    </div>
</div>

Now Add the SignalR related scripts in the page.

getAllMessages is a function that return the partialview data and bind it into the messagesTable div.
<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
 <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.messagesHub;
       
        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
            getAllMessages()
           
        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            alert("connection started")
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


    function getAllMessages()
    {
        var tbl = $('#messagesTable');
        $.ajax({
            url: '/home/GetMessages',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);
        }).error(function () {
            
        });
    }
</script>

Step 9 : Create Partial View Page

Create a partial view _MessagesList.cshtml that returns all the messages.

@model IEnumerable<SignalRDbUpdates.Models.Messages>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.MessageID)</th>
        <th>
            @Html.DisplayNameFor(model => model.Message)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmptyMessage)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MessageDate)
        </th>
        
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.MessageID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Message)
        </td>
        <th>
            @Html.DisplayFor(modelItem => item.EmptyMessage)
        </th>
        <td>
            @Html.DisplayFor(modelItem => item.MessageDate)
        </td>
        
    </tr>
}

</table>

Step 10: Set Up the Database

Create the database called blogdemos and run the following script

USE [BlogDemos]
GO

/****** Object:  Table [dbo].[Messages]    Script Date: 10/16/2014 12:43:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Messages](
	[MessageID] [int] IDENTITY(1,1) NOT NULL,
	[Message] [nvarchar](50) NULL,
	[EmptyMessage] [nvarchar](50) NULL,
	[Date] [datetime] NULL,
 CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED 
(
	[MessageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]
GO

Step 11: Run the project

When eve data is inserted into the table the dependency_OnChange method will fire.

Source Code

You can download the source from the Github

LINK: http://www.codeproject.com/Articles/874240/SignalR-Database-update-notifications-in-ASP-NET-M

Visual Studio 2015 and Apache Cordova

During this article, we are going to learn what Apache Cordova is and in which way this tool is now integrated into Visual Studio 2015.

Visual Studio 2015 and Apache Cordova

  

Before starting, ask yourself these questions:

  • Which is the proportion of developers being professionnally skilled about web technologies today ?
  • Which is the proportion of developers having a native mobile expertise (crossplatform tools users excepted) ?
  • Which is the proportion of developers which can say they have skill for both web and native mobile ?
  • Which is, among them, the proportion of developers  also competent on multiple mobile platforms ?

The proportion corresponding to this last question is, due to learning time and professionnal profile, more than reduced. Indeed, job market do rarely recruit profiles that are extremly multipurpose just because they are more expensive, but can not perform more than one task at a time. The expertise of a consultant grows then in adequation with this hypothesis. Crossplatform tools like Apache Cordova tend to sensibly increase this last number.

Overview of crossplatform solutions

Between web browser and native mobile operating system, we can quote 3 major tools. Unity, thought to a development usually going to video game is the closest to native. It has the particularity to be very performant but, of course, requires a specific and relatively sharp learning. Xamarin, development tool based on the Mono Project, is much more affordable, especially with .NET developers. It help bringing the benefice of this framework on Microsoft’s foreign platformes. Cordova allow at last, thanks to an almost zero learning curve, to realise mobile and multiplatform applications using the same techniques as mobile oriented web development.

Web

Cordova

Xamarin

Unity

Natif

Some history

The Cordova project was during 3 years the PhoneGap project launched by the Adobe corporation, worldwide known for its software suite for multimedia processing: Photoshop, Illustrator, Premiere and After Effect to quote only a few. It was given to the Apache Software Foundation in October 2011 and was graduated top level project in October 2012.

Back in May 2014, Microsoft release the Update 2 of Visual Studio 2013. On this occasion, appears a brand new extension named “Multi-Device Hybrid App”. It allow a better integration of Apache Cordova into Visual Studio through a new project type and a dependencies installer. After this first release which receive a nice echo from in the Microsoft community, a second version appears, and with it new functionnalities, better integration…

  

More recently, in November 2014 on the occasion of the release of the Visual Studio 2015 Preview, the extension is revamped and renamed “Tools for Apache Cordova”. It is now directly available through the Visual Studio installer from an option. If it is chosen, it trigger a second installer which allow to choose precisely the dependencies you want to install : Ant, Android, Java, NodeJS, and many more.

What Cordova brings

Impossible for a classic website to solicit a customer through its smartphone bypassing the standard channels that are SMS and email. Cordova offers a new dimension to web developers practically inacessible until then: the functionnalities of the device which runs the application. Notifications, geolocalisation, vibrator, camera, storage, … All of these functionnalities, out of range of oriented mobile development and yet essential, allow to access the target of a product in a very much efficient manner.
To allow  using web technologies in a native environnement, Cordova will produce an application during the compilation process with 2 major things:
  • An application with a WebView component, integrated web browser
  • A series of ressources to embed the web application files

Very few code is necessary to integrate Cordova’s API to an existent web page, simply add a fictitious JavaScript file only available after compilation:

<script src="cordova.js"></script>

At last, it is possible to attach a specific event trigger to detect that the API is available and ready to be use:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() { /* INIT */ }

What’s new in Visual Studio

In order to promote crossplatform development using Cordova, Visual Studio add a new project type under the Javascript and TypeScript categories.

In addition to initialize your development with a basic file tree, the IDE also add two new emulators.

Android Emulator

The first one is brand new and is the new concurrent of its little brother : it is the Visual Studio’s Emulator for Android. It is now possible to run and debug our application on an Android emulator directly from Visual Studio, without launching the Android SDK’s emulator. Among the improvements, we notice a startup time that is extremely quicker than its counterpart. Also, it is possible to stimulate some of the APIs of the emulated device like the accelerometer or the GPS.

Ripple Emulator

The second, also a product of the Apache Foundation, is Ripple. It was originally a Chrome extension aimed to test and stimulate Cordova’s APIs in a sensibly quicker environnement. Visual Studio, in addition to open it in a Google Chrome window (interesting opening from Microsoft), do not stop there. It is possible, once you have launched the emulator, to edit the source code of the application and see the emulator update itself to absorbe the usual reset debug time.

Visual Studio should go further soon and propose to deploy for you the application on a physical device and allow you to debug it as simple as local. Currently, there is still an issue keeping the debug mode from activating on a physical device. But the application is indeed deployed and launched. This bug is a known issue, so we shouldn’t wait very long before it is resolved. Android, iOS and Windows Phone are now in the scope of web developers of any level, but not only.

It is important to notice that Cordova do not just target mobile applications. It is also possible to create Windows Store applications or Ubuntu.

Points of interest

Cordova faciliates greatly web developers work and allow to put a first feet  in the mobile development environnement without loosing his bearings. It is by the way possible to keep most of his work habits, especially everything about responsive design which allow to beneficiate of a much more flexible technique than “layout” definition for each desired resolution.

However, it is important to care more about animations, generally realized in JavaScript to be compatible on more web browsers. With a native application, this is not necessary anymore. You can target a specific OS version to insure prerequisites, what we can not on a client station potentially using IE 6 or 7. On the other hand, le CPU and the available RAM are not as important as on a computer yet.

So we should replace “inline” JavaScript animated (what Foundation do, for example) by CSS transitions. Moreover, it is preferable to use new CSS3 functionnalities to impact the GPU when this is relevant in order to avoid a “reflow” phenomenon. We can observe it when an element dimensions are changing, which can temporary slow down the browser during the computing of what this change can do on the rest of the page. For example, it will be much more efficient to use a transition on the “transform” instruction (via “translate”) rather than “top” and “left” coordinates. At last, if optimize his DOM and JavaScript can be seen as unnecessary on a computer, this is much more important on a mobile device.

For example, this CSS will work on more web browsers but will be inefficient:

.slide.inactive {   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 0;   
    left: -100%;   
}   
.slide.active {   
    position: relative;   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 1;   
    left: 0;   
}

This one, on the contrary, will be less compatible but way more performant, since it will not trigger a reflow:

.slide.inactive {   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 0;   
    transform: translateX(-100%);   
    -webkit-transform: translateX(-100%);   
}   
.slide.active {   
    position: relative;   
    transition: all 0.5s ease-out;   
    -webkit-transition: all 0.5s ease-out;   
    opacity: 1;   
    transform: translateX(0);   
    -webkit-transform: translateX(0);   
}

To go further, we should experiment specialized front-end frameworks like Iconic. It is interesting to notice one of their mantra:

Performance obsessed
Speed is important. So important that you only notice when it isn’t there. Ionic is built to perform and behave great on the latest mobile devices. With minimal DOM manipulation, zero jQuery, and hardware accelerated transitions, one thing is for sure: You’ll be impressed.

To finish, there is a GitHub repository where is hosted the source code of a Cordova « PowerPoint » like application.

Link: http://www.codeproject.com/Articles/860150/Visual-Studio-and-Apache-Cordova

Hướng dẫn cài đặt XAMARIN trên Visual Studio 2012

XAMARIN  là nền tản lập trình mới giúp lập trình viên phát triển code trên đa nền tản. Chỉ cần code 1 lần và Buil ra được 3 nền tản trên di động ( Android  – iOS – WinPhone )

Mình sẽ hướng dẫn các bạn cài đặt Xamarin để lập trình trên Visual Studio 2012
Bước 1: Vào trang chủ của Xamarin để download file cài đặt:

1.png

Click vào Download now

3.jpg

Chọn Just me ->  sao đó download

Bước 2: Bắt đầu cài đặt
Bạn nên tắt tùy chọn Automatically send troubleshooting information
4.jpg

Chọn Continue

5.jpg

Chọn Next

6.jpg

Check vào I agree to license Items

7.jpg

Chọn Next

8.jpg

Chọn I agree to license tems

9.jpg

Đợi download xong! 1.51Gb

10.jpg

Đợi xong quá trình cài đặt:

11.jpg

Sau khi check hết các icon là hoàn thành quá trình cài đặt:

12.jpg
Bước 3: Xem thành quả và tạo project
Mở Visual Studio 2012 -> chọn new project
+ Android
13.jpg

+ iOS

14.png

Chọn iPhone, iPad, . . .

15.jpg