Tuesday 28 February 2017

AssetTracking 5, client side: jquery 2 listbox exchange items, Ajax send obj to controller. server sdie: async controller action



click assign asset menu, list unassigned employee, assets

select multiple asset, click unassigned asset, goes to selected asset, vice-versa

assets can be filtered, if employee or asset is not selected, alert, otherwise assign

employee with id SM1003 is assigned multiple assets

//asset controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using BLL;
using Data;
using Microsoft.AspNetCore.Mvc.Rendering;
using BLL.DTOs;
using System.Net.Http;
using System.Net.Http.Headers;

namespace AssetTracking.Controllers
{
    public class AssetController : Controller
    {
        asset_manager Manager;
        List<employee_dto> employees_from_HR;

        public AssetController(AssetContext context)
        {
            Manager = new asset_manager(context);        
        }    

        // GET: Asset
        public ActionResult Index()
        {
            var asset_types_list = Manager.get_asset_types();

            ViewBag.asset_types_viewbag = new SelectList(asset_types_list.OrderBy(x=>x.Name), "Id", "Name");

            var assets = Manager.get_all();

            return View(assets);
        }

        public async Task<IActionResult> Assign()
        {
         
            await Load_employees_from_HR();
            var employee_without_asset = Manager.find_employees_without_asset(employees_from_HR);

            var asset_types_list = Manager.get_asset_types();
            ViewBag.asset_types_viewbag = new SelectList(asset_types_list.OrderBy(x => x.Name), "Id", "Name");

            var unassigned_asset = Manager.get_unassigned_assets();
            ViewBag.unassigned_asset =unassigned_asset.OrderBy(x => x.name);
                     

            return View(employee_without_asset);
        }

        public async Task<IActionResult> Load_employees_from_HR()
        {
            employees_from_HR = new List<employee_dto>();
            //make call to web api
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:11111/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.
                    Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync("api/values");
                if (response.IsSuccessStatusCode)
                {
                    employees_from_HR = await response.Content.ReadAsAsync<List<employee_dto>>();
                }
            }

            return Content("employees are loaded from HR");
        }

        [HttpPost]
        public ActionResult update_assignment(List<asset_assign_class> assignment)
        {
            Manager.assign_asset(assignment);

            //redirect to Index is handled by Ajax on success event in Assign View 
            return Content("assignment success");
        }
}

---------------------------------------------------------------------------------------------------

//manager

using Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BLL.DTOs;
using System.Net.Http;
using System.Net.Http.Headers;

namespace BLL
{

    public class asset_manager
    {
        AssetContext DB;

        public asset_manager(AssetContext context)
        {
            DB = context;
        }

        public IList<asset_dto> get_all()
        {
            return DB.Assets.Select(x => new asset_dto
            {

                Id = x.Id,
                AssignedTo = x.AssignedTo,
                Description = x.Description,
                SerialNumber = x.SerialNumber,
                TagNumber = x.TagNumber,

                AssetTypeId = x.AssetTypeId.HasValue ? (int)x.AssetTypeId : 0,
                ManufacturerId = x.ManufacturerId.HasValue ? (int)x.ManufacturerId : 0,
                ModelId = x.ModelId.HasValue ? (int)x.ModelId : 0,

                AssetType = x.AssetTypeId.HasValue ? DB.AssetType.FirstOrDefault(y => y.Id == x.AssetTypeId).Name : "",
                Model = x.ModelId.HasValue ? DB.Models.FirstOrDefault(y => y.Id == x.ModelId).Name : "",

                //try to find manufacture from DB.Asset, if not found, try DB.Models, not found ""
                Manufacturer = x.ManufacturerId.HasValue ? DB.Manufacturers.FirstOrDefault(y => y.Id == x.ManufacturerId).Name :
                (x.ModelId.HasValue ? DB.Manufacturers.FirstOrDefault(M => M.Id ==
                DB.Models.FirstOrDefault(z => z.Id == x.ModelId).ManufacturerId).Name : "")

            }).ToList();
        }    

