Thursday, 25 June 2009

Common Table Expressions

Introduced in SQL 2005 was the Common Table Expression (CTE). These can act like subqueries or views within a SQL statement.

Good definition on 4GuysFromRolla and MSDN.

To use them you use the 'WITH' keyword, for example if you were using the following Subquery:


SELECT
*
FROM
(
SELECT
p.Forename
, p.Surname
, COUNT(m.MessageId) AS MessageCount
FROM
[Pupil] p
INNER JOIN [Message] m ON (p.PupilId = m.PupilId)
GROUP BY
p.Forename
, p.Surname
) AS PupilsWithMessages


to get all pupils with a message you could now use a CTE,


WITH PupilsWithMessages (Forename, Surname, MessageCount) AS (
SELECT
p.Forename
, p.Surname
, COUNT(m.MessageId) AS MessageCount
FROM
[Pupil] p
INNER JOIN [Message] m ON (p.PupilId = m.PupilId)
GROUP BY
p.Forename
, p.Surname
)

SELECT
*
FROM
PupilsWithMessages


This is a simple example but it looks a lot cleaner than subqueries and you can use them in the same way as you would a view. Better examples on the above links.

Recursive CTE's


You can also use them for recursing, a simple example I came up with was to loop through a comma delimited list of weekdays and return a seperate row for each one. Whereas previously you would need to use a Cursor you can now use a CTE.


DECLARE @String varchar(100)
SET @String = 'Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday,';

WITH List (Val, Rest, HierarchyLevel) AS (
SELECT
SUBSTRING(@String, 1, CHARINDEX(',', @String)-1) AS Val
, SUBSTRING(@String, CHARINDEX(',', @String)+1,200) AS Rest
, 1 AS HierarchyLevel
UNION ALL
SELECT
SUBSTRING(l.Rest, 1, CHARINDEX(',',l.Rest)-1) AS Val
, SUBSTRING(l.Rest, CHARINDEX(',', l.Rest)+1,200) AS Rest
, l.HierarchyLevel + 1 AS HierarchyLevel
FROM
List l
WHERE
CHARINDEX(',', l.Rest) <> 0
--AND HierarchyLevel < 5 /*You can limit how 'deep' the recursion goes*/
)

SELECT
*
FROM
List


In the 2nd query the CTE references itself (List) to continue splitting up the string until the conditions specified in the WHERE statement are true.

Thursday, 4 June 2009

New property syntax in C#3.0

Prior to C#3.0 we would use the following syntax for creating properties:

private string _GetAndSet;
public string GetAndSet { get { return _GetAndSet; } set { _GetAndSet = value; } }


private string _SetOnly;
public string SetOnly{ get { return _SetOnly; } set { _SetOnly = value; } }


C#3.0 allows us to use the following syntax which is the equivalent of above.

public string GetAndSet { get; set; }

public string SetOnly{ get; private set; }

Tuesday, 2 June 2009

Create report in Reporting Services 2008

This is a great link to show you how to create reports and deploy them:

http://www.accelebrate.com/sql_training/ssrs_2008_tutorial.htm

Add a parameter to report once report is created:

Right click parameter in the report data window - add parameter and fill out required fields.
Right click the grid - tablix properties - filters and add in the filter using the parameter as the value.

Friday, 15 May 2009

Upload XML File

To upload an XML file into SQL Server 2008:

1. Open SQL Server Business Intelligence Studio.
2. Create a new package ( shown in previous post)
3. Create Destination table on Server to upload file to.
4. Drag on Execute SQL Task - add TSQL to truncate the table.
5. Drag on Data Flow Task and double click
6. Drag on XML Source file and set the properties.
7. Drag on OLE DB Destination and set properties.

Job Done.

Thursday, 14 May 2009

Subsonic Parent -> Child saving

How to save subsonic objects to the db that have FK values needing set.

