Tuesday, August 25, 2015

Zurich Insurance Group proposes 8.8 billion usd takeover of RSA Insurance Group

Zurich Insurance Group v/s RSA Insurance Group:

Swiss insurance company, Zurich Insurance Group Ltd, made a takeover proposal for British insurance company, RSA Insurance Group on Tuesday. The amount is $8.8 billion. This is the Europe's biggest insurance deal.
Zurich Insurance Group
Zurich Insurance Group

Zurich Insurance Group Ltd is Switzerland's largest insurer.As of 2013, the group was the world's 75th largest public company according to Forbes' Global 2000s list and in 2011 it ranked 94th in Interbrand's top100 brands. Zurich employs around 60,000 people serving customers in more than 170 countries and territories around the globe.

RSA Insurance Group
RSA Insurance Group

Zurich said a month ago it was weighing a bid but left it to the last day under British takeover rules to unveil a cash offer of 550 pence per share, roughly in the middle of the price range expected by investors in Zurich and RSA.


RSA said it planned to recommend the proposal to its board and gave Zurich another four weeks to come up with a firm takeover offer, though the Swiss insurance company reserved the right to ultimately bid below 550 pence per share.
Zurich Insurance Group
Zurich Insurance Group

This is the same deal as Aviva's takeover the Friends Life insurance.


Zurich, which has said it would not overpay and is seeking a return on any investment in RSA of at least 10 percent, said it had reached a “common understanding” with RSA on how the British general and commercial insurer values itself.

RSA, known for its “More Than” home and car insurance brand in Britain, is in the early stages of a turnaround under former RBS boss Stephen Hester.

Let's see, Zurich will take over or not.

Add comments about your views.

Thanks

Sunday, August 23, 2015

Indian rupee down of 66.49 against United States Dollar, lowest in two years

Indian rupee down against United States Dollar, lowest in two years:


The rupee opened at fresh two-year lows on Monday morning, trading at 66.42 a dollar or 0.90% weak on the Interbank Foreign Exchange, a level it hasn't seen since September 2013.



A strong dollar demand from importers and banks, and heavy losses in domestic equity markets weighed on the local currency, forex dealers said.

The rupee has been under pressure since China devalued its currency by nearly 5% in three tranches in an attempt to make its exports more competitive in the global market. Since then, the rupee has been tied down by excess demand for the greenback from exporters and sustained capital outflows from foreign funds.

Indian rupee down of 66.49 against United States Dollar, lowest in two years
The Sensex opened over 600 points down in early trade, and  was later trading down 841 points. All Nifty stocks in the red, tracking a major sell-off in the global markets. The fall has been triggered by a massive sell-off in the global markets on Monday.


The rupee had lost 29 paise to close at two-year low of 65.83 against the US dollar on Friday on high demand for greenback from banks and importers.




Meanwhile, the benchmark BSE Sensex tanked 1,006.54 points, or 3.67%, to 26,359.53 in opening trade.

Thanks

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)?

Cyber city Gurgaon:

Gurgaon is situated in the north of India. Currently its a part of NCR. Its also known as cyber city, because Its a hub of IT work of north India.

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)
In last few years, Gurgaon is growing rapidly. More than 250 (over half) of the global Fortune 500 companies either have their India headquarters or their important offices in Gurgaon. These include firms such as Walmart, Shell, Microsoft, Samsung, GM, GE, PepsiCo, Coca Cola, Google, Toyota and Facebook.

Currently condition of Gurgaon:

No doubt, Gurgaon is growing very fast also generates Rs 16,500 crore of tax revenue for Haryana’s exchequer. But its matter what's its current condition.
I am describing its current condition here:


Roads in Gurgaon: 

If you are living or working in Gurgaon, then you must know about the roads of Gurgaon. You can see NH8 (the most famous Delhi-Jaipur Highway) here. Also, you can see its parallel road (old Delhi-Gurgaon road).


