SQL Search by Red-Gate is a great tool for searching within database objects. It is invaluable on brown field projects where you work with existing databases. My recent experience was working with a database which had hundreds of Stored procedures, Views, Triggers etc. I had to find out all objects which used a particular table. SQL Search made this job a breeze. SQL Search does a text search across all database objects so you can also look for things like column names.
Taking an example of Northwind database. You could to search for all database objects which have the word “customer” in their text. Below is a screenshot showing the search results.
The best thing is that SQL Search is free.
Recently I was working with some hierarchical data stored in SQL Server. The data was related to products where each product is a package which includes other packages which in turn can include individual products. The data was stored in a table where a a product row had a parentId column which indicated the parent of that product. This is a how we have stored hiearchies in tables. The solution has worked for years but is it the most efficient way to store hiearchichal data? Perhaps not. That’s why SQL Server 2008 had a data type called hierarchyId. This post is about working with the data type. Rather than divulging details of the application I’m working on commercially, I will use Northwind database as an example to demonstrate concepts talked in here.
Basic Setup
Northwind database has a table called Employees. This table stores information about an Employee and it also stores information about who an employee reports to. This structure is maintained by using a ReportsTo column in Employees table which links to EmployeeId within the same table.
As the objective here is to store this information using hierarchyId type, I created a new table called Employees2. To make things simple I only included EmployeeId, LastName and FirstName columns other than EmployeeNode which stores the hierarchical information and PlaceINHieararchy which indicates the place of a particular employee in organizational hierarchy. For example employee A can report to Employee B who reports to Employee C, so employee A’s place in hierarchy is 3.
This is the script I used to create Employees2 table.
CREATE TABLE Employees2 ( EmployeeNode hierarchyid NOT NULL PRIMARY KEY NONCLUSTERED, EmployeeId INT NOT NULL, LastName NVARCHAR(20) NOT NULL, FirstName NVARCHAR(10) NOT NULL, PlaceInHierarchy AS EmployeeNode.GetLevel() )
Populating Data
To have a meaningful example I decided to insert some data into Employees2 table from Employees table. This script inserts data into Employees2 table. It may not be the best way to insert this data especially me using a temp table. But this is a dirty script which means that I’ll only run it once so I am not too worried about its elegance.
WITH Emp AS ( SELECT '/'+CAST(EmployeeId AS VARCHAR(49)) AS PATH, EmployeeId FROM dbo.Employees b WHERE b.ReportsTo IS NULL UNION ALL SELECT CAST(Emp.path+'/'+CAST(b.EmployeeId AS VARCHAR(4)) AS VARCHAR(50)), b.EmployeeId FROM dbo.Employees b JOIN Emp ON b.ReportsTo = Emp.EmployeeId) SELECT * INTO #temp FROM Emp
INSERT INTO Employees2 ( EmployeeNode, EmployeeId, LastName, FirstName ) SELECT CAST( t.PATH+'/' AS hierarchyId) , b.EmployeeID, b.LastName, b.FirstName FROM #temp t JOIN dbo.Employees b ON t.EmployeeId = b.EmployeeId ORDER BY 1
A simple select from Employees2 table which shows data inserted into employees2 table.
Writing .NET Code
After creating a table and inserting data my first thought was how can I use Entity Framework or LINQ To SQL to do CRUD on Employees2 table. Unfortunately those are not valid options. Microsoft did not provide any support to work with hierarchyId data type in either Entity Framework or LINQ To SQL. A major draw back which I hope will be addressed in future versions of these ORMs.
Lack of support for hierarcyId data type in Entity Framework and LINQ To SQL does not mean that you don’t have any options. Good old raw ADO.NET is still around and comes in handy when working with hierarchyId data type. Another good thing is that Sql Server data type hierarchyId is available as SqlHierarchyId struct in Microsoft.SqlServer.Types assembly. To use the struct I added a reference to the Microsoft.SqlServer.Types assembly. The location of this assembly on my machine is
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies
Next I wanted to write some code which can retrieve data from employees2 table and display it on a console. This method fetches all rows form employees2 table and displays the EmployeeNode column. Note how I store the value of EmployeeNode column into a employeeNode SqlHierarchyId struct and then I call a ToString() method on the struct.
static void GetEmployeeNodes() { using (SqlConnection cn = new SqlConnection(connectionString)) { string query = "SELECT * FROM employees2"; SqlCommand cmd = new SqlCommand(query, cn); cn.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { SqlHierarchyId employeeNode = new SqlHierarchyId(); employeeNode = (SqlHierarchyId)reader["EmployeeNode"]; Console.WriteLine("Employee Node = " + employeeNode.ToString()); } } }
Output of the method looked like this.
I also wrote a method which displays ancestors for a particular employee. Getting an ancestor for a node is done by calling GetAncestor method on employeeNode which is of type SqlHierarchyId .
static void GetEmployeeDetails(int employeeId) { using (SqlConnection cn = new SqlConnection(connectionString)) { string query = "SELECT * FROM employees2 WHERE employeeId = " + employeeId.ToString(); SqlCommand cmd = new SqlCommand(query, cn); cn.Open(); SqlDataReader reader = cmd.ExecuteReader(); string output = string.Empty; while (reader.Read()) { SqlHierarchyId employeeNode = new SqlHierarchyId(); employeeNode = (SqlHierarchyId)reader["EmployeeNode"]; Console.WriteLine("Employee Node = " + employeeNode.ToString()); output = string.Format("{0} {1}", reader["LastName"], reader["FirstName"]); var ancestorNode = employeeNode.GetAncestor(1); while (!ancestorNode.IsNull) { using (SqlConnection cn2 = new SqlConnection(connectionString)) { query = "Select * from employees2 where EmployeeNode=hierarchyid::Parse(@node)"; SqlCommand cmd2 = new SqlCommand(query, cn2); cmd2.Parameters.AddWithValue("@node", ancestorNode.ToString()); cn2.Open(); SqlDataReader reader2 = cmd2.ExecuteReader(); while (reader2.Read()) { output += string.Format("/{0} {1}", reader2["LastName"], reader2["FirstName"]); } ancestorNode = ancestorNode.GetAncestor(1); } } } Console.WriteLine(output); } }
The output I got.
A bit about SqlHierarchyId struct
SqlHierarchyId struct provides other methods like GetDescendant, GetLevel, GetRoot etc. to retrieve more information. In my personal opinion I think that Microsoft needs to do a little more work on this and make it more useful. Of course the best thing to do will be to provide support for hierarchyId data type in Entity Framework and LINQ To SQL (if it’s not already dead).
I hope you enjoyed reading the post as much as I enjoyed writing it and learning something I didn’t know.
LINQPad is a must have tool for all .NET developers who write LINQ queries. It allows you to write and execute LINQ queries without compiling your code. In this post I will show you how to setup LINQPad to work along with Entity Framework.
The way LINQPad works with Entity Framework is that it consumes the EDM you would have generated by using Visual Studio. Your model could be in a class library and LINQPad can use that. For this example I have already created a class library project which contains my model. The model is generated over Northwind database.
After successfully compiling my project I launched LINQPad and clicked on Add connection. A dialog box appears which allows you to choose a data context. You can either build a context by connecting to a data source or you can build one from an assembly. In this case I selected the second radio button and clicked on Entity Framework.

