Get default audit field behavior with an external datasource

Others have posted and blogged extensively about creating a robust audit trail for LightSwitch. However, if you are looking to achieve the default behavior with an external datasource, you could simply add the fields to your database
and write code in every entity's Inserting() and Updating() method.  However, if you have many tables in your app this can be a lot of work.  Here is a very easy way to DRY this up. 
1. Add the audit fields to your tables
- CreatedBy
- DateCreated
- UpdatedBy
- DateUpdated
2. Use this code in the DataService class for your datasource.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
namespace LightSwitchApplication
public partial class ApplicationDataService
partial void SaveChanges_Executing()
EntityChangeSet changes = this.Details.GetChanges();
IReadOnlyCollection<IEntityObject> addedEntities = changes.AddedEntities;
IReadOnlyCollection<IEntityObject> modifiedEntities = changes.ModifiedEntities;
if (addedEntities.Any())
foreach (IEntityObject entity in addedEntities)
InsertAuditFields(entity);
if (modifiedEntities.Any())
foreach (IEntityObject entity in modifiedEntities)
UpdateAuditFields(entity);
private void InsertAuditFields(IEntityObject entity)
string userName = this.Application.User.FullName;
DateTimeOffset currentDateTime = DateTimeOffset.Now;
entity.Details.Properties["CreatedBy"].Value = userName;
entity.Details.Properties["DateCreated"].Value = currentDateTime;
entity.Details.Properties["UpdatedBy"].Value = userName;
entity.Details.Properties["DateUpdated"].Value = currentDateTime;
private void UpdateAuditFields(IEntityObject entity)
string userName = this.Application.User.FullName;
DateTimeOffset currentDateTime = DateTimeOffset.Now;
entity.Details.Properties["UpdatedBy"].Value = userName;
entity.Details.Properties["DateUpdated"].Value = currentDateTime;
Hopefully this helps someone.

