Monday, December 5, 2016

Node.js & Express - Hello world example



Node.js is an open-source, cross-platform JavaScript runtime environment for developing a diverse variety of tools and applications. Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript. The runtime environment interprets JavaScript using Google's V8 JavaScript engine.

I use Node.js at work, and find it to be very powerful. Forced to choose one word to describe Node.js, I'd say "interesting" (which is not a purely positive adjective). The community is vibrant and growing. JavaScript, despite its oddities can be a great language to code in. And you will daily rethink your own understanding of "best practice" and the patterns of well-structured code. There's an enormous energy of ideas flowing into Node.js right now, and working in it exposes you to all this thinking - great mental weightlifting.


Pros / Cons:
  • Pro: For a server guy, writing JavaScript on the backend has been a "gateway drug" to learning modern UI patterns. I no longer dread writing client code.
  • Pro: Tends to encourage proper error checking (err is returned by virtually all callbacks, nagging the programmer to handle it; also, async.js and other libraries handle the "fail if any of these subtasks fails" paradigm much better than typical synchronous code)
  • Pro: Some interesting and normally hard tasks become trivial - like getting status on tasks in flight, communicating between workers, or sharing cache state
  • Pro: Huge community and tons of great libraries based on a solid package manager (npm)
  • Con: JavaScript has no standard library. You get so used to importing functionality that it feels weird when you use JSON.parse or some other build in method that doesn't require adding an npm module. This means that there are five versions of everything. Even the modules included in the Node.js "core" have five more variants should you be unhappy with the default implementation. This leads to rapid evolution, but also some level of confusion.

Now, let's install Node.js and see how it working. Go to https://nodejs.org/en/ and download the version you need (in this case we are using v6.9.1 LTS)




Create a folder and let's name it: helloNode
Launch the Command Prompt and navigate to helloNode folder. Run: npm init
This will prompt you for some information about your node app and create package.json file....see the image bellow:





So you are in \helloNode folder, in Command Promt type: npm install express --save  
This command will add Express as dependency for our project. If you don't know what Express is, take a look here: Express .

After adding Express dependecies, a new folder (node_modules) is added to \helloNode. Now create a new file in \helloNode and let's name it index.js

In index.js add the following code:

var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

 The app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

At this point, your \helloNode should look like this:




Now, it's time to see our lil monster works! In Command Prompt type: node index.js
Go to: http://localhost:3000/
If you are able to see the "Hello World" message is because everything went as planned. If not, you might be missing something.   

You can see and download the code for this project from my git account:
https://github.com/rolando-febrero/helloNode





Programming thought of the day:


  • Hey! It compiles! Ship it!

Tuesday, October 25, 2016

Manipulating and showing data using .NET MVC


Here is sample code for a form in which we can show and pass data in .NET using MVC architecture. This simple example will show you how to place our code in the right way by using Model View Controller architecture. Just copy paste the next code into your project and run it...

