Archive for the ‘SQL’ Category

September 24th, 2008

How NOT To Optimize LINQ Statements

About a month ago I was experimenting with different ways to optimize my LINQ queries against the IdeaPipe database, in order to improve the read times. I wanted to improve the read times because our new Facebook Application was being launched and I anticipated an increase in our traffic to the server, which is used to host IdeaPipe and the Facebook Application component.

Whenever I am trying to optimize SQL queries I fire up SQL Server Profiler and take a look at how the queries are performing. This helps me identify queries that are taking a longer time to execute and probably need to be looked at or re-thought. One of the queries that I identified as needing improvement was the following LINQ query:

Old Query

from i in source
join xgl in GroupIdeaLinks on i.IdeaId equals xgl.IdeaId into groupLinksGroup
from gl in groupLinksGroup.DefaultIfEmpty()
let visibility = (gl == null ? 'O' : gl.Group.VisibilityPermission)
let groupId = (gl == null ? -1 : gl.GroupId)
where visibility == 'O' || GroupMembers.Count(m => m.GroupId == groupId && m.IsApproved && m.UserId == userId && (visibility == 'G' || (m.RoleId & (int)Role.Manager) == 0)) == 1
select i;

That produced this monster of a SQL statement:

SELECT [t5].[IdeaId], [t5].[CategoryId], [t5].[UserId], [t5].[IsPopular], [t5].[PopularOn], [t5].[Title], [t5].[SafeDescription], [t5].[Description], [t5].[Path], [t5].[Score], [t5].[Rank], [t5].[ExternalLink], [t5].[VideoLink], [t5].[BumpUpCount], [t5].[BumpDownCount], [t5].[TotalBumpCount], [t5].[TotalCommentCount], [t5].[CreatedOn], [t5].[rowversion]
FROM (
    SELECT [t4].[IdeaId], [t4].[CategoryId], [t4].[UserId], [t4].[IsPopular], [t4].[PopularOn], [t4].[Title], [t4].[SafeDescription], [t4].[Description], [t4].[Path], [t4].[Score], [t4].[Rank], [t4].[ExternalLink], [t4].[VideoLink], [t4].[BumpUpCount], [t4].[BumpDownCount], [t4].[TotalBumpCount], [t4].[TotalCommentCount], [t4].[CreatedOn], [t4].[rowversion], [t4].[value],
        (CASE
            WHEN [t4].[test] IS NULL THEN @p1
            ELSE [t4].[GroupId]
         END) AS [value2]
    FROM (
        SELECT [t0].[IdeaId], [t0].[CategoryId], [t0].[UserId], [t0].[IsPopular], [t0].[PopularOn], [t0].[Title], [t0].[SafeDescription], [t0].[Description], [t0].[Path], [t0].[Score], [t0].[Rank], [t0].[ExternalLink], [t0].[VideoLink], [t0].[BumpUpCount], [t0].[BumpDownCount], [t0].[TotalBumpCount], [t0].[TotalCommentCount], [t0].[CreatedOn], [t0].[rowversion], [t2].[test], [t2].[GroupId],
            (CASE
                WHEN [t2].[test] IS NULL THEN @p0
                ELSE CONVERT(NChar(1),[t3].[VisibilityPermission])
             END) AS [value]
        FROM [Ideas].[Ideas] AS [t0]
        LEFT OUTER JOIN (
            SELECT 1 AS [test], [t1].[GroupId], [t1].[IdeaId]
            FROM [Groups].[GroupIdeaLink] AS [t1]
            ) AS [t2] ON [t0].[IdeaId] = [t2].[IdeaId]
        INNER JOIN [Groups].[Groups] AS [t3] ON [t3].[GroupId] = [t2].[GroupId]
        ) AS [t4]
    ) AS [t5]
