Wednesday 8 February 2017

ASP.Net MVC + AngularJS for Application Development

Hello Friends,

Today,  we are going to discuss about MVC architecture and AngularJS for Application development.

I didn’t get a chance to work on MVC based applications earlier and used AngularJS slightly while many of my team member was working on MVC. 

So, finally I also decided to explore about MVC but when I started I came to know that MVC alone is not being used in most cases now but popular in application development along with AngularJS. But, when I started looking into it without prior much knowledge in MVC, I started with struggle in MVC + AngularJS parts being handled and understanding of related application development. 

So, we will discuss mainly about very basic problem I faced during my initial exploring and small introduction of other facts.

So, lets’s quickly discuss basic stuffs related to this topic.

1. MVC
2. AngularJs

MVC:- As we all knows that MVC stands for Model-View-Controller architecture of development which separates an application into three logical components. Where.

Model - Is associated and responsible for database related logic and operations.

View - Represents UI to display data/information to users and to allows user to perform operations.

Controller - It works as interface between View and Model and actually responsible to process requests and operation from view and processing data using model.

The ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We use Visual Studio to create ASP.NET MVC applications which can be added as template in Visual Studio.

For more details and quick learning, refer below URLs

https://www.asp.net/mvc/overview/getting-started/introduction/getting-started
https://www.tutorialspoint.com/mvc_framework/mvc_framework_introduction.htm

2. AngularJs :- AngularJS (commonly referred to as "Angular" or "Angular.js") is a completely JavaScript-based open-source front-end web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

AngularJS is a JavaScript framework. It is a library written in JavaScript. AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

For more details and quick learning, refer below URLs

https://docs.angularjs.org/guide/introduction
http://www.w3schools.com/angular/angular_intro.asp

Now, let’s come to the problem that I faced initially when tried to merge MVC and AngularJS for web application development.

Basically, MVC is itself has MVC architecture but AngularJS is also used with MVC architecture. So there was the problem arises when started to explore that what is the scope of MVC of Angular and Asp.Net MVC. It was bit confusing to me that why we need ASP.Net MVC while using AngularJS MVC. Because AngularJS MVC is dealing most of the part of application flow from front end and I concluded that this is true that Asp.Net MVC can be skipped and MVC Web API could be used to get any data from server side but then realize that this is OK but for authentication and basic stuff it will become a pain to handle authentication using API within same application while considering security concerns.

Then I rethink and found that in MVC + Angular, actually basic stuffs like authentication etc are being handled through Asp.Net MVC while all other front end level operation being handled by Angular MVC.

But to configure and setup application using MVC and angular was bit tricky according to me. So I am trying to specify exact steps to make it bit easier for new learners like me.

Below are the steps that can be followed to make it working while using MVC and AngularJS.
1. Open Visual Studio 12 or above and open New Project
2. Create ASP.Net Web Application
3. Select MVC as template to be used
4. Uninstall default added packages through package manager console. Use below commands to uninstall.
Uninstall-Package Microsoft.jQuery.Unobtrusive.Validation
Uninstall-Package jQuery.Validation
Uninstall-Package jQuery
Uninstall-Package Modernizr
Uninstall-Package Respond
Uninstall-Package bootstrap

5. Remove reference of above from BundleConfig.cs as well (Optional)
6. Remove Default controllers and views added (optional)
7. Open Index.html in Views -> Home and delete contents.
8. Download AngularJS library and add in your project structure (in Scripts folder - recommendation but not necessary)
9. Add blank page with reference to your angular.js library file in your folder structure like below

<!DOCTYPE html>
<html ng-app>
<head>
    <title></title>
</head>
<body>
    <script src="~/Scripts/libs/angular.js/1.2.20/angular.min.js"></script>
</body>
</html>

10. Now if all is well then your application is ready to use angular js. So add some Angular JS code on your index.html in body tag. For Ex. as below
    
    <input type="text" ng-model="helloAngular" />
    <h1>{{helloAngular}}</h1>

11. This looks okay but still angular not using MVC here. So, we need to update our folder structure a little bit with following.
      a)Add a folder in Scripts for your App's Angular MVC “/Scripts/AngularMVC/”
      b)Add a js file with your application name (i.e. "MVCWebAppDemo") in "/Scripts/AngularMVC/"
      c)Add folder “Controllers” in “AngularMVC” and add a js file named as "HomePageController" in controllers folder.


