Saturday, 19 August 2017

Angular js2 Set up in dot net

Step 1 : The first step is to install Node.js and npm. It is recommended that you have node version 4.6.x or greater and npm 3.x.x or greater. To check the versions that you have on your machine type the following commands in a command window.
node -v 
npm -v



Step 2 : Make sure you have Visual Studio 2015 Update 3 installed. To check the version of Visual Studio you have click on the "Help" menu and then select "About Microsoft Visual Studio". The following are the download links if you don't have Visual Studio 2015 Update 3.



how to check version of visual studio 

Step 3 : Configure environment settings for node and npm in Visual Studio
  1. In Visual Studio click on Tools - Options.
  2. In the "Options" window, expand "Projects and Solutions" and select "External Web Tools"
  3. In the right pane, move the global $(PATH) entry to be above the internal path $(DevEnvDir) entries. This tells Visual Studio to look for external tools (like npm) in the global path before the internal path.
  4. Click "OK" to close the "Options" window and then restart Visual Stduio for the changes to take effect
visual studio external web tools 

Step 4 :  Install TypeScript for Visual Studio 2015
  1. To develop Angular applications you need TypeScript 2.2.0 or later
  2. To check the version of TypeScript, clik on the "Help" menu in Visual Studio and select "About Microsoft Visual Studio"
    how to check version of typescript
  3. Download and install the latest version of TypeScript for Visual Studio 2015 from the following URLhttps://www.microsoft.com/en-us/download/details.aspx?id=48593
  4. After installing TypeScript, the installation wizard prompts you to restart Visual Studio. So, please restart Visual Studio for the changes to take effect.
Step 5 : Create Empty ASP.NET Web Application project
  1. Run Visual Studio as Administrator
  2. Click on File - New Project
  3. Select "Web" under "Visual C#". From the right pane select "ASP.NET Web Application"
  4. Name the project "Angular2Demo"
  5. On the next screen, select "Empty" template and click "OK"
Step 6 : Download the "Quick Start Files" from the Angular web site using the link below. Extract the contents of the downloaded .ZIP folder.
https://github.com/angular/quickstart

Step 7 : Copy the required "Starter files" to the web application project

We do not need all the starter files that we downloaded. As you can see from the image below, we need 4 folders/files
  • src folder and it's contents
  • bs-config.json
  • package.json
  • tslint.json
angular 2 setup in visual studio 

Copy the above files/folders and paste them in the root directory of "Angular2Demo" web application project. Now click "Show All File" icon in "Solution Explorer" and include all the copied files/folders in the project. At this stage your project structure in Visual Studio should be as shown below. 

visual studio 2015 angular 2 setup 

When including the files in the project if you get a prompt to "Search for Typescript Typings" click "No" 
search for typescript typings 

Step 8 : Restore the required packages. 
In the "Solution Explorer" right click on "package.json" file and select "Restore Packages" from the context menu. This takes a few minutes to load all the modules. You can see the status in "Visual Studio Output" window. After the restoration is complete, you will see a message "Installing Packages Complete". To see all the installed node modules, click on "Show all Files" icon in Solution Explorer. DO NOT include "node_modules" folder in the project.

installing angular 2 in visual studio 

Step 9 : Run the project


  1. In the "RUN" window type "cmd" and press enter
  2. Change the directory in the command prompt to the directory where you have the web application project. I have my web application project in "C:\Angular2Demo\Angular2Demo". So I have typed CD C:\Angular2Demo\Angular2Demo and upon pressing the enter key I am in the root folder.
  3. Type "npm start" and press "Enter" key
    npm start command
  4. This launches the TypeScript compiler (tsc) which compile the application and wait for changes. It also starts the lite-server and launches the browser where you will see the output - Hello Angular.
  5. At this point, open "app.component.ts" file from "Solution Explorer". This file is present in "app" folder in "src" folder.
  6. Change "name" value from "Angular" to "Angular 2!" and you will see the changes reflected on the web page automatically.



At the moment, if we run the application from Visual Studio, using F5 or CTRL+F5, we get the message "Loading AppComponent content here ..." but nothing happens beyond that. To be able to run the application using F5 or CTRL+F5 we need to make the following changes. 



1. Launch browser developers tools by pressing F12. Notice we have "404 Not Found"errors for the following files.
  • styles.css
  • systemjs.config.js
  • main.js
angular 2 loading appcomponent content here 