WHERE (UNICODE([t5].[value]) = @p2) OR (((
    SELECT COUNT(*)
    FROM (
        SELECT
            (CASE
                WHEN ([t6].[GroupId] = [t5].[value2]) AND ([t6].[IsApproved] = 1) AND (([t6].[UserId]) = @p3) AND ((UNICODE([t5].[value]) = @p4) OR (([t6].[RoleId] & @p5) = @p6)) THEN 1
                WHEN NOT (([t6].[GroupId] = [t5].[value2]) AND ([t6].[IsApproved] = 1) AND (([t6].[UserId]) = @p3) AND ((UNICODE([t5].[value]) = @p4) OR (([t6].[RoleId] & @p5) = @p6))) THEN 0
                ELSE NULL
             END) AS [value]
        FROM [Groups].[GroupMembers] AS [t6]
        ) AS [t7]
    WHERE [t7].[value] = 1
    )) = @p7)

So I started playing around with the LINQ statement until I reduced the size of my SQL query significantly. The following is the result of that optimization:

New Query

var groupMembership = (from gm in GroupMembers
                       let visibility = gm.Group.VisibilityPermission
                       where visibility == 'O' || (gm.IsApproved && gm.UserId == userId && (visibility == 'G' || (gm.RoleId & (int)Role.Manager) == 0))
                       select gm.GroupId).Distinct();

from i in Ideas
join xgl in GroupIdeaLinks on i.IdeaId equals xgl.IdeaId into groupLinksGroup
from gl in groupLinksGroup.DefaultIfEmpty()
where gl == null || groupMembership.Contains(gl.GroupId)
select i;

Which outputs the following SQL query:

SELECT [t0].[IdeaId], [t0].[CategoryId], [t0].[UserId], [t0].[IsPopular], [t0].[PopularOn], [t0].[Title], [t0].[SafeDescription], [t0].[Description], [t0].[Path], [t0].[Score], [t0].[Rank], [t0].[ExternalLink], [t0].[VideoLink], [t0].[BumpUpCount], [t0].[BumpDownCount], [t0].[TotalBumpCount], [t0].[TotalCommentCount], [t0].[CreatedOn], [t0].[rowversion]
FROM [Ideas].[Ideas] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[GroupId], [t1].[IdeaId]
    FROM [Groups].[GroupIdeaLink] AS [t1]
    ) AS [t2] ON [t0].[IdeaId] = [t2].[IdeaId]
WHERE ([t2].[test] IS NULL) OR (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM (
        SELECT DISTINCT [t3].[GroupId]
        FROM [Groups].[GroupMembers] AS [t3]
        INNER JOIN [Groups].[Groups] AS [t4] ON [t4].[GroupId] = [t3].[GroupId]
        WHERE (UNICODE([t4].[VisibilityPermission]) = @p0) OR (([t3].[IsApproved] = 1) AND (([t3].[UserId]) = @p1) AND ((UNICODE([t4].[VisibilityPermission]) = @p2) OR (([t3].[RoleId] & @p3) = @p4)))
        ) AS [t5]
    WHERE [t5].[GroupId] = [t2].[GroupId]
    ))

As you can tell the second query is much more compact and it does the exact same thing as the first query. I was pretty proud of my self and riding high on my genius, until this happened:

Well this didn’t really happen, but you get the point. I quickly came down from my high when I tested the performance of the new query in SQL Server Profiler, and received these results from the two queries:

  • OLD QUERY (Reads 130, Durration 5)
  • NEW QUERY (Reads 218, Durration 28)

That is right my optimization increased the number of times SQL has to read the table by 68% and time it takes to execute by 460%. So I reversed all my changes and learned a lesson on how not to optimize a LINQ statement.

The moral of the story is you probably don’t need to optimize your SQL query through LINQ, just keep it simple and optimize your LINQ statement and leave the rest up to the professionals at Microsoft who created the LINQ to SQL expression query generator.

Tags: , , ,

Posted in C#, How To, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 7 Comments »

April 25th, 2008

Why isn’t Journalistic integrity important to Slashdot anymore?

Slashdot has been around for over a decade now and many tech nerds first cut their teeth on Slashdot as an information source for everything tech related, because it predated the blogging revolution by almost a half decade.  I can say with an almost certainty that every person who visits my blog each day, has at one point in their life read Slashdot.  I know this because, many of you like myself, for many years Slashdot was the first place you visited in the morning to checkout the latest nerd-news, and it was such an honor if one of your stories actually made it the front page.  Everything was bliss because the editors of Slashdot really tried to get good content to the viewers of the site, the editors were a little slanted towards the LAMP stack, but at least the content that made it to the front page was accurate.