12. Now add your application AngularMVC script files in bundle in "App_Start/BundleConfig.cs"

bundles.Add(new ScriptBundle("~/bundles/MVCWebAppDemo").IncludeDirectory("~/Scripts/AngularMVC/Controllers", "*.js").Include("~/Scripts/AngularMVC/MVCWebAppDemo.js"));

13. Now add this bundle to the homepage (index), after the angular.min script tag itself:

 @Scripts.Render("~/bundles/MVCWebAppDemo")

14. Add code in AngularJS MVC controllers (i.e."HomePageController.js" ) (to control and process requests) as below.

var HomePageController = function($scope) {    $scope.models = {
helloAngular: 'I am home page!'    }; }
// The $inject property of every controller (and pretty much every other type of object in 
//Angular) needs to be a string array equal to the controllers arguments, only as strings

HomePageController.$inject = ['$scope'];

15. Now setup our application object (i.e. ApplicationName.js as added in angularMVC folder) to indicate controller to be used.

//This creates an app module object for angular app.
var MVCWebAppDemo = angular.module('MVCWebAppDemo',[]); 

//Add controller information in this app/module now. //Here we registered HomePageController as created in "/Scripts/AngularMVC/Controllers/HomePageController.js"

MVCWebAppDemo.controller('HomePageController', HomePageController) 

16. Now configure homepage to know about configured Angular App/module and associated controller.
      a) add "ng-app" directive in <html> tag to specify angular app/module name 
      
      b) add "ng-controller" directive in <html> tag to specify controller name to be used from added angular app/module

For Ex. - 
<html ng-app="MVCWebAppDemo" ng-controller="HomePageController">

17. Now run the application. If all done well you should see home page with message as "I am home page!"

So far we are good to configure ASP.net MVC Application which is using AngularJS in MVC structure but we have not yet used anything from ASP.Net MVC explicitly. Internally it is already working.

Now consider a situation where we need some data processed through ASP.Net server side and MVC is responsible for that. So, to understand that how server side controllers are being triggered and refer for request processing, we are going to use simple routing and will pass some data from ASP.Net MVC controller which will appear at front end.  

18. Create a new link on home page (index.html) to navigate to products as below

<ul>
        <li><a href="/#/products">Show Product</a></li>
</ul>

19. Add a div to render partial views. Create a view and add ng-view directive in this.

<div ng-view></div>

20. Add ngRoute module of Angular JS and load in your application by adding it as dependent module.
      a)Download/refer angular-route.js and add on home page below angularJS.

      <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>

      b) Add ngRoute in application module as dependent

       var MVCWebAppDemo = angular.module("MVCWebAppDemo", ['ngRoute']);

21. Now map routes being used in application. In our example "/products". So add below code in application module (i.e. MVCWebAppDemo.js)

var configFunction = function ($routeProvider) {
    $routeProvider.
        when('/products', {
            templateUrl: 'product/get'
        });
}
configFunction.$inject = ['$routeProvider'];
MVCWebAppDemo.config(configFunction);

22. Now observe above specified ConfigFunction for below code

$routeProvider.when('/products', { templateUrl: 'product/get' });

23. In above code 
      a) '/products' is client side URL called in browser
      b) templateURL is used to specify internal URL/MVC URL (i.e. "product/get")           that need to be processed and according to this internal URL respective             controller with specific action (i.e. "get" action of "ProductController" in             our example above) will be triggered.

          Note:- Please refer that default configuration for MVC URL is 
          "/Controller/Action/Id". 

So if we refer specified templateURL (I.e. “product/get”) that means it will trigger “get” function of “Product” controller. But product controller is not yet added so lets add “ProductController”

24. Now add an empty MVC controller in "/Controllers" folder and  name it as ProductController and add below code in it.
      
  public ActionResult get()
        {
         List<string> productList = new List<string>();
            productList.Add("Product 1");
            productList.Add("Product 2");
            productList.Add("Product 3");
            ViewBag.products = productList; 
return View("_products");
        }

Please not that in above code we are returning "_products" view from get action. But this is not yet created. So follow next step to add a new view.

25. Go to "/Views/Product/" folder in solution explorer and add a partial view and name it as "_products" with below code in it to render results.