Here's an example that also uses a transaction. Please note that you will have add a reference to the System.Transactions namespace in your project and then reference in your class.



   using (TransactionScope scope = new TransactionScope())

    {

        try

        {

            Order order = new Order();

            //populate order details.

            order.Save(); //Commit to DB





            OrderItem item = new OrderItem();

            //populate orderItem details.



            item.Order = order;   //THIS LINE SETS THE PARENT OBJECT TO ABOVE ORDER



            item.Save();  //Commit to DB



            //complete you transaction

            scope.Complete();



        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            throw ex;

        }

    }


Create a SSIS package

Basic steps to create an SSIS package (old DTS) to copy data from one database to another in SQL Server 2008:

Great link for the basic steps http://it.toolbox.com/blogs/coding-dotnet/creating-a-ssis-package-24699

However to truncate the tables before filling them with the above package:

1. Drag a Execute SQL Task into the control Flow window.
2. Double click and set the connection
3. Enter SQL Statement
4. Drag green line to the data flow task or the next step to run.

Point to Note: This tool is similar to Reporting Services where you create a project and then can have many packages within the project. Each package can then share the connections within the Data Sources folder.

Enjoy!

Friday, 8 May 2009

Setting up an ASP.Net site for membership using your own database

If you are setting up a new application and you want to use the membership and roles security then normally .Net will try to set this up for you in your local express server. If however you want to set this up in your application database, on your main server then do the following.

1) Run C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe
2) Use the wizard to select the server and database. (I believe this can be any of 2000/05/08)
3) Change the following in your web config to suit your DB and server settings. Cahnge any other settings to suit your application. Click here for MSDN article.


<configuration>

<connectionStrings>

<add name="MySqlConnection" connectionString="Data

Source=YOURSQLSERVENAME;Initial Catalog=YOURDBNAME;Integrated

Security=SSPI;" />

</connectionStrings>

<system.web>

<authentication mode="Forms" >

<forms loginUrl="login.aspx"

name=".ASPXFORMSAUTH" />

</authentication>

<authorization>

<deny users="?" />

</authorization>

<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">

<providers>

<clear />

<add

name="SqlProvider"

type="System.Web.Security.SqlMembershipProvider"

connectionStringName="MySqlConnection"

applicationName="MyApplication"

enablePasswordRetrieval="false"

enablePasswordReset="true"

requiresQuestionAndAnswer="true"

requiresUniqueEmail="true"

passwordFormat="Hashed" />

</providers>

</membership>

</system.web>

</configuration>






4) That should be you!


I got this info by using StackOverflow and asking this question.



Thursday, 7 May 2009

Problem with Infragistics Charts in a Web Site!

When using Infragistics Chart components in a web site, you may get a GDI+ error relating to image permissions.

There is an infragistics solution to this problem here.

You have to grant user permissions to the web site folder/virtual directory on the server.

Right click the folder > Properties > Security Tab > Add

On Windows Server 2003 you would do: servername\NETWORK SERVICE

And that should be it.

Calling server side ASP.NET method from jQuery

I was recently looking at calling a server side method from an ASP.NET 3.5 application using jQuery. The following example has a server side method that returns some HTML markup from a database to jQuery, which then inserts it into the page markup.

Server side code, in Default.aspx:


using System.Web.Services;

[WebMethod(true)]
>(public static string getMarkup()
{
return "<h3>Test Markup</h3>";
}


You need to make the method static and include the WebMethod(true) operator above it. You can also use the following code to call a WebMethod from an asmx or WCF web service.

You call this from the client side jQuery code using:


$("#loadHome").click(function(){
$.ajax({
type: "POST",
url: "./Default.aspx/getMarkup",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result){
$("#contentDiv").html(result.d);
}
});
});


This uses the jQuery ajax method to get the data from the server side method, which is returned as a JSON object. You use the .d notation on the JSON object to get the result supplied from the server side.

If you want to send any data to the method, send as a JSON object. For example if you had a server side method that takes 2 params, orderId and customerId, you would use:

var data = "{orderId:'2',customerId:'99'}";

Thursday, 30 April 2009

Error On Install: "Installation User Interface Option"

