Sunday, September 14, 2008

How to install adventureworks on SQL Server 2008

1. download and run the SQL2008.AdventureWorks_OLTP_DB_v2008.x86 from http://www.codeplex.com/MSFTDBProdSamples

The program does not actually attach the database to sql server. It only creates a backup that can be restored. You now will need to do some additional configuring to SQL Server.

2. You need to enable FILESTREAM
http://msdn.microsoft.com/en-us/library/cc645923.aspx

3. Next run the following script

EXEC sp_configure filestream_access_level, 2
RECONFIGURE

4. Finally, you run a script that restores the backup of the installed database.

C:\Program Files\Microsoft SQL Server\100\Tools\Samples
Open RestoreAdventureWorks2008 and modify the set path:

SET @source_path = 'C:\Program Files\Microsoft SQL Server\100\'

Now, you should be able to run the TSQL and the database will be created in the following folder
C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA

Remember to refresh your database listing.

Friday, August 22, 2008

Linq - A Basic Understanding

LINQ (Language Integrated Query) is provides a universal way to query your data and objects.
You use LINQ to query objects, SQL and XML.

Linq relies heavily on delegates, anonymous methods and lambda expressions.

The foundation layout is as follows:
  • Delegates exist for situations in which you want to pass methods around to other methods.
  • An anonymous method is a block of code that is used as the paremeter for the delegate.
  • Lambda expresions can be used with delegate types.

Using lambda expression reduces the number classes.

Lamba expressions can be used any place where type is a delegate.

The method that is invoked by the delegate does not need the exact same types ad defined by the delegate declaration. Convariance and contra-variance are possible.

  • Return Type Convariance is when the return type can derive from the type defined in the delegate.
  • The term parameter type contra-variance means that the parameters defined by the delegate might differ in the method that is called by the delegate.

To the left of the Lambda operator => are the parameters. It is ok not to added the parameter types because they are resolved by the compiler. The right side of the Lambda operator defines the implementation. With anonymous methods, curly brackets and the return statement are required. With Lambda expressions the syntax elements are not required because they are done by the compiler in any case. If you have move than one statement on the right side of the Lambda operator, curly brackets and the return stement are possible.

LINQ example

var query = from r in BroncRider.GetChampions() where r.State == "SD" orderby r.Wins decending select r;

for each (BroncRider in query) {Console.Writeline("{0:A}", r);

Notes:

  • where r.State == "SD" is converted to Where (r => r.State == "SD")
  • .orderby r.Wins decending is converted to OrderByDecending(r => r.wins)

The query expression must begin with a from clause and end with a select or group clause.

When the query expression is defined during runtime, the query does not run. The query runs when the items are iterated.

Let's have a look once more at the extension method Where(). This extension method makes use of the yield return statement to return the elements where the predicate is true. Because the yield return statement is used, the compiler creates an enumerator and returns the items as soon as they are access from the enumeration.

The collection is also to be sorted. This does not happen when the query is defined. Instead the iteration happens with the foreach statement, where all the items are iterated. Basically, the sort happens whenever you do a foreach. If you add items to the collection and later iteratate the items they will be sorted.

Thursday, July 03, 2008

How to synch Infragistics Grid with the form detail.

Infragistics

Infragistics sample of how to synch a grid and form detail only works if the grid is not allowed to be sorted.  Instead of using the grid's row position.  The record position of the underlying binding source should be used.

ugGradingLocation - is the Infragistics grid

ScopingScenarioTypicalGradingSecBindingSource - is the binding source for the grid and form detail.

 
  Sub GridSynchWithForm()

' Use CurrencyManager to set position (this will handle sorted grids)
If Me.ugGradingLocation.ActiveRow IsNot Nothing Then

Dim cmGrid As CurrencyManager = DirectCast(BindingContext(ugGradingLocation.DataSource, Me.ugGradingLocation.DataMember),

_ CurrencyManager)
Dim cmForm As CurrencyManager = Me.BindingContext(Me.ScopingScenarioTypicalGradingSecBindingSource)

If cmForm.IsBindingSuspended Then
cmForm.ResumeBinding()
End If


cmForm.Position = cmGrid.Position

'If the grid could not be synched with the from detail
'Assume the grid is adding a row and temporary suspend binding.
If cmForm.Position <> cmGrid.Position Then
cmForm.SuspendBinding()
End If
End If

End Sub
 
Called when the following events occur:
ugGradingLocation_AfterRowActivate
ugGradingLocation_AfterRowInsert
ugGradingLocation_AfterRowUpdate
 

Wednesday, July 02, 2008

DotNetNuke Installation Trouble Shooting

  • If you are using windows VISTA, prior to unzipping the file, change the file property settings. You need to "unblock" the file. This is under the general settings tab.
  • Read the readme file. It has importatant instructions like renaming files and setting up security. For example, rename release.config to web.config.
  • Grant access to the database folder to NETWORKSERICE
  • You may need to coment out the ScriptModule references in the WebConfig. You will know when you get an error.
  • wizard i infiinte loop at "Run Database Installation Scripts"


Once you gotten to the page with "infinite loop" track back using back button
up to the initial page and select Auto instead. At that point your connection
string and other settings are already saved to web.config, so Auto will
just run and do what you wanted. Not sure why, but on local machine, it
always gives me that problem. I never had it out on a remote server,
though. Also, it is hardly an infinite loop. It seems to me that the wizard
just dies internally for some odd reason and, since I got the workaround, I
just don't care to dig any deeper. :)

Thursday, November 02, 2006

Shout out to Horizon Data Processing

Horizon Data Processing is a great software development company. They have some of the most technically advance and business know how in the industry.

Monday, January 30, 2006

Using DataSets vs. DataReaders

DataSet
1. Create a database connection
2. Store query in a DataAdapter
3. Populate the Dataset with the Fill method
4. Create a DataView
5. Bind the DataView to list-bound control

DataReader
1. Create a database connection
2. Open a database connection
3. Store query in SqlCommand
4. Populate the DataReader with the ExecuteReader command
5. Call the Read method for each record, and the method Get for each field.
6. Manually display data
7. Close the DataReader and the connection

Creating a DataReader

To minimize the difficulty of such situations, the DataReader is designed to produce a read-only, forward-only stream that is returned from the database. Only one record at a time is ever in memory.

  • Call reader for each record
  • Get Fields
  • Call close to free up the reader and the connection

A DataReader keeps the connection open until the DataReader is closed.

The initial positioning in the DataReader is before the first record; therefore, you must call Read before accessing any data. When no more records are available, the Read method returns false.

Reading Fields form the current record
To retrieve the fields from the current record, call an appropriate Get method(for example GetDateTime, settable, GetInt32, or GetString). The parameter of the Get method is the ordinal value of the field that you want to read. For example, the following code reads the CustomerId and CompanyName fields from the current record of the DataReader by using the GetString method:

Dim customerId As String = myReader.Getstring(0)
Dim companyName As String = myReader.GetString(1)

You can also reference the fields of data in the current record of the DataReader by name, and the call the appropriate conversion function, as shown in the example code:

Dim customerId As String = myReader("CustomerId).ToString()
Dim companyName As String = myReader("CompanyName).ToString()

By name is preferred for readability purposes.

Looping Through All Records
  • you can use a While loop
While myReader.Read()
...
End While

Closing the DataReader
While the DataReader is in use, the associated connection is busy serving the DataReader. Therefore, you must call Close to close the DataReader when you are finished using it.

If Not(myReader IS Nothing) Then
myReader.Close()
End If

If mySqlConnection.State = ConnectionState.Open Then
mySqlConnection.Close()
End IF

Choosing between DataReader and DataSet

The benefit of using a DataSet is that it gives you a disconnected view of the database. For long-running applications, this is often the best method. However, for Web applications developers usually perform short, simple operations with each request, such as displaying data. For such brief operations, it is usually not effecient to maintain a DataSet object. In such cases, you can use a DataReader.

Use a Dataset when you need to do any of the following
  • Transmit data between tiers or from an XML web service
  • Interact dynamically with data, as when binding to a Windows Forms control or combing and relating data from multiple sources.
  • Cache data locally in your application
  • Provide a hierarchical XML view of rlational data, and use tools like an XSL Transformation or an XML Path Language (XPATH) Query on your data.
  • Perform extensive processing on data without requiring an open connection to the datasource, leaving the connection available to other clients.

If you do not require the functionality that is provided by the Dataset class, you can improve the performance of you application by using the DataReader class to return your data in a read-only /forward only fashion. Although, the DataAdapter class uses a DataReader to fill the contents of a DataSet, by using the DataReader class instead you can secure the following performance benefits:
  • The memory that would be consumed by the DataSet would instead be available.
  • The processing that would be required to create and fill the contents of the DataSet will not be needed.

Friday, January 27, 2006

ADO DataReader Vs DataAdapter

DataReader Objects
A data reader is like a firehose cursor. It is simular to a read-only/forward-only view of the data. A DataReader is returen after a commeand is executed against a database. Use this when you want to populate a listbox or a read only stand alone Table. Use the SqlCommand objects and ExecuteREader method to transfer data into a DataReader. The datareader behavior is database specific.

DataSet Objects
The dataset represents a cache of data, with database-like behavior. The dataset is a collection of one or more tables, more specifically, they are DataTable objects. The DataSet contains tables, columns, relationsships, constraints, and data. The DatasetSet is always disconnected. the Dataset provides a rich object model to employ passing data between various components. The dataset behavior is completely consistant and independent of the underlying database. As changes are made to the Dataset, they are tracked in a way similar to the way changes are tracked in a word processing document.

A dataset contain a collection of DataTable objects. A DataTable repesents the table's schema. A datatable also contains a collection of rows representing the data that is contained in the table.

You use the SqlDataAdapter object and the Fill method to populate the Dataset.

DataView Objects
A dataview enables you to crate different views of the data that is stored in a DataTable, a capability that is often used in data-binding applications. By using a DataView, you can display the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.

Note: This is different from the Select method of the DataTable, which returns a DataRow array from a table in accordance with a particular filter and/or sort order, and whose content reflects changes to the underlying table, but whose membership and ordering remain static.

The dynamic capabilities of the DataView make it ideal for data-binding applications.

DataAdapter Object
The DataAdapter class allows for the retrieval and saving of data between a DataSet and the source data store. It is responsible for pulling ou data from the physical store and pushing it into data tables and relations. The DataAdapter class is also responsible for transmitting any update, insertion, or deletion to the physical database. There are four command objects to make any updates: UpdateCommand, InsertCommand, DeleteCommand and SelectCommand.

Use the Fill method to populate the dataset table.
Because the Fill with not cause primary key and unique key information to be retrieved unless the AddWithKey is specified, you must set the must set the MissingSchemaAction property to AddWithKey.

mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

Name spaces for ADO.NET

  • System.Data - base object and types for ADO.NET
  • System.Data.OleDb - Managed OLE DB data store objects
  • System.Data.SqlClient - SQL Server-specific implementation of ADO.NET objects
  • System.Data.Common - Classes shared by the .NET providers
  • System.Data.SqlTypes - SQL data types

Looping throw a DataSet table

Because the data is stored a a collection of rows in a table....

dim my DataRow as DataRow
For Each myDataRow In myDataSet.Tables("Customers").Rows
Console.Writeline(" CustomerId: {0}, myDataRow("CustmerId").ToString())
Next

Use the .Delete to remove a row from a DataSet.
Use the .RejectChanges on the Dataset to restore a row back to the orginal state.

The RowChanging event allows you to access both the original and new values to decide whether you want the edit to proceed.


Saturday, December 31, 2005

How to data bind an Enum to a ComboBox

How to data bind an Enum to a ComboBox.

Assuming the following Enum:
Public Enum MyEnum
[Me]
Myself
Irene
End Enum

You could use this code to bind it:
Me.ComboBox1.DataSource = System.Enum.GetValues(GetType(MyEnum))

Or
Me.ComboBox1.DataSource = System.Enum.GetNames(GetType(MyEnum))

To convert the name back to a value use:
System.Enum.Parse(GetType(MyEnum), Me.ComboBox1.Text)

Tuesday, November 22, 2005

Screen Design

When exiting a screen, prompt the user to determine if unsaved changes should be saved. When possible, saves should be done by screen. An exception would be a quick pop-up form to collect information.


It is ok to use bound controls.


It is good to merge and inherit menus.

Designing Modules and Procedures


Give procedures and modules descriptive names
Give every procedure a single exit point
Give every procedure a clearly defined scope (Public, Friend, Private)

Use parameters to pass data between procedures,
Always validate parameters – never assume you have good data
Use enumerations when a parameter accepts only a small set of values

Call procedures in a consistent and self-documenting manner

Return values from a function by using the Return statement.

This in conjunction with the Finally for code cleanupIt is good to raise events and have modules respond to the event as necessary.

Variables

Note: in VB a long is now an integer in .Net and a .NET long is much larger than it ever was before.

Never use the plus sign for string concatenation.

Use the Option Strict to enforce strict typing


Use the string’s length property to determine whether it’s empty
Bad: if strMyString = “” Then …
Good: If strMyString.Length = 0


Use positive variables for Boolean values
Examples: bIsUnderAge, bIsEndOfFile

Take advantage of the .NET array features like the use of hash tables and dictionary arrays.

Commenting Code

  1. Document the purpose of the code
  2. Document the why rather than the how
  3. If you need to violate good programming style, explain why in the code.
  4. Comment before writing code
  5. Use solid-character comment lines only for major comments
  6. Avoid creating comment boxes
  7. Give each procedure a comment header
    Purpose
    Accepts
    Returns
  8. Document code processes by using inline comments

Handling Exceptions

Handling Exceptions
All top level events will have exception handling to prevent the application from crashing.
Important: Variables declared within the Try block of an exception handler have block scope – they aren’t available to any Catch or Finally blocks, and they aren’t available outside the Try..End Try construct. For this reason, it’s best to leave declarations outside of the Try block unless the declaration has an inherent risk of throwing an exception.

Important: You should always include a Catch section to deal with exceptions.

Ignoring an exception (by not including a Catch section) is worse than not including exception trapping to begin with because exceptions will occur and neither you nor your customers will know about them

When specifying multiple Catch blocks for an exception handler, order them from most specific to least specific. This ensures that exceptions are handled correctly.

A central exception handler will be used for unpredictable errors to keep exception handling from becoming tedious.

Programming Objects

Programming Objects

  1. Early bind objects whenever possible.
  2. Use .Net objects rather than API calls whenever possible.
  3. Expose public properties, not public variables.
  4. Always close what you open
    m_dstContacts.Close()
    m_cnADOConnection.Close()
  5. Use Overloads to create a property or method with the same name as another property or method but with a different argument list.
  6. Create Dispose methods for all your objects.
    Place cleanup code in that method
    Call the Dispose on each and every object that has one, once you are finished with the object.
    Note: When creating shared components, you must be careful about the code you place in a custom Dispose method. Releasing the resource could cause problems for the remaining clients that are sharing the object.
  7. Create constructors for a class whenever possible
    Note: You cannot use the keyword Overloads on constructors, even though creating multiple constructors is indeed creating overloaded methods.
  8. Add a finalizer to a class only when necessary.
    Caution: You should avoid referencing other objects in your finalize code because the nature of garbage collection is such that the finalizers aren’t executed in any special order.
  9. Use With..End With to increase performance and make code more readable.

Events should have only two arguments

Events should have only two arguments:
an Object argument named sender,
which represents the the object that's raising the event;
and an argument named e,
which exposes teh event's arguments throught its fields or properties. This second
argument should be a System.EventsArgs object or an object whose class inherits from
the System.EventsArg (The name of such a class should end with EventsArgs.)
This naming convention requires only a little extra code today, but it might simplify
your job a great deal tommorrow.

Friend Sub NewAgreement()
RaiseEvent CreateNew(Me, New System.EventArgs)
End Sub

Monday, November 21, 2005

re-throwing an exception with a paramenter it resets StackTrace

How about Throw without the ex

The Throw statement without an agrument rethrows the current exception object and must appear in a Catch clause to be valid.

If you throw an exception with a paramenter it resets StackTrace property of the exception object (as if a brand-new exeption were created).

The version without an argument is perferable for rethrowing the same exception becuase it lets the caller routine determine exactly where the exception occured.

Additional Notes:
- Throw an InvalidOperationException if a property or method call occurs when the object is in a state that can't handle the method call
- Throw and ArgumentException (or a class that inherits for the AgrumentException) if a bad argument is passed.
- Stick to predefined exceptions, and don't define custom exceptions unless strictly required.
- Don't throw expetions for relatively common errors, such as end-of -file or timeout; instead return a special value to the caller.