Now like most journalism, no facts are checked, and stories are pushed through in order to driven an agenda.  For example:

500 Thousand MS Web Servers Hacked

Posted by kdawson on Friday April 25, @11:48AM
from the scream-and-shout dept.

andrewd18 writes “According to F-Secure, over 500,000 webservers across the world, including some from the United Nations and UK government, have been victims of a SQL injection. The attack uses an SQL injection to reroute clients to a malicious javascript at nmidahena.com, aspder.com or nihaorr1.com, which use another set of exploits to install a Trojan on the client’s computer. As per usual, Firefox users with NoScript should be safe from the client exploit, but server admins should be alert for the server-side injection. Brian Krebs has a decent writeup on his Washington Post Security Blog, Dynamoo has a list of some of the high-profile sites that has been hacked, and for fun you can watch some of the IIS admins run around in circles at one of the many IIS forums on the ‘net.”

Every person that reads my blog should have a basic understanding of why this title is 180 degrees out of whack with the actual article that is quoted.  If not here is the short description of what in this article, on Slashdot, is totally wrong and the editor who approved it kdawson should be fired for gross negligence.  Luckily most of the comments on the Slashdot article show a more intelligence and greater understanding of the actual problem than the Slashdot poster and editor.  But you shouldn’t have to read between the lines to get the actual story from the Slashdot article.

First of all SQL injections are a result of bad programming and are platform independent.  And are usually the result of concatenating a SQL string together in code instead of using parameters in your SQL queries.  So as you can imagine scripting languages like PHP and Old ASP have a ton of problems with SQL injection, which is unfortunate because these two languages are in the top 5 languages that run the web, luckily Old ASP has been decreasing because of ASP.NET.  However just to reiterate SQL injection can happen in any language on any platform because there are bad developers that use everything language and every platform.

So basically to say that 500,000 Microsoft web servers were hacked is a gross misrepresentation of the problem that was illustrated in the article.  The original F-Secure article had to clarify that this wasn’t Microsoft’s problem, probably because of the Slashdot article listed above.

We’ve been receiving some questions on the platform and operating systems affected by this attack. So far we’ve only seen websites using Microsoft IIS webserver and Microsoft SQL Server being hit. Do note that this attack doesn’t use any vulnerabilities in any of those two applications. What makes this attack possible is poorly written ASP and ASPX (.net) code.

If you are interested in seeing all the pages effected and if one of your pages is involved you can use this Google Link, however make sure to take precautions against getting infected.  I will leave everybody with this last posting that was left in one of the IIS forums as a sign of what good programmers are combating every day.

I also have been hit by this attack on Saturday 4/12/08. It compromised our database and overwritten that script into all of your products. Luckily a database restore fixed the problem. Two days later the same thing happened, I have changed all the database and login passwords and did another db restore. Now today 4/18/08 we got hit again by the same thing but this time as the pages are loaded ActivX is activated and wants to run but of course I did not allow it. Anybody has successfully solved this situation?

Posted in Rant, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

February 24th, 2008

Nick Berardi’s Essential Software for 2008

Every developer has their favorite tool collection that they must have in order to survive while developing software. The list below is indispensable in my day-to-day activities and that is why I am sharing it with my readers. My list was inspired by Scott Hanselman’s own list of tools that he uses. However I would be really interested to see what Scott’s actual list is since it would be almost impossible to touch each and every tool once a week as he claims. Because many of them serve the same purpose.

The goal of my list is to keep the tool list up to date with my current tool set. So if I stop using a tool it will drop to the bottom of the list in a section called Not Using Anymore.

Creative Commons License This list is licensed under a slightly different license than the rest of my site. So please do not reproduce this work in it’s entirety. I would rather you link to http://www.coderjournal.com/essential-software/, because work like this takes much of my time. And I am going to do everything that I can to make sure the links stay relevant and up to date. You have this pledge from me, because the links below are also my source for downloading these tools.