        public IList<asset_short_dto> get_unassigned_assets()
        {
            return DB.Assets.Where(y=>y.AssignedTo==""||y.AssignedTo==null).
                Select(x => new asset_short_dto{
                    Id = x.Id,
                    name = x.ModelId.HasValue ? DB.Models.FirstOrDefault(z => z.Id == x.ModelId).Name : "",
                    type_id = x.AssetTypeId.HasValue ? (int)x.AssetTypeId : 0
                }).ToList();

        }

        public IList<asset_type_dto> get_asset_types()
        {
            var asset_types =  DB.AssetType.Select(x=> new asset_type_dto
            {
                Id=x.Id,
                Name=x.Name

            }).ToList();

            asset_types.Add(new asset_type_dto { Id = 0, Name = "" });

            return asset_types;
        }

        public void assign_asset(List<asset_assign_class> assignment)
        {
            foreach(var item in assignment)
            {
                DB.Assets.FirstOrDefault(x => x.Id == item.id).AssignedTo = item.employee_id;
                DB.SaveChanges();
            }
        }

        public IList<employee_dto> find_employees_without_asset(List<employee_dto> employees)
        {
            foreach(var item in DB.Assets)
            {
                if(item.AssignedTo!="")
                {
                    var employee_with_asset = employees.FirstOrDefault(x => x.Id == item.AssignedTo);

                    if (employee_with_asset != null)
                    {
                        employees.Remove(employee_with_asset);
                    }
                }
            }

            return employees;
        }
    }
}

--------------------------------------------------------------------------

//View

@model IEnumerable<BLL.DTOs.employee_dto>

