Mar 19, 2018

Simple Javascript class with closure example for form with panels activated using buttons

This JS design is described as revealing modul template.
Here are more patterns:

https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript


"use strict";
var Acme = Acme || {};
Acme.TravelAgency = Acme.TravelAgency || {};
Acme.TravelAgency.RegisterForm = (function () {
    const btnActiveCSS = "btn-danger";
    var options = null;

    var init = function (optionsParam) {
        options = {
            conjuctionWord: ' in '
        };
        if (optionsParam !== undefined) {
            $.extend(options, optionsParam);
        }
    }
    var dom = {
        btnYourInfoId: "#btnYourInfo",
        btnAccountSetup: "#btnAccountSetup",
        panelAccountSetupId: "#panelAccountSetup",
        panelYourInfoId: "#panelYourInfo"
};
function bindCallBacks() {
$(document).on('click', dom.btnAccountSetup, show);
        $(document).on('click', dom.btnYourInfoId, show);
}
function show(senderBtnId) {
$(dom.panelAccountSetupId).hide();
$(dom.panelYourInfoId).hide();
senderBtnId = resolveSender(senderBtnId);
switch (senderBtnId) {
    case dom.btnYourInfoId:
        activateStepIcon(senderBtnId);
$(dom.panelYourInfoId).show();
                break;
            case dom.btnAccountSetup:
                activateStepIcon(senderBtnId);
                $(dom.panelAccountSetupId).show();
break;
default:
break;
}
}
function activateStepIcon(btnId)
{   
        $(dom.btnYourInfoId).removeClass(btnActiveCSS);
        $(dom.btnAccountSetup).removeClass(btnActiveCSS);
    $(btnId).addClass(btnActiveCSS);
}
function resolveSender(senderId) {
var result = senderId;
if (senderId.currentTarget && senderId.currentTarget.id)
result = senderId.currentTarget.id;
if (senderId[0] !== "#") {
result = "#" + result;
}
return result;
}
var init = function () {
bindCallBacks();
show(dom.btnYourInfoId); }
return new Object({
Init : init
});
})();

Feb 28, 2018

.NET Core 2.0 SOAP platform not supported error

For developing SOAP / WCF services use:

System.ServiceModel.Http  NUPackage

Use SVCUTIL to generate proxy from WSDL file or url.

If you get error :

PlatformNotSupportedException: Compiling JScript/CSharp scripts is not supported

read this:

https://github.com/dotnet/wcf/issues/2219

Put this before Client method call:

    MethodInfo method = typeof(XmlSerializer).GetMethod("set_Mode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
    method.Invoke(null, new object[] { 1 });

Feb 15, 2018

Bootstrap Custom Controls

Feb. 2018

Bootstrap Date picker with localization

Only one package required for example Bower or npm:

bootstrap-datepicker 

Reference package and css with appropriate Locale file. Dist folder is here only due to Bower :

    <link rel="stylesheet" href="~/lib/bootstrap-datepicker/dist/css/bootstrap-datepicker.standalone.min.css" />
...

<script src="~/lib/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
 <script src="~/lib/bootstrap-datepicker/dist/locales/bootstrap-datepicker.hr.min.js"></script>

Set language param during init and it should work:

            $('input[name="Birthday2"]').datepicker({
                isRTL: false,
                format: 'dd.mm.yyyy',
                autoclose: true,
                language: 'hr'
            });


Bootstrap Multiselect Checkpoint

https://github.com/davidstutz/bootstrap-multiselect.git

http://davidstutz.de/bootstrap-multiselect/

Apply on existing <select> DOM element.

<script src="~/lib/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="~/lib/bootstrap-multiselect/dist/css/bootstrap-multiselect.css"/>


$(dom.multiselectCss).multiselect();

Feb 6, 2018

ASP.NET MVC - Injecting C# data into Java script

Inside Razor view use Newtonsoft JSON serialization from C# to JSON:

@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.CityList,  Newtonsoft.Json.Formatting.None));

Jan 31, 2018

ASP.NET MVC custom culture client validation

Further info here: http://www.c-sharpcorner.com/article/internationalization-in-asp-net-core-mvc/

Watch for @inject ... for Localization property

Install NuGet packages:
- jquery-globalize.0.1.3
- jquery.validation
- Microsoft.jQuery.Unobtrusive.Validation

Choose your culture and properly initialize globalize library:

    <script src="~/Scripts/globalize.0.1.3/globalize.js"></script>

    <script src="~/Scripts/globalize.0.1.3/cultures/globalize.culture.hr.js"></script>
    <script>

        $(document).ready(function () {

            Globalize.culture("hr");

            $.validator.methods.number = function (value, element) {

                return this.optional(element) || !isNaN(Globalize.parseFloat(value));

            }

            $.validator.methods.range = function (value, element, param) {

                return this.optional(element) || (Globalize.parseFloat(value) >= param[0] && Globalize.parseFloat(value) <= param[1]);

            }

            $.validator.methods.date = function (value, element) {

                return this.optional(element) || Globalize.parseDate(value);

            };

        });

    </script>

This handles check on client side on input values.

I haven't tried but for input validation there is DataFormatString param validation:


[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? BirthDate { get; set; }

https://stackoverflow.com/questions/13916991/mvc-datatype-errormessage

Dec 1, 2017

.NET Core 2.0 Tips For Beginners

Update 24.9.18

Since key feature of .NET Core is sandbox (running concurent Core app's with different versions of .NET Core) one needs to understand basics of .NET Core versioning. Here is good post on subject:

Issue - project has invalid or missing dependencies but SDK or NuGet package(s) exist

From DevCommand prompt navigate to Project folder (not root !) where is your PRJ file and run:

dotnet restore

ASP.NET Core 2.0 configuration


To make above example work add NuGet package:

Microsoft.AspNetCore.All
Microsoft.NETCore.App  <-- it seems that this one is by default, can't be removed?

Make sure to mark appsettings.json with Copy If Newer


Setting up IIS hosting of ASP.NET Core on development PC

https://docs.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x

Tip. No need for any extra coding. Just make sure to setup IIS. I think ASP.NET CoreModule is required.

WebAPI


  • There is not API route configuration in startup. Use this for each controller:


    [Route("api/[controller]/[action]")]

; then each action decorate like this:

        [HttpGet("{echoText}",Name ="Ping")]
        public PCPingRS Ping(string echoText)



  • If you need to execute something at app startup, what you have previously done in Global.asax Startup, now is not that simple.
    • You need to take into account Dependency Injection since all Core is supporting it by default.
    • You may try to place your calls inside:
               return WebHost.CreateDefaultBuilder(args)             

.ConfigureAppConfiguration((context, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());

  • Parameter binding - you CAN NOT bind more than one simple value type parameter from POST body using [FromBody]
    • This works:
      public ActionResult DoSomething( [FromBody] string myText )
    • But this doesn't:
      public ActionResult DoSomething( [FromBody] string myText, [FromBody] int year)
  • Parameter binding - POST - you MUST always use [FromBody] since WebAPI is capable to map complex type memebers from Uri
    • public ActionResult DoSomething( [FromBody] MyObject dummy )

Session

For some reason this:

_httpContextAccessor.HttpContext.Session.SetObject(_searchObjectContextKey, searchObjectModel);

works and saves to Session but this:

_httpContextAccessor.HttpContext.Session.SetObject<SearchObjectsModel>(_searchObjectContextKey, searchObjectModel);

; doesn't and it has no error.


Use inject to reference namespaces:

@inject MyNameSpace.MySubSpace


Good resources on new tags helpers in Core :

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro


Partial views  vs ViewComponent

https://forums.asp.net/t/2083792.aspx?What+is+the+advantage+of+View+Components+in+ASP+NET+Core+1+0

Ideally you should not design components / controls inside partial views.
Partial views should encompass only reusable layout with minimum presentation logic.
If there is complex js or servers side logic you should use view component since it provides clear separation of controller.

Sections

Often there is some JS code required by partial view. You may use @section Scripts in your layout to place together all you scripts created outside from layout.
Unfortunately you CAN'T use section tag in PARTAIL views!
Hence you can't easy place your JS code with your partial view. Why is that?
Above section explains it. You are not suppose to place any logic even client side in your partial view.
You may place your section tag only in Views. This design degrades your partials to mere HTML containers. All your JS code from all partials should be placed in hosting view.
In real world this is not so bad. You want to reuse partial's and their JS code. Right?
So place your JS in standalone JS file and then reference it and initialize from hosting view.
This makes sense. Ideally you should write one-liner in JS to reference proper initialization for your partial views.

Debuging


Open VS command prompt. Go to folder where is your solution.
DOTNET RUN
Attach debuger to DOTNET process.

Logging


Core has integrated logging. Turn it on like this:
<aspNetCore processPath="dotnet" arguments=".\App.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />

Don't forget to create logs folder.

Initial setup on IIS - How to prepare self-contained installation 


https://docs.microsoft.com/en-us/dotnet/core/deploying/deploy-with-vs

Key points:
1. Manually edit your CSPROJ file and modify like this:
<PropertyGroup>
    <OutputType>Exe</OutputType>
    <RuntimeIdentifiers>win10-x64</RuntimeIdentifiers> 
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
2. Perform Publish to folder
3. In publish folder edit web.config and enable Logging as noted above
4. Copy content to IIS folder with no managed code app pool
5. Create logs folder in root of your website