Development Tools

  • Notepad++
    This is a great program because it will open up any text based file and allow for quick editing. Also has built in context menu integration.
  • WinMerge
    This is still my favorite merge application, I know others have a growing following. But this is my chosen merge application because many of the others tools, check for and integrate this tool with their own to provide a free collaboration toolset.
  • PuTTY
    PuTTY is a wonderfully portable tool that doesn’t require an installation and can easily allow you to make SSH connections to any source that you may need to. I personally use it to create a tunnel in to my home network, which provides me complete access to all my computers via remote desktop with out exposing them on the internet.
  • PowerShell
    PowerShell allows for some advanced script processing and is readily being integrated in to many Microsoft projects. Now is a great time for developers to jump on board.
  • Reflector
    Reflector allows you to peer in to the .NET assemblies and view the code in your preferred language.
  • CodeSmith
    Great tool for generating any type of code that you may need from a template.
  • Fiddler
    This tool is one of my favorites because it allows me to watch the HTTP requests and view the headers. Fiddler acts as a proxy between for your HTTP connections.
  • NRegEx
    This JavaScript based tool RegEx evaluator is a great way to quickly test your regular expressions.
  • RhinoMock
    I have just started using RhinoMock for my unit testing and it really is an amazing piece of code.
  • WireShark
    WireShark use to be called Ethereal and monitors all network connections that pass through your network card.
  • Microsoft Network Monitor
    Microsofts answer to WireShark.
  • URL Rewriter and Reverse Proxy
    This is my own URL Rewriter and Reverse Proxy that I have developed. It uses the Apache style mod_rewrite syntax, so it should be familiar to most developers who have worked with Apache in the past. It is not very hard to understand so anybody can easily pickup the syntax.
  • Microsoft Best Practices Analyzer
    This is a great tool that analyzes your setup on your server and makes recommendations around best practices.
  • Visual Studio Team System 2008 Team Foundation Server Power Tools
    Extra power tools that provide access additional tools that were not shipped with the Gold Version of TFS 2008. It also includes an Team Foundation Server Analyzer that makes sure you server is setup properly.
  • Visual Studio 2005 Team Foundation Server Power Tools
    Same as above only for TFS 2005.
  • Team Foundation Server Administration Tool
    This is a great tool that lets you set permissions for each project in your server. Sometimes the permissions aren’t set correctly for each project for all the servers required, including SharePoint, SQL Reporting, and TFS. This can occur in installations were users are not defined by groups.
  • Visual Studio Express
    Don’t think this one needs explaining.
  • SQL 2005 Express
    Don’t think this one needs explaining either.
  • GhostDoc
    This is a wonderful tool that lets you document your source code pretty quickly. One thing I really love this tool for is that it helps me make self documenting code, because inorder for GhostDoc to work the methods and properties have to have some English flow to them.
  • TortoiseSVN
    Great tool with Windows Explorer Integration that allows you to work with the SVN source control server directly though Explorer.
  • AnkhSVN
    Lets you work with the SVN source control server by integration with Visual Studio.
  • Consolas Font Pack
    This is a wonderful font that is very easy to read. It is highly recommended for Visual Studio. I use it as my default.
  • SmartFTP
    A great FTP program.
  • Paint.NET
    This is one of my favorite projects currently on the internet. The developer of this application is constantly pushing C# to the limits. And does a great job with usability. It also has 99.9% of everything I require from a graphic editor as a software developer. The 0.1% that is missing is Icon support.
  • Microsoft Virtual PC
    This is a must have for any developer, especially when you are required to run operating systems that are not your current install.

Firefox Add-On

  • LinkedIn Companion for Firefox
    LinkedIn integration for keeping track of contacts.
  • StumbleUpon
    Great add-on that allows you to find sites you never knew you wanted to find.
  • IE Tab
    This is probably one of my favorites because it quickly lets me switch back and forth between Firefox and IE without ever leaving the Firefox browser.
  • User Agent Switcher
    Allows you to change the User Agent of FireFox with a quick drop down menu. I usually setup a User-Agent for Google Bot to see how websites react and change to the search engine.
  • Google Browser Sync
    Keeps your bookmarks in FireFox synced between your work and home PC.
  • Firebug
    Firebug is a must have for any professional web developer. It allows deep access to the HTML in a nice tree structure and event displays code that is generated by DHTML and JavaScript.

    • YSlow
      Grades your website and provides some useful hints on improving your score.