using System;  
 using System.ComponentModel.DataAnnotations;  
 using System.Collections.Generic;  
 using System.Web.Mvc;  
 namespace HelloWorldMvcApp  
 {  
      // Data models  
      public class Report  
      {  
           public int ID { get; set; }  
           public string Name { get; set; }  
      }  
      public class FileType  
      {  
           public int ID { get; set; }  
           public string Name { get; set; }  
      }  
      // View models  
      public class CronVM  
      {  
           public int ID { get; set; }  
           [Required(ErrorMessage = "Please select the name")]  
           public string Name { get; set; }  
           [Required(ErrorMessage = "Please select the frequency")]  
           [Display(Name = "Frequency")]  
           public string SelectedFrequency { get; set; }  
           public IEnumerable<SelectListItem> FrequencyList { get; set; }  
           public List<ReportVM> Reports { get; set; }  
           public IEnumerable<FileType> FileTypes { get; set; }  
      }  
      public class ReportVM  
      {  
           public int ID { get; set; }  
           public string Name { get; set; }  
           // Note you would apply a foolproof [RequiredIfTrue("IsSelected")]   
           // or similar attribute to this property  
           public int? SelectedFile { get; set; }  
           public bool IsSelected { get; set; }  
      }  
      public static class Repository  
      {  
           public static List<Report> FetchReports()  
           {  
                return new List<Report>()  
                {  
                     new Report(){ ID = 1, Name = "Report 1" },  
                     new Report(){ ID = 2, Name = "Report 2" },  
                     new Report(){ ID = 3, Name = "Report 3" }  
                };  
           }  
           public static List<FileType> FetchFileTypes()  
           {  
                return new List<FileType>()  
                {  
                     new FileType(){ ID = 1, Name = "File type 1" },  
                     new FileType(){ ID = 2, Name = "File type 2" },  
                };  
           }  
           public static List<string> FetchFrequencies()  
           {  
                return new List<string>(){ "Daily", "Weekly" };  
           }  
      }  
 }  


 using System;  
 using System.Web.Mvc;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace HelloWorldMvcApp  
 {  
      public class HomeController : Controller  
      {  
           [HttpGet]  
           public ActionResult Index()  
           {  
                var reports = Repository.FetchReports();  
                var fileTypes = Repository.FetchFileTypes();  
                var frequencies = Repository.FetchFrequencies();  
                var model = new CronVM()  
                {  
                     FileTypes = fileTypes,  
                     FrequencyList = new SelectList(frequencies),  
                     Reports = reports.Select(x => new ReportVM()  
                     {  
                          ID = x.ID,  
                          Name = x.Name,                           
                     }).ToList()  
                };  
                return View(model);  
           }  
           [HttpPost]  
           public ActionResult Index(CronVM model)  
           {  
                var selected = model.Reports.Where(x => x.IsSelected).Select(x => x.Name);  
                var message = string.Format("You selected reportss {0}", String.Join(" and ", selected));  
                return Content(message);  
           }  
      }  
  } 


 @model HelloWorldMvcApp.CronVM  
 @{  
      Layout = null;  
 }  
 <!DOCTYPE html>  
 <!-- template from http://getbootstrap.com/getting-started -->  
 <html lang="en">  
      <head>  
           <meta charset="utf-8">  
           <meta http-equiv="X-UA-Compatible" content="IE=edge">  
           <meta name="viewport" content="width=device-width, initial-scale=1">  
           <title>Bootstrap 101 Template</title>  
           <!-- CSS Includes -->  
           <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">  
           <style type="text/css">  
                .field-validation-error {  
                     color: #ff0000;  
                }  
                table {  
                     width: 100%;  
                }  
                td {  
                     padding: 2px 0;  
                }  
                td:first-child {  
                     width: 25px;  
                }  
                td:last-child {  
                     width: 150px;  
                }  
           </style>  
      </head>  
      <body>  
           <div class="container">  
                <div class="col-md-6 col-md-offset-3">  
                     <h1>Hello Big Bang Code</h1>  
                     @using (Html.BeginForm())  
                     {  
                          <div class="form-group">  
                               @Html.LabelFor(m => m.Name)  
                               @Html.TextBoxFor(m => m.Name, new { @class="form-control" })   
                               @Html.ValidationMessageFor(m => m.Name)  
                          </div>  
                          <div class="form-group">  
                               @Html.LabelFor(m => m.SelectedFrequency)  
                               @Html.DropDownListFor(m => m.SelectedFrequency, Model.FrequencyList, "-Please select-", new { @class="form-control" })   
                               @Html.ValidationMessageFor(m => m.SelectedFrequency)  
                          </div>  
                          <table>  
                               @for (int i = 0; i < Model.Reports.Count; i++)  
                               {  
                                    <tr>  
                                         <td>  
                                              @Html.HiddenFor(m => m.Reports[i].ID)  
                                              @Html.HiddenFor(m => m.Reports[i].Name)  
                                              @Html.CheckBoxFor(m => m.Reports[i].IsSelected)  
                                         </td>  
                                         <td>@Model.Reports[i].Name</td>  
                                         <td>  
                                              @Html.DropDownListFor(m => m.Reports[i].SelectedFile, new SelectList(Model.FileTypes, "ID", "Name"), "-Please select-", new { @class="form-control" })  
                                              @Html.ValidationMessageFor(m => m.Reports[i].SelectedFile)  
                                         </td>  
                                    </tr>  
                               }  
                          </table>  
                          <button type="submit" class="btn btn-success submit">Create</button>  
                     }  
                </div>  
           </div>  
           <!-- JS includes -->  
           <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  
           <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>  
           <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>  
           <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>  
           <script type="text/javascript">  
           </script>  
      </body>  
 </html>


