SYNTAX HIGHLIGHTER

Friday, October 13, 2017

Deploy nodeJs inside docker

Article Scope,

This article scope is limited to, Deploy existing node application inside docker container. this article does not discuss nodeJs and Docker, but I will briefly discuss what is nodeJ and Docker,

What is NodeJs,

You can find good documentation at  :

Node Documentation
W3School Node Tutorials
Tutorial point Node Tutorials

What is Docker,

You can find good documentation at :

Docker documentation

before jump in to the sample application  I would like to verify if you have installed node and docker in your local machine,

To verify node: open Powershell or Commad Propt ( I am in windows machine) if you are using Linux or Mac you can run below command in Terminal.

node -v : this command will print out current node version if you have install node correctly. if not please check your node installation in above guide line.

To verify Docker installation, run "docker" this will print out available option in docker, if you get error message , you need to check your installation

okay, here we go. Let's start sample node application. I am using Visual studio code, you can use your favorite editors like Atom, subline, webstorm etc..

This is a very simple node web app just shows hello world message inside Browser, I am using Express node module and you can use any http module like Http, hapiJs etc..  To initiate package json file just run below command  in powershell

create Directory name  "nodeInDocker" point terminal to that and run

npm init --yes



open up your editor and add new file called server.js, next install node dependency modules. In here we are using express module, to install latest express run command,

npm i express --save

This will pull the node module from npm site (registry) save on local directory inside node_module and update package json .











so we are good to start coding simple express web app, to do that insert below code to server.js

'use strict';

const express = require('express');
const PORT = 8080; //port for run web app
const HOST = '0.0.0.0';
const app = express();

app.get('/',(req,res)=>{
res.send('<h2>Hello world</h2>');
});

app.listen(PORT,HOST);
console.log(`Running on http://${HOST}: ${PORT}`);

To verify the code is working, run below command

node .\server.js :
This will print out  message "Running on http://0.0.0.0: 8080", open the browser and type address http://localhost:8080 if every thing is fine you, can see "Hello word" message in browser







So far, we did just create node express web app the main object is to run this application inside docker container. we will start that implementation. First add new file called "Dockerfile" do not specify any file extension. This contain all the information needed by docker to build docker image then place below content inside file.

FROM node
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY server.js .
EXPOSE 8080
CMD [ "npm","start" ]

Those are basic instructions which required by docker, 

1. FROM      : This specify what is a base image. so we used node image
2. WORDIR : Where to place deployment content inside the docker container
3. COPY       : Which one need to copy to above directory
4. RUN          : To run commands, in here it run npm install command which make sure install                                     required node modules
5. COPY        : Copy the server.js File which is our server app
6. EXPOSE  : Open port inside docker to access out side
7. CMD         : Final step to run command here start "node start "  will will run package.json "start                            script", in there we have mentions to run "node server.js"


{
"name": "nodeInDocker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express":"^4.16.2"
}
}


To build image you need  base image called node which mention in Dockerfile "From" instructions set. so first, install that using docker pull command

docker pull node






This command pulls node image form docker hub. you can find that in 

https://hub.docker.com/_/node/

you can see installed images using 

docker images







We have every thing in hand now, to build docker image for our node app, run below command 

docker build -t nodeindocker:1.0 .

-t flag tag the image name and version number : nodeindocker 1.0

This will read Dockerfile and execute each command one by one. After successfully create that image, you can check newly created docker image using 

docker images






So now we have built new docker image which contains sample app and the dependency required to build sample web app, to run newly created docker container, run below command

docker run  -p 6161:8080 nodeindocker:1.0

-p flag specify host machine port forward to docker container so local machine port 6161 forward to nodeindocker:1.0 port 8080 (which is used sample web app to run)

Fire up the browser and type http://localhost/6161 you can see same message like previously we ran web app in localhost now it is running on inside docker.

you can see ruining docker containers using below command 

docker ps

to stop running docker container, run  command

docker stop <container id  or image name>

in my case it is




docker stop 80c2437fd8ed

Thank you very much reading this article , if you have any issue when creating this sample application please feel free contact me









Tuesday, August 25, 2015

WCF self host application with MSMQ


