Monday 30 January 2017

MVC create edit index dropdownlist bootstrap viewbag tempdata && SQL foreign key relationship













//PersonalController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
    public class PersonalController : Controller
    {
        public void my_viewbags(int _department_id, int _asset_id)
        {
            var _department = department_manager.get_all();
            var _asset = asset_manager.get_all();

            ViewBag.department_dropdownlist = new SelectList(_department, "id", "name", _department_id);
            ViewBag.asset_dropdownlist = new SelectList(_asset, "id", "asset1", _asset_id);
        }

        // GET: Personal
        public ActionResult Index()
        {
            var _personal = personal_manager.get_all();
            return View(_personal.OrderBy(x=>x.name));
        }

        // GET: Personal/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Personal/Create
        public ActionResult Create()
        {
            my_viewbags(0,0);

            return View();
        }

        // POST: Personal/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                if (collection["name"] == "")
                {
                    ViewBag.error_message = "please enter name";
                    my_viewbags(0,0);
                    return View();
                }

                if(personal_manager.check_duplicate(collection["name"]))
                {
                    ViewBag.error_message = collection["name"] + " already exists";
                    my_viewbags(0,0);
                    return View();
                }

                var _personal = new personal_dto()
                {
                    id = Convert.ToInt32(collection["id"]),
                    name = collection["name"],
                    deparment_id = Convert.ToInt32(Request.Form["department_dropdownlist"]),
                    asset_id = Convert.ToInt32(Request.Form["asset_dropdownlist"])
                };

                
                personal_manager.add(_personal);

                TempData["index_status"] = collection["name"] + " is created";

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Personal/Edit/5
        public ActionResult Edit(int id=0)
        {
            var _personal = personal_manager.find(id);

            my_viewbags(_personal.deparment_id,_personal.asset_id);

            return View(_personal);
        }

        // POST: Personal/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                var _personal = personal_manager.find(id);

                if (collection["name"] == "")
                {
                    ViewBag.error_message = "please enter name";
                    my_viewbags(_personal.deparment_id, _personal.asset_id);
                    return View();
                }

                //name changed but coincide with another existing name
                if (collection["name"] != _personal.name && personal_manager.check_duplicate(collection["name"]))
                {
                    ViewBag.error_message = collection["name"] + " already exists";
                    my_viewbags(_personal.deparment_id, _personal.asset_id);
                    return View();
                }

                var new_personal = new personal_dto()
                {
                    id = Convert.ToInt32(collection["id"]),
                    name = collection["name"],
                    deparment_id = Convert.ToInt32(Request.Form["department_dropdownlist"]),
                    asset_id = Convert.ToInt32(Request.Form["asset_dropdownlist"])
                };

                personal_manager.update(id, new_personal);

                TempData["index_status"] = collection["name"] + " is updated";

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Personal/Delete/5
        public ActionResult Delete(int id)
        {
            var _name = personal_manager.find(id).name;

            personal_manager.delete(id);

            TempData["index_status"] = _name + " is deleted";

            return RedirectToAction("Index");
        }

        // POST: Personal/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

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

//~/Views/Index.cshtml

@model IEnumerable<WebApplication3.Models.personal_dto>

@{
    ViewBag.Title = "personal";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table table-striped">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.name)
        </th>

        <th>
            @Html.DisplayNameFor(model => model.deparment_name)
        </th>

        <th>
            @Html.DisplayNameFor(model => model.asset_name)
        </th>
        <th></th>
    </tr>

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

        <td>
            @Html.DisplayFor(modelItem => item.deparment_name)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.asset_name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
            @Html.ActionLink("Details", "Details", new { id=item.id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id }, new { onclick = "return confirm('Are you sure you wish to delete?');" })
        </td>
    </tr>
}


</table>

<div class="form-group">
    <div>
        @if (TempData["index_status"] != null)
        {
            @Html.Label("status:", htmlAttributes: new { @class = "text-left text-index-status col-md-1" })

            @Html.Label("status", (string)TempData["index_status"], htmlAttributes: new { @class = "text-left text-index-status col-md-11" })
        }
    </div>
</div>

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

//~/Views/Create.cshtml

@model WebApplication3.Models.personal_dto

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>personal_dto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.deparment_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("department_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.deparment_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.asset_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("asset_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.asset_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div>
                @if (ViewBag.error_message != null)
                {
                    @Html.Label("error:", htmlAttributes: new { @class = "text-right text-danger col-md-2" })

                    @Html.Label("error", (string)ViewBag.error_message, htmlAttributes: new { @class = "text-left text-danger col-md-10" })
                }
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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

//~/Views/Edit.cshtml

@model WebApplication3.Models.personal_dto

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>personal_dto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.id)

        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.deparment_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("department_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.deparment_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.asset_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("asset_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.asset_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div>
                @if (ViewBag.error_message != null)
                {
                    @Html.Label("error:", htmlAttributes: new { @class = "text-right text-danger col-md-2" })

                    @Html.Label("error", (string)ViewBag.error_message, htmlAttributes: new { @class = "text-left text-danger col-md-10" })
                }
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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

//~/App_Start/BundleConfig.cs

using System.Web;
using System.Web.Optimization;

namespace WebApplication3
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Content/Mystyle.css"));
        }
    }
}

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

