SlideShare una empresa de Scribd logo
1 de 15
Descargar para leer sin conexión
MyGeneration                                          dOOdads Quick Reference

                                TABLE OF CONTENTS

Preparation      Database Design Tips                                        2
                 Installation and Setup                                      2
                 CRUD procedures                                             3
                 dOOdads for tables                                          3
                 dOOdads for views                                           3
                 Concrete classes                                            3
                 ConnectionString                                            4
                 Enhancing concrete classes                                  4

Common tasks     Retrieve all rows                                           5
                 Retrieve one row by primary key                             5
                 Retrieve one or more rows based on other criteria           5
                 Insert row                                                  5
                 Delete row                                                  5
                 Update row                                                  5
                 Get number of rows                                          5
                 Iterate through rows                                        5
                 Set the sort expression                                     6
                 Set the filter expression                                   6
                 Calculated columns                                          6
                 Set ConnectionString explicitly                             6
                 Set the current row                                         6
                 String properties                                           6

DynamicQuery     WhereParameter enums                                        8
                 Retrieve rows                                               8
                 Limit columns returned                                      9
                 Order By                                                    9
                 Select Distinct                                             9
                 Select Top N                                                9
                 Parentheses                                                 9
                 GenerateSQL                                                 9
                 ReturnReader                                                9

Data binding     Datagrid                                                   10
                 ComboBox                                                   10
                 DropdownList                                               10

Special functions LoadFromSql*                                              11
                  FromXml/ToXml                                             12
TransactionMgr                                                              13
Object model                                                                14
Addenda           Creating a typed dataset                                  15




Steve Corn                          Page 1 of 15                      7/27/2005
MyGeneration                                                dOOdads Quick Reference


                                       PREPARATION

Database Design Tips (MS SQL Server)                                                   TOC
1. For each table, I use a single identity column as the primary key. You can use GUIDs or
    multi-column primary keys too.
2. For each table, I add a column named "RowVersion" with a datatype of timestamp.
   (dOOdads will use this column to handle concurrency.)
3. Since dOOdads doesn't handle joins, I prepare the joins ahead of time by creating
   views.
4. Wherever possible, I design my database and application to minimize problems with
   nulls. When I do run into problems with nulls, I use String Properties.

Install MyGeneration and add the dOOdads project to your solution                            TOC
1. Download from http://www.mygenerationsoftware.com and install.
2. The installer puts the application in Program Files.
3. Add the dOOdads project to your Visual Studio solution:
         a. Right-click on the Solution item and choose "Add Existing Project".
         b. Navigate to the dOOdads project (C:Program FilesMyGeneration
            ArchitecturesdOOdadsVB.NetMyGeneration.dOOdads
            dOOdads.vbproj) and select. The dOOdads project will now appear in your
            solution.
         c. In the DbAdapters folder, open the "Entity" corresponding to your database
            (e.g. “SqlClientEntity”). Find "Build Action" in "Properties" and set to "Compile".
            Repeat for the "DynamicQuery" adapter.
4. Build the dOOdads project.

Get your .Net project ready for dOOdads
1. Add a reference to the dOOdads assembly to your project:
       a. Right-click on "References" and choose "Add Reference".
       b. On the Projects tab, double-click on the dOOdads project and click "OK".
2. Add 2 folders to the project:
       a. DAL (data access layer) - to hold the abstract classes created by
           MyGeneration
       b. BLL (business logic layer) - to hold the concrete classes that inherit the
           abstract classes




Steve Corn                               Page 2 of 15                                7/27/2005
MyGeneration                                            dOOdads Quick Reference

With MyGeneration:

Create the CRUD stored procedures                                                    TOC
Start MyGeneration.
1. Edit | DefaultSettings and set the database.
2. Select the template that will generate stored procedures that will work with
    dOOdads (e.g., "SQL Stored Procedures").
3. Run the template, select the tables you want (usually all of them), and click OK.
4. The generated DDL will be copied to the Clipboard and displayed in the Output
    page.
5. Go to the query tool for your database, paste the DDL code, and execute to create
    the stored procedures.

Create the dOOdads for tables                                                       TOC
1. Return to MyGeneration and select the template that will generate the dOOdads
   code for tables (eg, "dOOdads Business Entity").
2. Run the template, change the output path to the DAL folder in your project, select
   the tables you want (usually all), and execute to create the abstract classes.
3. The class name for each of these dOOdads will start with an underscore.

Create the dOOdads for views                                                          TOC
1. Select the template that will generate the dOOdads code for views (e.g., "dOOdads
   Business View").
2. Run the template, change the output path to the BLL folder in your project, select the
   views you want (usually all), and execute to create the concrete classes.
3. The class name for each of these dOOdads will NOT start with an underscore
   because they are already concrete classes in the BLL folder.

Write the concrete classes corresponding to the abstract classes                     TOC
1. Run the Concrete Classes template, saving the code in the BLL folder of your project
2. or write the classes yourself as follows:

       Public Class Employees
          Inherits _Employees
       End Class




Steve Corn                            Page 3 of 15                             7/27/2005
MyGeneration                                             dOOdads Quick Reference

With Visual Studio:

Include the dOOdads in your project
1. Right-click on the DAL folder and select “Include in project”.
2. Repeat for the BLL folder.

Enter the connection string in the AppSettings section of the config file             TOC
1. Put the connection string in the web.config (for web apps) or app.config (for
    WinForms apps) file and name it "dbConnection".
2. If the connection string is not explicitly assigned in the dOOdad, the dOOdad will
    look in the config file for "dbConnection".

Enhance your concrete classes                                                         TOC
If you wish to add any custom properties and methods to your business entities, you can
do so in the concrete classes at any time. If your data structure changes and you need
to recreate your dOOdads, the code you add here will not be overwritten.

For processing related to the business entity that normal dOOdads methods won't
handle, consider using the special LoadFromSql* methods (see SPECIAL FUNCTIONS) here
in the concrete class.




Steve Corn                             Page 4 of 15                            7/27/2005
MyGeneration                                         dOOdads Quick Reference

                                  COMMON TASKS
Prep
Dim oEmps As New Employees
Dim EmpID as Long

Retrieve all rows                                                         TOC
oEmps.LoadAll

Retrieve one row by primary key                                           TOC
oEmps.LoadByPrimaryKey(EmpID)

Retrieve one or more rows based on other criteria                         TOC
See DYNAMIC QUERY

Insert row                                                                TOC
With oEmps
.AddNew()
   .EM_LastName = "Smith"
   .EM_HireDate = Now
.Save()
End With
EmpID = oEmps.EM_ID   'oEmp returns new key value

Delete row (also see SET THE CURRENT ROW)                                 TOC
'already have the desired row set as the current row, then...
With oEmps
   .MarkAsDeleted()
   .Save()
End With

Update row (also see SET THE CURRENT ROW)                                 TOC
'already have the desired row set as the current row, then...
With oEmps
   .EM_LastName = "Jones"
   .Save()
End With

Get number of rows                                                        TOC
oEmps.RowCount

Iterate through rows                                                      TOC
With oEmps
   If .RowCount > 0 Then
       .Rewind() 'move to first record
       Do While .MoveNext
           'do something with the current row
       Loop
   End If
End With




Steve Corn                            Page 5 of 15                   7/27/2005
MyGeneration                                                     dOOdads Quick Reference

Set the sort expression                                                                             TOC
With oEmps
   .Sort = .ColumnNames.EM_LastName & " DESC"
End With


Set the filter expression                                                                           TOC
With oEmps
   .Filter = .ColumnNames.EM_LastName & " LIKE A%"
End With

Calculated columns (used by your application in the dataset, but not stored in the database)        TOC
AddColumn
SetColumn
GetColumn
IsColumnNull
SetColumnNull

Example:
If oEmps.LoadAll() Then
   Dim col As DataColumn
   col = oEmps.AddColumn(“FullName”, Type.GetType(“System.String”))
   col.Expression = oEmps.ColumnNames.LastName + “ + ‘, ‘ + “ +
   oEmps.ColumnNames.FirstName
Dim fullName As String
fullName = CType(oEmps.GetColumn(“FullName”), String)

ConnectionString                                                                    TOC
Define the connection string in your config file, naming it "dbConnection".
If you choose not to do that or you are using more than one database, you can use the
ConnectionString property of the dOOdad.
oEmps.ConnectionString =
   “User=me;Password=pw;Database=Employees;DataSource=MyServer”

Set the current row                                                                   TOC
Before you can change values in a row or delete a row, the row to change must be
assigned to the DataRow property (the “current row”). This is accomplished in several
ways:
1. LoadAll or Query.Load – the current row is the first row
2. LoadByPrimaryKey – the current row is the returned row
3. AddNew – the current row is the new row before it is inserted into the database
4. Rewind and MoveNext – Rewind sets the current row to the first row in the existing
    DataTable; MoveNext sets the current row to the row it moves to.

String properties                                                                       TOC
Another very handy feature of dOOdads is called “string properties”. This simplifies the
handling of null values in both string and non-string columns. For each data column in
the dOOdad, there is a string property in addition to the column property.




Steve Corn                                  Page 6 of 15                                       7/27/2005
MyGeneration                                         dOOdads Quick Reference

For example:
        oEmps.EM_Salary and oEmps.s_EM_Salary
        oEmps.EM_HireDate and oEmps.s_EM_HireDate

Check if a value is null:
        if oEmps.s_EM_Salary = “”
        if oEmps.s_EM_HireDate = “”

Set a value to null:
        oEmps.s_EM_Salary = “”
        oEmps.s_EM_HireDate = “”




Steve Corn                            Page 7 of 15                   7/27/2005
MyGeneration                                             dOOdads Quick Reference

                                  DYNAMIC QUERY

The dynamic query property of the dOOdad (MyDoodad.Query) allows you to select
records in an ad hoc fashion without having to write a bunch of little stored procedures.
(And its design precludes the possibility of SQL-injection attacks.)

WhereParameter enums (see object model diagram for C#)                                 TOC


Conjunctions (WhereParameter.Conj)
       AND_
       OR_
       UseDefault

Directions (WhereParameter.Dir)
       ASC
       DESC

Operands (WhereParameter.Operand)
       Between
       Equal
       GreaterThan
       GreaterThanOrEqual
       In_
       IsNotNull
       IsNull
       LessThan
       LessThanOrEqual
       Like_
       NotEqual

Retrieve rows                                                                          TOC
With oEmps
   .Where.EM_LastName.Value = "%A%"
   .Where.EM_LastName.Operator = WhereParameter.Operand.Like_
   .Query.AddConjunction(WhereParameter.Conj.OR_)
   .Where.EM_HireDate.BetweenBeginValue = "'1/1/2001 00:00AM'"
   .Where.EM_HireDate.BetweenEndValue = "'12/31/2001 11:59PM'"
   .Where.EM_HireDate.Operator = WhereParameter.Operand.Between
   .Query.Load()
End With




Steve Corn                            Page 8 of 15                              7/27/2005
MyGeneration                                              dOOdads Quick Reference

Limit columns returned                                                                 TOC
With oEmps
   .Query.AddResultColumn(.ColumnNames.EM_ID)
   .Query.AddResultColumn(.ColumnNames.EM_LastName)
   .Query.Load
End With
(NOTE: .Save() cannot be called after limiting columns.)

Order By                                                                               TOC
oEmps.Query.AddOrderBy(.ColumnNames.EM_HireDate, WhereParameter.Dir.DESC)

Select Distinct                                                                        TOC
oEmps.Query.Distinct = True

Select Top N                                                                           TOC
oEmps.Query.Top = 10

Parentheses                                                                            TOC
oEmps.Query.OpenParenthesis
oEmps.Query.CloseParenthesis

GenerateSQL                                                                         TOC
A diagnostic function that returns the SQL statement created for the dynamic query.
Better to use LastQuery.
(NOTE: After calling this you cannot load the object.)

LastQuery                                                                              TOC
A string property that contains the SQL text of the most recently generated SQL
statement.

ReturnReader                                                                           TOC
Dim rdr as SqlClient.DataReader
rdr = oEmp.ReturnReader




Steve Corn                                 Page 9 of 15                           7/27/2005
MyGeneration                                                           dOOdads Quick Reference

                                             DATA BINDING

Data binding to a datagrid (Web app)                                             TOC
1. Create a typed Dataset (.xsd file) with a DataTable to match the dOOdad columns.
2. Add the Dataset to your form.
3. Add a DataView and assign the new Dataset.DataTable to its Table property.
4. Bind the datagrid to the DataView and design the DataGrid as you wish.
5. In the code-behind, change the DataView's Table property to the DefaultView
   property of the dOOdad:
         If oEmps.LoadAll() Then
            dvEmps = oEmps.DefaultView
            dgEmps.DataSource = dvEmps
            dgEmps.DataBind()
         End If
(NOTE: The only reason to use a dataset here is to help design the datagrid visually at design time. The dataset
is not referenced in code at all.)
6. If you wish, you can store the dataview in the Session as follows:
         Session("dvEmps") = oEmps.DefaultView
         dvEmps = Session("dvEmps")


Data binding to a ComboBox (WinForms app)                                                                   TOC
'get data
With oEmps
   .Query.AddResultColumn(.ColumnNames.EM_ID)
   .Query.AddResultColumn(.ColumnNames.EM_LastName)
   .Query.AddOrderBy(.ColumnNames.EM_LastName, WhereParameter.Dir.ASC)
   .Query.Load()
End With

'bind to combobox
With cmbEmployees
   .Datasource = oEmps.DefaultView
   .DisplayMember = oEmps.ColumnNames.EM_LastName
   .ValueMember = oEmps.ColumnNames.EM_ID
   .DataBind()
End With

Data binding to a DropDownList (Web app)                                                                    TOC
'get data
With oEmps
   .Query.AddResultColumn(.ColumnNames.EM_ID)
   .Query.AddResultColumn(.ColumnNames.EM_LastName)
   .Query.AddOrderBy(.ColumnNames.EM_LastName, WhereParameter.Dir.ASC)
   .Query.Load()
End With

'bind to drop-down list
With ddlEmployees
   .Datasource = oEmps.DefaultView
   .DataTextField = oEmps.ColumnNames.EM_LastName
   .DataValueField = oEmps.ColumnNames.EM_ID
   .DataBind()
End With



Steve Corn                                     Page 10 of 15                                        7/27/2005
MyGeneration                                                 dOOdads Quick Reference

                                      SPECIAL FUNCTIONS

Executing custom stored procedures and SQL statements:                                TOC


   Method Name               Overloads                   Returns       Fills dOOdad
LoadFromSql           (s)                       Boolean (true if any       Yes
                      (s, p)L                   rows are found)
                      (s, p, c)L
LoadFromSqlNoExec (s)                           Integer (number of          No
                  (s, p)L                       rows affected)
                  (s, p, c, t)L
LoadFromSqlReader     (s)                       DataReader                  No
                      (s, p)L
                      (s, p, c)L
LoadFromSqlScalar     (s)                       Object (first column        No
                      (s, p)L                   of first row in
                      (s, p, c, t)L             resultset)
LoadFromRawSql        (s, p)P                   Boolean (true if any       Yes
                                                rows are found)
s : stored procedure (or SQL statement depending on command type)
p : parameters (ListDictionaryL or ParamArrayP)
c : CommandType (sproc, table, SQL statement)
t : timeout (-1 is standard)

These functions can be used to extend the concrete class (in fact, they cannot be
accessed outside of the concrete class).

See examples on next page.




Steve Corn                               Page 11 of 15                        7/27/2005
MyGeneration                                       dOOdads Quick Reference


LoadFromSql* Examples:
LoadFromSql
Dim Parms As ListDictionary = New ListDictionary
With MyDoodad
   Parms.Add(.Parameters.EM_ID, 152)
   If .LoadFromSql("proc_GetSpecialEmployee", Parms) Then
       ...
   End If
End With

LoadFromSqlNoExec
NbrOfChecks = MyDoodad.LoadFromSqlNoExec("proc_CalculatePayroll")

LoadFromSqlReader
Dim rdr As New SqlDataReader
rdr = MyDoodad.LoadFromSqlReader("proc_GetSpecialEmployee", Parms)

LoadFromSqlScalar
Dim EarliestHireDate As DateTime
Parms.Clear
Parms.Add("@EM_Active", 1)
EarliestHireDate = MyDoodad.LoadFromSqlScalar("GetEarliestHireDate", Parms)

LoadFromRawSql
MyDoodad.LoadFromRawSql("SELECT MIN(EM_HireDate) FROM tEmployees WHERE
   EM_Active = {0}","1")

FromXml / ToXml                                                                TOC
Dim oEmps As New Employees
oEmps.Query.Load()
oEmps.FirstName = “Griffinski”          ‘Change first row
oEmps.GetChanges()                      ‘oEmps.RowCount now = 1
dim xml As String = oEmps.ToXml         ‘changed row is saved to string as XML

‘Now reload that single record into a new Employees object and save it
Dim oEmpsClone As New Employees
oEmpsClone.FromXml(xml)                 ‘load row values from the XML string
oEmpsClone.Save()




Steve Corn                        Page 12 of 15                          7/27/2005
MyGeneration                                     dOOdads Quick Reference


                                                                      TOC
                             TRANSACTIONMGR
Dim tx as TransactionMgr
tx = TransactionMgr.ThreadTransactionMgr()
Try
    Dim oEmps As New Employees
    oEmps.AddNew()
    oEmps.FirstName = “Jimmy”
    oEmps.LastName = “Doe”
    Dim oProds As New Products
    oProds.AddNew()
    oProds.ProductName = “Lunch Box”
    oProds.Discontinued = False
    tx.BeginTransaction()
    oEmps.Save()
    oProds.Save()
    tx.CommitTransaction()
Catch ex As Exception
    tx.RollbackTransaction()
    tx.ThreadTransactionMgrReset()
End Try




Steve Corn                       Page 13 of 15                   7/27/2005
MyGeneration                                                dOOdads Quick Reference

                                                                                             TOC
                                dOOdads Object Model

(This is the C# flavor. There are slight differences in the Enums in the VB version.)




Steve Corn                              Page 14 of 15                                   7/27/2005
MyGeneration                                             dOOdads Quick Reference

                                       ADDENDA

How to create a typed dataset:                                                          TOC
Assuming you’re in Visual Studio:
   1. From the menu, click File | Add new item.
   2. Select DataSet from the item types presented and give it a name.
   3. When the .xsd appears, you can do one of two things:
       (a) Drag and drop a table or view from Server Explorer, or
       (b) Hand-build a DataTable:
           i. Right-click on it and select Add | New element.
           ii. A DataTable will be created; type the name of the table in place of
                “element 1”.
           iii. List the fields and datatypes to match your dOOdad. This can match a
                table, a view, the fields selected in a dynamic query – anything that a
                dOOdad can represent.
   4. Save the xsd.
   5. Go to your web form and add a dataset from the Toolbox. Select the dataset
                you just created.




Steve Corn                            Page 15 of 15                              7/27/2005

Más contenido relacionado

Destacado

New fortran
New fortranNew fortran
New fortranhoahanh
 
Web Development (Basic)
Web Development (Basic)Web Development (Basic)
Web Development (Basic)Philippe Lee
 
Effective use of powerpoint as a presentation tool
Effective use of powerpoint as a presentation toolEffective use of powerpoint as a presentation tool
Effective use of powerpoint as a presentation toolpatricia1224
 
Dafpus revisi` nonik aisyah rohman-g41150606
Dafpus revisi` nonik aisyah rohman-g41150606Dafpus revisi` nonik aisyah rohman-g41150606
Dafpus revisi` nonik aisyah rohman-g41150606Nonik Rohman
 
Approach plan
Approach planApproach plan
Approach planlakhan75
 
동영상 제작 워크샵
동영상 제작 워크샵동영상 제작 워크샵
동영상 제작 워크샵Philippe Lee
 
Longest Common Subsequence
Longest Common SubsequenceLongest Common Subsequence
Longest Common SubsequenceSwati Swati
 
Treball del ordinador
Treball del ordinadorTreball del ordinador
Treball del ordinadordjgero
 

Destacado (14)

Jonite 2016 Catalogue
Jonite 2016 CatalogueJonite 2016 Catalogue
Jonite 2016 Catalogue
 
Aquaduct - Brochure 2017
Aquaduct - Brochure 2017Aquaduct - Brochure 2017
Aquaduct - Brochure 2017
 
New fortran
New fortranNew fortran
New fortran
 
Web Development (Basic)
Web Development (Basic)Web Development (Basic)
Web Development (Basic)
 
Bathroom & wetroom brochure
Bathroom & wetroom brochureBathroom & wetroom brochure
Bathroom & wetroom brochure
 
Effective use of powerpoint as a presentation tool
Effective use of powerpoint as a presentation toolEffective use of powerpoint as a presentation tool
Effective use of powerpoint as a presentation tool
 
Dafpus revisi` nonik aisyah rohman-g41150606
Dafpus revisi` nonik aisyah rohman-g41150606Dafpus revisi` nonik aisyah rohman-g41150606
Dafpus revisi` nonik aisyah rohman-g41150606
 
Approach plan
Approach planApproach plan
Approach plan
 
동영상 제작 워크샵
동영상 제작 워크샵동영상 제작 워크샵
동영상 제작 워크샵
 
Aquascape - Brochure 2017
Aquascape - Brochure 2017Aquascape - Brochure 2017
Aquascape - Brochure 2017
 
Aqualevel - Brochure 2017
Aqualevel - Brochure 2017Aqualevel - Brochure 2017
Aqualevel - Brochure 2017
 
Longest Common Subsequence
Longest Common SubsequenceLongest Common Subsequence
Longest Common Subsequence
 
Gimp
GimpGimp
Gimp
 
Treball del ordinador
Treball del ordinadorTreball del ordinador
Treball del ordinador
 

Similar a Doodads quickref

Make it test-driven with CDI!
Make it test-driven with CDI!Make it test-driven with CDI!
Make it test-driven with CDI!rafaelliu
 
Solving performance problems in MySQL without denormalization
Solving performance problems in MySQL without denormalizationSolving performance problems in MySQL without denormalization
Solving performance problems in MySQL without denormalizationdmcfarlane
 
Akiban Technologies: Renormalize
Akiban Technologies: RenormalizeAkiban Technologies: Renormalize
Akiban Technologies: RenormalizeAriel Weil
 
Akiban Technologies: Renormalize
Akiban Technologies: RenormalizeAkiban Technologies: Renormalize
Akiban Technologies: RenormalizeAriel Weil
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConqeTimeline, LLC
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning TalksBuilding Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning TalksAtlassian
 
Rule Engine & Drools
Rule Engine & DroolsRule Engine & Drools
Rule Engine & DroolsSandip Jadhav
 
GR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL SupportGR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL SupportGR8Conf
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseAndrew Eisenberg
 
NewSQL Database Overview
NewSQL Database OverviewNewSQL Database Overview
NewSQL Database OverviewSteve Min
 
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...inovex GmbH
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteDr Nic Williams
 

Similar a Doodads quickref (20)

Make it test-driven with CDI!
Make it test-driven with CDI!Make it test-driven with CDI!
Make it test-driven with CDI!
 
Solving performance problems in MySQL without denormalization
Solving performance problems in MySQL without denormalizationSolving performance problems in MySQL without denormalization
Solving performance problems in MySQL without denormalization
 
Akiban Technologies: Renormalize
Akiban Technologies: RenormalizeAkiban Technologies: Renormalize
Akiban Technologies: Renormalize
 
Akiban Technologies: Renormalize
Akiban Technologies: RenormalizeAkiban Technologies: Renormalize
Akiban Technologies: Renormalize
 
Scalax
ScalaxScalax
Scalax
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning TalksBuilding Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
 
Objective-C
Objective-CObjective-C
Objective-C
 
Rule Engine & Drools
Rule Engine & DroolsRule Engine & Drools
Rule Engine & Drools
 
GR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL SupportGR8Conf 2011: STS DSL Support
GR8Conf 2011: STS DSL Support
 
Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
NewSQL Database Overview
NewSQL Database OverviewNewSQL Database Overview
NewSQL Database Overview
 
Sql optimize
Sql optimizeSql optimize
Sql optimize
 
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
 
Linq to sql
Linq to sqlLinq to sql
Linq to sql
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 

Doodads quickref

  • 1. MyGeneration dOOdads Quick Reference TABLE OF CONTENTS Preparation Database Design Tips 2 Installation and Setup 2 CRUD procedures 3 dOOdads for tables 3 dOOdads for views 3 Concrete classes 3 ConnectionString 4 Enhancing concrete classes 4 Common tasks Retrieve all rows 5 Retrieve one row by primary key 5 Retrieve one or more rows based on other criteria 5 Insert row 5 Delete row 5 Update row 5 Get number of rows 5 Iterate through rows 5 Set the sort expression 6 Set the filter expression 6 Calculated columns 6 Set ConnectionString explicitly 6 Set the current row 6 String properties 6 DynamicQuery WhereParameter enums 8 Retrieve rows 8 Limit columns returned 9 Order By 9 Select Distinct 9 Select Top N 9 Parentheses 9 GenerateSQL 9 ReturnReader 9 Data binding Datagrid 10 ComboBox 10 DropdownList 10 Special functions LoadFromSql* 11 FromXml/ToXml 12 TransactionMgr 13 Object model 14 Addenda Creating a typed dataset 15 Steve Corn Page 1 of 15 7/27/2005
  • 2. MyGeneration dOOdads Quick Reference PREPARATION Database Design Tips (MS SQL Server) TOC 1. For each table, I use a single identity column as the primary key. You can use GUIDs or multi-column primary keys too. 2. For each table, I add a column named "RowVersion" with a datatype of timestamp. (dOOdads will use this column to handle concurrency.) 3. Since dOOdads doesn't handle joins, I prepare the joins ahead of time by creating views. 4. Wherever possible, I design my database and application to minimize problems with nulls. When I do run into problems with nulls, I use String Properties. Install MyGeneration and add the dOOdads project to your solution TOC 1. Download from http://www.mygenerationsoftware.com and install. 2. The installer puts the application in Program Files. 3. Add the dOOdads project to your Visual Studio solution: a. Right-click on the Solution item and choose "Add Existing Project". b. Navigate to the dOOdads project (C:Program FilesMyGeneration ArchitecturesdOOdadsVB.NetMyGeneration.dOOdads dOOdads.vbproj) and select. The dOOdads project will now appear in your solution. c. In the DbAdapters folder, open the "Entity" corresponding to your database (e.g. “SqlClientEntity”). Find "Build Action" in "Properties" and set to "Compile". Repeat for the "DynamicQuery" adapter. 4. Build the dOOdads project. Get your .Net project ready for dOOdads 1. Add a reference to the dOOdads assembly to your project: a. Right-click on "References" and choose "Add Reference". b. On the Projects tab, double-click on the dOOdads project and click "OK". 2. Add 2 folders to the project: a. DAL (data access layer) - to hold the abstract classes created by MyGeneration b. BLL (business logic layer) - to hold the concrete classes that inherit the abstract classes Steve Corn Page 2 of 15 7/27/2005
  • 3. MyGeneration dOOdads Quick Reference With MyGeneration: Create the CRUD stored procedures TOC Start MyGeneration. 1. Edit | DefaultSettings and set the database. 2. Select the template that will generate stored procedures that will work with dOOdads (e.g., "SQL Stored Procedures"). 3. Run the template, select the tables you want (usually all of them), and click OK. 4. The generated DDL will be copied to the Clipboard and displayed in the Output page. 5. Go to the query tool for your database, paste the DDL code, and execute to create the stored procedures. Create the dOOdads for tables TOC 1. Return to MyGeneration and select the template that will generate the dOOdads code for tables (eg, "dOOdads Business Entity"). 2. Run the template, change the output path to the DAL folder in your project, select the tables you want (usually all), and execute to create the abstract classes. 3. The class name for each of these dOOdads will start with an underscore. Create the dOOdads for views TOC 1. Select the template that will generate the dOOdads code for views (e.g., "dOOdads Business View"). 2. Run the template, change the output path to the BLL folder in your project, select the views you want (usually all), and execute to create the concrete classes. 3. The class name for each of these dOOdads will NOT start with an underscore because they are already concrete classes in the BLL folder. Write the concrete classes corresponding to the abstract classes TOC 1. Run the Concrete Classes template, saving the code in the BLL folder of your project 2. or write the classes yourself as follows: Public Class Employees Inherits _Employees End Class Steve Corn Page 3 of 15 7/27/2005
  • 4. MyGeneration dOOdads Quick Reference With Visual Studio: Include the dOOdads in your project 1. Right-click on the DAL folder and select “Include in project”. 2. Repeat for the BLL folder. Enter the connection string in the AppSettings section of the config file TOC 1. Put the connection string in the web.config (for web apps) or app.config (for WinForms apps) file and name it "dbConnection". 2. If the connection string is not explicitly assigned in the dOOdad, the dOOdad will look in the config file for "dbConnection". Enhance your concrete classes TOC If you wish to add any custom properties and methods to your business entities, you can do so in the concrete classes at any time. If your data structure changes and you need to recreate your dOOdads, the code you add here will not be overwritten. For processing related to the business entity that normal dOOdads methods won't handle, consider using the special LoadFromSql* methods (see SPECIAL FUNCTIONS) here in the concrete class. Steve Corn Page 4 of 15 7/27/2005
  • 5. MyGeneration dOOdads Quick Reference COMMON TASKS Prep Dim oEmps As New Employees Dim EmpID as Long Retrieve all rows TOC oEmps.LoadAll Retrieve one row by primary key TOC oEmps.LoadByPrimaryKey(EmpID) Retrieve one or more rows based on other criteria TOC See DYNAMIC QUERY Insert row TOC With oEmps .AddNew() .EM_LastName = "Smith" .EM_HireDate = Now .Save() End With EmpID = oEmps.EM_ID 'oEmp returns new key value Delete row (also see SET THE CURRENT ROW) TOC 'already have the desired row set as the current row, then... With oEmps .MarkAsDeleted() .Save() End With Update row (also see SET THE CURRENT ROW) TOC 'already have the desired row set as the current row, then... With oEmps .EM_LastName = "Jones" .Save() End With Get number of rows TOC oEmps.RowCount Iterate through rows TOC With oEmps If .RowCount > 0 Then .Rewind() 'move to first record Do While .MoveNext 'do something with the current row Loop End If End With Steve Corn Page 5 of 15 7/27/2005
  • 6. MyGeneration dOOdads Quick Reference Set the sort expression TOC With oEmps .Sort = .ColumnNames.EM_LastName & " DESC" End With Set the filter expression TOC With oEmps .Filter = .ColumnNames.EM_LastName & " LIKE A%" End With Calculated columns (used by your application in the dataset, but not stored in the database) TOC AddColumn SetColumn GetColumn IsColumnNull SetColumnNull Example: If oEmps.LoadAll() Then Dim col As DataColumn col = oEmps.AddColumn(“FullName”, Type.GetType(“System.String”)) col.Expression = oEmps.ColumnNames.LastName + “ + ‘, ‘ + “ + oEmps.ColumnNames.FirstName Dim fullName As String fullName = CType(oEmps.GetColumn(“FullName”), String) ConnectionString TOC Define the connection string in your config file, naming it "dbConnection". If you choose not to do that or you are using more than one database, you can use the ConnectionString property of the dOOdad. oEmps.ConnectionString = “User=me;Password=pw;Database=Employees;DataSource=MyServer” Set the current row TOC Before you can change values in a row or delete a row, the row to change must be assigned to the DataRow property (the “current row”). This is accomplished in several ways: 1. LoadAll or Query.Load – the current row is the first row 2. LoadByPrimaryKey – the current row is the returned row 3. AddNew – the current row is the new row before it is inserted into the database 4. Rewind and MoveNext – Rewind sets the current row to the first row in the existing DataTable; MoveNext sets the current row to the row it moves to. String properties TOC Another very handy feature of dOOdads is called “string properties”. This simplifies the handling of null values in both string and non-string columns. For each data column in the dOOdad, there is a string property in addition to the column property. Steve Corn Page 6 of 15 7/27/2005
  • 7. MyGeneration dOOdads Quick Reference For example: oEmps.EM_Salary and oEmps.s_EM_Salary oEmps.EM_HireDate and oEmps.s_EM_HireDate Check if a value is null: if oEmps.s_EM_Salary = “” if oEmps.s_EM_HireDate = “” Set a value to null: oEmps.s_EM_Salary = “” oEmps.s_EM_HireDate = “” Steve Corn Page 7 of 15 7/27/2005
  • 8. MyGeneration dOOdads Quick Reference DYNAMIC QUERY The dynamic query property of the dOOdad (MyDoodad.Query) allows you to select records in an ad hoc fashion without having to write a bunch of little stored procedures. (And its design precludes the possibility of SQL-injection attacks.) WhereParameter enums (see object model diagram for C#) TOC Conjunctions (WhereParameter.Conj) AND_ OR_ UseDefault Directions (WhereParameter.Dir) ASC DESC Operands (WhereParameter.Operand) Between Equal GreaterThan GreaterThanOrEqual In_ IsNotNull IsNull LessThan LessThanOrEqual Like_ NotEqual Retrieve rows TOC With oEmps .Where.EM_LastName.Value = "%A%" .Where.EM_LastName.Operator = WhereParameter.Operand.Like_ .Query.AddConjunction(WhereParameter.Conj.OR_) .Where.EM_HireDate.BetweenBeginValue = "'1/1/2001 00:00AM'" .Where.EM_HireDate.BetweenEndValue = "'12/31/2001 11:59PM'" .Where.EM_HireDate.Operator = WhereParameter.Operand.Between .Query.Load() End With Steve Corn Page 8 of 15 7/27/2005
  • 9. MyGeneration dOOdads Quick Reference Limit columns returned TOC With oEmps .Query.AddResultColumn(.ColumnNames.EM_ID) .Query.AddResultColumn(.ColumnNames.EM_LastName) .Query.Load End With (NOTE: .Save() cannot be called after limiting columns.) Order By TOC oEmps.Query.AddOrderBy(.ColumnNames.EM_HireDate, WhereParameter.Dir.DESC) Select Distinct TOC oEmps.Query.Distinct = True Select Top N TOC oEmps.Query.Top = 10 Parentheses TOC oEmps.Query.OpenParenthesis oEmps.Query.CloseParenthesis GenerateSQL TOC A diagnostic function that returns the SQL statement created for the dynamic query. Better to use LastQuery. (NOTE: After calling this you cannot load the object.) LastQuery TOC A string property that contains the SQL text of the most recently generated SQL statement. ReturnReader TOC Dim rdr as SqlClient.DataReader rdr = oEmp.ReturnReader Steve Corn Page 9 of 15 7/27/2005
  • 10. MyGeneration dOOdads Quick Reference DATA BINDING Data binding to a datagrid (Web app) TOC 1. Create a typed Dataset (.xsd file) with a DataTable to match the dOOdad columns. 2. Add the Dataset to your form. 3. Add a DataView and assign the new Dataset.DataTable to its Table property. 4. Bind the datagrid to the DataView and design the DataGrid as you wish. 5. In the code-behind, change the DataView's Table property to the DefaultView property of the dOOdad: If oEmps.LoadAll() Then dvEmps = oEmps.DefaultView dgEmps.DataSource = dvEmps dgEmps.DataBind() End If (NOTE: The only reason to use a dataset here is to help design the datagrid visually at design time. The dataset is not referenced in code at all.) 6. If you wish, you can store the dataview in the Session as follows: Session("dvEmps") = oEmps.DefaultView dvEmps = Session("dvEmps") Data binding to a ComboBox (WinForms app) TOC 'get data With oEmps .Query.AddResultColumn(.ColumnNames.EM_ID) .Query.AddResultColumn(.ColumnNames.EM_LastName) .Query.AddOrderBy(.ColumnNames.EM_LastName, WhereParameter.Dir.ASC) .Query.Load() End With 'bind to combobox With cmbEmployees .Datasource = oEmps.DefaultView .DisplayMember = oEmps.ColumnNames.EM_LastName .ValueMember = oEmps.ColumnNames.EM_ID .DataBind() End With Data binding to a DropDownList (Web app) TOC 'get data With oEmps .Query.AddResultColumn(.ColumnNames.EM_ID) .Query.AddResultColumn(.ColumnNames.EM_LastName) .Query.AddOrderBy(.ColumnNames.EM_LastName, WhereParameter.Dir.ASC) .Query.Load() End With 'bind to drop-down list With ddlEmployees .Datasource = oEmps.DefaultView .DataTextField = oEmps.ColumnNames.EM_LastName .DataValueField = oEmps.ColumnNames.EM_ID .DataBind() End With Steve Corn Page 10 of 15 7/27/2005
  • 11. MyGeneration dOOdads Quick Reference SPECIAL FUNCTIONS Executing custom stored procedures and SQL statements: TOC Method Name Overloads Returns Fills dOOdad LoadFromSql (s) Boolean (true if any Yes (s, p)L rows are found) (s, p, c)L LoadFromSqlNoExec (s) Integer (number of No (s, p)L rows affected) (s, p, c, t)L LoadFromSqlReader (s) DataReader No (s, p)L (s, p, c)L LoadFromSqlScalar (s) Object (first column No (s, p)L of first row in (s, p, c, t)L resultset) LoadFromRawSql (s, p)P Boolean (true if any Yes rows are found) s : stored procedure (or SQL statement depending on command type) p : parameters (ListDictionaryL or ParamArrayP) c : CommandType (sproc, table, SQL statement) t : timeout (-1 is standard) These functions can be used to extend the concrete class (in fact, they cannot be accessed outside of the concrete class). See examples on next page. Steve Corn Page 11 of 15 7/27/2005
  • 12. MyGeneration dOOdads Quick Reference LoadFromSql* Examples: LoadFromSql Dim Parms As ListDictionary = New ListDictionary With MyDoodad Parms.Add(.Parameters.EM_ID, 152) If .LoadFromSql("proc_GetSpecialEmployee", Parms) Then ... End If End With LoadFromSqlNoExec NbrOfChecks = MyDoodad.LoadFromSqlNoExec("proc_CalculatePayroll") LoadFromSqlReader Dim rdr As New SqlDataReader rdr = MyDoodad.LoadFromSqlReader("proc_GetSpecialEmployee", Parms) LoadFromSqlScalar Dim EarliestHireDate As DateTime Parms.Clear Parms.Add("@EM_Active", 1) EarliestHireDate = MyDoodad.LoadFromSqlScalar("GetEarliestHireDate", Parms) LoadFromRawSql MyDoodad.LoadFromRawSql("SELECT MIN(EM_HireDate) FROM tEmployees WHERE EM_Active = {0}","1") FromXml / ToXml TOC Dim oEmps As New Employees oEmps.Query.Load() oEmps.FirstName = “Griffinski” ‘Change first row oEmps.GetChanges() ‘oEmps.RowCount now = 1 dim xml As String = oEmps.ToXml ‘changed row is saved to string as XML ‘Now reload that single record into a new Employees object and save it Dim oEmpsClone As New Employees oEmpsClone.FromXml(xml) ‘load row values from the XML string oEmpsClone.Save() Steve Corn Page 12 of 15 7/27/2005
  • 13. MyGeneration dOOdads Quick Reference TOC TRANSACTIONMGR Dim tx as TransactionMgr tx = TransactionMgr.ThreadTransactionMgr() Try Dim oEmps As New Employees oEmps.AddNew() oEmps.FirstName = “Jimmy” oEmps.LastName = “Doe” Dim oProds As New Products oProds.AddNew() oProds.ProductName = “Lunch Box” oProds.Discontinued = False tx.BeginTransaction() oEmps.Save() oProds.Save() tx.CommitTransaction() Catch ex As Exception tx.RollbackTransaction() tx.ThreadTransactionMgrReset() End Try Steve Corn Page 13 of 15 7/27/2005
  • 14. MyGeneration dOOdads Quick Reference TOC dOOdads Object Model (This is the C# flavor. There are slight differences in the Enums in the VB version.) Steve Corn Page 14 of 15 7/27/2005
  • 15. MyGeneration dOOdads Quick Reference ADDENDA How to create a typed dataset: TOC Assuming you’re in Visual Studio: 1. From the menu, click File | Add new item. 2. Select DataSet from the item types presented and give it a name. 3. When the .xsd appears, you can do one of two things: (a) Drag and drop a table or view from Server Explorer, or (b) Hand-build a DataTable: i. Right-click on it and select Add | New element. ii. A DataTable will be created; type the name of the table in place of “element 1”. iii. List the fields and datatypes to match your dOOdad. This can match a table, a view, the fields selected in a dynamic query – anything that a dOOdad can represent. 4. Save the xsd. 5. Go to your web form and add a dataset from the Toolbox. Select the dataset you just created. Steve Corn Page 15 of 15 7/27/2005