Notes on C#, JavaScript, SQL, RavenDB, No-Sql, PHP and other software related activities.
Friday, October 11, 2013
Amazon Tech bookstore
Reading Code
Any app that is TDD is probably a good one to learn from. TDD supports good development style.
https://github.com/ravendb/ravendb
https://github.com/markrendle/Simple.Data
Not C# but still good.
https://github.com/angular/angular.js
Saturday, September 21, 2013
icon approach of checkbox in angularJs
When saving the change to the server on a click...this works too.
The icons are from font awesome.
<div ng-repeat="item in items"> <i ng-class="{'true':'icon-check','false':'icon-check-empty'}[item.selected]" ng-click="fooClick(item)"></i> </div>
Explained: The ng-class has a JavaScript object {...} with an item selector [item.selected]. All this happen inline to paint the proper icon.
The best part is you can see the icon choices in the html and do not have to look in the js files. For larger lists I would not do it inline.
When user clicks, fooClick is invoked and I change the item in the database and change the var in the item. Thanks to angularJs binding, the ui is updated.
My Controller code.
$scope.fooClick = function (item) { var tf = (item.selected === 'true') ? 'false' : 'true';//watchout... boolean strings item.selected = tf; saveToDatabase(id,val); }
Wednesday, September 18, 2013
Browsers vs Editors
I would be interested in a podcast that interviewed someone from the Amaya. Listen to their thoughts on Editors, the (x)ml movement, and maybe leading into editors for dsl (domain specific languages).
At what point does a browser become an editor? Many business desktop applications are moving to the web. As a developer I often question where browsing ends and where editing or work begins.
http://www.w3.org/Amaya/
Tuesday, September 17, 2013
Reinventing the wheel, actually Ninject
Code worked from beginning, middle, and end. The middle was a bunch of ugly unnecessary if statements that needed manual configuration for each class. I didn't have time to use (fight) reflection and assembly invoke.
First Refactor
Custom service locator / factory. Good old inversion of control.I stubbed out a few classes. Wired up the first item, then realized...
Realization I'm reinventing the wheel!
public virtual IAbstractXrxController ManualControllerFactory(Type controllerType) { var ctrl = (IAbstractXrxController)GlobalConfiguration .Configuration.DependencyResolver .BeginScope().GetService(controllerType); return ctrl;}
I used http://tohtml.com/ to create html code.
Saturday, September 14, 2013
Linkers vs. Controllers in AngularJS Directives
I have had mixed results using "ng-click" in the linker function. Binding "ng-click" in the controller always works. Not that there is a bug or problem with the linker function. It is invoked at a different time in the page load life cycle. With anything, order of operations is important.
The example below shows the same click activity implemented two different ways; as a linker function and as a controller. The example does not run, but is conceptually correct. I'm still trying to figure out how to debug efficiently in jsfiddle.
Thursday, September 12, 2013
Git Mergetool
Git does a good job or merging, but conflicts happen.
You could just open your IED and try to fix things, but don't.
Instead type
> git mergetool
This is the cool part...
Your merging tool will open with the conflicted file.
When the conflict is resolved, save the file and the next conflicted file will open.
This continues until all conflicts are resolved.
There are tons of good blogs out there on configuring your merge tool.
I'm using kdiff3 right now and it's working for me.
Tuesday, September 10, 2013
Simple Git Cheatsheet (beta)
Starting Work - (already have a clone on your box)
> git pull origin master (or branch name)
> git branch MyShinyNewFeature (create new branch)
> git checkout MyShinyNewFeature (switch to that branch)
Then do you work
Doing Work
Add all new files to current branch, commit files, push to remote server (origin)
> git add . (add all files)
> git commit -m 'message here'
> git push origin MyShinyNewFeature (save files to server)
Finishing your work for the day while on your branch
[MyShinyNewFeature] > git checkout master (switch to master)
[master] > git pull origin master (update local copy of master)
[master]> git checkout MyShinyNewBranch (switch to your branch)
[MyShinyNewBranch] git merge origin master (merge master into your branch)
See Doing work to commit the merge.
Merging new feature into master
issue a pull request to integrate your branch into master, it better merge without any errors.
Random
> get fetch (every once in a while just run this)
Simple Definitions
- add . (adds all files, you still need to commit)
- commit - something you do after add
- fetch - download the code from the server
- pull - is a fetch and merge in one command
- clone - copies code from the server to your box. Usually the first thing you do when starting a project.
- origin - is a shortcut term for a remote server url
- checkout is how you switch branches. You can checkout local or remote branches.
- branch - does branching stuff
- .gitignore - this is a file that prevents certain files from being checked in. There are several good ones out there.
http://windows.github.com/
Wednesday, May 22, 2013
Tuesday, May 21, 2013
Posts on compile function in directives
https://github.com/angular/angular.js/wiki/Understanding-Directives
http://plnkr.co/edit/qrDMJBlnwdNlfBqEEXL2?p=preview
http://docs.angularjs.org/guide/directive
http://stackoverflow.com/questions/14565121/whats-the-difference-between-the-2-postlink-functions-in-directive
http://www.cheatography.com/proloser/cheat-sheets/angularjs/
Sunday, May 19, 2013
AngularJs and Xml in IE8
On my second pomodoro break, I decided to look at the xml. It looked fine. Then I put it in a separate file, used ng-include and it worked perfectly in IE8. It always worked in Chrome. I usually develop in Chrome then work through any IE8 issues. This process speeds up my development cycle.
<div ng-include="'myfile.xml'"></div>
Be sure to use single quotes around the file name.
Note: you can also load files dynamically with ng-include.
Friday, May 10, 2013
XML Schema and SSDT Sql compare
Wednesday, May 8, 2013
Why AngularJs MVC is Different
In AngularJs the model definition can occur in many different places, this is why it is different. Adding a new model item to a form is simple. In an html form with an html input node, simply add an html attribute of ng-model="person.name". When the page is compiled, AngularJs crawls the DOM, and automatically binds all of the ng-model directives to the $scope object. $scope is where we find the M in MVC. Scope also contains other things.
Reading from the model is also easy, simply wrap it in curly braces in the html.
<div>{{person.name}}</div>
When I was first learning AngularJS the examples confused me. I often thought "why I would want to see what the user was typing somewhere other than in the input box?" You don't! In your form you don't want to have {{person.name}} display on the input form. It is redundant. You will want {{person.name}} inside of ng-repeat for an index page that lists all the records on the page.
Generating the model from a form is not the only way. Usually the model is populated from a service located in a controller. Note, the $scope variable is passed in via the dependency injection framework in AngularJs. $scope is a canned object that is injected into your method. After a while your controllers start to have many things passed in. This is just the simplest example.
var MyCtrl = function($scope){
id = '';
$scope.person = MySvc.getById(id);
}
Thursday, May 2, 2013
Re-Usable Directive Base in AngularJS
I have to admit something about this feels wrong! But it works.
Look for the RED text in the code, this re-mapping of data is what makes this pattern work. If you try using "this.someArg1" directly in the code...'undefined' error.
I would not use this 'pattern' if you are making a one off directive. I am making directives for xml documents. With 10 different xml nodes that all need the same base...I don't want to copy and paste that much code.
I'll show the usage first to add some context to the myFancyBase function. "p:" stands for person in a random xml example.
MyApp.directive('p:Name',['dependency1','dependency2',function(d1,d2){
var fb = myFancyBase().getBase();
fb.someArg1 = d1.foo;
fb.someArg3 = 'whatever';
return fb.getDirective();
}])
I've color coded things to give you a headache and to help match up instances of the same vars.
var myFancyBase = function(){
var getBaseFn = function(){
//This mapping just feels wrong
var someArg1=this.someArg1,
someArg2 =this.someArg2,
someArg3=this.someArg3;
var getDirectiveBaseFn = function(){
priority: 50,
replace: false,
transclude: false,
restrict: 'E',
scope: false,
link: function(scope, element, attrs) {
//special sauce for my fancy directive
var x= foo(someArg1);
var y = bar(x + someArg2);
}
}
return{
getDirectiveBase:getDirectiveBaseFn,
someArg1:undefined,
someArg2:'my default setting',
someArg3:undefined
};
}
return{
getBase:getBaseFn
};
}
Wednesday, May 1, 2013
.Net WebApi - four months later
- GET()
- GET(id)
- GET(id, oneMoreVar) - I don't recommend this unless it really makes sense
- POST
- PUT
- DELETE
- OPTIONS- if you want to get real fancy.
Tuesday, April 30, 2013
CKEditor and AngularJs Modal boxes
I can't take credit for writing this code, found it on http://stackoverflow.com/questions/11997246/bind-ckeditor-value-to-model-text-in-angularjs-and-rails/12021632#12021632
angular.module('yourApp').directive('ckEditor',function () { return { require: '?ngModel', link: function (scope, elm, attr, ngModel) { var ck = CKEDITOR.replace(elm[0], { toolbarGroups: [ { name: 'clipboard', groups: ['clipboard', 'undo'] }, { name: 'basicstyles', groups: ['basicstyles', 'cleanup'] } ] } ); if (!ngModel) return; ck.on('pasteState', function () { scope.$apply(function () { ngModel.$setViewValue(ck.getData()); }); }); ngModel.$render = function (value) { ck.setData(ngModel.$viewValue); }; } }; });
Saturday, April 6, 2013
Sql Data Projects in VS2012
There are two things that I do 'wrong' or 'backwards'. The two items are creating new database schema's (not tables) and installing xml schema collection objects.
It just works better if I do these tasks in sql studio first, then incorporate them in my project with schema compare. Then, I can use schema compare to create deployment packages, without any help from sql server management studio.
My most often used setting in Compare Schema is "Block on possible data loss".
To find the setting to show the dialog box, look for the cog or sprocket graphic after the scroll.
Compare->Update->Scroll->Cog
Monday, April 1, 2013
Samsung Note II
I have been using Personal Digital Assistants (PDA) since the mid 90's. I have to say my Note II is the fastest most useful phone. My usage is 75% PDA the rest laptop, for non work use, maybe some iPad. I don't write code on it yet. I still prefer a mouse, keyboard, and two screens for code; do I dare say copying and pasting code?
Sunday, March 31, 2013
Fun vs. the truth
I heard or overheard "Easter bunny is a lie... just like... parents lied about religion" three times this week.
I have children. They need to know that Easter is to celebrate the day Christ rose from the dead. They should also have easter day fun. I enjoy waking up, hunting for colorfully painted eggs, eating a big breakfast then going to church. It is fun! I do not want to take away their fun.
I never tell them the easter bunny is real or true. It is not! It's just fun. Santa Clause, the Easter Bunny, and the Tooth Fairy are probably not the false prophets mentioned in the Bible.
The connection between the Easter Bunny and Easter? Here in Virginia we start seeing bunnies in the spring. Grandma saw the first one of the season this morning, Easter morning! Signs of new life? I think every child knows chickens come from eggs. New Life! Spring and the resurrection have things in common.
To believe or not to believe; every American gets to make that choice for themselves. Not to believe something because of the easter bunny? I can't believe that.
Thursday, March 28, 2013
Optimizing Directives in AngularJs
Not many apps require this optimization technique. If the directive is applied 50+ times on a page, consider this technique.
I am displaying xml on a page. When the user clicks on a node, a drop down list (ddl) is displayed.
Initially my app rendered all nodes with a ddl. The ddl was hidden. This significantly increased the size of my dom. Most nodes are not selected for editing. Wasted work compiling on page load.
Using $compile(htmlStr)(scope) AngularJS compiles and renders ddl's only after the user clicks to edit.
HtmlStr is a string including the ng-select expression. Be sure to have all data loaded in scope before compiling.
I apologize for the lack of code, phone bogging today.
Another optimization would be one list on the page used by all directives. This would not support simultaneous editing.
Tuesday, March 26, 2013
Scrum poker
A round of Scrum Poker is good for any project. It's always fun to see how new participants come to terms with relative time measurements. "What is 3... hours, days, weeks?" Then the discussion about how humans are good at relative measurement. "Is a marker bigger than a pencil? Yes." If task A is bigger or more difficult than task B, assign it a higher number. Relationships between the numbering scale and time can be asserted after enough data is collected.
Saturday, March 23, 2013
jSad- jQuery on Small Documents
The fix is to wrap the fragment in a root elemement do the work, then remove the root element.
Wednesday, March 20, 2013
Constants in AngularJs
Using constants also helps keep some order in the app. I'm using the same names or interface for the constants on each page. Some constants such as apiUri are referenced five or six times on each page. Each page has different values, but the interface is the same. I prefer constants over hard coding strings.
The directive shown below is not my service, don't let the name fool you. I use it to call an xml file. Then directives with lower priorities generate behavioral aspects for the page. My app is more document centric than model centric. The MVC is very light.
//root module
var myApp = angular.module('CoiApp',[]);
//constants
myApp.constant('mySettings', {
apiUri: '/api/foo',
nsUri: 'mySite/foo.xsd',
nsPrefix: 's'
});
//directive using constants, mySettings is injected in using the minification safe method.
mayApp.directive('getById',
['$log', '$location', 'mySettings'
function ($log, $location, mySettings) {
return {
priority: 500,
templateUrl: mySettings.apiUri +'/' + ($location.search()).myid
};
}]);
Saturday, March 16, 2013
XML is Too Complicated
I can't believe I just said that 'XML is too complicated', but it must be true! By capital XML I mean, xml, xsl, xsd, and xpath or xquery. Raw xml is easy enough just angle brackets. But everything else is so marginally supported. Why? Must be too complicated? Right?
Let's compare xml to json as a base. Json is basically a key value pairs and arrays. Xml, the object model (DOM); namespaces, elements, and attributes. But each of these needs to be broken down into other parts. Elements alone have start tag, tag name, end tag, text, and children. The permutations start to really add up, making full implementation of the supporting technologies difficult. I find xml easy and intuitive, but I don't build the tools to support xml. The full lack of support is an impedance on workflow today.
Thursday, March 7, 2013
(jBAD)- jQuery on Big A$$ Documents
var xmlFrag = document.getElementById(“12345”);In the code sample above I'm searching xml with namespaces. My namespace prefix is f. I know the Id of the root node from an event (code not shown). I'm using plain old javascript getElementById to quickly grab that dom node and create a fragment. Then passing just that fragment of xml into jQuery for further processing.
$(“f\\:user > f\\:name”,xmlFrag);
<f:user xmlns:f="user.xsd"><f:name></f:name></f:user>
Tuesday, March 5, 2013
Visual Studio 2012 make string one line
Click the button to allow regex, then paste in [ \t\r\n]
Make sure only current document is selected, or hope you have version control!
AngularJs and Xml Priming the Pump
AngularJS is powerful data binder. It has MVC tools built in for basic tasks. AngulaJS Directives, I wouldn’t say they are really part of the MVC. They are powerful!
When using directives against xml, there is a chicken and an egg problem. Angular does a good job separating code from data. But sometimes they are the same. Think dynamic sql, (which I agree is bad). Putting raw xml on the page and then applying directives requires a different approach than the traditional MVC.
The code below will put the raw xml on the page. In the xml, each element must have a namespace prefix. The root must have the namespace uri.
Then other directives can be applied to the xml.
Directive
MyApp.directive('loadXmlGetById', function (MySvcApi) {
return {
priority: 500,
templateUrl: MySvcApi.getByIdUrl,
};
});
Html
<div load-xml-get-by-id></div>
MySvcApi
Is not much of a service, just a function that returns a string with the url for my services + the Id which it gets from the ($location.Search()).Id
Client Side Xml from IE Meets Server Side Xml C#
In Internet Explorer (8), when adding xml with namespaces to the DOM… it adds a partial xml declaration “<?xml:namespace prefix…”.
In IE this is not a problem, but in the asp.net webApi I’m using XElement.Parse(xml) to do some clean up like remove jquery id’s and some css that gets added from AngularJs.
XElement.Parse(xml) blows up! So before parse, I’m removing the node with the following code. I’ve written a few tests, seems to work. I’d like to say I’ll post my tests later, but I doubt that will happen.
public string FixIENamespace(string contentStream)
{
const string pattern = @"<\?xml:namespace prefix =.* />";
const string replacement = "";
var rgx = new Regex(pattern);
var result = rgx.Replace(contentStream, replacement);
return result.ToString(CultureInfo.InvariantCulture);
}
I have not had this problem with Chrome.
Monday, March 4, 2013
AngularJs: One Modal Many Controllers
I started seeing a common pattern in my app for adding a new xml node to a page. I’m tired of copy and pasting the html for a modal where the only change is two small pieces of text.
Problem: only one ng-view can be on a page. Where to put ng-controller’s? Nesting all the controllers around ng-view is not a good idea.
Solution: ng-template to the rescue. Be sure to update $routeProvider to include the route. If you use this route, don’t include the controller in the route.
We don’t have to use ng-template, but then we would have to create a whole new file with just two lines of code!
The script tag below is embedded inside <div ng-app>.
<script type="text/ng-template" id="addTask.html">
<div ng-controller="newTaskCtrl" class="form-inline">
<div ng-include src="'genericAddItemModal.html'"></div>
</div>
</script>
I’ve even gone so for as to include another <div ng-include src=”protoXmlFile”></div> where the protoXmlFile name is set in the controller with all my variables.
This can be further simplified by using the routeProvider by calling the same template , but different controller. Then you don’t even need to use the script template method shown above.
$routeProvider.when('/addCoi/:className', { templateUrl: 'addListModal.html', controller: addCoiCtrl });
Don’t forget the extra quotes on ng-include
On little thing that can be tough to remember when working with ng-include.
Works:
<div ng-include src="'tasksPrototype.xml'"></div>
Does Not Work
<div ng-include src="tasksPrototype.xml"></div>
AngularJS and Xml with Namespaces Manipulation
The code below (find.find) gave me the same ID for each task. Not really what I wanted.
Also notice the ‘\\:’ , this is a quick fix for working with namespaces in a document. Technically it’s not accurate since it totally bypasses checking the resolver to ensure the prefix really matches the namespace requested. But for most circumstances should work.
Below is the xml fragment we are looking for
<f:task><f:id>12345</f:id></f:task>
xmlDom.find("f\\:task").find("f\\:id").text(getId());
By moving to a loop, each item has a new id. Not a big fan of loops, but they are fast and well supported. I like Christian Johansen’s use of the map function to do this kind of work. Unfortunately map is not supported by all browsers. Not enough time tonight to find a substitute.
var taskList = xmlDom.find("f\\:task");
for (var k = 0; k < taskList.length; k++)
var id = angular.element(taskList[k]).find("f:\\id");
id.text(getId());
}
Wednesday, February 27, 2013
AngularJs and Xml
Scenario: using an xml database, need to make a list of documents for user to select to edit. This info is in the database as xml.
Problem: When converting xml to json on the server… single items are not arrays, more than one item is an array. Array items need to be an array even if there is only one item.
Solution: convert client side with https://code.google.com/p/x2js/
When x2js converts xml to Json, it provides both an array format or a single item format for elements that could be either.
Oh! Namespace support! That made my day! It was even done in an elegant manner. Namespaces stay out of the way till you get down to work on the text element!
I was expecting the JSON to be f.rows.f.row.f.name
but no, it was so much better - rows.row.name.__text
for the namespace – rows.row.name.__prefix
I found this on http://rabidgadfly.com/2013/02/ I’m glad he created this post a week before I needed it.
Mad style points for Glenn for use of http://plnkr.co and for the Guitar legends xml data set!
Tuesday, February 26, 2013
Directives, Buttons, and Directives
For the most part, this is considered a bad-dog thing to do in AngularJs. But sometimes… it just has to be done. I came across this after hours and hours of fighting, then I looked deeper into ng-view. If the directive tag was in a different file loaded in via the view, it will render properly.
Scenario:
Main page and a button. The button opens a modal with a form. When the form is submitted, that data is used to make a new directive DOM element on the main page.
Problem:
The new instance of the directive is just string on a page. The directive never get applied. We want the div on 8888 to say ‘Hello World!. Without this $compile function, we would see <div>Hello World</div>. The directive is never applied.
<div ng-app="poc">
<div ng-controller="mainCtrl">
<div>Test 1 : sanity check</div>
<div xrx-hello-world></div>
<div>Test 2 : applied using getElementById(8888)</div>
<div id="8888">Replace Me</div>
<div xrx-add-button=""></div>
</div>
</div>
var poc = angular.module('poc', ['ngResource', 'ngSanitize']);
poc.directive("xrxHelloWorld", function () {
return {
priority: 50,
restrict: 'A',
replace: false,
transclude: true,
scope: false,
template: '<div>Hello World</div><div ng-transclude></div>',
};
});
poc.directive('xrxAddButton', function ($compile) {
return {
priority: 50,
restrict: 'A',
replace: false,
transclude: true,
scope: false,
template: '<button>Click</button><div ng-transclude></div>',
link: function (scope, element, attr) {
var btn = angular.element(element.children()[0]);
var handleClick = function () {
var directiveStr = '<div xrx-hello-world></div>';
var directiveDom = angular.element(directiveStr);
var newDomHome = angular.element($('#8888')).html(directiveDom);
$compile(newDomHome);
};
btn.bind('click', handleClick);
}
};
});
Thursday, February 21, 2013
AngularJS ng-click button click notes
<div class="btn btn-info" ng-model="showSummary" ng-click="showSummary = 2/showSummary" ng-init="showSummary=0">
Show Summary
</div> <div class="well well-small" ng-show="showSummary">My Text Here</div>
Wednesday, February 20, 2013
Angular Notes for the day
Painful lesson earlier this week. Don't forget the 'ng-transclude' attribute in the HTML for your template!
Nice sample for calling controller methods in html with angular expression on jsFiddle.
<span ng-class="cssActiveIf(folder)">
<a href="javascript:void(0)">{{folder.name}}</a>
</span>
function AssetCtrl($scope) {
$scope.cssActiveIf = function(item) {
return (item === $scope.selection.currentFolder) ? "active" : "";
};
}