//~/Content/MyStyle.css

body {
}

.text-index-status{
    color:gold;
    font-weight: bold;
    font-size: 18px;
}


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

//~/Models/personal_manager.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using WebApplication3.sql_data;

namespace WebApplication3.Models
{
    public class personal_manager
    {
        public static testEntities3 db = new testEntities3();

        public static List<personal_dto> get_all()
        {
            var _personal = db.personals.Select(x => new personal_dto
            {
                id = x.id,
                name = x.name,
                asset_name = db.assets.FirstOrDefault(y => y.id == x.asset_id).asset1,
                deparment_name = db.departments.FirstOrDefault(z => z.id == x.deparment_id).name
            }).ToList();

            return _personal;
        }

        public static void add(personal_dto _personal)
        {
            var new_personal = new personal
            {
                id = _personal.id,
                name = _personal.name,
                asset_id = _personal.asset_id,
                deparment_id = _personal.deparment_id
            };

            db.personals.Add(new_personal);

            db.SaveChanges();
        }

        public static void delete(int _id)
        {
            var _personal = db.personals.Find(_id);
            db.personals.Remove(_personal);
            db.SaveChanges();
        }

        public static bool check_duplicate(string _name)
        {
            var _personal = db.personals.FirstOrDefault(x => x.name == _name);

            if(_personal==null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static personal_dto find(int _id)
        {
            var _personal = db.personals.Find(_id);

            var _personal_dto = new personal_dto()
            {
                id = _personal.id,
                name = _personal.name,
                deparment_id = Convert.ToInt32( _personal.deparment_id),
                asset_id = Convert.ToInt32(_personal.asset_id)
            };

            return _personal_dto;
        }

        public static void update(int _id, personal_dto _personal)
        {
            var new_personal = db.personals.Find(_id);

            new_personal.name = _personal.name;
            new_personal.deparment_id = _personal.deparment_id;
            new_personal.asset_id = _personal.asset_id;

            db.SaveChanges();
        }
    }

    public class personal_dto
    {
        public int id { get; set; }
        public string name { get; set; }
        public int deparment_id { get; set; }
        public string deparment_name { get; set; }
        public int asset_id { get; set; }
        public string asset_name { get; set; }
    }
}

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

//~/Models/department_manager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication3.Models
{
    public class department_manager
    {
        public static List<department_dto> get_all()
        {
            var _department = personal_manager.db.departments.Select(x => new department_dto
            {
                id=x.id,
                name=x.name
            }).ToList();

            return _department;
        }

        public static int find(int _id)
        {
            var department_id = personal_manager.db.personals.FirstOrDefault(x => x.id == _id).deparment_id;

            return Convert.ToInt32( department_id);
        }
    }

    public class department_dto
    {
        public int id { get; set; }
        public string name { get; set; }
    }
}





Reference:

http://www.itorian.com/2013/05/three-ways-to-populate-selected-value.html
http://stackoverflow.com/questions/22991387/how-to-set-default-value-for-asp-net-mvc-dropdownlist-from-model
http://stackoverflow.com/questions/27901175/how-to-get-dropdownlist-selectedvalue-in-controller-in-mvc
http://stackoverflow.com/questions/11103288/html-label-color-in-asp-net-mvc
http://stackoverflow.com/questions/7190682/add-html-textbox-value-from-viewbag
http://stackoverflow.com/questions/16083794/how-to-add-new-css-class-in-html-textbox-mvc4
https://msdn.microsoft.com/en-us/library/bb398783(v=vs.110).aspx
http://stackoverflow.com/questions/14892030/how-to-change-defult-css-file-which-is-apply-to-the-layout-cshtml-using-code-in
http://www.w3schools.com/bootstrap/bootstrap_tables.asp

Sunday 22 January 2017

outback truckers



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

MVC model








//CustomerController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CPRG102.Mod4.ModelDemo.Models;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace CPRG102.Mod4.ModelDemo.Controllers
{
    public class CustomerController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            var customers = CustomerManager.Customers;
            return View(customers);  //customers from model/CustomerManager/list<customers>
        }

        //the GET method:  Customer/Create
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Customer customer)
        {
            //add the customer to the system
            CustomerManager.Add(customer);
            return RedirectToAction("Index"); //add a new customer, display table again
        }
    }
}

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

//~/views/customer/index.cshtml

@model List<CPRG102.Mod4.ModelDemo.Models.Customer>

@*
    <ul>
        @foreach (var cust in Model)
        {
            <li>
                @cust.ToString()
            </li>
        }
    </ul>
*@ 
<h4>Customer Lookup</h4>

<table class="table">
    <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Phone</th>
    </tr>
    @foreach (var cust in Model)
    {
        <tr>
            <td>@cust.Id</td>
            <td>@cust.FirstName</td>
            <td>@cust.LastName</td>
            <td>@cust.Phone</td>
        </tr>
    }
</table>

<a href="~/Customer/Create">Create New Customer</a>

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

//~/views/customer/Create.cshtml

<h4>Add Customer</h4>
<!-- Post back to the same controller method-->
<form method="post">
<table class="table">
    <tr>
        <td>ID:</td>
        <td><input type="text" name="Id" /></td>
    </tr>
    <tr>
        <td>First Name:</td>
        <td><input type="text" name="FirstName" /></td>
    </tr>
    <tr>
        <td>Last Name:</td>
        <td><input type="text" name="LastName" /></td>
    </tr>
    <tr>
        <td>Phone:</td>
        <td><input type="text" name="Phone" /></td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="Submit" /></td>
    </tr>
</table>
</form>

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

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

namespace CPRG102.Mod4.ModelDemo.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }

        public override string ToString()
        {
            return $"{FirstName} {LastName}";
        }
    }
}

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

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

namespace CPRG102.Mod4.ModelDemo.Models
{
    public class CustomerManager
    {
        public static List<Customer> Customers { get; private set; }

        static CustomerManager()
        {
            Customers = new List<Customer>();
            Customers.Add(new Customer { Id = 1, FirstName = "John", LastName = "Doe", Phone = "403-555-5670" });
            Customers.Add(new Customer { Id = 2, FirstName = "Jane", LastName = "Smith", Phone = "403-555-1234" });
            Customers.Add(new Customer { Id = 3, FirstName = "Ken", LastName = "Hunter", Phone = "403-555-9950" });
        }

        public static void Add(Customer customer)
        {
            Customers.Add(customer);
        }

        public static Customer Find(int id)
        {
            var cust = Customers.SingleOrDefault(c => c.Id == id);
            return cust;
        }

    }
}

MVC viewbag




//HomeController.cs

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

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace model3.controller
{
    
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Default()
        {
            ViewBag.cities = new List<string> { "victoria", "vancouver", "calgary", "saskatoon", "regina" };

            return View();
        }

        [HttpPost]
        public IActionResult Process()
        {

            var full_name = HttpContext.Request.Form["ux_fullname"];
            var phone = HttpContext.Request.Form["ux_phone"];
            var city = HttpContext.Request.Form["ux_city"];

            var message = $"welcome {full_name} from {city},to the MVC course";

            ViewBag.cities = new List<string> { "victoria", "vancouver", "calgary", "saskatoon", "regina" };
            ViewBag.Message = message;
            //TempData.Add("Message", message);

            return View("Default");
            //return RedirectToAction("Default");
        }
    }
}

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

//default.cshtml

<h3>home page</h3>
welcome to mvc

<form method="post" action="~/Home/Process">
    <table>
        <tr>
            <td>FullName</td>
            <td><input name="ux_fullname" type="text"/></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td><input name="ux_phone" type="text" /></td>
        </tr>
        <tr>
            <td>City</td>
            <td>
                <select name="ux_city">
                    @foreach (var city in ViewBag.cities)
                    {
                        <option value=@city>@city</option>

                    }
                    @*<option value="1">Calgary</option>
                    <option value="2">Saskatoon</option>
                    <option value="3">Edmonton</option>*@
                </select>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center">
                <input type="submit" value="Submit" />
            </td>
        </tr>
    </table>


</form>


<h4>@ViewBag.Message</h4>

@*<h4>t@TempData["Message"].ToString()</h4>*@

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

//project.json

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",

    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Saturday 21 January 2017

mvc 1



//~/App_start/RouteConfig

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

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

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

-------------------------------------------------------------------------
//~/Controllers/StudentController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace model2.Controllers
{
    public class StudentController : Controller
    {
        // GET: Student
        //public ActionResult Index()
        //{
        //    return View();
        //}

        public ActionResult Default()
        {
            return Content("Hi there!");
        }

        public ActionResult Display()
        {
            return Json(new { Id = "a", FirstName = "b", LastName = "c", Phone = "d" }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Redirect()
        {
            return RedirectToAction("Default");
        }

        
    }
}



Thursday 19 January 2017

加拿大10大城市就业率

里贾纳(Regina),萨省

  人口(截止到2016年12月):202,700

  全职工作者:116,100

  全职工作就业率:57.2%

  圭尔夫(Guelph),安省

  人口(截止到2016年12月):131,200

  全职工作者:73,400

  全职工作就业率:55.9%

  Kitchener-Cambridge-Waterloo,安省

  人口(截止到2016年12月):428,200

  全职工作者:236,900

  全职工作就业率:55.3%

  埃德蒙顿,阿省

  人口(截止到2016年12月):1,127,400

  全职工作者:610,700

  全职工作就业率:54.2%



  卡尔加里,阿省

  人口(截止到2016年12月):1,210,300

  全职工作者:650,800

  全职工作就业率:53.8%

  奥沙瓦,安省

  人口(截止到2016年12月):329,200

  全职工作者:176,400

  全职工作就业率:53.6%

  魁北克城,魁省

  人口(截止到2016年12月):677,500

  全职工作者:360,300

  全职工作就业率:53.1%

  圣约翰市,纽省

  人口(截止到2016年12月):105,400

  全职工作者:55,800

  全职工作就业率:52.9%

  渥太华-加蒂诺(Ottawa-Gatineau),安省/魁省

  人口(截止到2016年12月):1,116,300

  全职工作者:568,600

  全职工作就业率:50.9%

  多伦多,安省

  人口(截止到2016年12月):5,231,800

  全职工作者:2,631,600

  全职工作就业率:50.3%

Tuesday 17 January 2017

Scrap car removal...buying cars


Serving Calgary for 25 years..... buying cars and scrap vehicles.... I will arrive on time and pay what I quote....pls call (403) 803-9290...NO EMAILS PLEASE!


Thursday 5 January 2017

c# string encryption/decryption



//service1.svc

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

namespace WcfService1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public string Encrypt(string clearText)
        {
            string EncryptionKey = "abc123";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }
        public string Decrypt(string cipherText)
        {
            string EncryptionKey = "abc123";
            cipherText = cipherText.Replace(" ", "+");
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
    }
}

------------------------------------------------------------
//default.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace password
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var proxy = new ServiceReference1.Service1Client();

            encryption.Text = proxy.Encrypt(ux_password.Text);

            decryption.Text = proxy.Decrypt(encryption.Text);
        }
    }
}

-------------------------------------------------------------
//default.asp

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="password.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table>
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="password"></asp:Label>
                    </td>
                <td>
                    <asp:TextBox ID="ux_password" runat="server" Width="800px"></asp:TextBox>
                </td>
                </tr>
            <tr>
                <td>
                    <asp:Label ID="Label2" runat="server" Text="encryption"></asp:Label>
                    </td>
                <td>
                    <asp:TextBox ID="encryption" runat="server" Width="800px"></asp:TextBox>
                </td>
                </tr>
            <tr>
                <td>
                    <asp:Label ID="Label3" runat="server" Text="decryption"></asp:Label>
                    </td>
                <td>
                    <asp:TextBox ID="decryption" runat="server" Width="800px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center">
                    <asp:Button ID="Button1" runat="server" Text="Button" style="width:100%" OnClick="Button1_Click" />
                </td>
            </tr>
        </table>

    </div>
    </form>
</body>
</html>