<h2>Asset Assignment</h2>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">

    var employee_list = [];
    var unassigned_asset_list = []
    var selected_asset_list = []
    var assignment_list = []

    $(document).ready(function () {

        //populate unassigned employee listbox
        @foreach (var item in Model)
        {
            <text>
        employee_list.push(new employee_class('@item.Id', '@item.name'));
        </text>
        }

        populate_employee();

        //populate unassigned assets listbox
        @foreach (var item in ViewBag.unassigned_asset)
        {
            <text>
        unassigned_asset_list.push(new asset_class('@item.Id', '@item.name', '@item.type_id'));
        </text>
        }

        populate_asset();
    });

    function employee_class(id, name) {
        this.id = id;
        this.name = name;
    }

    function asset_class(id, name, type) {
        this.id = id;
        this.name = name;
        this.type = type;
    }

    function assignment_class(id, employee_id) {

        this.id = id;
        this.employee_id = employee_id;
    }

    //delete element from array
    function array_delete(array, element_id) {

        //find index of the element going to be deleted in the arry
        indexes = $.map(array, function (obj, index) {

            if (element_id == obj.id) {

                return index;
            }
        })

        //return deleted element as asset class
        deleted_item = array.splice(indexes[0], 1);

        return new asset_class(deleted_item[0].id, deleted_item[0].name, deleted_item[0].type);
    }

    function populate_employee() {

        $.each(employee_list, function (index, value) {
            $('#ux_employee_unassigned').append('<option value=' + value.id + '>' + value.name + '</option>');
        });
    }

    //populate unassigned asset listbox
    function populate_asset() {

        $.each(unassigned_asset_list, function (index, value) {
            $('#ux_unassigned_asset').append('<option value=' + value.id + '>' + value.name + '</option>');
        });
    }

    //populate unassigned asset listbox based on type
    function populate_asset_baseon_type(_type) {

        $.each(unassigned_asset_list, function (index, value) {

            if (value.type == _type) {
                $('#ux_unassigned_asset').append('<option value=' + value.id + '>' + value.name + '</option>');
            }
        })
    }

    //populate selected asset listbox
    function populate_asset_selected() {      

        $.each(selected_asset_list, function (index, value) {
            $('#ux_selected_asset_listbox').append('<option value=' + value.id + '>' + value.name + '</option>');
        });
    }

    //populate selected asset listbox based on type
    function populate_asset_selected_basedon_type(_type) {

        $.each(selected_asset_list, function (index, value) {

            if (value.type == _type) {
                $('#ux_selected_asset_listbox').append('<option value=' + value.id + '>' + value.name + '</option>');
            }
        });
    }

    //asset type dropdownlist change event
    function asset_types_onchange() {

        $('#ux_unassigned_asset').empty();
        $('#ux_selected_asset_listbox').empty();

        //if selected type = "", populate with all assets
        if ($('#asset_types_viewbag :selected').text() == "") {
            populate_asset();
            populate_asset_selected();
        }
            //populate unassigned assets listbox based on asset type
        else {
            populate_asset_baseon_type($('#asset_types_viewbag').val());
            populate_asset_selected_basedon_type($('#asset_types_viewbag').val());
        }
    }

    //unassigned asset listbox onselect event, move asset to selected listbox
    function unassigned_asset_listbox_onchange() {

        //delete selected item from uassigned_asset_listbox
        deleted_element = array_delete(unassigned_asset_list, $("#ux_unassigned_asset").val());

        //add selected item to selected_asset_listbox
        selected_asset_list.push(deleted_element);

        //sort selectd asset list
        selected_asset_list.sort(function (a, b) {

            var aName = a.name.toLowerCase();
            var bName = b.name.toLowerCase();
            return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

        //repopulate unassigned_asset_listbox
        asset_types_onchange();        
    }


    //selected asset listbox onselect event, return asset to unassigned listbox
    function selected_asset_listbox_onchange() {

        //delete selected item from selected asset listbox
        deleted_element = array_delete(selected_asset_list, $("#ux_selected_asset_listbox").val());

        //add selected item to unassigned asset listbox
        unassigned_asset_list.push(deleted_element);

        //sort unassigned asset list
        unassigned_asset_list.sort(function (a, b) {

            var aName = a.name.toLowerCase();
            var bName = b.name.toLowerCase();
            return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

        //repopulate unassigned_asset_listbox and selected_asset_listbox
        asset_types_onchange();
    }

    //confirm button click event
    function button_confirm() {

        if ($('#ux_employee_unassigned').val() == undefined) { alert("please select employee"); return }

        if (selected_asset_list.length == 0) { alert("please select asset"); return}

        //create asset assignment to selected employee
        $.each(selected_asset_list, function (index, value) {

            assignment_list.push(new assignment_class(value.id, $('#ux_employee_unassigned').val()));
        })

        //send assignment to controller
        $.ajax({
            type: "POST",
            url: '/Asset/update_assignment',
            data: { "assignment": assignment_list },
            success: function (result) {
                //alert("success");
                window.location.replace("/Asset/Index");
            },
            error: function (xhr) {
                alert("Error button confirm Assign view");
            }
        });
    };
</script>

<div>
    <div class="col-md-3">

        <center>@Html.Label("select unassigned employee")</center>
        <select size="20" id="ux_employee_unassigned" class="form-control"></select>
    </div>

    <div class="col-md-6">

        <center> @Html.Label("select asset type")</center>
        <center> @Html.DropDownList("asset_types_viewbag", null, htmlAttributes: new { @class = "form-control", onchange = "asset_types_onchange()" })</center> 
        <br />

        <div class="row">
            <div class="col-md-6">

                <center>  @Html.Label("select unassigned asset")</center>
                <select size="15" id="ux_unassigned_asset" class="form-control" onchange="unassigned_asset_listbox_onchange()"></select>
            </div>

            <div class="col-md-6">

                <center> @Html.Label("return selected asset")</center>

                <select size="15" id="ux_selected_asset_listbox" class="form-control" onchange="selected_asset_listbox_onchange()"></select>
            </div>
        </div>
  
    </div>

    <div class="col-md-3">
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <center> <button onclick="button_confirm()" type="button" class="btn btn-success">Assign selected assets<br />to selected employee</button></center>
        <br />
        <br />
        <br />
        <br />
        <center> <button onclick="button_cancel()" type="button" class="btn btn-danger">Cancel assignment</button></center>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
       
    </div>
    
</div>

---------------------------------------------------------------------

//asset_assign_class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BLL.DTOs
{
    public class asset_assign_class
    {
        public int id { get; set; }
        public string employee_id { get; set; }
    }
}


reference:
http://stackoverflow.com/questions/12944329/add-onclick-function-to-a-submit-button
http://stackoverflow.com/questions/8893111/how-do-i-disable-input-element-whose-type-is-submit
https://www.w3schools.com/tags/att_input_required.asp
http://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button
http://stackoverflow.com/questions/2950152/iterate-through-select-options
https://www.w3schools.com/jsref/prop_option_disabled.asp
http://stackoverflow.com/questions/40422727/disable-drop-down-options-based-on-selected-value-with-jquery
http://stackoverflow.com/questions/1263852/prevent-form-redirect-or-refresh-on-submit
http://stackoverflow.com/questions/12944329/add-onclick-function-to-a-submit-button
http://stackoverflow.com/questions/23071795/how-to-add-required-attribute-to-mvc-5-razor-view-text-input-editor

Saturday 25 February 2017

AssetTracking 4 .aspcore web application consume webapi Cross-origin resource sharing




//~/assettracking/controllers/assetcontroller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using BLL;
using Data;
using Microsoft.AspNetCore.Mvc.Rendering;
using BLL.DTOs;
using System.Net.Http;
using System.Net.Http.Headers;

namespace AssetTracking.Controllers
{
    public class AssetController : Controller
    {
        asset_manager Manager;

        public AssetController(AssetContext context)
        {
            Manager = new asset_manager(context);    
        }

        // GET: Asset
        public ActionResult Index()
        {
            var asset_types_list = Manager.get_asset_types();

            ViewBag.asset_types_viewbag = new SelectList(asset_types_list.OrderBy(x=>x.Name), "Id", "Name");

            var assets = Manager.get_all();

            return View(assets);
        }

        public async Task<IActionResult> Assign()
        {
            var retValue = new List<employee_dto>();
            //make call to web api 
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:11111/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.
                    Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync("api/values");
                if (response.IsSuccessStatusCode)
                {
                    retValue = await response.Content.ReadAsAsync<List<employee_dto>>();
                }
            }

            return View(retValue);
        }
    }
}

-------------------------------------------------------------

//~/HRService/controllers/valuescontroller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using HRService.Models;
using Microsoft.AspNetCore.Cors;

namespace HRService.Controllers
{
    //[Authorize]
    [EnableCors("AllowAllOrigin")]
    [Route("api/[controller]")]  
    public class ValuesController : Controller
    {
        HRContext DB;

        public ValuesController(HRContext context)
        {
            DB = context;
        }
 
        [HttpGet]
        public JsonResult get_all()
        {

            var employees = DB.Employee.Select(x => new employee_dto
            { Id = x.EmployeeNumber, name = x.FirstName + " " + x.LastName }).ToList();

            return Json( employees);

        }
    }
}

------------------------------------------------------------------

~/assettracking/projectjson

"Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Domain": "1.0.0-*",
    "BLL": "1.0.0-*",
    "Microsoft.AspNet.WebApi.Client": "5.2.3",
    "System.Net.Http": "4.3.0",
    "System.Runtime.Serialization.Xml": "4.3.0"
  },

-----------------------------------------------------------------

~/assettracking/views/assign

@model IEnumerable<BLL.DTOs.employee_dto>

<div id="employee_table">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Id)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.name)
                    </th>

                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Id)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.name)
                        </td>

                    </tr>
                }
            </tbody>
        </table>
    </div>