How is the cyber city Gurgaon (current condition of cyber city Gurgaon)
NH8

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)
Old Delhi Gurgaon Road
Both the roads are connecting to Delhi. You can differentiates by watching the pics.

- First one is 8 Lane, also having service lane.
- Second one is 4 Lane, also having mini swimming pool for frogs. 

But the matching point is:

- There are a lot of jam on them. Mostly on weekdays (Mon-Fri) at 8AM - 10AM & 6PM - 8:00PM. If there is a rain in Gurgaon, then there is surely a heavy jam for undefined time period.

In Udhog Vihar (Also a big IT hub) you can see speeding Porsches and scrambling pigs share the same streets that are invariably unlit and pockmarked with potholes.

Sometimes you have to spend 45-50 minutes to cover a 2 KM distance for your office on your two wheeler. If you are thinking you can cover this distance using your feet for save time in jam, then you are wrong. Because, either there is no footpath or you'll see other two wheeler on footpath. For live example, goto Hanuman Mandir Chowk at 9:15AM. LOLZ

There are a lot of main holes are open on the roads. No one knows, when you'll be invited for a party with cockroaches.

I have traveled to Mumbai last month. I rode my friend's apache for 1 week.
It was a rainy season in Mumbai. Mumbai's population is many times as compare to Gurgaon. Even that was a rainy season, still there was no such jam as in Gurgaon.


Environment in Gurgaon:

As Gurgaon is situated in north india, also close to Rajsthan, then its environment is hot. Its average temperature in summers is nearby 38-40 degree celsius and in winters is nearby 8-12.

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)

As there are a lot of traffic problem in Gurgaon, there are a lot of pollution. Air pollution levels rival neighbouring Delhi’s (which is the worst in the world) in a city that has just a tenth of the population.

There is dust every where. You can save your money, just move on roads instead of  buying a body powder.

Basic needs in Gurgaon: 

Gurgaon’s streets are unplanned, unnamed and, in many instances, unnavigable; electricity for most hours of the day has to be generated by residents, offices and malls (there are 35 of those in the city) using their own captive generator sets that burn diesel for fuel; there is no public transport system worth mentioning that functions within the city; policing standards are akin to those of a village thana. There is no security system in nights, specially for women.


Water logging system:

Another pic of NH8


As you can see this pic, this is the water logging system of Gurgaon. It can happen on any road with the couple of hours rain. Its an example of NH8. Now you can assume any another road condition in rains.

Cost of living:

Gurgaon is just nearby Delhi. Still the rate difference in basic things are very high. It may be in case of petrol, grocery, rent, transport, electricity. If i compare Gurgoan with Delhi, then in every basic things which i mentioned are costly in Gurgaon.

How is the cyber city Gurgaon (current condition of cyber city Gurgaon)

The problem with Gurgaon is that it has grown haphazardly in the absence of any semblance of urban planning.

According to a senior Haryana bureaucrat, there never was a master plan for Gurgaon’s growth and there still isn’t one.

A master plan, among other things, demarcates zones for commercial, residential and other use and for civic infrastructure. Gurgaon has had none of that.



When a new commer comes in my office from out side of Gurgaon and after living a couples of week here, he started to complain about Gurgaon with saying that Gurgaon is consider as "Newyork of India" in his hometown, then everyone laughs at him saying that "Tera b kat dia".

Thanks

Friday, August 21, 2015

What is Red Green Refactor in Laravel?

Red Green Refactor in Laravel:

Red Green Refactor is used for testing purposes in Laravel. Stay flexible with the IoC container, and run your tests with PHPUnit.

What is the right reason? Well, that depends entirely on your circumstances and the code that you are writing and testing. 





Red: For The Right Reasons

Red should happen because the conditions of the test were not matched… not for any other reason. As one example: this means that if you are expecting an interface method to be called, the test should fail because the method was not called. It should not fail for any other reason.

An null reference exception is usually not the right reason. There are times when checking null or not-null is the right thing to do, but you should not be getting exceptions to tell you whether its null or not… most of the time, anyways. There’s some exceptions to this, of course.