Windows Communication Foundation (WCF) is a framework for building service-oriented applications, it is a unified component for work with existing technologies like Web service, Remorting, MSMQ act. This article I am going work with with WCF with MSMQ (Microsoft Messaging Queue). Which enable application to running at different times to across the network and system that be temporarily offline. When we compare MSMQ with web service MSMQ work without running server application at server. It just queue message and process later when server come up online.

before start  you should have basic knowledge of

1. Windows Communication Foundation (WCF) for more details click here.

2. Microsoft Messaging Queue for more details click here

3. Visual Studio (2012/2013)

1. Create a blank Solution name it as RetailsStore

2. Add new Class library project called "RetailStore.Services"

3. Add System.ServiceModel Reference to newly created project



3. Add new interface called "ITradeService" and below code

using System.ServiceModel;

namespace RetailStore.Services
{
    [ServiceContract]
    public interface ITradeService
    {
        [OperationContract(IsOneWay = true)]
        void DoTrade(string buystock, string sellStock, int amount);
    }
}

4. Add new class called "TradeService" and paste below code

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace RetailStore.Services
{
    public class TradeService : ITradeService
    {
        [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
        public void DoTrade(string buystock, string sellStock, int amount)
        {
            ReceiveContext receiveContext;

            if (!ReceiveContext.TryGet(OperationContext.Current.IncomingMessageProperties, out receiveContext))
            {
                Console.WriteLine("Recieve context is not available for the message");
                return;
            }
            Console.WriteLine("Received Reauest to Sell Stock {0} with the quantity of {1} from and buy {2}", sellStock,
                amount, buystock);
            if (amount == 50)
            {
                receiveContext.Complete(TimeSpan.MaxValue);
                Console.WriteLine("Amount is more than 50");
            }
            else
            {
                receiveContext.Abandon(TimeSpan.MaxValue);
            }

            Console.WriteLine();
        }
    }
}

5. Now your service library ready to host. here i have used Command line hosting.to do that Add new     Console project called "HostApp"  6. Add Reference "RetailStore.Services" to HostApp

7. Add System.ServiceModel Reference to  HostApp

8. Paste below code to main method
 
using System;
using System.ServiceModel;
using RetailStore.Services;

namespace HostApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string baseAddress = "net.msmq://localhost/private/TradeQueue";
            using (var servicehost = new ServiceHost(typeof (TradeService), new Uri(baseAddress)))
            {
                servicehost.Open();
                Console.WriteLine("The Trade Service is online");
                Console.WriteLine("Press Enter to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
                servicehost.Close();
            }
        }
    }
}

9. Add below configuration setting to HostApp App.config
 

    
      
        
          
            
          
        
        
      
    
    
      
        
          
            
          
        
      
    
    
      
        
          
        
      
    
  
10. Set HostApp as start project and run. copy "http://localhost:5051/TradeService" above line (07) address and paste it browser you can get below screen. now we are ready to access service form client.




11. Create new Console Application called it as "ClientApp"

12. To add service reference run host app in release mode to do that make sure Host app as start up           project and Press (Ctrl+F5). Then select ClientApp project and select service reference using               above Url and name Namespace as "TradeServiceRef"



12. Add System.Transaction Reference to ClientApp to available transaction

13. Paste below code to Client App

 
using System;
using System.Transactions;
using ClientApp.TradeServiceRef;

namespace ClientApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (var proxy = new TradeServiceClient())
            {
                using (var scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    proxy.DoTrade("MSFT", "IBM", 60);
                    Console.WriteLine("Selling 60 stocks of IBM and Buying MSFT");
                    proxy.DoTrade("ACN", "ABN", 100);
                    Console.WriteLine("Selling 100 stocks of ABN and Buying ACN");
                    scope.Complete();
                }
            }

            Console.ReadLine();
        }
    }
}

14. now you are complete all the coding. before run application please make sure MSMQ is installed in Dev box. if not use this link to configure MSMQ link

15. Create transaction Queue called "TradeQueue"

16. Stop the HostApp and run the ClientApp. you can see your message queuen in internal MSMQ

Running Client

Messages queue on private Queue




17. To process message stop the Client App and run HostApp you can see all the queue massages have been processed

note. As a series of this articles, next article we will look how to enable dependency injection for this application.

Download source code from here.Click
Coding Hunt!:)


Saturday, September 13, 2014

c# - Write values in app.config

Introduction

We all have used app.config appsettings in our applications. when try to add or edit appsettings in run time it will only persist state for current user session.  if restart the app the saved appsetting will have lost.in this post I am trying to resolve the problem.

Main View


Save appSetting in runtime

if this code block save appSetting that will not reflect to current user session. to change current session value you need to add next image's code



Update current user session


Complete code block



Download code sample Click here

I most welcome your comments

WPF DataGrid Row Select with MVVM + Prism 5

Introduction 

I have already published how to select Data grid row with MVVM. this article I am going to introduce Prism 5 data grid select.  you see my previous post in here


Main view




how to get new prism 5


View Model
 CustomerViewModel class has been derived in "BindableBase" this a new prism 5 class which implement INotifyProperyChanged. you can see new lambda expression for property change and set value with SetProperty Method
View

Download code sample Click here

I will most welcome your comments

Monday, March 11, 2013

WPF DataGrid Row Select with MVVM


Introduction

In this article I am going to discuss how to select Row in the DataGrid control with MVVM pattern. Basically, MVVM pattern directly engage with WPF/Silverlight using Command binding. Command binding is a power full feature in the WPF/Silverlight. you can find new version of this here

Prerequisites
In this sample, I am using Visual studio 2010 and .net framework 4.0

Solution
1.      1.  I am creating a WPF project Called “SolutionFileManager” and Add  3 folders called “Models,              ViewModels and Views” 


2         2.  Add new class called “DataFile” into Models .  This is our Domain Entity and that contains few properties

            3.       Add new “ViewModel “ called “DataFileListViewModel”.  DataFileListViewModel responsible for handing Command which are fired in the views and make data for the relevant view

       4.        Add new class for ICommand Implementation called “DelegateCommand”
          
5.      Add NuGet package Reference
a.       Right click on project and select “Manage NuGet Packages…”
b.      Type “expression blend” in the search box
c.       Select “Blend Interactivity for WPF v4.0” and click install


              d.  Nuget package manager add Reference for “Microsoft.Expression.Interactions and System.Windows.Interactivity”

     6.     Add new userControl for Views folder called “DataFileList.xaml” and set it as startup window
      
             
             7.   Add Xaml markup for DataFileList.xaml. Below  Xaml add “PreviewMouseUP” event triger using interactivity


      8.    Add Viewmodel binding to code behind  file

        9.   Run the application and click on grid Row

              Download code sample Click here

Wednesday, December 19, 2012

How to remove SharePoint 2010 feature



when you developing custom solution on SharePoint 2010, you might get error with custom feature which you develop may be  not have control with central admin then you can use SharePoint Power shell command to remove (uninstall) SharePoint Feature.

To remove SharePoint feature.

Before remove, you should know feature GUID (ID). To get feature id  run the below command on SharePoint PowerShell window.

          Get-SPFeature



      Copy the id of the feature

Run the below command to remove feature from SharePoint 2010

Uninstall-SPFeature -Identity "0808a7d5-aeab-s-409d-a975-c882351a507b"


Press "Y" to continue process.


Monday, December 17, 2012

Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'


Login failed for user 'NT AUTHORITY\ANONYMOUS  LOGON'

When you create Business Data Connectivity Services with SQL Server using SharePoint Designer, above error will come because of , External System not getting proper identity to connect. To resolve the problems relating BCS authentication consider below steps

How to change BCS Authentication Mode.

1.       Change the Authentication mode to BCS Identity



2.       If you get error, please update the BCS  “RevertToSelfAllowed”  to true using below Powershell command.


To list down SPservices Ids and then copy Business connectivity id
          Get-SPServiceApplication;



To get Business connectivity service

$bcs = Get-SPServiceApplication  -ID  ”<<Id>>”
$bcs. RevertToSelfAllowed  = $true
$bcs.Update();

Note: after update  you might need  reset IIS

3.       Although you update BCS credential  , it might show error message on the page like below


In my scenario ,I  saw below errors log the  in Event Viewer






To resolve the problem,

1.       Verify your site App pool account have sufficient credential in DB
2.       In SQL server , “User Mapping” data base for App pool account







3.       Verify relevant user “Schemas “ and  “Data base Role Membership”