All these files are present in "src" folder. So to fix these "404 Not Found" errors, in index.html file, change <base href="/"> to <base href="/src/"> 

2. Save the changes and reload the page. At this point we get another set of "404 Not Found" errors for the following files.
  • shim.min.js
  • zone.js
  • system.src.js
angular 2 node_modules 404

<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>

To fix these errors, in index.html change the above script references as shown below. Notice, we have included "/" just before node_modules

<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>

Also in systemjs.config.js file, CHANGE
'npm:''node_modules/'  TO  'npm:''/node_modules/' 

At this point reload the page and you will see "Hello Angular" message without any errors. 

One important point to keep in mind is that, now we will not be able to run the application using "npm start" command. 

We still have one more issue. Let us first understand the issue.
1. Expand "app" folder. This folder is inside "src" folder
2. Open "app.component.ts" file 
3. Set name="Angular 2!" from name="Angular"
4. Save the changes and reload the web page 
5. Notice, we do not see the changes on the web page
6. However, if we run the application by pressing F5 or CTRL+F5 from visual studio we see the changes in the browser.

So what is the issue?
TypeScript is not complied to JavaScript when we save the file and this the reason we do not see the changes in the browser. However, when we run the application by pressing F5 or CTRL+F5 from visual studio TypeScript is compiled to JavaScript and we see the changes.

If you want Visual Studio to compile TypeScript to JavaScript when the changes are saved, we need to turn this feature "ON" by including the following setting in tsconfig.json file. You will find this file in "src" folder. Notice we have set "compileOnSave" to true. With this change tsconfig.json file looks as shown below.
{
 "compileOnSave": true,
  "compilerOptions": {
    "noStrictGenericChecks": true,
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true }
}

At this point TypeScript is automatically compiled to JavaScript when the file is saved, so the changes are reflected in the browser when the page is reloaded.

At the moment, we are using Visual Studio built-in IIS express server. In a later video in this course we will discuss how to use full blown IIS instead of Visual Studi built-in IIS express. 

Sunday, 13 August 2017

CURD operation using REST WCF service and Angularjs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/Gets"
            )]
        List<EMP> Gets();
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        EMP Get(int EID);
        [OperationContract]
        [WebInvoke(Method = "POST",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Save")]
        string Save(EMP emp);
        [OperationContract]
        [WebInvoke(Method = "PUT",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Update")]
        string Update(EMP emp);
        [OperationContract]
        [WebInvoke(Method = "DELETE",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/Delete")]
        string Delete(int EID);


    }
}

    
Implemented


using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    public class Service1 : IService1
    {

        public List<EMP> Gets()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return obj.EMPs.ToList();
            }
        }

        public EMP Get(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return obj.EMPs.SingleOrDefault(m => m.EID == EID);
            }
        }

        public string Save(EMP emp)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                obj.Entry(emp).State = EntityState.Added;
                obj.SaveChanges();
                return "Data Saved.";
            }
        }

        public string Update(EMP emp)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp1 = obj.EMPs.SingleOrDefault(m => m.EID == emp.EID);
                emp1.NAME = emp.NAME;
                obj.Entry(emp1).State = EntityState.Modified;
                obj.SaveChanges();
                return "Data Updated.";
            }
        }

        public string Delete(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp1 = obj.EMPs.SingleOrDefault(m => m.EID == EID);
                obj.Entry(emp1).State = EntityState.Deleted;
                obj.SaveChanges();
                return "Data Deleted.";
            }
        }
    }
}

web.confic

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="SOAP" binding="basicHttpBinding" contract="WcfService1.IService1"></endpoint>
        <endpoint address="REST" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="eb"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="eb">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true" />
  </system.webServer>
  <connectionStrings>
    <add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>



View

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="bootstrap (1)/css/bootstrap.css" rel="stylesheet" />
    <link href="bootstrap (1)/css/bootstrap-theme.css" rel="stylesheet" />
    <script src="angularjs1.6/angular.js"></script>

