I move out to github http://lvasquez.github.io/ so see you there =)
febrero 19, 2014
septiembre 3, 2013
Microsoft Websockets on Windows 8
This is a little example that i found about one of the new features support of Windows 8 and that’s a native support for Websockets on server side. At the end of the post, i put some references about why websockets, the original code example, the websockets api client documentation, etc… and you can download the sourcecode of this example for here!!
So first we need to preparate the server side.
Note:
On the server side, we can host our WebSocket server through any one of the ways below:
- Using
HttpContext.AcceptWebSocketRequest - Creating a WCF service with
CallbackContractand the newnetHttpBinding - Using
WebSocketHandlerorWebSocketHostprovided in Microsoft.WebSockets.dll
On the client web side, HTML 5 provides WebSocket APIs and jQuery wraps those APIs for easier usage.
If we want to create a client side application, we can do that through either of the ways below:
- Using the
ClientWebSocketclass (System.Net.WebSockets). - Creating a WCF client and referencing the WCF service which supports WebSocket connection.
NOTE: We can only use .NET WebSocket on Windows 8, Windows Server 2012 and above, including both server-side and client-side applications. And the web server must be IIS 8 and above. IIS 8 Express which is also packaged in Visual Studio 2012 does NOT support WebSocket at present. I hope Microsoft will add support in future.
HTML 5 WebSocket API has no limitation on OS platform. The only limitation is the browser versions. Internet Explorer started supporting HTML 5 WebSocket since IE 10.
To enable WebSocket on the server side, you need to install WebSocket Protocol for IIS 8. On Windows Server 2012, you could do that through Server Manager -> Manage -> Add Roles and Features. Expand the Web Server (IIS) role and check Web Server -> Application Development -> WebSocket Protocol. You may be asked to install dependencies and just allow them. Then install all your selections. Windows 8 should be similar.
And now we can start to our project, first we need to create a ASP.NET Empty Web Application Project and in the Manage Nuget Packages search and install the Microsoft.Websockets package, also you can write the name of the nuget package in the Package Manager Console
PM> Install-Package Microsoft.WebSockets
so then we need to create out HttpHandler for intercepting requests made to your ASP.NET web application server
and create a synchronous handler inheriting of IHttpHandler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSocketExample
{
/// <summary>
/// Summary description for WSHttpHandler
/// </summary>
public class WSHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new MySocketHandler());
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
the we need to create a class that inherits from WebSocketHandler and create our sockets methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Web.WebSockets;
namespace WebSocketExample
{
public class MySocketHandler : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string name;
public override void OnOpen()
{
this.name = this.WebSocketContext.QueryString["name"];
clients.Add(this);
clients.Broadcast(name + " has connected.");
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format("{0} said: {1}", name, message));
}
public override void OnClose()
{
clients.Remove(this);
clients.Broadcast(string.Format("{0} has gone away", name));
}
}
}
and finally our view with a html file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebSocket Example</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var name = prompt('what is your name?:');
var url = 'ws://localhost:49941/WSHttpHandler.ashx' + '?name=' + name;
alert('Connecting to: ' + url);
ws = new WebSocket(url);
ws.onopen = function () {
$('#messages').prepend('Connected <br/>');
$('#cmdSend').click(function () {
ws.send($('#txtMessage').val());
$('#txtMessage').val('');
});
};
ws.onmessage = function (e) {
$('#chatMessages').prepend(e.data + '<br/>');
};
$('#cmdLeave').click(function () {
ws.close();
});
ws.onclose = function () {
$('#chatMessages').prepend('Closed <br/>');
};
ws.onerror = function (e) {
$('#chatMessages').prepend('Oops something went wront <br/>');
};
});
</script>
</head>
<body>
<input id="txtMessage" />
<input id="cmdSend" type="button" value="Send" />
<input id="cmdLeave" type="button" value="Leave" />
<br />
<div id="chatMessages" />
</body>
</html>
so as you see in the html file the client web side, HTML 5 provides WebSocket APIs and jQuery wraps those APIs for easier usage.
References:
http://msdn.microsoft.com/en-us/magazine/jj863133.aspx
http://weblogs.asp.net/dwahlin/archive/2013/04/13/building-an-html5-web-sockets-server-with-asp-net-4-5.aspx
http://www.jefclaes.be/2011/01/html5-installing-microsoft-websockets.html
http://msdn.microsoft.com/en-us/library/ie/hh673567%28v=vs.85%29.aspx
http://alexjmackey.wordpress.com/2012/05/01/websockets-with-asp-net-4-5-and-visual-studio-11/
agosto 31, 2013
Check Digit Algorithm mod 11 with c#
today I had a evaluation exam and one of the problems required to create a function in any language to implement the Check Digit Algorithm Mod 11, one of the interesting thing is that I never implemented this algorithm but thanks God they gave me the example and the steps, so basically the steps are these:
The procedure for calculating the check digit, which may be carried out automatically in a computer, is as follows:
- Take the first seven digits of the ISSN (the check digit is the eighth and last digit): 0317847
- Take the weighting factors associated with each digit : 8 7 6 5 4 3 2
- Multiply each digit in turn by its weighting factor: 0 21 6 35 32 12 14
- Add these numbers together: 0+21+6+35+32+12+14 = 120
- Divide this sum by the modulus 11: 120:11 =10 remainder 10
- Substract the remainder from 11: 11-10 = 1
- Add the remainder, which is the check digit, to the extreme right (low order) position of the base number of the ISSN: 0317-8471
If the remainder is 10, substitute an upper case X in the check digit position. If there is no remainder, put a zero in the check digit position.
and the code for c# is this:
public class Mod11
{
public static string AddCheckDigit(string number)
{
int Sum = 0;
for (int i = number.Length - 1, Multiplier = 2; i >= 0; i--)
{
Sum += (int)char.GetNumericValue(number[i]) * Multiplier;
if (++Multiplier == 8) Multiplier = 2;
}
string Validator = (11 - (Sum % 11)).ToString();
if (Validator == "11") Validator = "0";
else if (Validator == "10") Validator = "X";
return number + Validator;
}
}
as you can see is not a difficult code is a short code but requires a little of logic.
References:
http://www.pgrocer.net/Cis51/mod11.html
agosto 20, 2013
SignalR Demo
He aqui una de las nuevas features de ASP.NET 4.5, SignalR que es una opcion mas para poder trabajar aplicaciones en tiempo real, entiendase envio asincrono de datos entre servidor y clientes en tiempo real, esta es otra solucion mas que nos ofrece nuestro querido ASP.NET, porsupuesto que tambien tenemos la opcion de los Microsoft WebSockets que ahora ya tiene soporte nativo en Windows 8 que posteare mas adelante.
Para enteder mas como funciona SignalR aqui les dejo un excelente post que encontre donde explican mas detalladamente.
http://www.variablenotfound.com/2012/01/introduccion-signalr-i-conceptos.html
Yo aqui les dejo un pequeño ejemplo del codigo que pueden descargar de aqui!! y basicamente es el ejemplo demo que nos da Pluralsight y que es muy facil.
Primero cremos un Proyecto ASP.NET Empty Web Application, desde el Manage Nuget Packages agregamos jQuery, y creamos una carpeta dentro de la raiz de nuestro proyecto llamada HUB, dentro de ella agremos un nuevo item tipo SignalR Hub Class y la llamamos BabyNamesHub, al agregar este tipo de clase se agregaran unos js propios de SignalR en nuestra carpeta de scripts. Dentro de nuestra clase BabyNamesHub escribimos el siguiente codigo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRSample.Hubs
{
public class BabyNamesHub : Hub
{
public void AddBabyName(string name)
{
Clients.All.babyNamed(name);
}
}
}
la clase hereda una clase abstracta llamada Hub y creamos una funcion que recibe un parametro tipo string, utlizamos la clase de SignalR llamada Clients y All para que todos los clientes se conecten a la vez.
En nuestra carpeta Scripts creamos el siguiente script babyNames.js
/// <reference path="jquery-2.0.3.js" />
/// <reference path="jquery.signalR-1.0.0.js" />
$(document).ready(function () {
var hub = $.connection.babyNamesHub,
babyNamesTable = $('#BabyNamesTable'),
babyName = $('#BabyName');
hub.client.babyNamed = function (name) {
babyNamesTable.append('<tr><td>' + name + '</td></tr>');
babyName.val('');
};
$.connection.hub.start().done(function () {
$('#AddButton').click(function () {
var name = babyName.val();
hub.server.addBabyName(name);
});
});
});
despues creamos nuestro archivo html llamado BabyNames.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.0.3.js"></script>
<script src="Scripts/jquery.signalR-1.0.0.js"></script>
<script src="/signalR/hubs"></script>
<script src="Scripts/babyNames.js"></script>
</head>
<body>
<h1>Baby Names</h1>
Proposed Name: <input type="text" id="BabyName" /> <button id ="AddButton">Add Name</button>
<br /><br />
<table id="BabyNamesTable"></table>
</body>
</html>
y por ultimo agregamos un Global.asax a nuestro proyecto y agregamos esto en el Application_Start
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
y resolvemos la con la referencia
using System.Web.Routing;
y obtendremos esto, un pequeño demo de una aplicacion en tiempo real como otra alternativa a Microsoft Websockets u otras cosas como NodeJs, RabbitMQ, MassTransit, etc.
Referencias:
http://pluralsight.com/training/Player?author=dan-wahlin&name=aspnet-webforms45-new-features-m3-framework&mode=live&clip=12&course=aspnet-webforms45-new-features
http://www.variablenotfound.com/2012/01/introduccion-signalr-i-conceptos.html
agosto 19, 2013
ASP MVC 4 Unity Dependency Injection, Automapper and KendoUI Example
A long long time that I not publish nothing about code, but today is the day =) and this is a little example that I created with ASP MVC 4 using Dependency Injection, Automapper, EF and KendoUI. I start to work with ASP MVC 4 a couple months ago and right now I love it!!
In this sample i only want to show one way to use Dependency Injection with IoC, in my case I used Unity but you can use another options like:
Castle Windsor
Structure Map
Sring.NET
Autofac
Ninject
The Sample has the NorthWind database with Entity Framework for my DomainModel, I used Automapper to mapping my DomainModels with my ViewModels and has two CRUD, the classic ASP MVC CRUD and the Kendo Grid simulate the CRUD.
So you can download the sourcecode at github here https://github.com/lvasquez/ASP-MVC4-Unity
So this is my interface ICategoriesServices
public interface ICategoriesServices
{
IEnumerable<Categories> GetAll();
Categories Add(Categories categories);
Categories Get(int id);
Categories Update(Categories categories);
Categories Delete(int id);
}
and my methods CategoriesServices:
public class CategoriesServices : ICategoriesServices
{
public IEnumerable<Categories> GetAll() {
using (var context = new NorthwindEntities())
{
return context.Categories.ToList();
}
}
public Categories Add(Categories categories) {
if (categories == null)
{
throw new ArgumentNullException("categories");
}
using (var context = new NorthwindEntities())
{
context.Categories.Add(categories);
context.SaveChanges();
return categories;
}
}
public Categories Get(int id) {
using (var context = new NorthwindEntities())
{
Categories categories = context.Categories.Find(id);
return categories;
}
}
public Categories Update(Categories categories) {
if (categories == null)
{
throw new ArgumentNullException("categories");
}
using (var context = new NorthwindEntities())
{
context.Entry(categories).State = EntityState.Modified;
context.SaveChanges();
return categories;
}
}
public Categories Delete(int id) {
using (var context = new NorthwindEntities())
{
Categories categories = context.Categories.Find(id);
context.Categories.Remove(categories);
context.SaveChanges();
return categories;
}
}
}
using Unity i register my components
container.RegisterType<ICategoriesServices, CategoriesServices>();
and finally I inject to my controller in the constructor
public class CategoriesController : Controller
{
readonly ICategoriesServices _categoriesServices;
public CategoriesController(ICategoriesServices categoriesServices) {
_categoriesServices = categoriesServices;
}
//
// GET: /Categories/
public ActionResult Index()
{
var dm = this._categoriesServices.GetAll();
IEnumerable<CategoriesViewModel> vm = Mapper.Map<IEnumerable<Categories>, IEnumerable<CategoriesViewModel>>(dm);
return View(vm);
}
public ActionResult Details(int id)
{
var dm = this._categoriesServices.Get(id);
if (dm == null)
return HttpNotFound();
var vm = Mapper.Map<Categories, CategoriesViewModel>(dm);
return View(vm);
}
public ActionResult Create()
{
return View(new CategoriesViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoriesViewModel vm)
{
if (ModelState.IsValid)
{
var dm = Mapper.Map<CategoriesViewModel, Categories>(vm);
this._categoriesServices.Add(dm);
return RedirectToAction("Index");
}
return View(vm);
}
public ActionResult Edit(int id)
{
var dm = this._categoriesServices.Get(id);
if (dm == null)
return HttpNotFound();
var vm = Mapper.Map<Categories, CategoriesViewModel>(dm);
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CategoriesViewModel vm)
{
if (ModelState.IsValid)
{
var dm = Mapper.Map<CategoriesViewModel, Categories>(vm);
this._categoriesServices.Update(dm);
return RedirectToAction("Index");
}
return View(vm);
}
public ActionResult Delete(int id = 0)
{
var dm = this._categoriesServices.Get(id);
if (dm == null)
return HttpNotFound();
var vm = Mapper.Map<Categories, CategoriesViewModel>(dm);
return View(vm);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
this._categoriesServices.Delete(id);
return RedirectToAction("Index");
}
}
This is a quickly how it looks
Default CRUD

Kendo CRUD

I hope that helps
Some References
http://www.dotnet-tricks.com/Tutorial/dependencyinjection/632V140413-Dependency-Injection-in-ASP.NET-MVC-4-using-Unity-IoC-Container.html
http://tecexplorer.blogspot.com/2013/01/using-automapper-with-aspnet-mvc.html