Click Next and LINQPad then gives you an option to browse for the assembly. Click on browse next to “Path to custom assembly” and browse to the assembly which contains the model.
Once an assembly which contains a Entity Framework model is selected, LINQPad shows the models within that assembly.
Click OK and OK again on the LINQPad Connection dialog. LINQPad is now connected to the model and you can run queries against it.
Visual Studio 2010 Feature pack is now available for download. You must have access to MSDN subscribers download to get the Feature pack. Here is a list of what’s included straight from the download page.
Testing features:
- Use Microsoft Test Manager to capture and playback action recordings for Silverlight 4 applications.
- Create coded UI tests for Silverlight 4 applications with Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.
- Edit coded UI tests using a graphical editor with Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.
- Use action recordings to fast forward through manual tests that need to support Mozilla Firefox 3.5 and 3.6.
- Run coded UI tests for web applications using Mozilla Firefox 3.5 and 3.6 with Microsoft Visual Studio 2010 Premium or Visual Studio 2010 Ultimate.
Code visualization and modeling features (requires Visual Studio 2010 Ultimate):
- Use the Generate Code command to generate skeleton code from elements on UML class diagrams. You can use the default transformations, or you can write custom transformations to translate UML types into code.
- Create UML class diagrams from existing code.
- Explore the organization and relationships in C, C++, and ASP.NET projects by generating dependency graphs.
- Import elements from UML sequence diagrams, class diagrams, and use case diagrams as XMI 2.1 files that are exported from other modeling tools.
- Create links and view links from work items to model elements.
- Create layer diagrams from C or C++ code and validate dependencies.
- Write code to modify layer diagrams and to validate code against layer diagrams.
In an earlier post we looked at how to generate an Entity Data Model using Visual Studio 2010. The data model we created was not generated from a database. This is a follow up post in which we will generate a database using the model we have already created.
First thing we will do is open the project which contains our EDM. Next we will open Model Browser in Visual Studio.
To generate a database we need to right click on the root node within Model Browser and click on Generate Database from Model…
Generate Database Wizard is started and the first step is to specify a valid connection to a database. We can create a New Connection which connects to a blank database called MyBank. We can also instruct the wizard to save the connection string in App.config file.
Second step in the wizard generates and displays the SQL script which will create database objects as per our EDM.
After clicking Finish on the wizard a new file of type .sql is added to the project. The script which was generated by the wizard is saved in this file.