Product List
<ul>
    @for (int i = 0; i < ViewBag.products.Count; i++)
    {
        <li>@ViewBag.products[i]</li>
    }
</ul>

26. Now run application and if all configured correctly then you should see same home page with “Products” link on it and when click on “Products” link then it should display “Product 1”, “Product 2”, “Product 3” below the link.

So, as we seen that how we used ASP.Net MVC and AngularJS together. Now you are free to explore more as per your requirement and can manage most of front end business logics through AngularJS MVC also powered with ASP.Net MVC server side processing.

I hope this may help some newbies who is struggling with setup/configuration of ASP.Net MVC along with AngularJS. So keep sharing feedback if this help anyone or let me know feedback to improve it. 

Alright, so, see you soon, till then keep exploring and sharing.

References


Thursday 19 November 2015

Symbolic Link

Hi Friends,

Today I am back with very small thing but I was not aware and faced some problem with that. So I am here with the thought that this might help someone. 

Did you heard about “Symbolic Link”?

I did not heard about it earlier but found a requirement in one of the project as per suggestion from my coordinator. Then I started exploring it and found that in Windows environment it is just like a shortcut which points to another location. 

But later i found that there is some differences in Symbolic link and shortcuts. Shortcuts need a specific application to make it working which is supported by windows like operating system. But in case of Linux/Unix based system this is not working (not declaring this but found such in initial phase). 

Shortcut is just a file which keep information of target file or directory with additional information like icon etc. But very important fact is that Shortcut is a file and not behaves as a directory to navigate to targeting location. Here symbolic link comes into existence in my requirement.

Definition:- In computing, a symbolic link (also symlink or soft link) is a special type of file that contains a reference to another file or directory in the form of an absolute or relative path and that affects path name resolution.

So in my words, Symbolic link is a bridge between two directories (or directory to file) which are linked through a symbolic link file. This symbolic link file provides a door to navigate directly to the targeting location and behaves like an actual directory/sub directory which can be used/referenced in path while saving or accessing file.

Now point is how to create symbolic link, so below are the steps to create symbolic link.

Windows Environment :- In windows environment, symbolic link creation is easy through command prompt.
Step 1 :- Open command prompt with run as administrator option.
Step 2:- Use mklink command to create symbolic link as given below 

MKLINK [[/D] | [/H] | [/J]] Link Target

/D      Creates a directory symbolic link.  Default is a file
symbolic link.
/H      Creates a hard link instead of a symbolic link.
/J      Creates a Directory Junction.
Link    specifies the new symbolic link name.
Target  specifies the path (relative or absolute) that the new link
refers to.

For ex. Suppose we need to create a symbolic link named sftp from the root directory to the \Users\User1\data directory, then type:

mklink /D \sftp \Users\User1\data

This will create a symbolic link “sftp” at root which will navigate user to “\Users\User1\data” directory when opened.

2. Linux environment :- In Linux/Unix based environment “ln” command is used to create link. With “-s” parameter it creates a symbolic/soft link. Below is “ln” command to create a symbolic link.

ln -s [source_dir] [Link_Name]

For ex. Suppose we need to create a soft link named as “sftp” at root which should point to “/var/opt/data”. Then:

ln -s /var/opt/data /sftp  

This will create a soft link “sftp”which will point to “/var/opt/data”

To remove existing symbolic link navigate to the directory where symbolic link exists and then execute below command.

rm [Link Name]

For Ex. If “sftp” symbolic link exist already then we can remove it through below command

rm sftp

Now below are few important points while creating or removing links.
1. Create specific type of link as per need (i.e Soft or Hard)

2. By removing soft link it just removes soft link file and actual linked file or directory is safe.

3. By removing a link which is hard link and created with /h or -h option then it actually represents target file or directory and removing such link may remove actual linked file or directory as well. So be careful with it.

4. If you have created a soft link “sftp”at “/tmp/sftp” then you can use it to create new file or directory at targeting location. For ex. If sftp pointing to “/var/opt/data”then you can try to create a directory at “/tmp/sftp/dev-data”which will create “dev-data” directory at targeting location that means at “/var/opt/data/dev-data”

5. Similarly you can access a file from targeting location using this soft link like “/tmp/sftp/test.html”where “test.html” is placed at linked location (i.e. “/var/opt/data/test.html”)

I hope it will give you some idea about symlink/symbolic link or soft link and about their use and you can start thinking where you can gain an advantage from this.

