when we implement an web app with knockout JS, we encounter an issue in the page load.
we create an observable object to store an object with observable properties.
self.MyObservable=ko.observable();
self.myObject=new MyObject(){
property1: ko.observable(),
property2: ko.observable(),
property3: ko.observable()
}
self.MyObservable(self.myObject);
in the method.. we have the logic to check the property1 value
then we have to access the property1 with the following code
self.MyObservable().property1()
unfortunately we encounter TypeError:property1 is not a function in chrome debugger
here is the work around to fix the error.
if (ko.isObservable(self.MyObservable().property1)) {
return self.MyObservable().property1();
}
a blog to share Microsoft technologies Azure, DotNet, SharePoint, SQL Server,JavaScript Framework: Node.JS, Angular, React
Thursday, June 13, 2019
Monday, June 10, 2019
how to create a Knockout JS custom handler for duplicate email validation?
In the current Knockout JS web application, we want to validate the user input in the email field to make sure the input does not exist in our system.
i implemented the business logic in the textbox blur event. it means that the validation call to the back end when the cursor leaves the textbox.
here is snippet of code to implement binding handler in Knockout JS
ko.bindingHandlers.validateEmail = {
init: function (element, valueAccessor, allBindingsAccessor, data, context) {
var options = allBindingsAccessor().validateEmailParams || {};
$(element).blur(function () {
var customerId = options.customerID();
var email = options.emailAddress();
var value = valueAccessor();
var dataModel = sci.dataModel;
dataModel.CheckDuplicateEmail(customerId, email).then(function (response) {
if (response != null) {
if (response) {
valueAccessor().setError(loc.DuplicateEmailMySubaruAccount);
}
}
});
});
return ko.bindingHandlers.value.init.apply(this, arguments);
},
update: ko.bindingHandlers.value.update
};
HTML Code
<input autocomplete="off" id="email" class="form-control" type="text" data-bind="value: email,validationElement:email, validateEmail:email, validateEmailParams:{emailAddress: email, customerID:accountNumber}, attr: { placeholder: loc.Email }" />
i implemented the business logic in the textbox blur event. it means that the validation call to the back end when the cursor leaves the textbox.
here is snippet of code to implement binding handler in Knockout JS
ko.bindingHandlers.validateEmail = {
init: function (element, valueAccessor, allBindingsAccessor, data, context) {
var options = allBindingsAccessor().validateEmailParams || {};
$(element).blur(function () {
var customerId = options.customerID();
var email = options.emailAddress();
var value = valueAccessor();
var dataModel = sci.dataModel;
dataModel.CheckDuplicateEmail(customerId, email).then(function (response) {
if (response != null) {
if (response) {
valueAccessor().setError(loc.DuplicateEmailMySubaruAccount);
}
}
});
});
return ko.bindingHandlers.value.init.apply(this, arguments);
},
update: ko.bindingHandlers.value.update
};
HTML Code
<input autocomplete="off" id="email" class="form-control" type="text" data-bind="value: email,validationElement:email, validateEmail:email, validateEmailParams:{emailAddress: email, customerID:accountNumber}, attr: { placeholder: loc.Email }" />
Tuesday, June 4, 2019
How to embedded HTML code in the asp.net MVC resource file?
currently i am building an web application to support both English and French users.
we have a some words that already under registered trade mark My Trade Mark®. unfortuately the registered in not show in superscript.
we have to use the following HTML code to show registered trade mark in superscript.
<sup>®</sup>
since <> have been used for open and close tag
we have use the following code to embedded HTML code in the resource file.
<data name="MyTradeMark" xml:space="preserve">
<value>My Trade Mark<![CDATA[<sup>®</sup>]]></value>
</data>
in the MVC page we can use the code below to localize the text.
@Html.Raw(MVCPage_ascx.MyTradeMark)
in ASP.NET page. we just need to put this code in aspx page
<%=@MVCPage_ascx.MyTradeMark%>
we have a some words that already under registered trade mark My Trade Mark®. unfortuately the registered in not show in superscript.
we have to use the following HTML code to show registered trade mark in superscript.
<sup>®</sup>
since <> have been used for open and close tag
we have use the following code to embedded HTML code in the resource file.
<data name="MyTradeMark" xml:space="preserve">
<value>My Trade Mark<![CDATA[<sup>®</sup>]]></value>
</data>
in the MVC page we can use the code below to localize the text.
@Html.Raw(MVCPage_ascx.MyTradeMark)
in ASP.NET page. we just need to put this code in aspx page
<%=@MVCPage_ascx.MyTradeMark%>
Friday, May 10, 2019
How to run an old legacy Angular 2 App from the local?
Today, one of my teammate gave me a old legacy AngularJS app which is implemented
with Angluar 2. the Angular framework have been evolved into Angular 7. we usually start the project with angular/CLI. it is much easy and faster to spin up a project and make it running.
Since the legacy project is running under Angular 2,I try to migrate it to latest Angular 7. the structure and configuration is much different between the legacy AngularJs and new Angular.
I try different approaches with upgrade to lastest @angular/CLI, clear the cache. added all latest component in the node_modules folder.
unfortunately those tries were never succeed. After i check the project configuration setting in Package.json file. under Scripts section
we can use npm to manuplate the project, instead of ng serve and ng command
launch CMD Window and go to angular project
run npm install to get all the requirement components for the project.
run npm start to launch the project in the browser.
Now i can play around with this legacy App. it is a good way to start the migration. you can launch it and see how it work..
with Angluar 2. the Angular framework have been evolved into Angular 7. we usually start the project with angular/CLI. it is much easy and faster to spin up a project and make it running.
Since the legacy project is running under Angular 2,I try to migrate it to latest Angular 7. the structure and configuration is much different between the legacy AngularJs and new Angular.
I try different approaches with upgrade to lastest @angular/CLI, clear the cache. added all latest component in the node_modules folder.
unfortunately those tries were never succeed. After i check the project configuration setting in Package.json file. under Scripts section
"scripts": {
"build": "tsc -p src/",
"build:watch": "tsc -p src/ -w",
"serve": "lite-server -c=bs-config.json",
"prestart": "npm run build",
"start": "concurrently \"npm run build:watch\" \"npm run serve\"",
"lint": "tslint ./src/**/*.ts -t verbose"
},
we can use npm to manuplate the project, instead of ng serve and ng command
launch CMD Window and go to angular project
run npm install to get all the requirement components for the project.
run npm start to launch the project in the browser.
Now i can play around with this legacy App. it is a good way to start the migration. you can launch it and see how it work..
Wednesday, May 8, 2019
How to save your day with a simple command on existing anuglarJS with angular/CLI running on Node.JS?
Today, I got a chance to run an application that I download from Angular office website
when I run ng serve to launch the SPA web application. I got compile error immediately

i can fix it by run this command line in the CMD Windows
npm install -save/dev PackageName
It will really take time to fix all the missing package error. there is a much simple approach with the following line
npm install
this command will automatically re-install all the missing packages for the existing project.
when I run ng serve to launch the SPA web application. I got compile error immediately
i can fix it by run this command line in the CMD Windows
npm install -save/dev PackageName
It will really take time to fix all the missing package error. there is a much simple approach with the following line
npm install
this command will automatically re-install all the missing packages for the existing project.
Wednesday, April 17, 2019
how to fix DateTime.parseExact exception in Windows Server 2019?
when I deployed the ETL that use the exact date format like MM/dd/yyyy to load the date from configuration setting section.
i got the following error from the application log
Application: DealerETL.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.FormatException
at System.DateTime.ParseExact(System.String, System.String, System.IFormatProvider)
at DealerETL.SciAzure.Utilities.DaxHelper..cctor()
Exception Info: System.TypeInitializationException
at DealerETL.SciAzure.Utilities.DaxHelper.rangeOfDealers()
at DealerETL.SciAzure.DealerService+<UpdateDealer>d__1.MoveNext()
Exception Info: System.AggregateException
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean)
at System.Threading.Tasks.Task.Wait(Int32, System.Threading.CancellationToken)
at DealerETL.Program.Main(System.String[])
it is working fine to "MM/dd/yyyy" in the local development.. however the exception will be thrown if we did not change it to "MM'/'dd'/'yyyy".
i got the following error from the application log
Application: DealerETL.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.FormatException
at System.DateTime.ParseExact(System.String, System.String, System.IFormatProvider)
at DealerETL.SciAzure.Utilities.DaxHelper..cctor()
Exception Info: System.TypeInitializationException
at DealerETL.SciAzure.Utilities.DaxHelper.rangeOfDealers()
at DealerETL.SciAzure.DealerService+<UpdateDealer>d__1.MoveNext()
Exception Info: System.AggregateException
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean)
at System.Threading.Tasks.Task.Wait(Int32, System.Threading.CancellationToken)
at DealerETL.Program.Main(System.String[])
it is working fine to "MM/dd/yyyy" in the local development.. however the exception will be thrown if we did not change it to "MM'/'dd'/'yyyy".
Thursday, April 11, 2019
how to use general approach on caching in Web Api Development?
it is quite simple and stupid to implement a straight forward caching..
first we will define a MemoryCache and AsyncLock
second we will write the logic to utilize the cache from MemoryCache.
if we have more objects to be cache in the project, then we will have code redudent issue. since cache logic need to copy everywhere. the maintainance will be an issue as well. since the logic had been copied everywhere
i copied the idea from this link after i google for a solution.
How to cache data in a MVC application
i just a modification so that it handle the async call on loading the data for caching..
how to use this caching service. please view the following snippet of code.
if you like it, feel free to take it and your feed back will be greatly appreciated.
Happy programming
first we will define a MemoryCache and AsyncLock
private static readonly MemoryCache cache = MemoryCache.Default; private static readonly AsyncLock myAsyncLock = new AsyncLock();
second we will write the logic to utilize the cache from MemoryCache.
const string CacheKey = "MyCacheKey"; var myCacheObjects = cache.Get(CacheKey) as Cache Object type; if (myCacheObjects == null) { using (await myAsyncLock.LockAsync()) { //your logic here to load the cache objects
cache.Set(CacheKey, titles, new CacheItemPolicy()
{ AbsoluteExpiration = DateTimeOffset.Now.AddHours(12) }); } } return myCacheObjects ;
if we have more objects to be cache in the project, then we will have code redudent issue. since cache logic need to copy everywhere. the maintainance will be an issue as well. since the logic had been copied everywhere
i copied the idea from this link after i google for a solution.
How to cache data in a MVC application
i just a modification so that it handle the async call on loading the data for caching..
public class MemoryCacheService : ICacheService { public async Task<T> GetOrSetAsync<T>(string cacheKey, Func<Task<T>> getItemCallback)
where T : class { T item = MemoryCache.Default.Get(cacheKey) as T; if (item == null) { item =await getItemCallback(); MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddHours(12)); } return item; } } interface ICacheService { Task<T> GetOrSetAsync<T>(string cacheKey, Func<Task<T>> getItemCallback)
where T : class; }
how to use this caching service. please view the following snippet of code.
[Route("api/title")] public async Task<IList<Title>> GetMYTitles() { const string cacheKey = "WebApi-GetTitles"; MemoryCacheService memoryCacheService = new MemoryCacheService(); System.Func<Task<IList<Salution>>> myFunGetTitles =
async () => await GetTitlesAsync(); return await memoryCacheService.GetOrSetAsync<IList<Salution>>
(cacheKey, myFunGetTitles); } private async Task<IList<Title>> GetTitlesAsync() { string url = "salutations"; APIResult result = await InvokeAzureAPICall(url); IList<Salution> titles = (List<Title>)JsonConvert.DeserializeObject
(result.apiResponse, typeof(List<Title>)); return titles; }
if you like it, feel free to take it and your feed back will be greatly appreciated.
Happy programming
Subscribe to:
Posts (Atom)