Upon executing the generated script our database objects are created.

Few days ago I finished reading Programming Entity Framework Second Edition by Julia Lerman. This is a review of the book.
Julia has written a book which targets a broad spectrum of EF expertise. If you are a beginner then this book is for you to learn Entity Framework. If you are an expert then this book is for you to learn advance Entity Framework concepts. Her writing style is seldom found in technical books these days. The ability to write chapters that just flow one after another is not something many technical authors these days can accomplish. The book was very easy to read with sensible examples and well balanced code to content ratio.
I am a LINQ To SQL kinda guy and I’ve always had something against Entity Framework. I guess a part of it was my first benchmark which I did with Entity Framework version 1.0 and I was shocked to see abysmal performance. My second reason for staying away from EF was the fear of learning LINQ To Entities. This book took that fear away after one reading of the chapter on LINQ To Entities. BTW: Entity Framework 4 is a much better ORM than its predecessor and it is my preferred choice now. Microsoft has addressed most of the issues with performance.
Back to the book review. One thing which underwhelms me about programming books is either they have too much code or they don’t have much code at all. Julia maintained a perfect balance between code examples and explanatory text.
Chapters on Customizing Entities, POCOs and performance optimization are by themselves worth the money and time you’ll spend reading this book.
Overall a well written, highly enjoyable and substantially informative book.
Julia also maintains a site for this book LearningEntityFramework.
This article shows you how to generate an Entity Data Model for Entity Framework 4 using Visual Studio 2010. Entity Data Model is widely known by its acronym EDM. A common misconception among developers is that a EDM is always backed up by a database. This is not accurate as we will see in this article. A database is a storage medium to store the data processed via EDM. Database schemas could also be different from EDM and this difference is resolved by using mapping concepts when the need comes to persist or load data from a physical database.
For this article we will create a model for a fictitious bank called MyBank. To get started we will create a project of type Class Library in Visual Studio 2010. Next we will add a new item of type ADO.NET Entity Data Model

Entity Data Model wizard then starts and on the first window of the wizard we are given a choice of either generating our model from an existing database or creating a blank model. For this article we will go with the later. Once we click Finish, our blank model is generated for us. As our model is blank, we will need to create some entities within our model for our Bank. Let’s start by creating a customer entity. By this time our project also contains a MyBank.edmx file and if it is not open then we can open it by double clicking on the file. This opens up the Entity Model Designer where we will create our entities. So the customer entity first.
To create our customer entity we right-click on and empty area in the designer and select Entity…

This brings up the Add Entity dialog box where we will enter basic details such as Entity Name, Base type which will be none in this case and Entity set. We will also check the Create key property. It indicates that our customer entity will have a property which will be its unique identifier. We can go with the name “Id” or supply our own name. We will stick with “Id”.

After clicking OK we see our newly created entity in the designer.

At this point customer entity can only store Id for customer. Storing just an Id for a customer is a bit useless regardless of the bank being fictional or not. We will add some more fields to store other information such as name, date of birth etc. To do this we can right-click on customer entity and then click Add –> Scalar Property. Scalar properties in EDM are used to store what I call base-level information which in this case will be first name, last name and date of birth. Navigation Properties are used to store relationships with other entities for example a customer could have accounts in which case we could put a Accounts navigation property on customer entity. For now we will go with scalar property.

We will add three properties here FirstName, LastName and DateOfBirth.

By default all our newly added properties store data of type string. This is okay for FirstName and LastName but won’t work well for DateOfBirth. We will now change the data type for DateOfBirth. Best way to do this is by opening Model Browser window and then selecting a property and modifying its properties. Sounds a bit confusing? Don’t worry it’s very simple. To make our life easy we can pin Model Browser and Properties window so that they are both viewable at the same time.

Here by selecting DateOfBirth property in Model Browser we can change its data type in properties window.

We will now create another entity called Account. We will follow similar steps as we did while creating Customer entity. In Account entity we will create x fields
- Id: Primary identifier of Account
- AccountNumber: Used to store the actual account number.
- BranchNumber: Stores a code which indicates the branch where this account was opened.
- CurrentBalance: Obvious enough.
- CreatedDate: Obvious enough.
Now we should have two entities in our EDM, a Customer entity and an Account entity. Let’s say that a customer can have more than one account. To reflect this properly in our EDM we will create an Association. To create an Association we right-click on the designer then click Add –> Association…