A “Throw NotImplementedException();” is never the right reason. No, I do not want to throw an exception from that method that I just generated. I want it to be empty, or return a null or some other default value if there is a return type. (and yes, i know there is an option for this in Resharper… but i’ve never seen that option work, no matter how many times i’ve tried to make it work).

There are plenty of other bad reasons for red, and each specific test has to be evaluated to understand the right reason for red. Context truly is king.


Green: For The Right Reasons

A test should pass not just because the conditions stated in the assertions exist, but because the simplest thing that could possibly meet the requirements was implemented.

Back when I was doing all state based testing, I would often make my test go “green” by hard coding a value into it. For example, if I was asserting that the output of some calculation was supposed to be 60, I would hard code a “return 60;” in the method that was being called. I did this to “calibrate” the test… to make sure that the test could pass for the right reasons, even if the implementation was not yet correct. I’m not sure I buy this anymore, really. Do I really need to know that “Assert.AreEqual(60, myOutputVariable);” will work because I hard coded a value of 60 into the method being called? I really don’t think so.

The simplest thing that could possibly work is a misnomer. Hard coding a value is the simplest thing, but it’s worthless. Setting up the very basics of structure and process, without regard for any not-yet-coded functionality is a much more appropriate way to look at the simplest thing. You need to account for the actual requirements of what you are implementing, the core of the architecture that your team has standardized on, and any other bits and pieces of standards that make sense and should be in place for the system in question.

Did you get your test to pass? Good. Did it pass because you wrote production worthy code, without writing more than would make the test pass? Great!

laravel red green refactor

Refactor: For The Right Reasons

STOP! Hold on a second… before you go any further and before you even think about refactoring what you just wrote to make your test pass, you need to understand something: if your done with your requirements after making the test green, you are not required to refactor the code. I know… I’m speaking heresy, here. Toss me to the wolves, I’ve gone over to the dark side! Seriously, though… if your test is passing for the right reasons, and you do not need to write any test or any more code for you class at this point, what value does refactoring add?

Just because you wrote some code to make a test pass, doesn’t mean you need to refactor it. There is no rule or law that says you must refactor your code after making it green. There is a principle that says you should leave the campsite cleaner than when you got there. Sometimes the process of adding code and functionality leaves it clean to begin with and you just don’t need to do any additional work to clean it up.

If you write your first chunk of code to make a test pass and it’s simple, elegant and easy to understand and modify, then stop. You’re done. You don’t need to refactor. If you are adding the 25th chunk of code based on the 25th test and the code remains simple, elegant and easy to understand and modify, then stop! You don’t need to refactor. If, however, you write some code that is a duplication or is using some nested if-thens and loops, or is using hard coded values, or for whatever other reason it does not conform to all of the principles and guidelines that you follow in order to make your code simple, elegant, easy to understand and modify… ok, then you need to refactor.

So why should you follow the refactor portion of red/green/refactor? When you have added code that makes the system less readable, less understandable, less expressive of the domain or concern’s intentions, less architecturally sound, less DRY, etc, then you should refactor it.


Thanks

Thursday, August 20, 2015

What are the Pros and Cons of Laravel ?

Laravel (Pros and Cons): 

Some time ago Laravel 5 released and its consider that Laravel is the best PHP Framework. I am also using this framework. There are alot of pros and cons in laravel as in every framework. These are the following.

Laravel Pros and Cons
Pros:

- In Laravel we are using Composer for install the third party. This is same like  Ruby's gem bundle.  This is a easy way to get all updated code in package with just run a command

composer update

-Eloquent ORM is a simple, super fast ORM that makes working with database relations easy



-Very configurable and extendable. I can set up apps with the folder structure the way I like it and how it works best for me.

-Blade template engine. Very fast (compiles to PHP then caches the results) and very extendable. So easy to add new features without hacking the core.

-Artisan (CLI). Before I started using Laravel I had zero use for CLI tools like migrations and tasks. It’s so easy to create both of those things with Artisan that I can’t believe I waited so long to try it out!

