this.Blog.Find(entry => entry.IsHelpful);
 Wednesday, April 30, 2008
Using Miado with Powershell

One of the nice things about Miado is that it wraps a lot of tedious, repetitive ADO.Net code and therefore greatly reduces the amount of code you actually do need to write. 

Here's a quick example.  One of the tasks I had to do at my last last gig was upload a set of prices from a CSV file every month.  I wrote a PowerShell script to use Miado to do the DB inserts:

  1. function BuildSql()   
  2. {   
  3.   # build the SQL   
  4.   $sb = New-Object System.Text.StringBuilder   
  5.   $sb.Append("insert into VendorPrice(VendorID, FixedPrice, VariablePrice, ");   
  6.   $sb.Append("CreationDate, LastUpdatedDate) ");   
  7.   $sb.Append("values(@VendorID, @FixedPrice, @VariablePrice, ");   
  8.   $sb.Append("current_timestamp, current_timestamp)");   
  9.     
  10.   return $sb.ToString();   
  11. }   
  12.   
  13. [Reflection.Assembly]::LoadFile("C:\dev\VS2008\Miado\src\Miado\bin\Release\Miado.dll")   
  14.   
  15. # setup the configuration   
  16. $connString = "Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabase;User Id=user;Password=passw0rd"  
  17. $dbProvider = System.Data.SqlClient.SqlClientFactory::Instance;
  18. $repository = Miado.MiadoRepositoryFactory::CreateMiadoRepository($dbProvider, $connString);
  19.   
  20. $sql = BuildSql;   
  21.   
  22. foreach ( $row in Import-Csv prices.csv | Select VendorID, FixedPrice, VariablePrice )    
  23. {  
  24.   $repository.ExecuteNonQuery($sql.ToString(), $row.VendorID, $row.FixedPrice, $row.VariablePrice);     
  25. }  

As you can see, the script iterates over each row in the CSV file and inserts a record for each row.  There's no need to write all the code necessary to create the DbConnection and DbCommand objects, nor do you have to dynamically create DbParameter objects for each row.  Just pass the SQL and the variables (in order of replacement) into the IMiadoRepository.ExecuteNonQuery() call and Miado takes care of all the ugly details.  One line for each insert - that's it!

Edit: This post was updated to reflect the changes in the 0.7.10530.1


Kick it on DotNetKicks.com
Wednesday, April 30, 2008 11:38:38 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | Miado | Powershell