---------------------------------------------------------

~/bll/dto/employee.dto

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BLL.DTOs
{
    public class employee_dto
    {
        public string Id { get; set; }
        public string name { get; set; }
    }
}

----------------------------------------------------------


reference:

http://stackoverflow.com/questions/9619776/how-to-create-a-listbox-in-html-without-allowing-multiple-selection
http://stackoverflow.com/questions/3854120/add-item-to-a-listbox-using-jquery
http://html.com/attributes/select-multiple/
http://stackoverflow.com/questions/18150954/how-can-i-render-a-list-select-box-dropdown-with-bootstrap
http://stackoverflow.com/questions/26845994/databinding-system-web-mvc-selectlistitem-does-not-contain-a-property-with-th
https://www.williamghelfi.com/blog/2013/06/09/bootstrap-3-the-new-grid-system-for-starters/
https://www.w3schools.com/tags/tag_center.asp
https://www.w3schools.com/bootstrap/bootstrap_buttons.asp
https://www.w3schools.com/jsref/event_onclick.asp
https://www.w3schools.com/jsref/event_onselect.asp
http://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
http://stackoverflow.com/questions/15997879/get-the-index-of-the-object-inside-an-array-matching-a-condition
https://www.w3schools.com/jsref/jsref_splice.asp
http://stackoverflow.com/questions/10024866/remove-object-from-array-using-javascript
http://stackoverflow.com/questions/5503900/how-to-sort-an-array-of-objects-with-jquery-or-javascript
http://stackoverflow.com/questions/7469088/html-can-i-display-button-text-in-multiple-lines
http://stackoverflow.com/questions/21578814/how-to-receive-json-as-an-mvc-5-action-method-parameter
http://stackoverflow.com/questions/22569877/how-to-redirect-to-another-action-in-an-action
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