I had a problem installing a new version of a windows application, even after I uninstalled all previous versions. I toyed the following steps, but I had to search the registry myself with the produce code form the MSI project in .Net. Just deleted the whole folder once it was found.

Here a snippet of the web page I found with the solution:

If the application is a Windows or Web application -

1. Go to START, RUN and type the following: MSIEXEC /X "path to the .MSI
file you
want to uninstall" and click OK.
2. After the application is uninstalled, try installing your MSI file
again. If you
get the same error, then some portion of the application still exists on
the
machine. You will want to use MSIZAP to remove the product, or you can
search for
the PRODUCTID of the msi package in the registry and remove the associated
registry
keys. The Product ID looks like {xxxxx-xxxxx-xxx-xxxxx-xxxxx}


Link to source: http://www.tech-archive.net/Archive/VisualStudio/microsoft.public.vsnet.general/2005-10/msg00086.html

Wednesday, 29 April 2009

Website Accessibility

There are no set laws in the UK regarding Website Accessibility, but your website should at least meet Priority Level 1 and it is recommended to meet Priority Level 2.

Her is the link to Website Accessibility Level 1 (A) reference:

http://www.w3.org/WAI/WCAG20/quickref/Overview.php

Using multiple versions of browsers (IE + FF)

Internet Explorer


I found this handy tool, IETester, for testing your websites in multiple versions of IE, each in a different tab. Currently it can test IE 5.5, 6, 7 and 8 beta.

Since it's an early alpha release there is a list of known bugs on their homepage but it is good enough to view pages in.

Firefox


I found the easiest way of testing in various versions of FF was to use a portable version since it doesn't need any installation and won't mess with whichever current install you have.

You can find all portable legacy versions if FF here.

Tuesday, 28 April 2009

Extension Methods in C# 3.0

A new function of C# 3.0 is Extension Methods.

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."

For example, if you wanted a method to convert a temperature from celsius to fahrenheit, where previously you would use

int temp = 30;
int i = myClass.CelsiusToFahrenheit(temp);


using extension methods you can now use

int temp = 30;
int i = temp.CelsiusToFahrenheit();

To do this you would create a new static class to contain the static method CelsiusToFahrenheit. The key to extension methods is passing in the this keyword along with the variable. For example,


public static class myClass
{
public static int CelsiusToFahrenheit(this int temp)
{
return (9 / 5) * temp + 32;
}
}


This will now allow you to use the CelsiusToFahrenheit method on any integer variables.

You can also add methods to extend your own custom classes, and the methods can have different return types. For example, if you have your own class, TestClass, you can create a static method using extending TestClass, e.g.


public static DateTime doSomething(this TestClass t)
{
//do something
}


Which will then allow you to use:

TestClass t = new TestClass();
DateTime x = t.doSomething();

Monday, 27 April 2009

jQuery events not firing for dynamic content

When adding dynamic content (using AJAX or DOM modification) using jQuery, events are not fired for the new objects, for example if you have the following html:

<button id="load" href="#">Test</button>
<div id="container"></div>


When I click the load button I want to add a link to another page inside the container DIV, so I use the following jQuery.


$(function() {
$("#load").click(function() {
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>")
});

$("#popup").click(function(){
alert("Clicked");
return false;
});
});


The click event for the dynamically created anchor tag (id="popup") will not fire using the above because this code is run once the document is ready, and at that time jQuery will look for an object with an Id of popup which doesn't exist yet.

I've found a few different ways to do this:

1. Add a generic click event for the body tag and check what was clicked, for example:


$("body").click(function(e){
var target = $(e.target);
if (target.is("#popup")) {
alert("Clicked");
return false;
}
});


Using this example you check what was clicked using target.is(), you can use any valid CSS selector statements to check the item clicked. This way is simple to implement but can quickly grow if you have a lot of dynamic content.

2. Use the live command, which will tell jQuery to bind any current and future references of "#popup" to the click event.



$("#popup").live("click",function(){
alert("Clicked");
return false;
});



The following 3 ways are variations on the same theme in that the events are bound after content creation.