-It also including reverse routing.

-Its documentation is also very beautiful.

Laravel Pros and Cons


Cons:

-Laravel is a new framework. So, for finding answers are still limited in comparison to CakePHP and CodeIgniter. However, the forums and IRC seem to be quite active with helpful people, so usually the answer is findable.



-Laravel’s core files are all within (at least) the Laravel namespace and not all of the files in core use a namespace slash ( a \ ) in front of a call to another core file, which makes extending some classes a bit trickier. This is not a huge issue and one not every developer will need to worry about.


Thanks

Tuesday, August 18, 2015

How to get value of protected object without getter/setter in php

Get value of protected object in php without getter/setter:

If there are any protected object and we want to get its value without creating any get() and set() method & without overriding, then use this method.

for e.g.
 I have a protected array:


Stripe\Coupon Object
(
    [_opts:protected] => Stripe\Util\RequestOptions Object
        (
            [headers] => Array
                (
                )
            [apiKey] => sk_test_Ghjgah2wFtSWkmvJXLge5siVGrM
        )
    [_values:protected] => Array
        (
            [id] => INSTA100
            [created] => 1439875363
            [percent_off] =>
            [amount_off] => 100
            [currency] => usd
            [object] => coupon
            [livemode] =>
            [duration] => once
            [redeem_by] =>
            [max_redemptions] =>
            [times_redeemed] => 0
            [duration_in_months] =>
            [valid] => 1
            [metadata] => Stripe\AttachedObject Object
                (
                    [_opts:protected] => Stripe\Util\RequestOptions Object
                        (
                            [headers] => Array
                                (
                                )
                            [apiKey] => sk_test_Gah2wFtSWkmvJXLge5siVGrM
                        )
                    [_values:protected] => Array
                        (
                        )
                    [_unsavedValues:protected] => Stripe\Util\Set Object
                        (
                            [_elts:Stripe\Util\Set:private] => Array
                                (
                                )
                        )
                    [_transientValues:protected] => Stripe\Util\Set Object
                        (
                            [_elts:Stripe\Util\Set:private] => Array
                                (
                                )
                        )
                    [_retrieveOptions:protected] => Array
                        (
                        )
                )
        )
)





Now i want to get all values of _values


For this i will use ReflectionClass which is a php class
               
$reflector = new \ReflectionClass($cpn);
                $classProperty = $reflector->getProperty('_values');
                $classProperty->setAccessible(true);
                $data = $classProperty->getValue($cpn);


Here $cpn is my object

Now print $data and you will get your required array.

Thanks

Sunday, August 16, 2015

How to create real time chat using with Node.js, Socket.io and ExpressJS

Real time chat using Node.js, Socket.io, ExpressJS:

For creating a real time chat you have to do some following steps:

Setup Environment
Of course, the first thing to do is get NodeJS installed on your system.Once you have NodeJS installed, you're ready to setup the needed instruments.

ExpressJS - this will manage the server and the response to the user
Jade - template engine
Socket.io - allows for real time communication between the front-end and back-end

Continuing on, within an empty directory, create a package.json file with the following content.



{
    "name": "RealTimeWebChat",
    "version": "0.0.0",
    "description": "Real time web chat",
    "dependencies": {
        "socket.io": "latest",
        "express": "latest",
        "jade": "latest"
    },
    "author": "developer"
}


By using the Terminal (under Windows - command prompt), navigate to your folder and execute:

npm install

Within a few seconds, you'll have all the necessary dependencies downloaded to the node_modules directory

Developing the Backend
Let's begin with a simple server, which will deliver the application's HTML page, and then continue with the more interesting bits: the real time communication. Create an index.js file with the following core expressjs code:

var express = require("express");
var app = express();
var port = 3700;

app.get("/", function(req, res){

    res.send("It works!");
});

app.listen(port);
console.log("Listening on port " + port);

Above, we've created an application and defined its port. Next, we registered a route, which, in this case, is a simple GET request without any parameters. For now, the route's handler simply sends some text to the client. Finally, of course, at the bottom, we run the server. To initialize the application, from the console, execute:

node index.js

The server is running, so you should be able to open http://127.0.0.1:3700/ and see:

It works!

Now, instead of "It works" we should serve HTML. Instead of pure HTML, it can be beneficial to use a template engine. Jade is an excellent choice, which has good integration with ExpressJS. This is what I typically use in my own projects. Create a directory, called tpl, and put the following page.jade file within it:

<!DOCTYPE html>
html
    head
        title= "Real time web chat"
    body
        #content(style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;')
        .controls
            input.field(style='width:350px;')
            input.send(type='button', value='send')


The Jade's syntax is not so complex, but, for a full guide, I suggest that you refer to jade-lang.com. In order to use Jade with ExpressJS, we require the following settings.

app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res){
    res.render("page");
});


This code informs Express where your template files are, and which template engine to use. It all specifies the function that will process the template's code. Once everything is setup, we can use the .render method of the response object, and simply send our Jade code to the user.

The output isn't special at this point; nothing more than a div element (the one with id content), which will be used as a holder for the chat messages and two controls (input field and button), which we will use to send the message.

Because we will use an external JavaScript file that will hold the front-end logic, we need to inform ExpressJS where to look for such resources. Create an empty directory, public, and add the following line before the call to the .listen method.

app.use(express.static(__dirname + '/public'));

So far so good; we have a server that successfully responds to GET requests. Now, it's time to add Socket.io integration. Change this line:

app.listen(port);

to:

var io = require('socket.io').listen(app.listen(port));


Above, we passed the ExpressJS server to Socket.io. In effect, our real time communication will still happen on the same port.

Moving forward, we need to write the code that will receive a message from the client, and send it to all the others. Every Socket.io application begins with a connection handler. We should have one:

io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});


The object, socket, which is passed to your handler, is actually the socket of the client. Think about it as a junction between your server and the user's browser. Upon a successful connection, we send a welcome type of message, and, of course, bind another handler that will be used as a receiver. As a result, the client should emit a message with the name, send, which we will catch. Following that, we simply forward the data sent by the user to all other sockets with io.sockets.emit.

With the code above, our back-end is ready to receive and send messages to the clients. Let's add some front-end code.
Developing the Front-end

Create chat.js, and place it within the public directory of your application. Paste the following code:

window.onload = function() {

    var messages = [];
    var socket = io.connect('http://localhost:3700');
    var field = document.getElementById("field");
    var sendButton = document.getElementById("send");
    var content = document.getElementById("content");

    socket.on('message', function (data) {
        if(data.message) {
            messages.push(data.message);
            var html = '';
            for(var i=0; i<messages.length; i++) {
                html += messages[i] + '<br />';
            }
            content.innerHTML = html;
        } else {
            console.log("There is a problem:", data);
        }
    });

    sendButton.onclick = function() {
        var text = field.value;
        socket.emit('send', { message: text });
    };

}


Our logic is wrapped in a .onload handler just to ensure that all the markup and external JavaScript is fully loaded. In the next few lines, we create an array, which will store all the messages, a socket object, and few shortcuts to our DOM elements. Again, similar to the back-end, we bind a function, which will react to the socket's activity. In our case, this is an event, named message. When such an event occurs, we expect to receive an object, data, with the property, message. Add that message to our storage and update the content div. We've also included the logic for sending the message. It's quite simple, simply emitting a message with the name, send.

If you open http://localhost:3700, you will encounter some errors popup. That's because we need to update page.jade to contain the necessary JavaScript files.

head
    title= "Real time web chat"
    script(src='/chat.js')
    script(src='/socket.io/socket.io.js')

Notice that Socket.io manages the delivery of socket.io.js. You don't have to worry about manually downloading this file.

We can again run our server with node index.js in the console and open http://localhost:3700. You should see the welcome message. Of course, if you send something, it should be shown in the content's div. If you want to be sure that it works, open a new tab (or, better, a new browser) and load the application. The great thing about Socket.io is that it works even if you stop the NodeJS server. The front-end will continue to work. Once the server is booted up again, your chat will be fine too.

Thursday, August 13, 2015

Short and easy way to write a route path in Laravel 5.1

Short & Easy way to define route in Laravel:

In Laravel 4.2, Genrallay we define any route like this:



Route::post('/sign-in', 'UserController@signIn');
                              
                           OR

Route::get('/sign-in', 'UserController@signIn');

In Laravel 5.1 we can write route like this & also can write a different method.


We don't need to write 'Route::' for define any route. We can simply write it down as

post('/sign-in', 'UserController@signIn');
                              
                           OR

get('/sign-in', 'UserController@signIn');

 Thanks

Add extra field in migration after creating table in Laravel 5.1

Add extra field in migration after creating table:

First time we create a table's migration & execute migration command. After this , we realize that we have to add a new field in database.

For this, we can modify table by this easy way.

Firstly run this command for create a new migration file.

php artisan make:migration add_email_in_users_details_table

It will create a new file in migration file. Write in its up() function the following lines.



        Schema::create('user_details', function ($table) {
            $table->string('email');
          });


and in down() function write the following lines:



Schema::create('user_details', function ($table) {
            $table->drop_column('email');
          });


Make sure you put the same table name which you want to edit.

Now run migration command for this file.

Thanks

Wednesday, August 12, 2015

How to send email using Node.js?

 Send email using Node.js:

In this blog i am going to discuss about sending e-mail with Node.js, Express.js and NodeMailer package. In many forums and blogs people used to ask about sending e-mail’s using Node.js for account verification, password recovery and promotion. So let’s begin with tutorial and at the end you will have Node application which is able to send e-mail’s to any one’s account.



Create package.json file and keep it in any folder. Put the below code in it.

package.json

{
"name": "email-node",
"version": "1.0.0",
"dependencies": {
"nodemailer": "~0.7.1",
"express": "~4.5.1"
}
}




Once done. Switch to that folder using Command prompt or Terminal and type npm install. It will download and install the dependencies our project need.

npm install

After completion you will able to see node_modules folder in your project directory.

Implementing Server.js:



Let’s begin with creation of our Server file. Paste code shown below in file named as “Server.js”.

Server.js

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});




This is basic block of our app. If you run it in Terminal you will see console message. Now let’s add some routing logic to tell our app what is supposed to do when Request comes from browser. Add these code just above the app.listen line.

app.get('/',function(req,res){
res.sendFile('index.html');
});


Now when you try to open your app from browser, it will return the index.html as response. Let me show you basic snippet of HTML code.

index.html

<div id="container">
<div></div>
Node.JS Email application
<div>
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>


Now next thing to do is to call our Server from HTML page when user hit on ‘Send Email’ Button. To do so at client end i am using jQuery. Here is code snippet of jQuery inside HTML page only.

index.html

<script>
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){    
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("Email is been sent at "+to+" . Please check inbox !");
        }

});
    });
});
</script>



Notice : At $.get we are calling our app with ‘/send’ as handler so now we have to add router in our Server.js file in order to deal with this request. So let’s add some code to handle this route request. Add these code just below of app.get(‘/’) line. File name : Server.js

Server.js

app.get('/send',function(req,res){
//code to send e-mail.
//Will be shown soon.
});


Adding NodeMailer code:

Okay we are almost there, now we have to handle the Mail system. First of all we have to Define Mail transport System (SMTP) so that from that E-mail box our e-mail will be sent. For ease, you can add your Gmail account and password. Add this code just in Server.js just below the ‘var app=express()’ line.

var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "yourID@gmail.com",
pass: "Your Gmail Password"
}
});


We will use this Object to send e-mail. Our app design is when user click on ‘Send email’ Button then only e-mail should be sent, and we have did that part in “app.get(‘/send’)” router. So in that block only paste the code shown below.

var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});




In above code we have read GET variables send from HTML page and we have call “sendMail()” function using Transport object we have created above. In case there is any confusion here is a complete Server.js file.

Server.js

var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
/*
Here we are configuring our SMTP Server details.
STMP is mail server which is responsible for sending and recieving email.
*/
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "yourID@gmail.com",
pass: "Your G-mail password"
}
});

/*------------------SMTP Over-----------------------------*/

/*------------------Routing Started ------------------------*/

app.get('/',function(req,res){
res.sendFile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});



/*--------------------Routing Over----------------------------*/

app.listen(3000,function(){
console.log("Express Started on Port 3000");
});


And this is how HTML page looks like with all styles and JS.

index.html

<html>
<head>
<title>Node.JS Email application</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script>// <![CDATA[
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){    
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("

Email is been sent at "+to+" . Please check inbox !

");
        }

});
    });
});
</script>
</head>
<body>
<div id="container">
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>
</div>
</body>
</html>

Secure site with Password Protection

Secure Site using password:

Step1:- At first open your apache configuration file and add the line AllowOverride All to it.



<Directory /home/abhimanyu/workspace/test/>

    AllowOverride All

Step2:- Now open your .htaccess file and add the following line of code to it



AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/apache2/securepass/.htpasswd
Require valid-user

For details of these lines go here.




Step3:- We need a package of apache as utils to get password utility
and can get it by the following command

sudo apt-get install apache2-utils



Step 4:-Now create securepass dir by running



sudo mkdir /etc/apache2/securepass/
                                              then
sudo htpasswd -c /etc/apache2/securepass/.htpasswd username
and add your password



Step 5:--Now restart your apache server by following command
  sudo service apache2 restart
and check at for your site(domain)  and its got password protected.

Tuesday, August 11, 2015

How to solve [ReflectionException] error in Laravel 5.1 seeding

Resolve [ReflectionException] error in seeding:

Sometimes its make a problem which we are getting in Laravel 5.1 and this is [ReflectionException]

I just got this error when i was running this command for seeding

php artisan db:seed --class=ZoneTableSeeder

and it was showing this error:

  [ReflectionException]                
  Class ZoneTableSeeder does not exist 


For solved out, I just found a solution and its working in my case.

composer dump-autoload

After that run again this command and it will work

php artisan db:seed --class=ZoneTableSeeder

 Thanks

Sunday, August 9, 2015

Easy way to set multiple seeders in Laravel 5.1

Multiple seeders in a table:

For entry multiple data in table it is a easy way to create a seeder.

For creating a seeder run the following command:

php artisan makd:seeder ClassNameSeeder

After this , in its run() function, write it

        $zones = [
            ['zone_id' => 1, 'zip' => '94133', 'rate' => '1.00'],
            ['zone_id' => 1, 'zip' => '94111', 'rate' => '2.00'],
            ['zone_id' => 1, 'zip' => '94104', 'rate' => '3.00'],
            ['zone_id' => 2, 'zip' => '94109', 'rate' => '4.00']

        ];

            \App\Zone::insert($zones);


Here the upper array is the multiple value , which you wana enter in your table.

After that run this command.

php artisan db:seed --class=ClassNameSeeder
Thanks

Friday, August 7, 2015

How and why to use Middleware in Laravel 5.1

Middleware in Laravel 5.1:

Middleware is used for check the request and then process it for particular url.

e.g. There are two types of users. One is Vendor and another is Users. Then for both kind of users will get different authorization.

For this:

Create a Middleware File

php artisan make:middleware VendorMiddleware

Now in routes.php we will set its url

route code
Route::group(['middleware' => 'auth'], function () {
    Route::get('/', ['middleware' => 'vendor', function () {
        return view('welcome');
    }]);


In VendorMiddleware:
<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class VendorMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user= Auth::user();
        if($user->user_type=='vendor'){
            echo "vendor login";
        }else{
            echo "you are unauthorized person";
        }
        //return $next($request);
    }
}


Write in app/Http/Kernel.php

 'vendor' => \App\Http\Middleware\VendorMiddleware::class,

Thanks