And this is how our app should look like...enjoy






Programming thought of the day:
  • In a world without fences and walls, who needs Gates and Windows?
  • =)

C# - Dependency Injection and Controllers in .NET 4 (MVC)


Dependency injection is a technique that follows the Dependency Inversion Principle, allowing for applications to be composed of loosely coupled modules. ASP.NET Core has built-in support for dependency injection, which makes applications easier to test and maintain.

ASP.NET Core’s built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that type using its built in service container. Services are typically, but not always, defined using interfaces. For example, if your application has business logic that depends on the current time, you can inject a service that retrieves the time (rather than hard-coding it), which would allow your tests to pass in implementations that use a set time.

For this exercise we are going to need Unity package installed in our Visual Studio.
Go to Tools -> NuGet Package Manager and browse for Unity and click "install"

Create a folder and name it "Interfaces", then create interface "IDateTime":
using System;

namespace ControllerDI.Interfaces
{
    public interface IDateTime
    {
        DateTime Now { get; }
    }
}
Create another folder and name it "Services".Add a class and name it "SystemDateTime"
using System;
using ControllerDI.Interfaces;

namespace ControllerDI.Services
{
    public class SystemDateTime : IDateTime
    {
        public DateTime Now
        {
            get { return DateTime.Now; }
        }
    }
}
With this in place, we can use the service in our controller. In this case, we have added some logic to the HomeController Index method to display a greeting to the user based on the time of day.
using ControllerDI.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ControllerDI.Controllers
{
    public class HomeController : Controller
    {
        private readonly IDateTime _dateTime;

        public HomeController(IDateTime dateTime)
        {
            _dateTime = dateTime;
        }

        public IActionResult Index()
        {
            var serverTime = _dateTime.Now;
            if (serverTime.Hour < 12)
            {
                ViewData["Message"] = "It's morning here - Good Morning!";
            }
            else if (serverTime.Hour < 17)
            {
                ViewData["Message"] = "It's afternoon here - Good Afternoon!";
            }
            else
            {
                ViewData["Message"] = "It's evening here - Good Evening!";
            }
            return View();
        }
    } 
}
When we use dependency injection is important to remember that we need to "tell" the compiler that we need our object ready when we call our class. At the moment we installed Unity plugin, some files are created, find UnityConfig.cs and open it.
In "public static void RegisterTypes" method add: container.RegisterType<IDateTime, SystemDateTime>(); Save and compile your project. If you see any problem related to some UserManager initialization, you might need to the next lines under the code you just addedabove:
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<AccountController>(new InjectionConstructor());
Now, save and compile again. 





Programming Thought of the day

If you give someone a program, you will frustrate them for a day; if you teach
them how to program, you will frustrate them for a lifetime. =)


Friday, September 30, 2016

Send data by post method in C#


If you need to POST some data (XML) in a particular URL using C#, you just need to perform the next steps:

  • Create a request to the url
  • Put required request headers
  • Convert the request XML message to a stream (or bytes)
  • Write the stream of bytes (our request xml) to the request stream
  • Get the response and read the response as a string