Friday 24 February 2017

How do I report the amounts from my T5008 slip?

Boxes 20 & 21: You’ll need to include both the proceeds (box 21) and your adjusted cost base (ACB) (box 20), even if box 20 is blank. Many T5008 issuers report only the proceeds because they don’t know your ACB. It’s your responsibility to track your ACB and enter the correct amount in box 20. If you aren’t sure, contact your advisor or broker.

https://help.simpletax.ca/questions/t5008-slip

Wednesday 22 February 2017

AssetTracking 3 .aspcore navbar




//~/AssetTracking/wwwroot/css/site.css

/*navbar background color*/ 
.navbar-custom {
    background-color:#229922;
    color:#ffffff;
    border-radius:0;
}

/*navbar menu text color*/
.navbar-custom .navbar-nav > li > a {
    color:#ffff00;
}

/*navbar menu button color when mouse hover on it*/
.navbar-custom .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    background-color: #ffff00;
    color: #ff3300;
}

/*navbar logo text color*/
.navbar-custom .navbar-brand {
    color:#ffff00;
}

-------------------------------------------------------------------

//~/AssetTracking/Views/Shared/_laout.cshtml

<div class="navbar navbar-custom navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <a asp-area="" asp-controller="Asset" asp-action="Index"><img src="~/images/logo.png" /></a>
             
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Asset" asp-action="Index">Display Asset</a></li>
                    <li><a asp-area="" asp-controller="Asset" asp-action="Assign">Assign Asset</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                @*@await Html.PartialAsync("_LoginPartial")*@
            </div>
        </div>
    </div>

reference:
http://www.tutorialsteacher.com/mvc/layout-view-in-asp.net-mvc
http://stackoverflow.com/questions/18529274/change-navbar-color-in-twitter-bootstrap-3
http://stackoverflow.com/questions/16625972/change-color-of-bootstrap-navbar-on-hover-link

Monday 20 February 2017

AssetTracking 2 .aspcore web application dropdownlist filter





@model IEnumerable<BLL.DTOs.asset_dto>

<h2><label id="title_label">All Asset</label></h2>

