Why Node.Js? install express,Mongo DB and Jade

Hey Guys,

In this tutorial I want to show you how we can convert Node.Js to a web-server or even more. To do this conversion you need to install express, and also you need to do a few things:

run you command prompt and follow the steps:

  1. Create a directory for Node.js project

E:/mkdir node

2. now you need to install express, please use this command:

E:\node>npm install -g express-generator

3. Create a simple project in your node directly that you created in step 1

E:\node>express nodetest1

4. if you go to that folder you can see a few files and folders are added, this is simple project which is created for us and we want o change some of the configurations. if you open the node folder you can see the package.json, this json file contains list of dependency packages that are needed for this project. if you open the file in any text editor you can see something like :

{
“name”: “nodetest1”,
“version”: “0.0.0”,
“private”: true,
“scripts”: {
“start”: “node ./bin/www”
},
“dependencies”: {
“body-parser”: “~1.12.4”,
“cookie-parser”: “~1.3.5”,
“debug”: “~2.2.0”,
“express”: “~4.12.4”,
“jade”: “~1.9.2”,
“morgan”: “~1.5.3”,
“serve-favicon”: “~2.2.1”
}
}

we only need to add a few items to the dependencies, as I want to show you how to use mongoDB in node js, so we need to add mongoDB dependency to this file. Please change the dependencies section like this:

“dependencies”: {
“body-parser”: “~1.12.4”,
“cookie-parser”: “~1.3.5”,
“debug”: “~2.2.0”,
“express”: “~4.12.4”,
“jade”: “~1.9.2”,
“morgan”: “~1.5.3”,
“serve-favicon”: “~2.2.1”,
“mongodb”: “~2.0.33”,
“monk”: “~1.0.1”
}

5. Next step is to install all dependencies that are mentioned in the package.json. run the command prompt and execute the below command:

E:\node\nodetest1>npm install

6.Once you install everything, you need to create a data directity in node folder, the reason that we need to create data folder is that we want to user mongoDB and we already installed dependency for mongoDB, so without data folder you will face with error 🙂 , so easily run this command in command prompt:

E:\node\nodetest1>mkdir data

7. Now everything is ready to run the Node.js, to run Node.js  you can execute the below command:

 E:\node\nodetest1>npm start

8: To see the result of what have done in this tutorial type this address in browser:

http://localhost:3000

Maybe you are still a bit confused about node.js, but do not be please, it is very normal specially for those programmers that are not familiar with these kind of coding and environments. we just started and you need go through the whole training to understand what exactly is happening. 🙂

Bye bye

Why Node.js?

Hey Guys,

I decided to start a tutorial about node.js. I know sounds is boring because there are plenty tutorials outside which can help you to learn. but in this tutorial I want to start differently. I want to start developing a real application. but we start it slowly and I will try to post  a few times per day. before we start lets say why node.js ?

My answer to this questions is : because node.js is very cool. hahaha… but if you really want to know why node.js,  you can look at this web page, this is a really good explanation about node.js

Why node.js?

Any way, after you read Why Node.js, please do not waste your time to search about it. if you really want to know more about it, you only have one choice:

  1. Move your ass and work on it … hahahah

How we can install Node.Js?

Ok, this a first question that you may ask and it is right question. to install node.Js, Please click Node.Js  and click on the Green INSTALL button ( I hope you can see it there !!!!! 😉  ). Just follow the install instruction and install the Node.Js,

Note: if you do not know how to install this app please turn off your PC and do something else. because installing node.js is as easy as installing Adobe Acrobat Reader 5.5.

How can check whether the Node.Js is installed properly or not?

it is a good questions. to check Node.Js installed properly or not, please open command prompt and type node -v

In response you may get something like this :

Node Version Control

I think for now is enough, I will try to post new things :

Bye bye

How can merge two datatables?

Here I will teach you how can merge two datatables :
You can whatch the video here

 Private Sub MergeDatatable()

        Dim dt1 As New DataTable
        Dim dt2 As New DataTable

        dt1.Columns.Add("Id")
        dt1.Columns.Add("Name")
        Dim dtrow1 As DataRow
        dtrow1 = dt1.NewRow
        dtrow1("Id") = 12
        dtrow1("Name") = "Mehran"
        dt1.Rows.Add(dtrow1)



        dt2.Columns.Add("Id")
        dt2.Columns.Add("Name")
        Dim dtrow2 As DataRow
        dtrow2 = dt2.NewRow
        dtrow2("Id") = 12
        dtrow2("Name") = "Nush"
        dt2.Rows.Add(dtrow2)


        dt1.Merge(dt2)

    End Sub

Click here to convert this Vb.net code to C#

What is NuGet and How does it work?

NuGet is a package-management system for .NET and Visual Studio. Take a look at this scenario:

You want to add JQuery library to your project, so you will follow these steps:

1. Go to www. JQuery.com and download the latest Version of JQuery.

2. Unzip the packages

3. Add it to your project

You should follow these 3 steps to add any free package to your project meanwhile, the most time it is not as easy as JQuery package. I am sure that you have faced with so many errors during adding packages and references to your project. The other important issue is that, how you can trust the packages, especially ZIP packages because they may contain viruses and marvels.

The other problem that will be happened after adding references is, how update these packages? How can find the latest version? How can replace it with old version?

These are the problems that you may be faced during manual adding references. NuGet has solved the problems. NuGet is a places that you could find the latest free packages and add them to your project or get the latest update for current references.

For those who use Visual Studio 2010:

By default the 2010 version of visual studio does not support the NuGet, so first you should  install the NuGet extension, please follow these steps:

  1. Select tools menu
  2. Select Extension manager
  3. In the Extension manager page , search NuGet and the download it ( take a look at following screen shut)

NuGet

Let start Using NuGet to add JQuery to your project:

  1. In the solution Explorer panel right click on your References and select Manage NuGet Packages.
  2. In the Mange NuGet Packages first click on the online (left panel) then type the JQuery on the search box (right panel) after some seconds you will see the list of items that is related to your search (middle panel). Select JQuery and press Install button.

The latest JQuery is downloaded and added to your project.in the next post I will teach you how to update your current references via NuGet.

What is Routing In MVC and how does it work ?

Hello everybody , Today I am going to talk about MVC-routing , if you are a ASP.net developer , you know that how it is easy in ASP.net to make a page as a startup page, just you need to right click on a page and choose “Set as start page”. But the story in MVC is totally different because, you cannot access pages directly, you can just access and call methods, YES IT IS!!! It means the first page of your project that will be displayed after running the project is a view page that is made for a function. But you cannot start view directly, you should call the function.

www.mysample-mvc.com/home/index

Take a look at the above URL, it has three parts

  1. www.mysample-mvc.com(domain)
  2. Home ( name of controller)
  3. Index ( name of function)

As you see I do not mention any page in URL address, just I mention controller and function name, but in ASP.net you should mention the name of page same as this example:

www.mysample-mvc.com/home.aspx

Now the question is that how we can change the startup page. For this purpose please expand App-Start folder (kindly find it in main root of your project) and the open RouteConfig.vb, You will see this code there:

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new
 { controller = "Home", 
action = "Index", id = UrlParameter.Optional }
            );
        }

Please take a look at URL section it is look like this:

 url: "{controller}/{action}/{id}",

This part tell the system that all URLs should have three parts

  1. Controller ( name of controller )
  2. Action( name of function that you want to be run )
  3. Id ( parameters that will be passed to the function)

You may ask if your function does not have any parameter, why you have to pass ID. You are right if the function does not have any parameter you do not need to pass any Id or parameter because we will consider it in the next line of code:

defaults: new { controller = "Home", action = "Index", 
id = UrlParameter.Optional }

As you see URL is an optional parameter not mandatory.

Now everything is ready for you to change the startup page of your project, you just need to change the name of controller and action (function) in this line of code as you want:

  defaults: new { controller = "Home", 
action = "Index", 
id = UrlParameter.Optional }

How can prevent Cross-Site Request Forgery in MVC? Part 1

What is Cross-site request?

wikipedia: is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. more info click here

You have a Logout function in AccountController that users use it to exit from the site. Now assume you have a forum in your site and user should login to your forum to post comments or read them, one of the ability in your forum is that users can upload an image now a devil user upload an image in this way with malicious content:

<img src="/account/logout" />

From now on, each user that visit this page, automatically sign-out from the site, because the Logout function is run automatically by the page.

Token Verification:

You can use token verification to prevent this attach, first you should use @Html.AntiForgeryToken() inside the Form Tag that you want to submit or you want to post to the controller :

<form action="/account/logout" method="post">
@Html.AntiForgeryToken()
…
</form>

Then you should put [ValidateAntiforgeryToken] above the function that is called by the submit button from the view file.

[ValidateAntiforgeryToken]
public ActionResult logout
{
//put your code here
}

How it works?
@Html.AntiForgeryToken() generates a code like this:

<input type="hidden" value="012837udny31w90hjhf7u">

The value of the Token will be compared before running the function that uses [ValidateAntiforgeryToken], if both values will be same the function will be fire, by this method if the function is called from other places or by malicious code it won’t be run.

How To Write File Through VB.Net & C#

ms_visual_studio

As I have promised ,today I am going to show you how to create a file, you can write (create) file in different ways same as reading file.

Before you start, have to import System.IO.

[VB.Net]

Imports System.IO