I know it looks complicated, but once you see the code, you will clarify your ideas...
namespace HttpPostRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlMessage = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" +
            "construct your xml request message as required by that method along with parameters";
            string url = "http://XXXX.YYYY/ZZZZ/ABCD.aspx";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);


            byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(xmlMessage);
            request.Method = "POST";
            request.ContentType = "text/xml;charset=utf-8";
            request.ContentLength = requestInFormOfBytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestBytes, 0, requestInFormOfBytes.Length);
            requestStream.Close();


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
            string receivedResponse = respStream.ReadToEnd();

            Console.WriteLine(receivedResponse);
            respStream.Close();
            response.Close();
        }
    }
}
Now, if the XML message is formed well, everything should be fine....



Programming Joke

Q:  Why do Java programmers have to wear glasses?
A:  Because they don't C#. (see sharp)

because, they are Visually Basic, uh?

=)



Wednesday, September 14, 2016

Redirect to login page when session state time out is completed in asp.NET MVC


If you are working in asp.NET and need your application to redirect users to login page when session timeout is completed, you just need to implement 3 simple steps, and today is your lucky day because I'll show you how to do it...

1. Set the session timeout:
In AccountController.cs find you login method and find where SignStatus is success and place this line:

Session.Timeout = 20;  //put any number, remember this is in minutes

2. Script in _Layout.cshtml
In your Shared folder, open _Layout.cshtml and place this code:

<script>
    //session end 
    var sessionTimeoutWarning = @Session.Timeout- 1;

    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
    setTimeout('SessionEnd()', sTimeout);

    function SessionEnd() {
        document.getElementById('logoutForm').submit();
    }
</script>
What we are doing here is is just calling SessionEnd() method 1 minute before session expires.


As you see, we just need a few steps to perform this event. It is recommended to set a timeout for our apps because increase security, but of course, all depends on kind of project we are working on

Tuesday, September 6, 2016

Stack trace and how to use it to debug your applications...


If you are a developer, you know how important is to debug your application correctly. Knowing how to handle exceptions is a must. We always need to pay attention to the logs generated by our code in order to identify those bugs....evil bugs!
What is a Stacktrace?
A stacktrace is a very helpful debugging tool. It shows you the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:
What is an Exception?
An Exception is what the Runtime Environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object.

Simple Example
With the example given in the question, we can determine exactly where the exception was thrown in the application. Let's have a look at the stack trace:
Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
        at com.example.myproject.Author.getBookTitles(Author.java:25)
        at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
This is a very simple stack trace. If we start at the beginning of the list of "at ...", we can tell where our error happened. What we're looking for is the topmost method call that is part of our application. In this case, it's:
at com.example.myproject.Book.getTitle(Book.java:16)
To debug this, we can open up Book.java and look at line 16, which is:
public String getTitle() {
    System.out.println(title.toString()); <-- line 16
    return title;
}
This would indicate that something (probably title) is null in the above code.

Example with a chain of exceptions
Sometimes applications will catch an Exception and re-throw it as the cause of another Exception. This typically looks like:
try {
....
} catch (NullPointerException e) {
  throw new IllegalStateException("A book has a null property", e)
}
This might give you a stack trace that looks like:
Exception in thread "main" java.lang.IllegalStateException: A book has a null property
        at com.example.myproject.Author.getBookIds(Author.java:38)
        at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
Caused by: java.lang.NullPointerException
        at com.example.myproject.Book.getId(Book.java:22)
        at com.example.myproject.Author.getBookIds(Author.java:35)
        ... 1 more
What's different about this one is the "Caused by". Sometimes exceptions will have multiple "Caused by" sections. For these, you typically want to find the "root cause", which will be one of the lowest "Caused by" sections in the stack trace. In our case, it's:
Caused by: java.lang.NullPointerException <-- root cause
        at com.example.myproject.Book.getId(Book.java:22) <-- important line
Again, with this exception we'd want to look at line 22 of Book.java to see what might cause the NullPointerException here.

So, just to summarize, To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.