This version will check whether the table has the audit properties, thus allowing you to opt in.  Paul's solution is going to be better in the long run because it checks at compile time.  This was meant to be a quick way to get the default behavior. 
This is not a substitute for a full audit capability (see Paul's blog) if that is your requirement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
using Microsoft.LightSwitch.Details;
namespace LightSwitchApplication
public partial class ApplicationDataService
partial void SaveChanges_Executing()
EntityChangeSet changes = this.Details.GetChanges();
IReadOnlyCollection<IEntityObject> addedEntities = changes.AddedEntities;
IReadOnlyCollection<IEntityObject> modifiedEntities = changes.ModifiedEntities;
if (addedEntities.Any())
foreach (IEntityObject entity in addedEntities)
if (AuditProperties(entity))
InsertAuditFields(entity);
if (modifiedEntities.Any())
foreach (IEntityObject entity in modifiedEntities)
if (AuditProperties(entity))
UpdateAuditFields(entity);
private bool AuditProperties(IEntityObject entity)
bool hasAuditProperties = true;
bool createdBy = entity.Details.Properties.Contains("CreatedBy");
bool dateCreated = entity.Details.Properties.Contains("DateCreated");
bool updatedBy = entity.Details.Properties.Contains("UpdatedBy");
bool dateUpdated = entity.Details.Properties.Contains("DateUpdated");
bool[] checkForAuditProperties = new bool[]
createdBy,
dateCreated,
updatedBy,
dateUpdated
if (checkForAuditProperties.Any(a => a == false))
hasAuditProperties = false;
return hasAuditProperties;
private void InsertAuditFields(IEntityObject entity)
string userName = this.Application.User.FullName;
DateTimeOffset currentDateTime = DateTimeOffset.Now;
entity.Details.Properties["CreatedBy"].Value = userName;
entity.Details.Properties["DateCreated"].Value = currentDateTime;
entity.Details.Properties["UpdatedBy"].Value = userName;
entity.Details.Properties["DateUpdated"].Value = currentDateTime;
private void UpdateAuditFields(IEntityObject entity)
string userName = this.Application.User.FullName;
DateTimeOffset currentDateTime = DateTimeOffset.Now;
entity.Details.Properties["UpdatedBy"].Value = userName;
entity.Details.Properties["DateUpdated"].Value = currentDateTime;

Similar Messages

  • How can I get Aperture to re- synchronise with an external folder

    Does anyone know how to get Aperture to re- synchronise with an external folder?
    I reference my images on an external hard-drive.
    I often will move images or add them via other programs. I would like to then re-sync and have Aperture add the new images to its library.
    Lightroom does this very well but no joy in Aperture.
    Joe Barrett

    OK I know understand your question
    I do this as part of my workflow - I put all images into folders on the hard drive and then import them into Aperture as Referenced Masters
    I select the Library Inspector and select the higher levelProject I want to store the images in (or create a New one)
    Then I go to the
    File
    Import
    Folders as Projects
    Then select the folder tree that you wish to import - BUT ENSURE that you select where you want to store the files.
    I keep them in the current location as I prefer to have referenced files
    also adjust the other import controls as required.
    Then run the import - it may take a while to create the library records ad Thumbnails.
    Use the Aperture Preferences window to switch off Faces.
    Hope this solves your problem

  • I keep getting the eject disc error with my external hd plugged in

    hello, i get the pop up box saying my disc must be ejected before being removed. its my external hard drive that is plugged in, but i don't even be unplugging it an it gives me that error. can someone help me? thanks i jus bought a new cord for my hd an it still does it

     
    Care to share which OS you are using?
    http://support.apple.com/kb/HT1411 Apple Portables: Resetting the System Management Controller (SMC)
    http://support.apple.com/kb/HT1379 Resetting your Mac's PRAM and NVRAM

  • How do i get my iphone to sync with an external hard

    I have maxed out the memory on my macbook, so I'm trying to sync my phone through an external hard drive. I would appreciate any help.

    See Here   Syncing with iTunes
    From Here   http://www.apple.com/support/iphone/syncing/
    To take advantage of All the Features in iOS 5 See Here...
    iPhone User Guide

  • Strange rendering behavior with AdvancedDataGrid

    I'm getting strange (wrong) rendering behavior with a Flex datagrid... any idea what might be causing this?  It only happened one time for me... but now I'm worried that customers might be seeing this from time to time.
    Take a look:
    http://www.screencast.com/t/ZWMwMzEzMG
      -Josh

    Can you log this issue with your application (or a similar sample file in which it is reproducible) here - http://bugs.adobe.com/flex/
    -Sameer

  • How can I get Time Machine to back up an external hard drive (iPhotos) that is attached to airport extreme base station. Note: Time machine is usb to macbook pro and external drive with iphotos is usb to airport extreme base station. Help please. Thanks!

    How can I get Time Machine to back up an external hard drive (iPhotos) that is attached to airport extreme base station. Note: Time machine is usb to macbook pro and external drive with iphotos is usb to airport extreme base station. Help please. Thanks!

    Once you have the drive connected to your Mac, click System Preferences (gear icon) on the dock
    Click Time Machine
    Click Options
    Be default, the hard drive will be Excluded from backups. Click the drive to highlight it, then click the "-" (minus) button at the bottom of the list to remove the drive from Excluded items.
    The drive will be backed up on the next Time Machine pass
    Everything above assumes that the hard drive has been formatted in Mac OS Extended (Journaled) as Time Machine will only backup drives in that format.

  • Problems with getting default Texts (HRRCF00_GET_DEFAULT_TEXTS)

    Hi experts,
    we are using EHP4 and I have implemented and activated BADI HRRCF00_GET_DEFAULT_TEXTS for getting default Text during the posting procedure within SAP E-Recruiting based on WebDynpro.
    The BADI is called from WD Controller ERC_C_REQ_MGMT_UI.
    get default text values from BADI HRRCF00_GET_DEFAULTS_TEXT
        wd_assist->read_default_posting_text( EXPORTING iv_language                 = ls_language-langu
                                                        is_post_hrobject            = ls_hrobject
                                              IMPORTING ev_company_desc_default     = ls_language_tab-company
                                                        ev_department_desc_default  = ls_language_tab-department
                                                        ev_project_desc_default     = ls_language_tab-project
                                                        ev_task_desc_default        = ls_language_tab-tasks
                                                        ev_requirement_desc_default = ls_language_tab-requirements ).
    Directly after the call of BADI HRRCF00_GET_DEFAULTS_TEXT it seems that the company description is correctly filled.
    But unfortunately I am not able to see the default text within the Input Field of the view.
    As far that I know there should be a Button to fullfill the company description with the default text. But I can't see any button.
    Is there anything else I have to configure?
    Many Thanks!

    Hi Roman,
    I have testet it both. With a complete new requisition and with a old one. Same problem.
    But know I have recognized a strange system behaviour.
    If I toogle the first language I am not able to see my default_text. But if I toggle a second on(English etc) I can see the default text within this second tab.
    So the result is that I am able to see the default texts but only if I toggle two languages
    I am thinking I am missing something within my BADI implementation.
    The only thing I have done is to prorgram follwing section within the method GET_PROJECT_DESC
    method IF_EX_HRRCF00_GET_DEFAULT_TEXT~GET_PROJECT_DESC.
    *{   INSERT         M11K900044                                        1
    break erec1.
    project_desc = 'This is a example for the project description'.
    *}   INSERT
    endmethod.
    And it seems fine becaus if I switch to debugging mode I can see that the method is called and tht the variable project_desc will be filled correctly.
    Would be great if you could give me a helping hand on this.
    Many Thanks!
    Marco

  • I have a problem with the external sound of my ipod, when I take the headphones the music keeps playing and the ipod recognizes still have a headset connected. how do I get external sound out?

    I have a problem with the external sound of my iPod, when I take the headphones the music keeps playing and the ipod recognizes still have a headset connected. how do I get external sound out?

    - Try insering and removing the headphone plug a dozen times or so.
    - Try cleaning out the headphone jack in the iPod.
    - Resett he iPod. Nothing is lost
    Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Restore from backup
    - Restoe to factory defaults/new iPod
    If yu still have the problem that indicates a hardware problem, likely a bad headphone jack. Yu can make an appointment at the Genius Bar of an Apple store to confirm.
    If not underwarranty Apple will only exchange your iPod for a refurbished one for:
    Apple - Support - iPod - Repair pricing
    A third-party place like the following is less expensive. Here is one. Google for more.
    iPhone Repair, Service & Parts: iPod Touch, iPad, MacBook Pro Screens

  • Can 'Region' field gets defaulted based on owner of account?

    Hi
    Can 'Region' field in Account sales information gets defaulted based on owner of account?
    Owner belongs to 'West' region then account should get defaulted with same region.
    I have defined 'West' as territory for this owner.
    Do anybody has expression available for making field default ?
    Thanks
    Santosh

    Mahesh,
    Read-only is an option, but only if you never want users to change the values. If your users always work in the same Div, Region, and Sub-Region, then it would be reasonable to lock it so they don't feel like they have to update it. If,however, you have users that work in more than one sub-region, and they need to update it, then you wouldn't make it read-only.
    As far as workflow is concerned, you would need it to update the values when the ownership changes, if that is a requirement. If you choose not to update it, then it might not reflect the correct values for the new owner. Your decision on whether or not to implement the workflow would be based on whether or not your business rules require it. Most of the time, customers want the data to reflect the correct values for the current owner, but not always, so check with your customers and let the requirements drive the decision.
    Good Luck,
    Thom

  • HT201250 I use Time Machine to back up my entire computer with my external hard drive. I am getting a brand new iMac this month and was wondering what is the process of using this back up to restore my new computer exactly how my old computer was?

    I use Time Machine to back up my entire computer with my external hard drive. I am getting a brand new iMac this month and was wondering what is the process of using this back up to restore my new computer exactly how my old computer was? I want to make sure I will still have various important files on my new computer, like my songs in iTunes, my photos in iPhoto, etc, etc. Thanks so much in advance!

    Welcome to the Apple Support Communities
    When you turn on the new iMac for the first time, Setup Assistant will ask you to restore a backup, so connect the external disk and follow steps to restore all your files to your new iMac. Your new Mac will have the same settings and programs as your old computer.
    In other cases, I would recommend to restore the whole backup without using Migration Assistant or Setup Assistant, but a Late 2012 iMac uses a special OS X build, so the OS X version that you're using on your old Mac won't work on the new one. For more information, see > http://pondini.org/OSX/Home.html

  • In iTunes 10, I could type "Sinatra" in the search file, and would get a list of all tracks with "Sinatra" in any field.   In iTunes 11 I get these clever little windows, with nice arrows, but no lists to view.   What am I missing?

    In iTunes 10, I could type "Sinatra" in the search file, and would get a list of all tracks with "Sinatra" in any field.   In iTunes 11 I get these clever little windows, with nice arrows, but no lists to view.   What am I missing?

    Thanks for chipping in.   I discovered something after trying what you suggested.   I have quite a few collections of hits by year from Time Life and Billboard.  I've eliminated duplicate tracks that appear in both collections (or other CDs for that matter), but cross-reference the CD where I deleted the track and placed in in the comments section of the CD track I retained.   If I "search" by song name, only the remaining track appears.   But if I want to hear for example Classic Rock 1964, only those tracks remaining would be there when I pull up that CD.   So, I type "Classic Rock 1964,"  in the search field.  First the boxes on the right of the screen open up showing album icons.  Showing four tracks by album with a button to view 10 more, then four songs with an option to vies 18 more.   I finally noticed that at the top of the boxes is a blue band that reads, :Show Classic Rock 1964 in Music.  When I double click on this blue band, all 24 tracks from the original CD appear in the song list format even though I had deleted two of them because they appeard in a Beach Boys CD.   On those tracks, I had referenced Classic Rock 1964 in the comments field.    So, bottom line, Search will also look in the comments field if you click "filter by all" in the magnifying glass to the left of the search field.   And you can move all tracks that if finds into a song list by double clicking on the blue band.

  • I just updated my latest java but the update is causing problems with some externale devices. So i would like to uninstall this latest java update and get back the previous one. That should solve to problems with my external device

    i just updated my latest java but the update is causing problems with some external devices. So i would like to uninstall this latest java update and get back the previous one. That should solve to problems with my external device.
    Is this possible and how do i do that?
    Anyone who responds thanks for that!
    Juko
    I am running
    Hardware Overview:
      Model Name:          Mac Pro
      Model Identifier:          MacPro1,1
      Processor Name:          Dual-Core Intel Xeon
      Processor Speed:          2,66 GHz
      Number of Processors:          2
      Total Number of Cores:          4
      L2 Cache (per Processor):          4 MB
      Memory:          6 GB
      Bus Speed:          1,33 GHz
      Boot ROM Version:          MP11.005D.B00
      SMC Version (system):          1.7f10
      Serial Number (system):          CK7XXXXXXGP
      Hardware UUID:          00000000-0000-1000-8000-0017F20F82F0
    System Software Overview:
      System Version:          Mac OS X 10.7.5 (11G63)
      Kernel Version:          Darwin 11.4.2
      Boot Volume:          Macintosh HD(2)
      Boot Mode:          Normal
      Computer Name:          Mac Pro van Juko de Vries
      User Name:          Juko de Vries (jukodevries)
      Secure Virtual Memory:          Enabled
      64-bit Kernel and Extensions:          No
      Time since boot:          11 days 20:39
    Message was edited by Host

    Java 6 you can't as Apple maintains it, and Java 7 you could if you uninstall it and Oracle provides the earlier version which they likely won't his last update fixed 37 remote exploits.
    Java broken some software here and there, all you'll have to do is wait for a update from the other parties.

  • I've been getting the error message "The disk you inserted was not readable by the computer". I can't open system preferences, disk utility, or Time Machine. I'm guessing it has something to do with my external hard drive, although it hasn't been touched.

    I've been getting the error message "The disk you inserted was not readable by the computer". I can't open system preferences, disk utility, or Time Machine. I'm guessing it has something to do with my external hard drive, although it hasn't been touched lately, but I can't figure out how to solve the problem. Any suggestions? Thank you!

    Thanks for your quick response. I had a look at your discussion... I tried it on a Windows machine and I thought that was compatible with ExFAT?
    Therefore I need to attempt to use my external hard drive with a machine that boasts OS X 10.6.5 or above and then it should work?
    Thanks

  • I back up with an external hard drive using time machine.  I am trying to reload my iphoto library from an earlier date then it will let me.  How do I get to an earlier date in time machine?

    I back up with an external hard drive using time machine.  I am trying to reload my iphoto library but it won't let me get back to a date that I need to.  How do I do this?

    Try Pondini's articles;
    http://pondini.org/TM/15.html - scroll down to the pink box for iPhoto restoation.
    Also http://pondini.org/TM/15A.html to clarify how to use the timeline.

  • Hello i have a problem my mac butoos up but cant get to move de curser with the trackpad or external mouse please help

    Hello i have a problem my mac butoos up but cant get to move de curser with the trackpad or external mouse please help

    Try a PRAM reset.
    Instructions here > Resetting the PRAM

Maybe you are looking for

  • Concurrent Program Open in XML format Instead of PDF in R12

    Hi , I register 1 concurrent program and set its output in "XML" also attach this CP with XML template , when i run CP it show warning but output show in XML format instead of PDF format which is define in XML Template . Below text is log file of CP

  • Mail in Mavericks is Extremely Slow and a Resource Hog

    Since upgrading to Mavericks it is taking a very long time to fetch mail, and during this wait my computer is pretty much non-responsive.  (For example, fetching 56 emails using my webmail client took 4 seconds, while fetching the same 56 emails usin

  • Formatting a string

    Hello All Is there a way I can use format specifiers with variables? OK so I need to format a string to be a certain length equal to the longest string I am using. So what I would like to use is something like: %xs where x is the number of the length

  • ALV one  cell as checkbox based on some conditions

    Hi All,    I have a requirement which is as follows: For every NEW VBELN, I need a checkbox in the ALV. So, the output should look like this :-   Checkbox     VBELN   otherFields   Required      11111         42   Not Req.      11111         43   Req

  • 9iAS javac is running well but also want to compile Servlets

    Dears! I have installed Oracle 9iAS on Windows NT4.I want to develop servlet & JSP using Oracle 9iAS. I have tried compiling my servlet in Command Prompt after setting up the PATH for the JSDK & JDK shipped with 9iAS but i got the following error: Pa