[C#]

using System.IO;

Writing File

Let met to start with the easiest way,

1.WriteAllText

With this function you can create and write file at the same time!

[VB.Net]

File.WriteAllText("c:\CodingTips.txt", "coding is easy !")

[C#]

File.WriteAllText("c:\\CodingTips.txt", "coding is easy !")

2.StreamWriter:

This Pattern is much like reading file.

[VB.Net]

Dim writer As StreamWriter =File.CreateText("c:\CodingTips.txt") 
writer.WriteLine("coding is easy") 
writer.Close()

[C#]

StreamWriter writer = File.CreateText("c:\\CodingTips.txt");
writer.WriteLine("coding is easy");
writer.Close();

3.MemoryStream:

Sometimes you will need to create a stream (the string that you want to write to the file) before you really need to store it somewhere (like in a file). for example you have 5 functions in your code, and each function has a specific result and you want to store the results of these functions in one file, you cannot use the methods that I explained above, in this case, first you need to prepare the stream and then write it to the file, for this purpose MemoryStream would be a good choice,

[VB.Net]

Dim memoryStrm As New MemoryStream()
Dim writer As New StreamWriter(memoryStrm) 

'This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.
writer.WriteLine("Function1") 
writer.WriteLine("Result1")

[C#]

MemoryStream memoryStrm= new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStrm);

//This part can to be repeated anywhere in your code 
that you want to you want to append text to the memoryStream.
writer.WriteLine("Function1");
writer.WriteLine("Result1");

After you prepared your MemoryStream you can write it to the file:

[VB.Net]

' Here you must ask the writer to push the data into the 
' underlying stream 
writer.Flush() 
' the create a file stream 
Dim MyFile As FileStream = File.Create("c:\CodingTips.txt") 
' now Write the MemoryStream to the file
memoryStrm .WriteTo(theFile) 
' the you have to Clean up the objects 
writer.Close() 
theFile.Close() 
memoryStrm .Close()

[C#]

// Here you must ask the writer to push the data into the 
// underlying stream 

{
    writer.Flush();
    // the create a file stream 
    FileStream MyFile = File.Create("c:\\CodingTips.txt");
    // now Write the MemoryStream to the file
    memoryStrm.WriteTo(theFile);
    // the you have to Clean up the objects 
    writer.Close();
    theFile.Close();
    memoryStrm.Close();
}

How can send mail through VB.Net or C# ?

For a developer, e-mail is an effective way to allow an application to send files or reports to users and to notify users of problems or events.Here i am going to explain how can send mail through VB.net or C#.

To send an email you need two objects:

1.MailMessage object: with this object you can create your message that you want to send.

2.SmtpClient object: with this object you can  send your MailMessage to the recipients.

Before you create a function that send mail ,you need to import System.Net.Mail :

[VB.Net]

Imports System.Net.Mail

[C#]

using System.Net.Mail;

Now your code is ready for creating SendMail function

[VB.Net]

 Private Sub SendMail()
        Dim Message As MailMessage = New MailMessage()
        Message.From = New MailAddress("Arman@codingtips.net", "Arman")
        Message.To.Add(New MailAddress("Mehran@codingtips.net", "Mehran"))
        Message.To.Add(New MailAddress("Mike@codingtips.net", "Mike"))
        Message.To.Add(New MailAddress("JM@codingtips.net", "JM"))
        Message.Subject = "Quarterlydata report."
        Message.Body = "See the attached spreadsheet."
        Message.Attachments.Add(New Attachment("C:\Test.txt"))

        Dim sc As SmtpClient = New SmtpClient("smtp.gmail.com")
        sc.Port = 587
        sc.EnableSsl = True
        sc.Credentials = New NetworkCredential("Username", "Password")
        sc.Send(Message)

    End Sub

[C#]

private void SendMail()
{
    MailMessage Message = new MailMessage();
    Message.From = new MailAddress("Arman@codingtips.net", "Arman");
    Message.To.Add(new MailAddress("Mehran@codingtips.net", "Mehran"));
    Message.To.Add(new MailAddress("Mike@codingtips.net", "Mike"));
    Message.To.Add(new MailAddress("JM@codingtips.net", "JM"));
    Message.Subject = "Quarterlydata report.";
    Message.Body = "See the attached spreadsheet.";
    Message.Attachments.Add(new Attachment("C:\\Test.txt"));

    SmtpClient sc = new SmtpClient("smtp.gmail.com");
    sc.Port = 587;
    sc.EnableSsl = true;
    sc.Credentials = new NetworkCredential("Username", "Password");
    sc.Send(Message);

}

Caution:

SmtpClient.port: it depends on the server that you want to use it to send mail.

SmtpClient .Host: it depends on the server that you want to use it to send mail. (here I used “smtp.gmail.com”)

SmtpClient.EnableSsl: If your server is using the SSL you can user this option.