</head>
<body>
    <div class="container" ng-app="app" ng-controller="Ctrl" style="padding-top:20px">
        <form class="form-horizontal" novalidate name="frmEmp">
            <div class="form-group " ng-class="{'has-error':frmEmp.txtEid.$invalid,'has-success':frmEmp.txtEid.$valid}">
                <label class="control-label col-lg-4">EID</label>
                <div class="col-lg-4">
                    <input type="text" name="txtEid" class="form-control" ng-model="EMP.EID" required />
                    <span class="has-error help-block" ng-show="frmEmp.txtEid.$invalid && frmEmp.txtEid.$touched ">
                        Eid should not be blank.
                    </span>
                </div>
            </div>
            <div class="form-group " ng-class="{'has-error':frmEmp.txtName.$invalid,'has-success':frmEmp.txtName.$valid}">
                <label class="control-label col-lg-4">NAME</label>
                <div class="col-lg-4">
                    <input type="text" name="txtName" class="form-control" ng-model="EMP.NAME" required />
                    <span class="has-error help-block" ng-show="frmEmp.txtName.$invalid && frmEmp.txtName.$touched ">
                        Name should not be blank.
                    </span>
                </div>
            </div>
            <div class="form-group ">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <input type="button" value="Save" style="width:80px" class="btn btn-primary" ng-click="save(frmEmp.$valid)" />
                    <input type="button" value="Update" style="width:80px" class="btn btn-primary" ng-click="update(frmEmp.$valid)" />
                    <input type="button" value="Reset" style="width:80px" class="btn btn-primary" ng-click="reset()" />
                </div>
            </div>
            <div class="form-group ">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <table class="table table-bordered table-condensed table-hover table-responsive">
                        <thead class="bg-primary">
                            <tr>
                                <th>EID</th>
                                <th>NAME</th>
                                <th>ACTION</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="c in list">
                                <td>{{c.EID}}</td>
                                <td>{{c.NAME}}</td>
                                <td>
                                    <a ng-click="edit(c.EID)">Edit</a> |
                                    <a ng-click="del(c.EID)">Delete</a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
</body>
</html>
<script type="text/javascript">
    angular.module("app", [])
    .controller("Ctrl", function ($scope, empService, $cacheFactory) {
        $scope.cacheObject = $cacheFactory("newCacheInstance");
        function CLR()
        {
            $scope.EMP = new emp();
        } CLR();
        function fill()
        {
            empService.gets().then(function (promise) {
                $scope.list = promise.data;
            });
        } fill();
        $scope.save = function (isValid)
        {
            if (isValid)
            {
                empService.save($scope.EMP).then(function (promise) {
                 
                    alert(promise.data);
                    $scope.cacheObject.removeAll();
                    $scope.cacheObject.destroy();
                    CLR();
                    fill();
                });
            }
           
        }
        $scope.update = function (isValid) {
            if (isValid) {
                empService.update($scope.EMP).then(function (promise) {

                    alert(promise.data);
                    $scope.cacheObject.removeAll();
                    $scope.cacheObject.destroy();
                    CLR();
                    fill();
                });
            }

        }
        $scope.edit = function (s)
        {
            empService.get(s).then(function (promise) {
                $scope.EMP = promise.data;
            });
        }
        $scope.del = function (s) {
            if(confirm('Do you want to delte it ?'))
            empService.delete(s).then(function (promise) {
                alert(promise.data);
                fill();
            });
        }
        $scope.reset = function ()
        {
            $scope.EMP = new emp();
        }
    })
    .service("empService", function ($http) {
        this.save = function (EMP)
        {
       
            return $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Save',
                data: EMP,
                cache: false
            });
        }
        this.update = function (EMP) {

            return $http({
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Update',
                data: EMP,
                cache: false
            });
        }
        this.gets = function ()
        {
            return $http({
                method: 'Get',
                cache: false,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Gets'
            });
        }
       this.get = function (eid) {
            return $http({
                method: 'Get',
                cache: false,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                url: 'http://localhost:49612/Service1.svc/REST/Get?EID='+eid
            });
       }
       this.delete = function (eid) {
       
           return $http({
               method: 'DELETE',
               cache: false,
               headers: {
                   'Content-Type': 'application/json; charset=utf-8'
               },
               data:eid,
               url: 'http://localhost:49612/Service1.svc/REST/Delete'
           });
       }

    });
    function emp()
    {
        return {
            EID: null,
            NAME:null
        }
    }
</script>

Monday, 7 August 2017

Custom Model binding in MVC

Add a Class.

using CustomModelBinding.Models;

namespace CustomModelBinding.Common
{
    public class CustomModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            return new EMP { EID=Convert.ToInt32(controllerContext.HttpContext.Request.Form["EID"]),FIRSTNAME= controllerContext.HttpContext.Request.Form["FNAME"] ,LASTNAME= controllerContext.HttpContext.Request.Form["LNAME"],FULLNAME= controllerContext.HttpContext.Request.Form["FNAME"]+" "+ controllerContext.HttpContext.Request.Form["LNAME"] };
        }
    }
}

