Saturday, 18 March 2017

aspcore authorize 1 async, webpage onclosing event











//controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using authorize.Models;
using Microsoft.EntityFrameworkCore;

namespace authorize.Controllers
{
    public class AuthorizeController : Controller
    {
        private AuthorizeContext DB;

        //private List<UserPassword> user_password_list;

        public AuthorizeController(AuthorizeContext context)
        {
            DB = context;
        }

        // GET: Authorize
        public async Task<IActionResult> Index()
        {
            await get_log_info();

            return View(await DB.UserPassword.ToListAsync());
        }

        [HttpPost]
        public async Task<IActionResult> Index(IFormCollection collection)
        {
            var login_id = Convert.ToInt32(collection["Id"]);

            var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);

            //if computer is registered, update login, otherwise register computer and login
            if (existing_login_record != null)
            {
                existing_login_record.LoginId = login_id;
            }
            else
            {
                DB.Login.Add(new Login { Computer = machine, LoginId = login_id });
            }

            await DB.SaveChangesAsync();

            return Content("successful");
        }

        public async Task<IActionResult> Login_out()
        {
            var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);

            //clear login id
            if (existing_login_record.LoginId != null)
            {
                existing_login_record.LoginId = null;
                await DB.SaveChangesAsync();
            }

            return RedirectToAction("Index");
        }

        public async Task<JsonResult> webpage_open()
        {
            var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);

            //open new webform count +1, else count =1
            if (existing_login_record.OpenWindow != null)
            {
                existing_login_record.OpenWindow++;
            }
            else
            {
                existing_login_record.OpenWindow = 1;
            }

            await DB.SaveChangesAsync();

            return Json(existing_login_record.OpenWindow);
        }

        public async Task<JsonResult> webpage_close()
        {
            var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);

            //close webform count -1
            existing_login_record.OpenWindow--;

            await DB.SaveChangesAsync();

            return Json(existing_login_record.OpenWindow);
        }

        public async Task<IActionResult> another_view()
        {
            await get_log_info();

            return View();
        }

        public async Task get_log_info()
        {
            var machine = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

            ViewBag.computer_viewbag = machine;

            var existing_login_record = await DB.Login.FirstOrDefaultAsync(x => x.Computer == machine);

            //if is logged in, add user name to viewbag, otherwise add "log in" to viewbag
            if (existing_login_record != null && existing_login_record.LoginId != null)
            {
                var user = await DB.UserPassword.FirstOrDefaultAsync(x => x.Id == existing_login_record.LoginId);

                ViewBag.login_record_viewbag = user.Name;
            }
            else
            {
                ViewBag.login_record_viewbag = "log in";
            }
        }


    }
}

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

//index.cshtml

@model IEnumerable<authorize.Models.UserPassword>

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

        var user_password_list = [];
        var open_webpages = 0;

        //webpage open event
        $(document).ready(function () {

            $.ajax({
                url: '/Authorize/webpage_open',
                type: "GET",
                data: { },
                success: function (result) {

                    open_webpages = result;
                    $('#log_lable').append(' open webpages = ' + open_webpages);
                },
                error: function () {
                    alert("Error");
                }
            });

            //change navbar label log status text
            var login_record = '@ViewBag.login_record_viewbag';

            if (login_record == "log in") {

                $('#log_navbar').text('log in');
            }
            else {
                $('#log_navbar').text('log out ' + '@ViewBag.login_record_viewbag');

                $('#log_lable').text('@ViewBag.login_record_viewbag' + ' logged in ' + '@ViewBag.computer_viewbag');
            }

            @foreach (var item in Model)
            {
                <text>
                user_password_list.push(new user_password_class('@item.Id', '@item.Name', '@item.Password'));
            </text>
            }

        });

        //webpage close event
        window.onbeforeunload = function () {

            $.ajax({
            type: "POST",
            url: '/Authorize/webpage_close',
            data: {  },
            success: function (result) {
                //alert("success");

                //all open webpages close
                if (result == 0) {

                    //if (confirm("log out?")) {

                        //log out
                        $.post('/Authorize/Login_out', {});

                }
            },
            error: function (xhr) {
                alert("Error close web page");
            }
        });
        }


        function user_password_class(id, name, password) {

            this.id = id;
            this.name = name;
            this.password = password;
        }

        function submit_onclick() {

            var user_password_correct = false;

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

                var name = value.name.replace(/\s/g, '');
                var password = value.password.replace(/\s/g, '');

                if (name == $('#ux_user').val() && password == $('#ux_password').val()) {

                    $('#log_navbar').text('log out ' + name);

                    $.ajax({
                        type: "POST",
                        url: '/Authorize/Index',
                        data: { Id: value.id },
                        success: function (result) {
                            //alert("success");
                            window.location.replace("/Authorize/another_view");
                        },
                        error: function (xhr) {
                            alert("Error button confirm Assign view");
                        }
                    });

                    user_password_correct = true;
                    return;
                }
            });

            if (!user_password_correct) {

                alert("user name & password not correct");
            }

        }