Other Software That Makes My Life Easy

  • Mozy *** My Review ***
    Everybody should back up their computer, and Mozy provides unlimited backup for $4.95 per month. Also Mozy Pro allows you to backup your SQL Server and Exchange installs.
  • Skype
    Great for making VOIP calls to your friends and family. Also many contractors are starting to use this as their primary communication especially over seas.
  • Picassa
    Very good program for keeping track of your family photos.
  • Gtalk
    I love it because it has a very small foot print.
  • Google Pack
    Get a whole host of software provided by Google and it also updates other common programs for you, such as Skype, FireFox, Acrobat, and others.
  • 7-Zip
    I mainly use this on my Servers because it provides better and quicker support for archiving of Zip files than the built in Windows Zip Archiver.
  • PowerArchiver
    I became disenchanted with WinZip about 4 years ago, and I happened to stumble across this application that had the look and feel of WinZip but provided support for 7-Zip, RAR, CAB, ZIP, GZip, and many others.
  • Virtual TI-89
    Because every once and a while you need to graph out more complex equations.
  • CCleaner
    It’s a very good idea to clean your registry every Spring. It is really amazing the speed in boot time when Windows doesn’t have to load a bloated Registry.
  • Ultimate Boot CD
    Wonderful set of tools.
  • WordPress
    I use it on Coder Journal, and even though my forte is .NET I still haven’t found a better blogging application.
  • Windows Live Writer
    Allows for quick and easy posts.
  • Deamon Tools
    Quickly mount and dismount ISO images for your favorite software.
  • LinkedIn Outlook Toolbar
    Allows you to keep your Outlook Contacts in sync with your LinkedIn network information and connections
  • gSyncIt
    Allows me to keep my Google Calendar in sync with Microsoft Outlook, so that my wife always knows what is going on during the day. Also has the added benifit of syncing stuff from Google to Outlook when she wants to add something to my calendar.

Tags: , , , , , , ,

Posted in ASP.NET, C#, Personal, Programming, Review, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

February 11th, 2008

How To: Change Instance Name Of SQL Server

Recently I change the network name of one of my servers at work, because the box changed its job from a virtual machine server to the database server. Everything was going great until I decided to setup the server for replication and received the following error message.

New Publication Wizard
——————————

SQL Server replication requires the actual server name to make a connection to the server. Connections through a server alias, IP address, or any other alternate name are not supported. Specify the actual server name, ‘old_name’. (Replication.Utilities)

——————————
OK
——————————

So with a little hunting and SQL queries I found out that SQL Server doesn’t use the network name, it only excepts that as an alias. My SQL Server instance was still named “old_name”. I found that out by running these two queries:

sp_helpserver
select @@servername

So in order to get the network name and the SQL Server instance name back in sync I had do these steps:

  1. Run this in Microsoft SQL Server Management Studio:
    sp_dropserver 'old_name'
    go
    sp_addserver 'new_name','local'
    go
  2. Restart SQL Server service. I prefer the command prompt for this, but you can just as easily do it in Services under the Control Panel
    net stop mssqlserver
    net start mssqlserver

Then after that is done run this again, to make sure everything is changed:

sp_helpserver
select @@servername

I don’t understand why SQL Server uses it’s own name versus the network name, might be due to the fact you can have multiple SQL Server instances install on one machine. It wasn’t too hard to change and probably stems from the days when SQL Server was known as Sybase, all in all, I learned something new and it only took 30 minutes of my day to fine the answer.

Tags: , , , , ,

Posted in How To, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

February 3rd, 2008

Does anybody have a name for this programming pattern?

Recently I have been working very hard on getting a new Web 2.0 initiative off the ground. With most new initiatives I like to start out by looking for software development patterns that will help me standardize my structure as well as make the programming experience common for any new members that are brought on the team. However I recently ran in to a structural “pattern” that seems like it is pretty simple and it addresses a common problem in software development. I researched as much as possible on all the common pattern websites that I visit and even went as far as posting on ASP.NET Forums to see if anybody could help me, give it a name. If this “pattern” hasn’t been named yet I am going to be shocked.

