Tuesday, December 13, 2016

PetaPoco nuances and triggers

The PetaPoco shortcut ppDB.Insert(obj) or ppDB.Update(obj) cannot be used if the database table has trigger because the following error will be generated:

“The target table '[db table name]' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.
  

This is because the sql generated by PetaPoco is the following:
INSERT INTO [db table] ([col1], [col2], ... [coln]) OUTPUT INSERTED.[identityColName] VALUES (@0,@1,...@n)

PetaPoco nuances with transactions

PetaPoco has a couple of really easy ways of inserting/updating records. 

The following are the object initializations used below:

private PetaPoco.Database ppObj = new PetaPoco.Database("[connection string name]");
ClassName.ObjName objInstance = new ClassName.ObjName();


One way is to create an object based upon the class created from the database.tt file and use the insert()/update() method:
objInstance.Insert();

As I found out, this approach does not allow you to rollback a transaction. If you run the insert()/update() on the PetaPoco object instead then you can rollback transactions:
ppObj.Insert(objInstance);

Monday, December 12, 2016

Trapping emails generated in C# when there is no SMTP server

If you need to generate emails in your app, I’ve found a way to test them in the dev environment. Visit http://smtp4dev.codeplex.com/downloads/get/269147 and download the tool. The executable in the ZIP file will spawn a mini-smtp server. Click the “options” button and then the “server” tab. Set the listen interface to 127.0.0.1, I think you can leave the port at 25.
Add the following to your web.config file in the <configuration> section. Port will be whatever number you specified for smtp4dev:
<system.net>
   <mailSettings>
     <smtp>
       <network host="localhost" port="25" />
     </smtp>
   </mailSettings>
</system.net>
Write your code as normal to generate & send the email. Smpt4dev will notify you that you’ve received an email and you can click the “view” button to see the email message in Outlook.
The app sits in the tool tray under “hidden icons”, so no need to start the executable again. Closing the smpt4dev UI doesn’t end the process and running the exe again will produce a “server failed” message as shown below. View hidden icons in the tool tray close any extra occurrences of smtp4dev.