</script>

<div class="text-right">
    <label id="log_lable"></label>
</div>

<h2>Enter User name, Password</h2>
<div class="row">
    <div class="col-md-4">
        <h4>user name</h4>
        <input id="ux_user" type="text" class="form-control" />
    </div>

    <div class="col-md-4">
        <h4>password</h4>
        <input id="ux_password" type="text" class="form-control" />
    </div>

    <div class="col-md-4">
        <h4>submit</h4>
        <input type="button" value="Log in" class="form-control" onclick="submit_onclick()" />
    </div>
</div>

<br />

<div>
    <a href="/Authorize/another_view">another view</a>
</div>

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

//another_view.cshtml


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

    var open_webpages = 0;

    //webpage open event
    $(document).ready(function () {

        $.ajax({
            url: '/Authorize/webpage_open',
            type: "GET",
            data: {},
            success: function (result) {

                open_webpages = result;
                $('#log_lable').append(' open webpages = ' + open_webpages);
            },
            error: function () {
                alert("Error");
            }
        });


        var login_record = '@ViewBag.login_record_viewbag';

        if (login_record == "log in") {

            $('#log_navbar').text('log in');
        }
        else {
            $('#log_navbar').text('log out ' + '@ViewBag.login_record_viewbag');

            $('#log_lable').text('@ViewBag.login_record_viewbag' + ' logged in ' + '@ViewBag.computer_viewbag');
        }
    });

    //webpage close event
    window.onbeforeunload = function () {

        $.ajax({
            type: "POST",
            url: '/Authorize/webpage_close',
            data: {},
            success: function (result) {
                //alert("success");

                //all open webpages close
                if (result == 0) {

                    //if (confirm("log out?")) {

                    //log out
                    $.post('/Authorize/Login_out', {});

                }
            },
            error: function (xhr) {
                alert("Error close web page");
            }
        });
    }

</script>

<h2>another view</h2>

<p>You are authorized to view this page</p>

<div class="text-right">
    <label id="log_lable"></label>
</div>

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

//_logout.cshtml

<body>
    <nav class="navbar navbar-inverse 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="Home" asp-action="Index" class="navbar-brand">authorize</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>

                <ul class="nav navbar-nav navbar-right">

                    <li>
                        <a id="log_navbar" href="/Authorize/Login_out">login</a>
                    </li>
                </ul>

                    @*@await Html.PartialAsync("_LoginPartial")*@

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

//AuthorizeContext.cs

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

namespace authorize.Models
{
    public partial class AuthorizeContext : DbContext
    {
        public virtual DbSet<Login> Login { get; set; }
        public virtual DbSet<UserPassword> UserPassword { get; set; }

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

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Login>(entity =>
            {
                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.Computer)
                    .HasColumnName("computer")
                    .HasColumnType("nchar(50)");

                entity.Property(e => e.LoginId).HasColumnName("login_id");

                entity.Property(e => e.OpenWindow).HasColumnName("open_window");

                entity.HasOne(d => d.LoginNavigation)
                    .WithMany(p => p.Login)
                    .HasForeignKey(d => d.LoginId)
                    .HasConstraintName("FK_Login_UserPassword");
            });

            modelBuilder.Entity<UserPassword>(entity =>
            {
                entity.Property(e => e.Id).HasColumnName("id");

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

                entity.Property(e => e.Password)
                    .HasColumnName("password")
                    .HasColumnType("nchar(20)");
            });
        }
    }
}

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

//userpassword.cs

using System;
using System.Collections.Generic;

namespace authorize.Models
{
    public partial class UserPassword
    {
        public UserPassword()
        {
            Login = new HashSet<Login>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }

        public virtual ICollection<Login> Login { get; set; }
    }
}

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

//login.cs

using System;
using System.Collections.Generic;

namespace authorize.Models
{
    public partial class Login
    {
        public int Id { get; set; }
        public string Computer { get; set; }
        public int? LoginId { get; set; }
        public int? OpenWindow { get; set; }

        public virtual UserPassword LoginNavigation { get; set; }
    }
}

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

reference:

http://stackoverflow.com/questions/3960701/javascript-to-remove-spaces-from-a-textbox-value
http://stackoverflow.com/questions/1816740/how-can-i-call-a-controller-action-directly-from-a-javascript-function
http://chuanshuoge1.blogspot.ca/search?q=.asp+final
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d4a58414-cc38-43ba-b7ef-1578767a823d/how-to-get-the-computer-name-using-c?forum=csharpgeneral
http://stackoverflow.com/questions/10389649/possible-to-access-mvc-viewbag-object-from-javascript-file
http://windowsitpro.com/powershell/files-powershell-cmdlets

Entity framework async
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/update-related-data