I like to consider myself pretty educated when it comes to some of the recent developments in structured software development. However I am at a total loss here so I am presenting this pattern to my readers to see if they have seen it before? For now I am calling this “The Modeling Pattern”:

The pattern I had in mind is to have the same object with different interfaces each modeling the required data for a specific type of User Interface.

In many websites you normally have the same information represented in various different ways. I originally arrived at this pattern after listening to Scott Hanselman’s MVC Screencast. The idea of a model, as in the M in the Model View Controller (MVC), really intrigued me. The more I thought about standard web page designs and how they are mostly based around only one “object”, the more it convinced me I was using the right model. For example you have these two different views of a article on the .NET Kicks site. (Which is a great site by the way.)

.NET Kicks Article Card

I call this a card just for the fact that it is a small representation of all the information for this article, much like a business card is a small representation of all the information about a person.
.NET Kicks Article Card

.NET Kicks Article

.NET Kicks Article

Notice how most of the information is similar between the two images above. We know they are similar because it is the same information represented from the database in different views. However the main difference is the amount of information show. Obviously it would be a massive overkill to load the users who kicked the story, and comments, when all that is required is the card view for the front page. I imagine most of this is not new to many of my readers, because SQL lets you create your datasets (models) however you want at will, the real trick in software development is creating the finite number of objects for the infinite number of datasets that SQL can return. That is what I am trying to address with “The Modeling Pattern”, creating a finite number of objects that makes sense based on the views I need for my application, because you obviously don’t want to dirty load all the properties for performance reasons. This is how I would code the above in “The Modeling Pattern”.

interface IUserModel
{
	int Id { get; set; }
	string UserName { get; set; }
	DateTime JoinedOn { get; set; }
}

interface IArticleCardModel
{
	int Id { get; set; }
	string Name { get; set; }
	string Description { get; set; }
	int KickCount ( get; set; }
	int CommentCount ( get; set; }
	void Kick (IUserModel user);
}

interface IArticleModel : IArticleCard
{
	List<string> Comments { get; }
	List<IUserModel> UserKicks { get; }
}

Then with these interfaces you create the objects.

class User : IUserModel
{
	// implement interfaces plus supporting code
}

class Article : IArticleModel, IArticleCardModel
{
	// implement interfaces plus supporting code
}

Then you create a helper class to fill these methods in the data layer.

static class DataHelper
{
	public static IArticleCardModel GetArticle (int id)
	{
		IArticleCardModel a = new Article();
		// get data from database and only fill in IArticleCardModel interfaces
	}

	public static IArticleModel GetArticle (int id)
	{
		IArticleModel a = new Article();
		// get data from database and fill in IArticleModel interfaces
		// including supporting tables such as the collections
		// or fill in some and dirty fill the others
	}

	// do the same for User
}

To use this pattern in something like the MVC framework, you would just use the interfaces instead of the actual object. What this does for you is two fold. Defines the UI model that is required and because it is an interface it doesn’t allow you access to the other properties of the class that maybe null.

So if anybody has seen this pattern before I would love to here about it. Also if you have a better name for it and you haven’t heard of it, I would love it to have something more than the tactical “The Modeling Pattern”.

Tags: , , , , , ,

Posted in ASP.NET, C#, Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

July 9th, 2007

Evolution Of LINQ And Its Impact C# 3.0

One of the things I love to learn about is the history of how things come to be. Specifically my interests have always been in the evolutions of religion and the tech world (yeah I know pretty much polar opposites, but that is what I like to learn about). I came across an interesting article in my MSDN subscription that talked about how language features of C# 3.0 came to be. The features I am talking about are:

  • Lambda Expressions
  • Extension Methods
  • Anonymous Types
  • Implicitly Typed Local Variables
  • Object Initializers
  • Query Expressions
  • LINQ

All these features were made possible because of they wanted to add a feature that let you query collections much like how you query SQL (LINQ) and the strong convictions of the C# language maintainers to not implement hacked together solutions. Much of the same convictions that I try to promote on this blog, and because of these convictions C# developers got some very nice features out of the language.

