Sunday, 24 April 2016

Cluster In Node (Multi-Core System auto Start Server Node)

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load.
The cluster module allows you to easily create child processes that all share server ports.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);
}
Running Node.js will now share port 8000 between the workers:
$ NODE_DEBUG=cluster node server.js
23521,Master Worker 23524 online
23521,Master Worker 23526 online
23521,Master Worker 23523 online
23521,Master Worker 23528 online
Please note that, on Windows, it is not yet possible to set up a named pipe server in a worker.

Sunday, 3 April 2016

C# - What is Delegates in C# Example | Use of Delegates in C#

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.
Syntax of Delegate & Methods Declaration
Check below sample code for delegate declaration and methods declaration
public delegate int Delegatmethod(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}
If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.
Complete Example
public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output

Whenever we run above code we will get output like as shown below
Add Result : 30
Sub Result : 10
What is the use of Delegates?
Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.
Delegates are two types
      -   Single Cast Delegates
      -  Multi Cast Delegates
Single Cast Delegates
Single cast delegate means which hold address of single method like as explained in above example.
Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=
Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list
Check below sample code for delegate declaration and methods declaration

Syntax of Multicast Delegate & Method Declaration
Check below sample code for multicast delegate declaration and methods declaration
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
If you observe above code I declared MultiDelegate method with void return type.
Complete Example
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output

Whenever we run above code we will get output like as shown below
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50

How to use payment gateway in asp.net c#

How to use payment gateway in asp.net c#

Call This Function

 string StrStatus = fillOnlineAmount();

                if (StrStatus == "SUCCESS")
                {
                    st = 1;
                }
                else if (StrStatus == "FAILED")
                {
                    st = 0;
                }




 private String fillOnlineAmount()
    {
        string url = "http://www.payeservices.co.in/api_users/balance?username=xxxxx&pwd=xxxxx";
        HttpWebRequest httpreq = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse httpres = (HttpWebResponse)httpreq.GetResponse();
        StreamReader sr = new StreamReader(httpres.GetResponseStream());
        string results = sr.ReadToEnd();
        txt_mainBalance.Text = results;
        sr.Close();
        return results;
    }

MEAN (Full-Stack JavaScript)

What’s the MEAN Stack?

MEAN is an acronym made up of commonly used technologies for an all JavaScript web stack. You don’t have to use this combination and there are many alternative choices, especially on the client-side such as Backbone, Ember etc.
This particular combination of tools has generated a lot of traction in the enterprise area and is framework based, making it a good place to start.
The key components are:
  • MongoDB (Database)
  • ExpressJS (Web Framework)
  • AngularJS (Front-end Framework)
  • NodeJS (Application Server)

Before you begin we recommend you read about the basic building blocks that assemble a MEAN application:
mean stack tutorial

All Server side code write in expressJS ex:-

// Updated By : Om Prakash
// Updated on : 14 March 2016
//Purpose   : (1.0)  Insert and Get Repository in Mongo DataBase.
var express = require('express');
var fs = require('fs');
var mongoClient = require('./Mongo.js'); // For Modularity
var mkdirp = require('mkdirp');
var app = express();
app.use(express.static('public'));
app.use(express.static('WebContent'));
var appConfig = require('./AppConfig');


//Get Repository fields 1.0
app.get('/repository/getFields', function (req, res) {
console.log("My Request This", req.query);
mongoClient.getRepositoryFields(req.query.repositoryName, function (err, result) {
if (err) {
res.status(500).send("Oops! Error while get Source configuration. Please contact your administrator.")
return;
}
console.log("Result This", result);
res.send({ err: null, data: result});
});
});
//Get Repository Data 1.2
app.get('/repository/getRepositoryData', function (req, res) {
console.log("My Request This", req.query);
mongoClient.getRepositoryData(req.query.repositoryName, function (err, result) {
if (err) {
res.status(500).send("Oops! Error while get Source configuration. Please contact your administrator.")
return;
}
console.log("Result This", result);
res.send({ err: null, data: result });
});
});

//get Repository data 1.0
app.get('/repository/repositoryList', function (req, res) {
console.log('going to get recon results');
mongoClient.getRepository({}, function (err, result) {
console.log("req This", req.params);
if (err) {
res.status(500).send("Oops! Error while get Source configuration. Please contact your administrator.")
return;
}
res.send({ err: null, data: result });
});
});

//save Repository 1.0
app.post('/repository', LoaderInput.any(), function (req, res) {
mongoClient.saveRepository(req.body, function (err, result) {

if (err) {
//res.status(500).send("Oops! Error while Save repository. Please contact your administrator.")
res.status(500).send(err);
return;
}

res.send({ err: err, data: result });
});
});

var port = appConfig.getConfig("ServerPort");
app.listen(port, function () {
    console.log("server started on port : " + port);
});


//Mongo.js for mongo client

// Created By : Om Prakash
// Created on : 14 March 2016
//Purpose   : (1.0) Create for Mongo DataBase Operation.

var appConfig = require('./AppConfig'); // For Modularity
var mongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var mongoURL = 'mongodb://' + appConfig.getConfig("mongoServerIP") + ':' + appConfig.getConfig("mongoServerPort") + '/' + appConfig.getConfig("mongoDBName");

// Insert collection
var insertCollection = function (TableName, doc, callback) {
mongoClient.connect(mongoURL, function (err, mongodb) {
//assert.equal(err, null);
if(err){
console.log("unable to connect to db:", mongoURL);
console.log(err);
callback(err.message,null);
return;
}
//console.log("connected to db:", mongoURL);
mongodb.collection(TableName).insert(doc, function(err, result){
if(err){
console.log(err);
callback(err.message,null);
return;
}
callback(err, result);
mongodb.close();
});
});
};
// Table Exists
var getTableExists = function (TableName, doc, callback) {
//console.log("Collection exists!", TableName);
mongoClient.connect(mongoURL, function (err, mongodb) {
//assert.equal(err, null);
if(err){
console.log("unable to connect to db:", mongoURL);
console.log(err);
callback(err.message,null);
return;
}
mongodb.collection("system.namespaces").find({ name: appConfig.getConfig("mongoDBName") + "." + TableName }).toArray(function (err, result) {
//console.log("Collection doesn't e", result);
if (result.length) {
err = "Collection alredy exists!";
console.log(err);
callback(err.message, result);
return;
}
callback(err, result);
mongodb.close();
});
});
};
// Get Table collection
var getCollection = function (TableName, doc, callback) {
mongoClient.connect(mongoURL, function (err, mongodb) {
//assert.equal(err, null);
if(err){
console.log("unable to connect to db:", mongoURL);
console.log(err);
callback(err.message,null);
return;
}
mongodb.collection(TableName).find(doc).toArray(function(err, result){
if(err){
callback(err.message,null);
return;
}
callback(err, result);
mongodb.close();
});
});
};

var removeCollection = function (TableName, doc, callback) {
mongoClient.connect(mongoURL, function (err, mongodb) {
//assert.equal(err, null);
if(err){
console.log("unable to connect to db:", mongoURL);
console.log(err);
callback(err.message,null);
return;
}
mongodb.collection(TableName).remove(doc)(function(err, result){
if(err){
callback(err.message,null);
return;
}
callback(err, result);
mongodb.close();
});
});
};

// Get Table collection with selected fields and where
var getCollectionFields = function (TableName, doc, fields, callback) {

console.log(TableName, doc, fields);
mongoClient.connect(mongoURL, function (err, mongodb) {
//assert.equal(err, null);
if(err){
console.log("unable to connect to db:", mongoURL);
console.log(err);
callback(err.message,null);
return;
}
mongodb.collection(TableName).find(doc, fields).toArray(function(err, result){
//console.log('result',result);
if(err){
callback(err.message,null);
return;
}
callback(err, result);
mongodb.close();
});
});
};
// Get Table collection top n
var getTop = function (TableName,objSort,limit, doc, callback) {
mongoClient.connect(mongoURL, function (err, mongodb) {
//assert.equal(err, null);
if(err){
console.log("unable to connect to db:", mongoURL);
console.log(err);
callback(err.message,null);
return;
}
mongodb.collection(TableName).find(doc.where, doc.fields).sort(objSort).limit(limit).toArray(function(err, result){
if(err){
callback(err.message,null);
return;
}
callback(err, result);
mongodb.close();
});
});
};

// save Repository in table
var saveRepository = function (repository, callback) {
//console.log("repository", repository);
repositoryMaster = {
name: repository.name,
fields: repository.fields,
collectionName : "Repository_" + repository.name
}
//console.log(repositoryMaster);
getCollection("Repository", {name: repository.name}, function (err, result) {
if (err) {
console.log("Repository get:", err);
callback(err, null);
return;
}
if(result.length > 0){
err="Entity already exists. Please try another name";
console.log(err + ":" + repository.name);
callback(err, null);
return;
}
insertCollection("Repository", repositoryMaster, function (err, result) {
if (err) {
console.log("insert error:", err);
callback(err, null);
return;
}
//console.log(" Repository.data", Repository.data);
insertCollection(repositoryMaster.collectionName, repository.data, function (err, result) {
if (err) {
console.log("insert error:", err);
callback(err, null);
removeCollection("Repository", repositoryMaster,function(err,result){
console.log("remove err, result:",err,result);
})
return;
}
callback(null, "Repository Saved Successfully");
});
});
});
};
module.exports.saveRepository = saveRepository;

// get Repository List
var getRepository = function (config, callback) {
getCollectionFields("Repository", {}, { name: 1, _id: 0 }, function (err, result) {
if (err) {
console.log("getRepository:", err);
callback(err, null);
return;
}
callback(null, result);
});
};
module.exports.getRepository = getRepository;

// get Repository Data keys
var getRepositoryFields = function (repositoryName, callback) {
//TODO: { fields: 1, _id: 0 } is giving parsing error to be debugged
getCollectionFields("Repository", {name: repositoryName}, { _id: 0 }, function (err, result) {
if (err) {
console.log("getRepositoryFields:", err);
callback(err, null);
return;
}
else if(result.length == 0){
err= "Invalid repository name :" + repositoryName;
callback(err, result);
return;
}
//console.log('result',result);
callback(null, result[0].fields);
});
};
module.exports.getRepositoryFields = getRepositoryFields;

// get Source Config
var getSourceConfig = function (config, callback) {
getCollection("SourceMaster", config, function (err, result) {
if (err) {
console.log("getSourceConfig:", err);
callback(err, null);
return;
}
callback(null, result);
});
};
module.exports.getSourceConfig = getSourceConfig;

var getRepositoryData = function (repositoryName, callback) {
getCollectionFields("Repository_"+repositoryName,{}, {_id: 0 }, function (err, result) {
if (err) {
console.log("getRepositoryData:", err);
callback(err, null);
return;
}
callback(err, result);
});
};
module.exports.getRepositoryData = getRepositoryData;

App.config.js 

var config = {};
config["mongoServerIP"] = "localhost";
config["mongoServerPort"] = "27017";
config["mongoDBName"] = "DataLoader";
var getConfig = function (keyName) {
return config[keyName];
}
module.exports.getConfig = getConfig;


use in Angular Create Factory and use angular resource


//Create factory for Repository Operation 1.0
izLoader.factory('repository', function ($resource, $http, Upload) {
return $resource('/repository/:cmd', {}, {
repositoryList: { method: 'GET',isArray:false, params: { cmd: 'repositoryList' } }
});
});


call this service get method with query

repository.get({//method: "GET", isArray: false,
"cmd": 'getFields', "repositoryName": config.inputSourceProperties.ddlRepositoryName, isArray: false
}, function (result, headers) {
callback(result.err, result.data);
}, function (err) {
callback("Oops it seems some problem on the server or network connectivity", null);
});

Another method

 repository.repositoryList({}, function (result, headers) {
cb(result);
}, function (err) {
console.log('error in getRepositoryList', err);
});








Full Stack Developer

a Full Stack Developer is someone with familiarity in each layer, if not mastery in many and a genuine interest in all software technology.
Good developers who are familiar with the entire stack know how to make life easier for those around them. This is why I’m so against silos in the work place. Sure, politics and communication challenges get in the way in large organizations. I think the point Facebook is going for with their hiring policy is, if smart people use their heads and their hearts, a better product gets built in less time.

layers of the full stack:

  1. Server, Network, and Hosting Environment.
    1. This involves understanding what can break and why, taking no resource for granted.
    2. Appropriate use of the file system, cloud storage, network resources, and an understanding of data redundancy and availability is necessary.
    3. How does the application scale given the hardware constraints?
    4. What about multi-threading and race conditions? Guess what, you won’t see those on your development machine, but they can and do happen in the real world.
    5. Full stack developers can work side by side with DevOps(DevOps is a new term emerging from the collision of two major related trends. The first was also called “agile system administration” or “agile operations”; it sprang from applying newer Agile and Lean approaches to operations work.). The system should provide useful error messages and logging capabilities. DevOps will see the messages before you will, so make them count.
  2. Data Modeling
    1. If the data model is flawed, the business logic and higher layers start to need strange (ugly) code to compensate for corner cases the data model doesn’t cover.
    2. Full stack developers know how to create a reasonably normalized relational model, complete with foreign keys, indexes, views, lookup tables, etc.
    3. Full stack developers are familiar with the concept of non-relational data stores and understand where they shine over relational data stores.
  3. Business Logic
    1. The heart of the value the application provides.
    2. Solid object oriented skills are needed here.
    3. Frameworks might be needed here as well.
  4. API layer / Action Layer / MVC
    1. How the outside world operates against the business logic and data model.
    2. Frameworks at this level should be used heavily.
    3. Full stack developers have the ability to write clear, consistent, simple to use interfaces. The heights to which some APIs are convoluted repel me.
  5. User Interface
    1. Full stack developers: a) understand how to create a readable layout, or b) acknowledge they need help from artists and graphic designers. Either way, implementing a good visual design is key.
    2. Can include mastery of HTML5 / CSS.
    3. JavaScript is the up and coming language of the future and lots of exciting work is being done in the JavaScript world (node, backbone, knockout…)
  6. User Experience
    1. Full stack developers appreciate that users just want things to work.
    2. A good system doesn’t give its users carpal tunnel syndrome or sore eyes. A full stack developer can step back and look at a process that needs 8 clicks and 3 steps, and get it down to one click.
    3. Full stack developers write useful error messages. If something breaks, be apologetic about it. Sometimes programmers inadvertently write error messages that can make people feel stupid.
  7. Understanding what the customer and the business need.
    1. Now we are blurring into the line of architect, but that is too much of a hands off role.
    2. Full stack developers have a grasp of what is going on in the field when the customer uses the software. They also have a grasp of the business.
 Other Pieces of the Puzzle:
  1. Ability to write quality unit tests. By the way, even JavaScript can have unit tests these days.
  2. Understanding of repeatable automated processes for building the application, testing it, documenting it, and deploying it at scale.
  3. An awareness of security concerns is important, as each layer presents its own possible vulnerabilities.
 Closing Thoughts:
It is very bad practice to tightly couple code to a specific implementation (library, OS, hardware, etc). Just because a full stack developer understands the entire spectrum doesn’t mean they have license to take shortcuts. Well, actually they do if it is a build and throw away prototype.
Technology start-ups need full stack developers for their versatility!  However, as an organization matures, it needs more and more focused skills.
I’m not sure you can call yourself a full stack developer until you have worked in multiple languages, platforms, and even industries in your professional career. Full stack goes beyond a ‘senior engineer’, as it is along the same lines as a polyglot programmer but with a higher view of all the connecting pieces. Note that on my list, only items 3-5 involve writing code.
 Now we choose only javascript for making your self as like Full Stack Developer using MEAN:-