javascript async
https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript?gclid=CjwKEAjwtbPGBRDhoLaqn6HknWsSJABR-o5sv97LSSc7fgPD6C1qmnKX8Du83JUxGNXYXN68U5WJIBoCti3w_wcB

client side webpage onclose event
http://stackoverflow.com/questions/21227383/how-to-detect-browser-window-tab-close-event

Friday, 17 March 2017

麦堡Syncrude油田发生爆炸!

阿省中部油田重镇Fort McMurray 这两年真的是多事之都呀,还没从去年山林大火中恢复过来,昨天,那里的油田又发生了爆炸事故





爆炸发生在麦堡北部40公里的地方,Syncrude公司位于Mildred Lake的油田。具体地理位置如下:








爆炸时间大约是周二下午2点,先是不知道什么原因着了火,然后就“Bang”的巨大一声响!现场已然变成火光冲天,黑烟耸起,十分可怕

















油田着火那可是不得了的事情,现场那么多可燃可爆炸物质,一旦火势蔓延下来,损失就无法估量了,去年那场大火还历历在目呢~~~~








根据CBC报道,有一名员工在爆炸中严重受伤!目前已经被转到了麦堡的一家医院,重症监护,后来又被紧急转到埃德蒙顿医院,目前情况总算稳定下来。





油田的员工已经从现场被紧急疏散撤离








当时在爆炸现场到底有多少员工目前还不清楚,但是Syncrude公司在Mildred Lake油田一共有3000名雇员。








水牛城的RCMP和消防员都赶到现场灭火,阿省能源管理局官员也已经赶到现场监督。





经过几个小时的消防奋战,着火区域已经被隔离,火势不再蔓延,情况总算得到控制了!










在今天的新闻发布会上,爆炸原因已经出来了。Syncrude公司的发言人说,生产线出了问题,导致石脑油泄漏了,而石脑油是一种高度可燃的化合物,石脑油燃烧引发了爆炸。。。





但是直到目前,记者仍然不被允许进入现场。

















爆炸可能引发Syncrude公司石油大减产!





2015年8月份时,Mildred Lake油田也发生了一次爆炸事故,在那场事故过后,因为管道,电力和沟通系统都在爆炸中被损坏,导致该油田的产油量能力直线下降了80%,直到第二年的10月份,该油田才能恢复到正常产油量水平。





目前还不清楚这次爆炸到底有多大的损害影响,但是依现场的可怕爆炸程度来看,减产可能不可避免。

Tuesday, 14 March 2017

Search for the Super Battery - PBS NOVA Documentary 2017




https://www.youtube.com/watch?v=JPcLWF4hask

.aspcore sql visual studio 2017 publish

after publish on server, able to access my website via smartphone


create database first project, reference:

//controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using publish_test.Models;

namespace publish_test.Controllers
{
    public class dataController : Controller
    {
        testdataContext DB;

        public dataController(testdataContext context)
        {
            DB = context;
        }

        // GET: data
        public ActionResult Index()
        {
            var schools = DB.School.ToList();

            return View(schools);
        }

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

//view


@model IEnumerable<publish_test.Models.School>

    <h2>School table </h2>

    <table class="table table-striped">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Location)
                </th>
            </tr>
        </thead>

        <tbody>
            @foreach (var item in Model)
            {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Id)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Location)
                </td>
            </tr>
            }
        </tbody>
    </table>

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

//testdataContext

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

namespace publish_test.Models
{
    public partial class testdataContext : DbContext
    {
        public virtual DbSet<School> School { get; set; }

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

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

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

                entity.Property(e => e.Location)
                    .HasColumnName("location")
                    .HasColumnType("nchar(10)");

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

--------------------------------------------------------
//school.cs

using System;
using System.Collections.Generic;

namespace publish_test.Models
{
    public partial class School
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
    }
}

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

publish to iis


next

save


myweb is published on iis, iis setup reference:

add iis to sql user, reference:




-------------------------------------------------------------------------------------------------------
//not related to publish
//visual studio 2017 dependency System.Net.Http has conflict with Microsoft.AspNet.WebApi.Client
//use method alternative to ReadAsAsync

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>>();
                    var stringResult = await response.Content.ReadAsStringAsync();
                    employees_from_HR = JsonConvert.DeserializeObject<List<employee_dto>>(stringResult);
                }
            }

            //employees_from_HR.Add(new employee_dto { Id = "", name = "" });

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


reference:
https://docs.microsoft.com/en-us/aspnet/core/publishing/iis
http://stackoverflow.com/questions/6167648/visual-studio-reformat-code-document
http://stackoverflow.com/questions/40699424/project-json-not-found-in-visual-studio-2017-rc-solution-explorer
https://wildermuth.com/2017/02/11/Updating-My-Blog-to-Visual-Studio-2017-and-csproj
http://stackoverflow.com/questions/30400358/cant-find-system-net-http-formatting-dll
https://jonhilton.net/2017/01/24/retrieve-data-from-a-third-party-openweather-api-using-asp-net-core-web-api/