Register in global.asax.cs

using CustomModelBinding.Models;

namespace CustomModelBinding
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders[typeof(EMP)] = new Common.CustomModelBinder();
        }
    }
}

Thursday, 3 August 2017

Excell manupulation in dot net

CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Office.Interop.Excel;
using System.IO;

namespace  ABC.Controllers
{
    public class HomeController : Controller
    {
       
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Fetchexcelfile()
        {
            try
            {
                var file = Request.Files[0];
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/ExcelFileFolder/"), fileName);
                if (!System.IO.File.Exists(path))
                {
                    file.SaveAs(path);
                }
                int index = 0, Tr = 0, Pv = 0, Fopv = 0;
                string cvalue = string.Empty;
                Range objRange = null;
                Application app = new Application();
                Workbook WB = app.Workbooks.Open(path);
                List<string> listMT = new List<string>();
                foreach (Worksheet obj in WB.Worksheets)
                {
                    if (obj.Name.Substring(0, 2) == "MT")
                    {
                        for (index = 1; index < obj.Columns.Count; index++)
                        {
                            objRange = obj.Cells[1, index];
                            cvalue = objRange.Text;
                            string[] tvalue = cvalue.Split('\n');
                            cvalue = tvalue[0].Trim() + " " + tvalue[1].Trim();
                            if (cvalue.Trim() == "T R".Trim())
                                Tr = index;
                            if (cvalue.Trim() == "P V".Trim())
                                Pv = index;
                            if (cvalue.Trim() == "F O P V".Trim())
                            {
                                Fopv = index;
                                break;
                            }
                        }
                        listMT.Add("T r : " + ((Range)obj.Cells[3, Tr]).Text + "  Iv : " + ((Range)obj.Cells[3, Pv]).Text + "  O v : " + ((Range)obj.Cells[3, Fopv]).Text);
                    }
                }
                return Json(listMT, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }


        }

       
    }

}

View

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="@Url.Content("~/Content/sd-common-style.css")" rel="stylesheet">
<div class="well" style="height:600px">
    <div class="container">`
        <p class="section_title">Convert Excell to XML</p>
        <form class="form-horizontal" enctype="multipart/form-data">
            <fieldset>
                <legend></legend>
                <div class="form-group">
                    <label class="col-sm-3 abc">Excel File Upload</label>
                    <div class="col-sm-5">
                        <input type="file" id="Upload" value="Upload" class="form-control"/>
                        <span id="errorMessage" style="color:#a94442"></span>
                    </div>
                    <div class="col-sm-4">
                        <input type="button" id="btnUpload" value="Upload" class="sd-btn sd-btn-default disabled" />
                    </div>
                </div>
            </fieldset>
            <fieldset class="fields">
                <legend></legend>
                <div class="form-group">
                    <label class="col-sm-3 abc">Product</label>
                    <div class="col-sm-9">
                        <span class="cbGroup"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3"></label>
                    <div class="col-sm-9">
                        <input type="button" id="btnUpload" value="Convert Into XML" class="sd-btn sd-btn-default disabled" />
                    </div>
                </div>
            </fieldset>
        </form>
    </div>
</div>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $(function () {

        $('#Upload').change(function () {
            if ($('#Upload').val() == "") {
                $('#errorMessage').text('Please select a file');
                return false;
            }
            else {
                $('#errorMessage').text('');
            }
        }); $('.fields').hide();
        $('#btnUpload').click(function () {
            if ($('#Upload').val() == "") {
                $('#errorMessage').text('Please select a file');
                return false;
            }
            else {
                $('#errorMessage').text('');
            }
            var formData = new FormData();
            var file = document.getElementById("Upload").files[0];
            formData.append("rcexcel", file);
            $('.cbGroup').empty();
            $('.fields').hide();
            $.ajax({
                type: "POST",
                url: '/EXCELLTOXML/Fetchexcelfile',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (data) {
                    $('.fields').show();
                    $.each(data, function (i, j) {
                        $('.cbGroup').append("<input type='checkbox' class=\"checkbox\"/>  " + j + "<br>");
                        $('.cbGroup').addClass("checkbox");
                    });
                 
                },
                error: function (error) {
                    alert("errror");
                }
            });
        });
    });
</script>