So keep exploring and share your thoughts and findings.

References

https://kb.iu.edu/d/abbe

Monday 1 December 2014

Basic Git Operations With GIT GUI for Windows User



Recently I started working on a project which is using GIT as its repository for version controlling. Previously I worked with SVN, CVS but not yet got a chance to work with GIT and was really excited to work with it. But later on I came to know that most of the operations done in GIT are done using commands which most of the window users not found very convenient and so I am.

Anyways, I found a window based utility called GIT GUI for basic operation with GIT repository like download contents from GIT repository, Get latest version, commit your changes to repository etc. I faced some problem in using it with available help for basic operation and concluded something to make its use simple. 

So Today, I am sharing steps in very simple way for basic operation with GIT GUI These steps might be really helpful to you guys if you are just starting working with GIT.

To access GIT repository we needs following mandatory things.
1. GIT GUI tool - Click Here to get it now
2. GIT based repository root location
3. Credentials to access GIT repository

Assuming you have already downloaded and installed GIT - GUI on your windows machine. Now we are going to discuss following basic operations.

1. Clone Repository - This operation creates a clone of actual repository (Actual repository resides on remote server) on your local machine. This clone on your local machine will be your working copy. Below are the steps to create clone of a repository.
For Ex - Assume we have GIT repository as below to work with

Step 1 - Right click in a directory where you want to download contents from GIT repository and select Git GUI here from context menu.





Step 2 - Click on Clone Existing Repository link



Step 3 - Enter remote repository location in source 
Enter path of directory in target to create local copy of repository on your machine and click on Clone” button. 



It will download content of repository in specified path on your local machine. Now you are ready to work with content code or anything.  

2. Pull latest changes - Pull operation is used to get latest changes from remote repository to your local repository or you can say that pull command is used to sync your local repository with remote repository. Steps are given below.

Step 1 - Right click directory where you created your local repository using Clone operation and select Git GUI here from context menu. GIT GUI will be open and pointing to your local repository as below. This window has various option to perform various operation with GIT repository but we are just going to cover most basic operations that are needed at beginner level. 



Step 2 - Select Remote --> Fetch from --> origin
This will fetch (pull) all latest changes from remote repository to your local repository from head/root level, that means all latest changes committed in repository will be in your local repository as well now.



Note:- There is also option to pull specif changes as well if you don’t want to refresh complete copy for any reason.

3. Commit Changes to local repository : - Once we have created our local repository and taken latest changes than we are ready to add or modify files in repository. Assuming you have made some changes in main.txt file as available in your local repository. Below are the steps to scan your modified files and commit them in your local repository.

Step 1 - Select your local repository folder and right click and select Git GUI here. This will open GIT GUI utility.



Step 2 - All modified files will appear in left upper box (titled with Unstaged changes”). You can Rescan for modified files if GUI was not already open and not showing your modified files. Tool will show you contents of selected filed in right upper box and displays your modification in content with green (for addition) and red (for deletion).

Step 3 - Select specific file which you want to commit in repository and click on file icon in left of file name from “Unstaged changes” box. This will move your file to lower left box (titled with  “Staged Changes (Will Commit)” )


Step 4 - Enter commit message in right lower box for this specific commit and click on “Commit” button. This will commit your changes to local repository.



Note:- There is option available to add specific line to commit from specific file through selecting file in unstaged box and content will appear in right upper box. Now select specific line and right click, context menu option will appear to stage changes and unstage changes. All staged changes will commit to your local repository.


4. Push changes to remote repository:- Now after commit what else? Here comes the twist in case of GIT repository. As we have created a clone of repository and that is on our local machine only. So this local repository is maintaining version only for our changes to not to lost your changes. But these changes are still not uploaded to remote repository. 
There is Push operation which is used to push your committed changes to remote.   repository. Below are the steps to push changes to remote location. 

Step 1:- Click on “Push” button which will open “Push” window and titled with “Push Branches”


Step 2:- Select master in source branches and enter your remote GIT repository location (As used earlier during cloning of repository) in Arbitrary Location text box. Various options available but not select any check box for now and click on “Push” button. Screen shown above.

Step 3:- Provide the credentials (Username/Password) for repository and click on OK button.



Success screen will appear if your changes successfully pushed to remote repository.



Important points