If you have not heard of LINQ before, this is the basic C# language construct (notice the similarities to SQL):

var overdrawnQuery = from account in db.Accounts
                     where account.Balance < 0
                     select new { account.Name, account.Address };

This article, The Evolution Of LINQ And Its Impact On The Design Of C#, is well worth the read and I recommend it to anybody that wants to learn more about C# 3.0 or is just interested in how good coding practices can have great impact on projects.

Tags: , , ,

Posted in C#, Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

June 26th, 2007

SQL Server 2008 Will Have 7 New Datatypes

I haven’t even herd of a new version of SQL Server 2008, coming out, but according to this blog the new version has some very interesting and new data types that will come in useful for geography processing.

DATE - ANSI-compliant date data type
TIME - ANSI-compliant time data type with variable precision
DATETIMEOFFSET - timezone aware/preserved datetime
DATETIME2 - like DATETIME, but with variable precision and large date range

GEOMETRY - “flat earth” spatial data type
GEOGRAPHY - “round earth” spatial data type
HIERARCHYID - represents hierarchies using path enumeration model

The first four datatypes are regular SQL datatypes but the last three datatypes are exposed as .NET system UDTs.

Tags: , ,

Posted in C#, Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

March 16th, 2007

Using Distributed Transactions in your Data Layer

Many developers use a pattern called ORM or Object Relation Mapping to generate data layers for their application. Many other developers choose to create their own data layers by hand. I have done both and I don’t have a preference of one over the other. With an ORM generator you have an easy to maintain data layer for your applications, when you create one by hand you have much more control of the data layer as far as object creation goes.

Most of the time a business layer will access the data layer in order to provide rules and logic to how the data objects in the data layer are accesses or relate to each other. An example of of how a business layer might relate to data layer is the following. You have a Sales table, a Products table, and a Customers table and objects for each of those in the data layer. In the business layer you may just have an object that is called Checkout that decrements the quantity in the Product table, and then combines the products and customer in the Sales table.

Data integrity is very important in applications like this, you cannot have a sale that is half complete because the revenue numbers would be off for the store. So one problem with keeping all these tables in separate objects is that it is hard to use some of the nice features that SQL provides, like Transactions.

Transactions:

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the atomicity, consistency, isolation, and durability (ACID) properties, to qualify as a transaction.

Properties of a transaction:

  • Atomicity:A transaction must be an atomic unit of work; either all of its data modifications are performed, or none of them is performed.
  • Consistency:When completed, a transaction must leave all data in a consistent state. In a relational database, all rules must be applied to the transaction’s modifications to maintain all data integrity. All internal data structures, such as B-tree indexes or doubly-linked lists, must be correct at the end of the transaction.
  • Isolation:Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either recognizes data in the state it was in before another concurrent transaction modified it, or it recognizes the data after the second transaction has completed, but it does not recognize an intermediate state. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed.
  • Durability:After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure.

Creating Distributed Transactions:

A new feature introduced in the .NET Framework 2.0 is the System.Transactions namespace, which provides support for transactions across different types of transaction managers, which include data sources and message queues. The System.Transactions namespace defines the TransactionScope class, which automatically manages transactions for you.

To create and use transactions, create a TransactionScope block, and specify whether you want to create a new transaction context or enlist in an existing transaction context. You can also exclude operations from a transaction context if appropriate.

You can call multiple data layer objects, which really creates multiple database connection within the same transaction scope. The transaction scope decides whether to create a local transaction or a distributed transaction. The transaction scope, automatically promotes a local transaction to a distributed transaction if necessary, based on the following rules:

  • When you create a TransactionScope object, it initially creates a local, lightweight transaction. Lightweight transactions are more efficient than distributed transactions because they do not have the overhead of the Microsoft Distributed Transaction Coordinator (DTC).
  • For SQL Server 2005 databases the first connection that you open in a transaction is automatically set as a local transaction. The resource manager then works with the System.Transactions namespace and supports automatic promotion of local transactions to distributed transactions when additional connections are created in the transaction scope.
  • For Non SQL Server 2005 database the first connection that you open is automatically promoted to a distributed transaction. This promotion occurs because the resource managers for these Non SQL Server 2005 databases do not support automatic promotion from local to distributed transactions.