3. Use the jQuery Bind command to bind the click event to a particular function on creation. e.g.:


$("#load").click(function(){
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>").bind('click', loadClick);
//can also use
//$("#container").html("<a id='popup' href='contactForm.html'>popup</a>").click(loadClick);
});

function loadClick(){
alert("Clicked");
return false;
}


4. Insert the function for handling the click event within the initial click event when you create the popup link. This runs the event binding as soon as the item is added.


$("#load").click(function(){
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>");
$("#popup").click(function(){
alert("Clicked");
return false;
});
});


5. Similar to the above method except this way you create a method which does all data binding (bindEvents()). This can be useful if you have a lot dynamic content that needs to be bound at the same time, it can be encapsulated into 1 event.


$("#load").click(function(){
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>");
bindEvents();
});

function bindEvents(){
$("#popup").click(function(){
alert("Clicked");
return false;
});
};



There's also a plugin called livequery that makes binding easier.

Sunday, 26 April 2009

Firebug for all browsers!

When designing websites I've found firebug for FireFox invaluable for checking out exactly what's going on. I've now found you can get Firebug lite for use on any browser!

It's very easy to use, all you have to do is include the following code in any page that you want to use it in:
<script type="'text/javascript'" src="%27http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js%27"></script>

Genius.

Wednesday, 1 April 2009

TSQL script to loop round all databases

Hi Guys

Quick script to loop round all databases and perform an action - in this case its setting all databases to simple recovery. The keyword here is sp_msforeachdb - pure genius :)

use master
GO
sp_msforeachdb '
declare @sql VARCHAR(1000)
IF DATABASEPROPERTYEX(''?'', ''Rjavascript:void(0)ecovery'') <> ''SIMPLE''
begin
set @sql = ''ALTER DATABASE ? SET RECOVERY SIMPLE''
PRINT @sql

end'

Sunday, 29 March 2009

Using keyword

When using anything that implements IDisposable (SqlDateReader, SqlConnection etc) you can use the using keyword to ensure that the object is disposed, e.g.

using (SqlDataReader reader = Dal.ExecuteReader(GetConnection(), "SelectProductAll"))
{
dsScrum.ProductTask.Clear();
if (reader.HasRows)
dsScrum.Product.Load(reader);
}



Is the same as:

SqlDataReader reader = Dal.ExecuteReader(GetConnection(),"SelectProductAll");
try
{
dsScrum.ProductTask.Clear();
if (reader.HasRows)
dsScrum.Product.Load(reader);
}
finally
{
if (reader != null)
reader.Dispose();
}

Wednesday, 25 March 2009

jQuery

I've been looking at using Javascript libraries recently, in order to revamp Lesley's site there are a lot out there (Prototype, Mootools, scriptaculous, Dojo, YUI). I've decided to use JQuery as it appears to have the largest following, which means more support, tutorials and extra plugins. It's also easily extensible meaning you can customise and extend.

What is it? "jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript." In short, you can get Flash-type effects and general all-round sexiness using only javascript, could be used for cool menus, client side table sorting, tabs, AJAX data/image loading, page manipulation, custom dialog boxes, charts etc.

To use you need some understanding of CSS as it uses CSS-style selectors ("li", "#Id", ".class", "a>img" etc) to access elements using jQuery and it appears a lot of the functionality uses CSS to move/position elements.

Here are some good links that I've found:

Tuesday, 24 March 2009

SubSonic

SubSonic..... fed up writing boring DAL code? Me neither.. but if you are this may be for you.

SubSonic has several things we would be interested in but the main selling point is that it auto generates a DAL for you. It also has CMS starter site that seems really cool... more on that later.

I'm not going to re-write their web site help here; so I recommend you visit their site and enjoy the videos. Code is available from codeplex... their site was a little flaky when downloading so I used that instead.

The forums are really good and its been around for a few year now so I think this is something we should all be considering when taking on a new project.

Almost forgot the good news (yes folks it gets better!) its.... wait for it...... OPEN SOURCE!

Enjoy
Free Hit Counter