1. Keep backup of your changes initially for few days until you got confident with the tool.
2. Always get latest changes from remote repository before pushing your changes to it
3. Avoid committing complete branch until you are sure to commit
4. If there is any conflict in file while you taking latest changes resolve them first and commit changes to you local repository and then push your repository changes to remote repository.

Now you are good to go with very basic operations to play with GIT repository. There is lots of other options available in GIT GUI utility that you can explore further.

A good article for further detailed operations with GIT GUI  is here to explore more. Till than keep exploring.

Wednesday 11 June 2014

SFTP upload with .Net Application


Today I was working on a utility which need to upload data on FTP. I have implemented code to upload on FTP using FTP web request. But end of the day when I finally deployed the code, I received the details of SFTP account with host, username, password and port. When I configured these details in utility the utility has failed to upload file on FTP.

Then I started researching reason of failure and found that .Net don’t support secured FTP i. e. SFTP. After searching over net I found that we need to use third party library to upload files on SFTP while using with .Net. There are many third party libraries available for SFTP, two of them are given below that could be used for this purpose.

         1.      Rebex SFTP
         2.      SharpSSH

SharpSSH is open source library and published with BSD License. I have decided to use this one for SFTP functionality implementation.

SharpSSH is a pure .NET implementation of the SSH2 client protocol suite. It provides an API for communication with SSH servers and could be integrated into any .NET application.

I am just going to discuss quick integration of this library to implement SFTP functionality in your application. You can download source code or DLLs for SharpSSH here.

Sharp SSH is actually using some java library and commands to support SFTP which is covered in a wrapper to work with .Net.

You will get following three DLLs in download
          1.      Tamir.SharpSSH.dll
          2.      Org.Mentalis.Security.dll
          3.      DiffieHellman.dll

You need to add reference to Tamir.SharpSSH while two other DLLs should also be referenced or added in bin. Org.Mentalis.Security dll is used for encryption. Now let’s come directly to the small piece of code which is doing SFTP here.

//Include namespace for Tamir.SharpSSH and System.IO as below.
using Tamir.SharpSsh;
using System.IO;

//Collect SFTP account details and root directory to upload file in.
string m_FTPServerAddress = "x.x.x.x"; // this is host IP or host domain name
string m_FTPUser = "username"; // this is username as needed to access SFTP
string m_FTPPassword = "Password"; // this is password as needed to access SFTP
string m_FTPPort = "Port"; //this is port number which is configured in SFTP for communucation.

string m_RemoteFTPFolder = "/RootFolderName/"; // this is root folder name as configured in SFTP.

string filePathAndName = "File path"; //This is cmplete file name with physical path.

//Create object for SFTP class as in Tamir.SharpSSH dll.
Sftp scp = new Sftp(m_FTPServerAddress, m_FTPUser, m_FTPPassword);

//Connect to SFTP using port as provided.
scp.Connect(m_FTPPort.ToIntSafe());

//Put/upload file on SFTP from source location to destination location in SFTP root directory.
scp.Put(filePathAndName, m_RemoteFTPFolder + Path.GetFileName(filePathAndName));

//Close connection from SFTP after uploading.
scp.Close();

Now refer above code and notice three magical lines which are doing actual job here as below.
1.      Following line of code creates an object of a SFTP class as in Tamir.SharpSSH using available ftp server address which is host ip/name, SFTP user name and SFTP password.

Sftp scp = new Sftp(m_FTPServerAddress, m_FTPUser, m_FTPPassword);

2.      Following line connects and creates a communication channel between application and SFTP host using specific post as provided in “m_FTPPort” variable.

scp.Connect(m_FTPPort.ToIntSafe());

3.      Following line of code uploads file from source path to destination path on Sftp root.

//scp.Put(source_file, destination_file);
scp.Put(filePathAndName, m_RemoteFTPFolder + Path.GetFileName(filePathAndName));

4.      Following line of code finally closes connection and communication channel from SFTP host.

scp.Close();

The code as explained above is tested and working properly. While I was trying to implement this code I came with an exception with no information in it. But after researching and trying I come to know that I was giving just file name in destination file as specified in point 3. While root folder of SFTP was needed as prefixed with file name to successfully upload file on SFTP server.

I just mentioned above point so that no one other should stuck in such a small problem.
Now enjoy SFTP upload just like normal FTP upload.