<script type="text/javascript">
    function filter() {

        $('#asset_table tbody').empty();

        var asset_list = [];

        @foreach (var item in Model)
        {
         <text>
        if ($('#asset_types_viewbag').val() == @item.AssetTypeId)
        {
            asset_list.push(new asset_class('@item.Id', '@item.Model', '@item.Manufacturer', '@item.AssetType'));
    }
    </text>

        }
 

    $.each(asset_list, function (key, value) {
        $('#asset_table').append('<tr>\
              <td>' + value.id + '</td>\
              <td>' + value.model + '</td>\
              <td>' + value.manfacture + '</td>\
              <td>' + value.asset_type + '</td></tr>');
    });

    }

    function asset_class(id, model, manufacture, asset_type) {
        this.id = id;
        this.model = model;
        this.manfacture = manufacture;
        this.asset_type = asset_type;
    }
</script>

<div class="col-md-2">

    @Html.DropDownList("asset_types_viewbag", null, htmlAttributes: new { @class = "form-control", onchange = "filter()" })
</div>

<div class="col-md-10">

    <table id="asset_table" class="table table-striped">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Model)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Manufacturer)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.AssetType)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.AssignedTo)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Description)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.TagNumber)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.SerialNumber)
                </th>
            </tr>
        </thead>

        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Model)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Manufacturer)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.AssetType)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.AssignedTo)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Description)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.TagNumber)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.SerialNumber)
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>


reference:

https://www.w3schools.com/jsref/met_table_insertrow.asp
http://stackoverflow.com/questions/2620181/clear-table-jquery
http://stackoverflow.com/questions/171027/add-table-row-in-jquery
https://forums.asp.net/t/1758990.aspx?How+to+get+access+to+a+list+of+Models+in+jQuery+
http://stackoverflow.com/questions/21808054/appending-jquery-selector-variable-into-a-table
http://stackoverflow.com/questions/2729323/javascript-pushing-object-into-array
https://davidwalsh.name/multiline-javascript-strings
http://stackoverflow.com/questions/23612268/how-to-select-a-drop-down-value-using-jquery
http://stackoverflow.com/questions/4029281/get-drop-down-value
http://stackoverflow.com/questions/3584145/how-to-change-the-text-of-a-label-in-jquery

Zamfir Greatest Hits



https://www.youtube.com/watch?v=1mHuf8owjoQ
https://www.youtube.com/watch?v=zV-GXhY7nf0
https://www.youtube.com/watch?v=JilFZLaksnE
https://www.youtube.com/watch?v=aayAA-bK9HM

Sunday 19 February 2017

AssetTracking 1 .asp core web application setup

//package manager console

PM> Add-Migration initial -Context AssetContext
PM> update-database -Context AssetContext

-------------------------------------------------------------
//~AssetTracking/appsetting.josn

{
  "ConnectionStrings": {
    "AssetConnection": "server=localhost;database=AssetTracking;Integrated Security=True;",
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-AssetTracking-62da8af5-da00-4796-b32b-b56cd08d19d9;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }

}

--------------------------------------------------------------------
//~/AssetTracking/Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            var cs = Configuration.GetConnectionString("AssetConnection");
            services.AddDbContext<AssetContext>(options =>
                       options.UseSqlServer(cs));

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

------------------------------------------------------------------
//~/Data/AssetContext.cs

using Domain;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Data
{
    public class AssetContext:DbContext
    {
        public AssetContext(DbContextOptions<AssetContext> options) : base(options){ }

        public DbSet<Asset> Assets { get; set; }
        public DbSet<AssetType> AssetType { get; set; }
        public DbSet<Manufacturer> Manufacturers { get; set; }
        public DbSet<Model> Models { get; set; }
    }
}

----------------------------------------------------------
//~/Domain/Asset.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain
{
    public class Asset
    {
        public int Id { get; set; }
        public string TagNumber { get; set; }
        public Nullable<int> AssetTypeId { get; set; }
        public Nullable<int> ManufacturerId { get; set; }
        public Nullable<int> ModelId { get; set; }
        public string Description { get; set; }
        public string AssignedTo { get; set; }
        public string SerialNumber { get; set; }

        public virtual AssetType AssetType { get; set; }
        public virtual Manufacturer Manufacturer { get; set; }
        public virtual Model Model { get; set; }
       
    }
}

--------------------------------------------------------------
//~/Domain/Model.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain
{
    public class Model
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> ManufacturerId { get; set; }

        public virtual ICollection<Asset> Assets { get; set; }
        public virtual Manufacturer Manufacturer { get; set; }
    }
}

-----------------------------------------------------------------
//~/Domain/AssetType.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain
{
    public class AssetType
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Asset> Assets { get; set; }
    }
}

----------------------------------------------------
//~/Domain/Manufacturer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain
{
    public class Manufacturer
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Asset> Assets { get; set; }
        public virtual ICollection<Model> Models { get; set; }
    }
}


reference:
http://stackoverflow.com/questions/38162227/asp-net-core-ef-add-migration-command-not-working
http://stackoverflow.com/questions/17127351/introducing-foreign-key-constraint-may-cause-cycles-or-multiple-cascade-paths
http://stackoverflow.com/questions/1030041/if-statement-inside-a-linq-select
http://stackoverflow.com/questions/6062192/there-is-already-an-open-datareader-associated-with-this-command-which-must-be-c

Sunday 12 February 2017

MVC core sql javascript database first


Scaffolding generated form


Javascript modified form








//install NuGet package

a.       Microsoft.EntityFrameworkCore.SqlServer
b.      Microsoft.EntityFrameworkCore.SqlServer.Design

c.       Microsoft.EntityFrameworkCore.Tools

---------------------------------------------------------------------

//enter command in package manage console

scaffold-dbcontext “server=localhost;database=manymany;Integrated Security=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

------------------------------------------------------------------

//manymanyContext.cs is generated in Models folder

//replace onConfigure method with

 public ClassName(DbContextOptions<ClassName> options) : base(options){   }

-------------------------------------------------------------

//in startup.cs add code

var cs = Configuration.GetConnectionString(“NameOfConnectionString”);
services.AddDbContext<ContextName>(options => options.UseSqlServer(cs));

-------------------------------------------------------------------

//in appsettings.json add connectionstring

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-core_web1-1e7da360-f6fc-44b9-ad72-95113ff21505;Trusted_Connection=True;MultipleActiveResultSets=true",
    "manymanyConnection": "server=localhost;database=manymany;Integrated Security=True;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

---------------------------------------------------

//CustomersController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using core_web1.Models;

namespace core_web1.Controllers
{
    public class CustomersController : Controller
    {
        private readonly manymanyContext _context;

        public CustomersController(manymanyContext context)
        {
            _context = context;  
        }

        // GET: Customers
        public async Task<IActionResult> Index()
        {
            var manymanyContext = _context.Customer.Include(c => c.Order);
            return View(await manymanyContext.ToListAsync());
        }

        [HttpGet]
        public JsonResult find_order_name(int id)
        {
            var order_name = _context.Order.FirstOrDefault(x => x.Id == id).OrderName;

            return Json(order_name);
        }

        // GET: Customers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customer.SingleOrDefaultAsync(m => m.Id == id);
            if (customer == null)
            {
                return NotFound();
            }

            return View(customer);
        }

        // GET: Customers/Create
        public IActionResult Create()
        {
            ViewData["OrderId"] = new SelectList(_context.Order, "Id", "Id");
            return View();
        }

        // POST: Customers/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,OrderId")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                _context.Add(customer);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            ViewData["OrderId"] = new SelectList(_context.Order, "Id", "Id", customer.OrderId);
            return View(customer);
        }

        // GET: Customers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customer.SingleOrDefaultAsync(m => m.Id == id);
            if (customer == null)
            {
                return NotFound();
            }
            ViewData["OrderId"] = new SelectList(_context.Order, "Id", "Id", customer.OrderId);
            return View(customer);
        }

        // POST: Customers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,OrderId")] Customer customer)
        {
            if (id != customer.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(customer);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CustomerExists(customer.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            ViewData["OrderId"] = new SelectList(_context.Order, "Id", "Id", customer.OrderId);
            return View(customer);
        }

        // GET: Customers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customer.SingleOrDefaultAsync(m => m.Id == id);
            if (customer == null)
            {
                return NotFound();
            }

            return View(customer);
        }

        // POST: Customers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var customer = await _context.Customer.SingleOrDefaultAsync(m => m.Id == id);
            _context.Customer.Remove(customer);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool CustomerExists(int id)
        {
            return _context.Customer.Any(e => e.Id == id);
        }
    }
}

------------------------------------------------------------------

//~/Views/Customers/index.cshtml

@model IEnumerable<core_web1.Models.Customer>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayName("Order")
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>

                    <label id="order_label(@item.OrderId)">abc</label>

                    <script src="~/lib/jquery/dist/jquery.min.js"></script>
                    <script type="text/javascript">

                        get_order_name( @item.OrderId)

                        function get_order_name(order_id) {

                            $.ajax({
                                url: '/Customers/find_order_name',
                                type: 'GET',
                                dataType: 'json',
                                data: { "id": order_id },
                                success: function (result) {

                                    document.getElementById("order_label(@item.OrderId)").innerHTML = result;;
                                },
                                error: function () {
                                    alert("Error");
                                }
                            });
                        }

                    </script>
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

-----------------------------------------------------------

//manymanyContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace core_web1.Models
{
    public partial class manymanyContext : DbContext
    {
        public virtual DbSet<Customer> Customer { get; set; }
        public virtual DbSet<Order> Order { get; set; }

        public manymanyContext(DbContextOptions<manymanyContext> options) : base(options){ }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>(entity =>
            {
                entity.ToTable("customer");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.Name)
                    .HasColumnName("name")
                    .HasColumnType("nchar(10)");

                entity.Property(e => e.OrderId).HasColumnName("order_id");

                entity.HasOne(d => d.Order)
                    .WithMany(p => p.Customer)
                    .HasForeignKey(d => d.OrderId)
                    .HasConstraintName("r2");
            });

            modelBuilder.Entity<Order>(entity =>
            {
                entity.ToTable("order");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.CustomerId).HasColumnName("customer_id");

                entity.Property(e => e.OrderName)
                    .HasColumnName("order_name")
                    .HasColumnType("nchar(10)");

                entity.HasOne(d => d.CustomerNavigation)
                    .WithMany(p => p.OrderNavigation)
                    .HasForeignKey(d => d.CustomerId)
                    .HasConstraintName("r1");
            });
        }
    }
}

---------------------------------------------------------

//~/Models/customer.cs

using System;
using System.Collections.Generic;

namespace core_web1.Models
{
    public partial class Customer
    {
        public Customer()
        {
            OrderNavigation = new HashSet<Order>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public int? OrderId { get; set; }

        public virtual ICollection<Order> OrderNavigation { get; set; }
        public virtual Order Order { get; set; }
    }
}

-------------------------------------------------------

//~/Models/Orders.cs

using System;
using System.Collections.Generic;

namespace core_web1.Models
{
    public partial class Customer
    {
        public Customer()
        {
            OrderNavigation = new HashSet<Order>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public int? OrderId { get; set; }

        public virtual ICollection<Order> OrderNavigation { get; set; }
        public virtual Order Order { get; set; }
    }
}


reference:

http://stackoverflow.com/questions/16303085/how-to-call-java-script-function-from-mvc-view
https://msdn.microsoft.com/en-us/magazine/mt767699.aspx
https://www.exceptionnotfound.net/using-async-and-await-in-asp-net-what-do-these-keywords-mean/
http://stackoverflow.com/questions/13198136/how-to-get-data-from-asp-net-mvc-controller-to-jquery-dynamically
http://stackoverflow.com/questions/33947882/pass-model-to-controller-using-jquery-ajax
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api
http://stackoverflow.com/questions/4488714/change-label-text-using-javascript
http://stackoverflow.com/questions/6840311/razor-syntax-dynamically-name-html-elements