Integrating Transactions Into Your Code
So now that we have gone over what a transaction is and the different types of transactions that .NET can use depending on the database you are connecting too. Lets get to an actual example. We will once again use our example of the Store that needs to make a sales and deduct those quantities from the database.

public class ShoppingCart
{
	public Customer Customer { get; }

	public Product[] Products { get; }

	public bool Checkout ()
	{
		try
		{
			// create the transaction scope to guarantee that all the data gets committed to the database
			using (TransactionScope scope = new TransactionScope())
			{
				// create the sale
				Sale sale = new Sale();
				sale.Customer = this.Customer;

				// save the sale to the database
				sale.Save();

				decimal cost = 0.0M;

				foreach(Product p in Products)
				{
					SaleItem item = new SaleItem();
					item.SaleId = sale.SaleId;
					item.ProductId = p.ProductId;

					// subtract one item from quantity
					p.QuantityInStock--;

					// save the product quantity update to the database
					p.Save();

					// add cost of product
					cost += p.Cost;

					// save item to database
					item.Save();
				}

				sale.Cost = cost;

				// save the sale so the cost is reflected in the database
				sale.Save();

				// commit all database changes to database
				// if complete is not called, due to an exception from the code above, the transaction is rolled back
				scope.Complete();
			}
		}
		catch (Exception exc)
		{
			Debug.Write(exc.ToString());
		}
	}
}

What is happening above is two sales commits and a commit for each product. If any of the lines above the scope.Complete() were to throw an exception the TransactionScope using block would immediately exit and the database saves would be rolled back. Like I mentioned before this is done to keep the integrity of the data in the database intact. For instance if I never made it to the part where I updated the sale.Cost the revenue for the store would be out of whack.

Stay tuned I plan on documenting more of the new features coming in .NET 3.0 and .NET 3.5. I hope this post was informative.

Tags: , , , ,

Posted in C#, How To, Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

March 1st, 2007

Visual Studio Team Edition for Database Professionals Error Connecting in Vista

As you may all know I have Windows Vista Ultimate x64 and last post I talked about upgrading to SQL Server 2005 SP2. However while starting my first Database Project I encountered the following error.

—————————
Microsoft Visual Studio
—————————
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
—————————
OK
—————————

It has basically taken me around 24 hours to finally find a solution. The solution was so simple, but yet totally undocumented on if you encounter this error do this. So I am hoping to at least correct that with this post for all the future Googler’s out there.

  1. In VS 2005 go to Tools > Options > Database Tools > Design-time Validation Database and clear out text box SQL Server Instance Name. Click OK.
  2. Also for good measures I did this under Database Connections too.

Yeah that is it for some reason localhost isn’t considered a valid SQL Server Instance name. But my problem is solved and I hope this helps somebody else.

Tags: , ,

Posted in C#, Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

February 28th, 2007

Microsoft SQL Server 2005 SP2 for Vista

Microsoft with out much fan far released service pack 2 for SQL Server 2005. There is a whole laundry list of new features and bug fixes listed on MSDN. However one of the biggest features at least for early adopters is the support for Windows Vista both x86 and x64 versions of the operating system. This release brings with it a great new tools for Windows Vista that are not available for previous operating systems.

Download SQL Server 2005 Service Pack 2

In order to prove Microsoft is really serious about security and that UAC (User Account Control) is here to stay. They don’t automatically grant all Administrators of the machine access to SysAdmin privileges in SQL 2005. The SysAdmin privileges have to be granted on the basis of who needs them, which is common practice in any role based security. The new tool can be found at C:\Program Files (x86)\Microsoft SQL Server\90\Shared\SqlProv.exe and is pictured below. I personally welcome this added level of security and control I have over who has SysAdmin access to SQL Server. Not that I worry about my wife going in and screwing with my data, it is just nice to have control over your computer. Thank you Microsoft for you continued focus on security.

SQL Server 2005 Vista User Provisioning

Tags: , , ,

Posted in Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »