Set Default Values

A common task in any database application is to set default values.  In fact, I was a little disappointed that LightSwitch didn’t include this concept natively. SQL certainly has it.  Nonetheless, I have to handle it myself.

Doing a quick search, I found this excellent video from Beth Massi.  She has like a bizillion videos out there.  God bless her! She’s been an excellent resource for me.  Unfortunately, this did not work for me.

http://msdn.microsoft.com/en-us/vstudio/hh307861.aspx

I realize that I am developing an HTML client and that she was working from the desktop in her video.  But due to the three-tier separation enforced by LightSwitch this should work.  In fact, Beth refers to this in her video.  Because the default is put at the data tier, it should work – regardless of how the record is created.

Okay. To be completely honest, I’m sure it still works. However, I’m facing a sequencing issue.  When using the HTML client, the database record is not actually being created until after you save the changes. The desktop version is creating the record before displaying it to the user.  Maybe.  I’m just guessing. Regardless, the two are different. Sadly!

The solution is actually quite simple.  While in the data table designer, switch to the HTMLClient. (See the button at the bottom of the pane.)  Then click the Write Code dropdown and select created.

image

You will then be taken to a code window where you can now set your defaults.  It is sad that this has to be done in the HTMLClient in the first place.  I’m sure it saves a server roundtrip or two – but, personally, I’d prefer an option to take a small bandwidth hit in place of having to code all my created logic in two places (and in two languages).

Detect Add vs. Edit

LightSwitch provides a nice ability to reuse a single screen for Add or Edit functionality.  However, I frequently have events that I only want to fire in one mode versus another.

I did only a little digging on this topic, but came up with no definitive method.  I have something that works – for now.  But I would prefer something a little more explicit.  If I come across a better way, I’ll post it.

For now, I use the existence of the Id field on the record.  If the Id field is defined, I must be editing.  If it is not defined, I am adding.  Unfortunately, this depends on the existence of an Id field.  For my purposes, that’s fine.

Add code to the created event.  My screen is tied to the Account table.  Here’s a small example:

myapp.AddEditAccount.created = function (screen) {

    if (screen.Account.Id === undefined)
        alert("Adding");
    else
        alert("Updating " + screen.Account.Id);
};

This will do for now.

Respond to Data Change in HTML Client

I’m rewriting an old DOS billing system built for garbage removal companies. Since their business revolves around pickups at street addresses, getting the street address correct and consistently entered is a pretty big deal. You don’t want to enter West A Street one time and then use W A ST the next.  Obviously, such inconsistencies ruin searching and sorting.

I could write a web service call to use something like Google (or Microsoft) Maps. Unfortunately, there’s a cost for these services that many of my customers would like to avoid.  Some larger customers will want this, so I’ll be sure to add it later.  However, I don’t need official USPS validation. I simply need to make sure that the address is entered the same way every time.  And, while I’m at it, I might as well follow USPS guidelines in the process.

Anyway, enough back story.  Attaching to a field’s change event is done by adding code to the screen’s create event.  As shown here, I’m binding a function call to changes in the StreetAddress field.  Every time the StreetAdress field changes, I scrub it doing things like converting it to all upper-case and replacing spelled out directionals (like “West”) with their abbreviations (e.g.”West” becomes “W”).  I also break it apart into several parts according to USPS rules.  But none of that’s relevant for the moment.  Here’s my code:

myapp.AddEditAccount.created = function (screen) {
    // Write code here.
    screen.findContentItem("StreetAddress").dataBind("value", function (newValue) {
        if (newValue !== undefined && newValue !== null) {
            // value of street address has changed
            // Parse the address, see if we can understand it
            // remove all periods
            var parts = parseAddress(newValue);

            screen.Account.PreDirection = parts[1];
            screen.Account.StreetName = parts[2];
            screen.Account.StreetType = parts[3];
            screen.Account.PostDirection = parts[4];
            if (parts[0] !== screen.Account.StreetAddress) {
                screen.Account.StreetAddress = parts[0];
            }
        }
    });
};

Starting MS LightSwitch Project

Been away from blog for far too long – though, it’s primarily just for me.  Maybe this new project will revive my commitment.

I’ve started a project to port a very old DOS project of mine.  (That’s right!  It’s still running DOS.)

I’m enamored by the MS LightSwitch/Azure promise and thought this was a good project to give them a try.  In the end, I’m still not convinced that this is the right approach for my application.  But, if LightSwitch is everything it’s promised to be, it should serve as a pretty good prototyping/design tool.

I thought I’d try to record what I learn during this process – if only as a way to easily find solutions to old problems.

Regardless, I’m intrigued by what I’ve read and videos I’ve seen for LightSwitch so far.  I’m looking forward to diving into it.

Empty or Null dates in SharePoint 2010

Turns out that my first, “simple” foray into SharePoint Workflows already hit upon a snag.

How do you test for an empty date in SharePoint 2010?

I did some digging and found that the common consensus was to convert the date to a string (using String Builder) and then use string comparison.  Unfortunately, this didn’t work quite as expected.

Attempt 1: Test Date.“as String” begins with “1/1/0001”

Unfortunately, I don’t know enough about SharePoint to understand why this didn’t work.  Through playing around, I found that if I used String Builder to convert an empty date to a string, the resulting string would be “1/1/0001 12:00:00 AM”.  So, logic would seem to indicate that all I had to do was test to see if a string begins with “1/1/0001.”  However, this did not work!  Maybe someone could tell me why.

Here’s what I did:

    • Set Variable: Date as String to [%Current Item: Cutoff Date%]
      • Note: In String Builder, I set Return field as to As String
    • If Variable: Date as String begins with 1/1/0001
      • Log Date is empty. to the workflow history list

And, of course, the “Date is empty.” message never appeared in the workflow history.

I never did find out why “begins with” wasn’t operating as expected. I even changed the test to “does not begin with” and my logged output to be “Date does not start with 1/1/0001.  Its value is ‘[%Variable: Date as String%]’.”  Not surprisingly at this point, this time I DID get a message and it stated:

Date does not start with 1/1/0001.  Its value is ‘1/1/0001 12:00:00 AM’.

Someone explain THAT one to me.  Nevertheless, I persisted.

Attempt 2: Test Date.“Short Date” equals “1/1/0001”

Obviously, it occurred to me that I could test the value of the entire string.  But while I was at it, I tried using the “Short Date” setting in String Builder.

image

I was then able to use essentially my original logic, and this time it worked!

  • Set Variable: Date as String to [%Current Item: Cutoff Date%]
    • Note: In String Builder, I set Return field as to Short Date
  • If Variable: Date as String equals 1/1/0001
    • Log Date is empty. to the workflow history list
    This one worked!  There must be something I’m missing in the “begins with” operator.  But for now, I have a solution to my problem.

When life gets in the way…

I’ve had to put all this “Framework stuff” on hold for a bit as I investigate the potential of workflows in MS SharePoint.  (Still can’t quit my “day job.”  Not that I’d want to!)  I have to admit that I’m pretty impressed so far.  But my evaluation thus far is limited to what I’ve read.  I have no experience.

I plan to rectify that last limitation shortly…

Write my own PHP Web Framework?

I may regret this, but I think I’m going to start my own PHP Web Framework.  I’m just not finding what I want out there.  (Though, CakePHP has a lot going for it and the recently announced 3.0 version may eventually meet my needs.)

I want something that leverages the built-in aspects of PHP as much as possible, is completely based on OOP principles and doesn’t reinvent the wheel.  As a simple (somewhat silly) example, PHP’s spl_autoload functions work pretty well; I don’t need a framework that has a proprietary means of loading classes.

I also want something that is completely extensible and modular – without requiring modification to the framework itself.  And I want this to ability to run deep – meaning, virtually every aspect of the framework should be replaceable.  If a user doesn’t like the way something works – then he or she should be able to simply override it (without modifying the framework’s code).

To accomplish this, I want the framework core to be little more than a means of loading and configuring replaceable modules. I’ll then use this system to incrementally add modules I need in my framework.

Sounds simple enough!  (Oh, don’t I wish…)

I’ve already started a Github for the project called clic-framework.  It’s empty!  Basically, I just wanted to reserve the name.

Fix to CakePHP Simple Authentication Tutorial

I’m trying to learn the “correct” way to do things in Cake.  So, naturally, I’m starting by closely following a few tutorials the CakePHP site.

The first tutorial was a fairly traditional Blog Tutorial.  It was well written and even started by leading me through the installation process.  I was able to follow it without much trouble.

The next tutorial is a Simple Authentication and Authorization Application.  I ran into trouble on this one – despite the fact that I literally copied the code directly from the site.

The Error

When I tried to access the users/add page, I got the following error:

Notice (8): Undefined property: View::$Form [CORE/Cake/View/View.php, line 804]
Code Context
<!-- app/View/Users/add.ctp --> <div class="users form"> <?php echo $this->Form->create('User');?>
$name = 'Form'
View::__get() - CORE/Cake/View/View.php, line 804 include - APP/View/Users/add.ctp, line 3 View::_evaluate() - CORE/Cake/View/View.php, line 908 View::_render() - CORE/Cake/View/View.php, line 872 View::render() - CORE/Cake/View/View.php, line 463 Controller::render() - CORE/Cake/Controller/Controller.php, line 959 Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 110 Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 85 [main] - APP/webroot/index.php, line 96 Fatal error: Call to a member function create() on a non-object in /home/content/08/7445108/html/dev/app/View/Users/add.ctp on line 3

This was very frustrating.  After verifying that I had copied everything correctly from the tutorial – I turned to Google for help.  Unfortunately, the answer still wasn’t obvious.  Thus, I decided to blog my own solution.

The Solution

The problem comes from the “$this->Form” object – which appears to be missing.  As it turns out, Form is a Helper in CakePHP. Helpers must be declared.

You can correct the problem by declaring a the Form helper in either /app/Controller/AppController.php or /app/Controller/UsersController.php.  I put it in the AppController.  Since the Session helper was already declared there, the resulting code ended up being:

class AppController extends Controller { 
    public $helpers = array('Session', 'Form'); 
    public $components = array( 
        'Session', 
        'Auth' => array( 
            'loginRedirect' => array('controller' => 'posts', 'action' => 'index'), 
            'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home') 
        ) 
    );
. . .

Changed line is in red.

Nitpicking CakePHP–Issues 1 & 2

I’m playing with CakePHP.  I’m looking for a framework for a new web project of mine.  Frankly, I’d like CakePHP to be it.  There is much to love about CakePHP.  It has a very wide range of features and broad support.  Unfortunately, I’m finding CakePHP to require much more coding effort than I had anticipated.

The user support has made up for my tarnished expectations.  And, as it has been pointed out to me, my current experiences are based on “out-of-the-box” CakePHP.  Perhaps plug-ins will help.

A lot of developers love Cake!  As such, I can only assume that I am missing something.  For this reason, I will press on; hoping that I will find the plugins or that something will just click and suddenly make sense.  But right now, it’s a journey.

The Sample Case

I’m working through the User Authentication Tutorial.  In this example, I’ve created a very basic users table with an admittedly simple model.  Here it is in its entirety:

class User extends AppModel { 
    public $name = 'User'; 
    public $validate = array( 
        'username' => array( 
            'required' => array( 
                'rule' => array('notEmpty'), 
                'message' => 'A username is required' 
            ) 
        ), 
        'password' => array( 
            'required' => array( 
                'rule' => array('notEmpty'), 
                'message' => 'A password is required' 
            ) 
        ), 
        'role' => array( 
            'valid' => array( 
                'rule' => array('inList', array('admin', 'author')), 
                'message' => 'Please enter a valid role', 
                'allowEmpty' => false 
            ) 
        ) 
    ); 
} 

Nitpick #1 – You Have OOP, Use it!


I understand the simplicity of using an array for a type of configuration.  But I would have much preferred an object oriented approach here… And unfortunately, this isn’t the first time I’ve had this complaint.

This could have been much more powerful, extensible – and even required much less code, had we done something as simple as used an array of Constraint objects!  Simple things should be simple – and that’s the beauty of OOP.

Yes!  I’m nitpicking. (Uh, that’s the point of this post.)  But how common is it to have a required field?  Do I really need to code the “The {field label} field is required” message every time?  A better approach would be:

class User extends AppModel { 
    public $name = 'User'; 
    public $validate = array( 
        'username' => array(new RequiredConstraint(‘username’)),  
        'password' => array(new RequiredConstraint(‘password’)), 
        'role' => array(new EnumerationConstraint(‘role’, array('admin', 'author')))  
    ); 
} ?>

I’d probably even refactor the $validate array and ultimately change AppModel to use a constructor that created a list of Column or Field objects that, in turn had a list of constraints… But I digress…

Nitpick #2 – You Have a Model, Use It!


Back to the model… Without knowing anything about CakePHP, it’s pretty easy to see that the role column is (essentially) an enumeration.  It’s value must be either admin or author.  I love it when code is self describing!

So, since the model tells me this; why must I express it again in the view?  Looking at a snippet of the add.ctp, this is what I find:

<!-- app/View/Users/add.ctp --> 
    <?php 
        echo $this->Form->input('role', array( 
            'options' => array('admin' => 'Admin', 'author' => 'Author') 
        )); 
    ?> 
 

Again, simple things should be simple!  Yes.  We certainly need the ability to override the list of presented options.  Maybe we don’t want all the options available in a particular view.  But the view options are commonly the same.

This is also an example where we should be saving much more than development time and initial effort.  How many views are going to eventually have this input field?  How many are going to need to be changed every time I update the list of options?  How often am I going to fat-finger one of the options?  How easy is that bug going to be to find?

Parting Disclaimer


I am not a CakePHP hater!  In fact, I totally expect to grow to love CakePHP.  I am a complete neophyte in the CakePHP world and expect to find the genius in the design far more frequently than I find warts to criticize.  I have not even scratched the surface of CakePHP and its many plug-ins and may find simple solutions already exist. 

CakePHP is the way!  At least, I still believe it is.  I have much to learn on this new journey…

Switching back to WordPress

I had only just started this blog some time ago when I decided to host my own website (cliffchaney.com).  I wanted my own server for hobby/development reasons; so it just made sense to host my blog there… or so I thought.

I was wrong.

Thought I’m hardly a regular “blogger” in the typical sense; I found that I was constantly dealing with security and spam issues on the WordPress installation.  I thought about trying something else (e.g. Drupal), but in the end feared that I’d spend a lot of time setting up something new – only to have basically the same problems.

I decided that I wanted to be OUT of the admin & security business!  Hence, I’ve moved my blog back to the WordPress host. I’m not bothering to move any content.  As noted, most my posts are “for me” anyway. This is also a nice change to begin anew!

I’ll put a redirect up form my old URL. That way I won’t lose the one reader I actually had… 😛

Create your own website, free on WordPress.com.Create your own website.
Start free