We are now presented with a dialog where we can supply information for this association.

Because we only have two entities within our designer, Visual Studio has acted clever and read our mind. It has already filled in all the information we need to create this association. We will quickly go through some of what’s already in the dialog box. First thing we have is the name for Association, second and more important is the two end-points it has created (note: this has nothing to do with WCF endpoints). First end point describes the relationship from Customer’s side and the second end point describes the relationship from Account’s side. In Multiplicity drop-down we can see that there are many accounts for a customer. We will now click OK.
Our entities now indicate visually that a one to many relationship exists between customer and account. We can also see that Navigation properties have also been added to both Account and Customer entities.

We have successfully created an Entity Data Model for a fictitious bank which stores information about customers and their accounts. This EDM does not store information in a database. However it is fully functional EDM and we can use it within an application of course the data we create will not be persisted anywhere. In a future article we will see how to generate a physical database form this Entity Data Model.
Once in a while I have to step out of the known environment of TFS and VSS and find myself in SVN land. Honestly I don’t mind SVN at all. In fact I think that certain features in SVN are much more intuitive and overall it’s a good source control system. If you work with Visual Studio and use SVN for source control then you need a SVN client which integrates well with Visual Studio. Till now there has been Visual SVN, but recently Axosoft announced their own product called Rocket SVN. I downloaded and installed Rocket SVN and I am using it with an online SVN repository. I have to say that I am impressed. Other than few icons which can be tidied up, the tool works without any issues.
Rocket SVN which is integrated with Visual Studio provides easily access information on pending changes.

You also get a repository explorer and a working copy explorer.

Also within the Solution Explorer, Rocket SVN indicates with little icons the files that have changed and the files which have not.
I’ve been running Rocket SVN for last 3 days and I’m very happy with the tool.
Rocket SVN is available for free download. Axosoft has indicated that sometime in future they will start charging for the product.
This post is to mark a little milestone for ThereforeSystems. My second post on this site was a LINQ To SQL Tutorial which was a basic tutorial to get the reader started with LINQ To SQL. This post has also been one of the most popular I have ever written. I don’t check the site too often due to a busy schedule with work and family. However yesterday when I looked at the site I found that LINQ To SQL crossed 100,000 views. Even though this is miniscule compared to traffic that some other more established sites receive, I nevertheless thought this was a mini milestone which should be marked and celebrated.
As always, I thank the visitors and hope that content on ThereforeSystems has been helpful.
This example shows you how to retrieve the name of temporary folder for your operating system using Java code.
All it takes is one line of code to get this information.
public static void main(String[] args) {
String property = System.getProperty("java.io.tmpdir");
System.out.println(property);
}
In this post I will show you how to establish a connection to Microsoft SQL Server from NetBeans IDE.
I use a Mac so the screenshots here are from Mac but NetBeans IDE is the same on all other platforms. There should not be any differences.
First thing we need to do is download the JDBC driver for Microsoft SQL Server from Microsoft. Current version of driver is 3.0 and it can be downloaded here. Download the drivers for UNIX and extract the archive on your machine. Once you have extracted the archive you’ll get a folder sqljdbc_3.0 under which there is another folder enu. Within enu are the jar files which implement JDBC drivers.
Now we will start the process to establish our connection to SQL Server from NetBeans. First thing click on Services tab and the Right Click on Databases and then click on New Connection.

You will see this window. Next to Driver Name click on the drop-down and choose New Driver…

Here click on the Add button and browse to your jar file for SQL Server JDBC driver.

NetBeans is now aware of SQL Server JDBC driver. You can now start creating the connection to SQL Server. Enter the details for SQL Server. You will need the IP address, port which by default is 1433 and username and password.

Click OK and you will be connected to SQL Server.
On the Server tab in NetBeans under Database you’ll see your SQL Server. You can browse server objects, view tables, stored procedures etc.

You can also run SQL queries on your SQL Server from NetBeans IDE.

The title of this post “Running Glassfish In Verbose Mode From NetBeans” is slightly misleading because what I am showing here is a way to view Glassfish logs within NetBeans IDE.
To start Glassfish in verbose mode on a command prompt or Terminal on a mac you’ll use this command.
asadmin start-domain –verbose
This will show you a nice verbose log of Glassfish activity on the Terminal.
From NetBeans all you need to do is start Glassfish as you normally would.

Now click on View Server Log and you’ll see a log of all Glassfish activity in NetBeans IDE.

Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML

