Tuesday, December 20, 2016

Java SOAP WebService and WebService Client with Apache Axis



Creating and deploying a simple WebService is not as hard as you think. For this example we are going to work with Apache Axis WebService. Axis is essentially a SOAP engine ,a framework for constructing SOAP processors such as clients, servers, gateways, etc.
Apache Axis is a SOAP toolkit that makes it easy to create, deploy, and consume web services. By using Axis, you will be able to quickly convert existing Java functionality into web services, deploy those services, and be able to communicate with them remotely via the Internet, usually through firewalls (if necessary).

More precisely, Axis is an implementation of SOAP. Most people like to think of it as a toolkit. From the programmer's point of view, it's like an API. It makes it easy for you to communicate - with SOAP - to a remote object, without having to worry about the details associated with the protocol. In practice, it is a lot like using RPC, CORBA, RMI, or any of the other distributed computing technologies you may have experience with. The process is largely the same: you describe the target of your communication, invoke the remote method and marshall your parameters, and then demarshall the return values. Since AXIS makes this process simpler than ever, development is a breeze.

Well, let's start coding...
For this example we are going to use:
  • Java (here I'm using JDK 1.7, Click here if you need help installing Java JDK in Windows)
  • Apache Tomcat v7.xx
  • Eclipse Luna

Install Apache Tomcat and add it to Eclipse... File --> New --> Other. Type in server, and follow the wizard.

Open Eclipse and create a "Dynamic Web Project"
For project Name: JavaApacheAxisWebService




On your Eclipse project, expand Java Resources and under /src create a 
new class: MyJavaWebServiceHelloWorld 
and for Package: rolandofebrero.com.web.service



                                 


Now, double click on MyJavaWebServiceHelloWorld.java and add the following code:



Right click on MyJavaWebServiceHelloWorld.java --> Web Services --> Create Web Service


                                   



On the next screen, make sure you have selected Tomcat and Apache Axis in both service and client. Please see the image bellow:



If after clicking finish you see any error regarding to you server, make sure you can start Tomcat with no errors. If not, delete your server, and add it again. Server should start with no errors before creating WebService.

If everything was OK, your project should look like this:



If the server started correctly, JavaApacheAxisWebService and JavaApacheAxisWebServiceClient are automatically deployed to Tomcat server.

By default Eclipse provides a Web service Test Client Window in which we can consume our service



If we click on getEndpoint() link, it will provide us with the endpoint of our service, which is:

        http://localhost:14823/JavaApacheAxisWebService/services/MyJavaWebServiceHelloWorld

put that endpoint in your browser and add ?WSDL at the end. We will see the WSDL created. If you want to consume this service, you might need the WSDL, or just use SoapUI and create a soap project and start testing this new service....    
     


You can download the code for this project from my GitHub account:

https://github.com/rolando-febrero/JavaApacheAxisWebService




Programming thought of the day:


  • My software never has bugs. It just develops random features.

Monday, December 5, 2016

Installing and Running Node.js applications on IIS – Windows



Go to: https://nodejs.org/en/#download and download Node.js for Windows. For this exercise, we are using v6.9.1 LTS version.
Place it in C:\node 



 Also, we need to install iisnode. Go to: https://github.com/tjanczuk/iisnode/releases

Download and install the version Windows OS requires (32 or 64 bits). For this exercise, we are using iisnode-full-v0.2.21-x64.msi





Install URL rewrite module for IIS. Go to: http://www.iis.net/downloads/microsoft/url-rewrite
URL Rewrite allows Web administrators to easily build powerful rules using rewrite providers written in .NET, regular expression pattern matching, and wildcard mapping to examine information in both URLs and other HTTP headers and IIS server variables. Rules can be written to generate URLs that can be easier for users to remember, simple for search engines to index, and allow URLs to follow a consistent and canonical host name format. URL Rewrite further simplifies the rule creation process with support for content rewriting, rule templates, rewrite maps, rule validation, and import of existing mod_rewrite rules.

For testing purposes, create a Default site in IIS to test our Node.js installation. Follow the next steps:

Go to Internet Information Services Manager (IIS). Right click on Sites and click on Add Web Site…


   


Add Web Site dialog box will prompt for some input. Fill out this dialog with:
·        Site Name: Default Web Site
·        Application pool: choose DefaultAppPool
·        Physical path: C:\Program Files\iisnode\www

Make sure to Test your settings before clicking OK.

  


To set up samples, from the administrative command prompt call:

%programfiles%\iisnode\setupsamples.bat   (it is recommended to run it as Administrator)

Or go to: C:\Program Files\iisnode and run setupsamples.bat from there

The setupsamples.bat will:
·        Unregister existing "iisnode" global module from your installation of IIS if such registration exists
·        Register iisnode as a native module with your installation of IIS
·        Install configuration schema for the "iisnode" module
·        Remove existing "iisnode" section from system.webServer section group in applicationHost.config
·        Add the "iisnode" section within the system.webServer section group in applicationHost.config
·        Delete the iisnode web application if it exists
·        Add a new site iisnode to IIS



At this point your site should look like:



And if you click on Modules for this Site in IIS7 you should see iisnode as a native module:


                      

If everything went well, you should be able to hit:  http://localhost/node




Navigate to: http://localhost/node/helloworld/hello.js and if you are able to see this:





It is because the installation was successful and your Node.js app is running within IIS on Windows!








Programming thought of the day:

  • Michael Sinz: “Programming is like sex, one mistake and you have to support it for the rest of your life.”

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