0

Create a Database using SQL

by Jon 27. April 2011 22:37

Dynamic SQL saves the day.  I needed to script create some databases but I want to specify a number of parameters to be used as part of the Create Database Command:

  1. I want to specify where the database files will be created
  2. I want the all databases to be Prefixed with a standard set of characters
  3. I want to create one or more databases
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-- Please set the following Two Variables Correctly

Declare @InstallDbPath as nvarchar(500)
Declare @DbPrefix as nvarchar(50)
set @InstallDbPath = 'D:\Databases\QA\'
set @DbPrefix = 'QA_'

------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-- Dont Change any SQL after this line, just set the Variables at the above
-- Some Variables that we will use
Declare @InstallDbName as nvarchar(50)
Declare @SQLCmd as nvarchar(max)
Declare @DbName as nvarchar (50) -- DbName Changes, its the name of the database we want to create

-- TODO : Change this to run in a loop, reduce repeated SQL

------------------------------------------------------------------------------------
-- Change the Variable @DbName  to be the name of the databse you want to create

-- Create Database1
set @DbName = 'Database1'
set @SQLCmd = 'CREATE DATABASE ' + @DbPrefix + @DbName + ' ON PRIMARY
(NAME = ''' + @DbPrefix + @DbName + '_Data'' , FILENAME = ''' + @InstallDbPath + @DbPrefix + @DbName + '_Data.mdf'', SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%) 
LOG ON
(NAME = ''' + @DbPrefix + @DbName + '_Log'' , FILENAME = ''' + @InstallDbPath + @DbPrefix + @DbName + '_Log.mdf'', SIZE = 4096KB , MAXSIZE = 2GB, FILEGROWTH = 10%)' 
exec (@SQLCmd)

-- Create Database2
set @DbName = 'Database2'
set @SQLCmd = 'CREATE DATABASE ' + @DbPrefix + @DbName + ' ON PRIMARY
(NAME = ''' + @DbPrefix + @DbName + '_Data'' , FILENAME = ''' + @InstallDbPath + @DbPrefix + @DbName + '_Data.mdf'', SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%) 
LOG ON
(NAME = ''' + @DbPrefix + @DbName + '_Log'' , FILENAME = ''' + @InstallDbPath + @DbPrefix + @DbName + '_Log.mdf'', SIZE = 4096KB , MAXSIZE = 2GB, FILEGROWTH = 10%)' 
exec (@SQLCmd)

-- Create Database3
set @DbName = 'Database3'
set @SQLCmd = 'CREATE DATABASE ' + @DbPrefix + @DbName + ' ON PRIMARY
(NAME = ''' + @DbPrefix + @DbName + '_Data'' , FILENAME = ''' + @InstallDbPath + @DbPrefix + @DbName + '_Data.mdf'', SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%) 
LOG ON
(NAME = ''' + @DbPrefix + @DbName + '_Log'' , FILENAME = ''' + @InstallDbPath + @DbPrefix + @DbName + '_Log.mdf'', SIZE = 4096KB , MAXSIZE = 2GB, FILEGROWTH = 10%)' 
exec (@SQLCmd)

Tags:

SQL

0

The Free Wp7 Icon Pack! where is saved on my pc?

by Jon 21. April 2011 18:02

Because they are incredibly useful, and I keep on forgetting where they are saved to here is a post remind myself where they are located.  The free WP7 icons are now bundled with the Phone SDK and you can find them at:

C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Icons

or

C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons

 

Another Interesting place for WP7/Metro Friendly icons is the Noun Project, check it out

Tags: , ,

WP7

0

Temporal ASP.NET Bug strikes again, crazy problem crazy solution.

by Jon 15. April 2011 23:32

Just 4 months ago I posted about a weird bug with ASP.Net/IIS 6 around compiling in the UK and releasing to a different time zone.  I got hit again by it again, after a customer release we discovered parts of the system werent working correctly, several controls weren’t styling or working correctly.  It took almost an hour of diagnostics to remind myself of my original blog post, so I defiantly need to write a second post on the subject.

The problem is caused when you deploy to a timezone that’s behind you, i.e. you live in the UK and you are deploying to the USA, and it only effects iis6/server 2003 or below. When you have assemblies that return content from a webresource.xsd it will throw an exception when the dll timestamp is in the future.

You have a couple of ways to fix this:

  • Don’t use old Servers/IIS6, can be tricky if you are maintaining older code, or restricted by server choice.
  • Make sure you leave enough hours between compiling and deployment to make up for the time difference
  • Make sure your server time/computer time is set at –12 timezone time
  • After you deploy to a customer site, re-timestamp the dlls

The only sensible Option

So it appears the only sensible option is to re-timestamp the DLLs, you could do this on your CI server so this never happens (but telling your CI to compile and timestamp the dlls in the future may be tricky), or you could do it on the customer site after deployment when you hit the problem.  The command to touch/re-timestamp dlls can be done from the command line.  It involves copying the dlls over the top of themselves, and applying the correct timestamp when you do it.  The command to do this is almost more crazy than the problem:

copy /b *.dll +,,

 

yeah…. you need the + and the two ,, for it to work, crazy problem, crazy solution

Tags:

asp.net | Deploy | development

0

Upgrading from the AjaxControlToolkit Collapsible Panel using jQuery in Asp.Net WebForms: Remembering the Panel State across postbacks.

by Jon 7. April 2011 22:11

In 06?/07 the AjaxControlToolkit was the Jewel in the Crown in the Microsoft Web Development Platform , an easy way to do Ajax for Asp.Net Web Forms.  It was really easy rapid development, tightly integrated into Visual Studio and it was Open Source, it was new and cool and quick to use.  Things changed, the cool kids moved onto other things, and people discovered that although it had its advantages the AjaxControlToolkit to wasted lots of bandwidth, constricted you to a particular look and feel, and had the potential to introduce bugs you couldn’t fix.  The current state of play is the toolkit hasn’t seen a new release since September 2009, and frameworks and browsers progressed massively.

There are lot of sites and systems that still use ASP.Net WebForms and many of them use the AjaxControlTookit to fill UI gaps.  We still use this toolkit in our day job system and I decided that we need to swap out the functionality the toolkit provides to jQuery.  The two controls I needed to replace were the Collapsible Panel and the Accordion.  There were examples online on doing both but I couldn’t find any examples that persisted postback.  I needed a collapsible panel that I can expand and contract with AJAX/JQuery but when the user presses a button that posts back to the server I want the server to return the page in the same state before the postback, i.e. still expanded, or still collapsed.  I also need jQuery/a Pattern that can easily be swapped out and to keep the UI experience consistent so I can update multiple pages and controls in one refactor sweep.

Surviving Postback: Collapsible Panel , using jQuery

The following snippet of code is a drop in replacement for the AjaxControlToolkit Collapsible Panel, it has been written to be a simple replacement for he AJAX extender but using jQuery and a small amount of code behind to return the panel in the correct state on postback.  This is what you need to do if you want to create the sample in Asp.Net Webforms from scratch on a separate page but it is even easier to replace and customise all your collapsible panels in your existing application.

Include jQuery in your Page Header

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
 

Add a Hidden Field to your Page/Control to store the Expanded State

<asp:HiddenField ID="ExpandState" runat="server" />

There is a Panel that shows some header information

<asp:Panel ID="Panel_Title" runat="server" Height="15px">
    <asp:Label ID="Label_Expander" runat="server" style="float: left" Text="Edit (Show...)" />
    <asp:Image ID="Image_Expander" runat="server" ImageUrl="/images/dn.gif" style="float: right" />
</asp:Panel>

 

There is a Panel that shows some content

<asp:Panel ID="Panel_Content" runat="server" style="overflow:hidden">
    This is some Content
</asp:Panel>
 

Add some jQuery to Expand and Contract the Content Panel when a user clicks on the Title Panel

<script type="text/javascript">
    $(document).ready(function () {

        // When a user clicks on the Title Panel
        $("#<%= Panel_Title.ClientID%>").click(function () {

            // Toggle the Panel_Content Visibility
            $("#<%= Panel_Content.ClientID%>").slideToggle(300, function () {

                // When the Content Panel has completed its animation check to see if the Content Panel is visible
                if ($("#<%= Panel_Content.ClientID%>").is(":visible")) {

                    // Set the HiddenValue Expanded State to 'Expanded' and Update the UI
                    $("#<%= ExpandState.ClientID %>").val("Expanded");
                    $("#<%= Label_Expander.ClientID %>").html("Edit (Hide...)");
                    $("#<%= Image_Expander.ClientID %>").attr("src", "/images/up.gif");

                } else {

                    // Reset the Hidden Value and reset UI back to its original State
                    $("#<%= ExpandState.ClientID %>").val("");
                    $("#<%= Label_Expander.ClientID %>").html("Edit (Show...)");
                    $("#<%= Image_Expander.ClientID %>").attr("src", "/images/dn.gif");

                }

            });

        });

    });
</script>

 

In your code behind add this code in the page/control load:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Serverside Expander Code
    If Me.ExpandState.Value = "Expanded" Then
        Label_Expander.Text = "Edit (Hide...)"
        Image_Expander.ImageUrl = "/images/up.gif"
        Panel_Content.Style.Clear()
    Else
        Label_Expander.Text = "Edit (Show...)"
        Image_Expander.ImageUrl = "/images/dn.gif"
        Panel_Content.Style.Add("display", "none")
    End If
End Sub
 

Surviving Postback: AjaxControlToolkit Accordion, using jQuery

The following snippet of code is a drop in replacement for the AjaxControlToolkit Accordion, you can simply replace the AJAX extender with the jQuery and add a small amount of code behind always show the correct panel on postback.  This accordion only shows one panel at a time. This is what you need to do if you want to create the sample in Asp.Net Webforms from scratch but it was written so it is really simple to swap out your old Accordions.

Include jQuery in your Page Header

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>

 

Add a Hidden Field to your Page/Control to store the clientid of the currently Expanded Panel.  The value of this hidden field is “” when there is no expanded panel

<asp:HiddenField ID="ExpandedClientID" runat="server" />

 

Any Number of Title and Content Panels

<asp:Panel class="TitlePanel" ID="Panel_Title1" runat="server" Height="15px">
    <asp:Label ID="Label_Expander1" runat="server" style="float: left" Text="Title 1" />
</asp:Panel>
<asp:Panel runat="server" ID="Panel_Content1" class="ContentPanel">
    Content 1
</asp:Panel>
<asp:Panel class="TitlePanel" ID="Panel_Title2" runat="server" Height="15px">
    <asp:Label ID="Label_Expander2" runat="server" style="float: left" Text="Title 2" />
</asp:Panel>
<asp:Panel runat="server" ID="Panel_Content2" class="ContentPanel">
    Content 2
</asp:Panel>

 

Add the following jQuery code

<script type="text/javascript">
    $(document).ready(function () {

        //toggle the component with class ContentPanel when the corresponding Title is clicked
        $(".TitlePanel").click(function () {

            // The Content Panel we want to manipulate is the Next One after this
            var ThisNextContentPanel = $(this).next(".ContentPanel");

            // Toggle This Content Panel
            ThisNextContentPanel.slideToggle(300, function () {

                // and then Hide the Other Content Panels
                $(".ContentPanel").not(ThisNextContentPanel).hide(200);

                // Set the Selected Panel to the Hidden Variable
                $("#<%= ExpandedClientID.ClientID %>").val(ThisNextContentPanel.attr('id'));

            });

        });

    });
</script>

 

Add the follow code behind to make sure we only display the correct panel on each postback:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Show/Hide Panel_Content1
    If Panel_Content1.ClientID = ExpandedClientID.Value Then
        Panel_Content1.Style.Clear()
    Else
        Panel_Content1.Style.Add("display", "none")
    End If

    ' Show/Hide Panel_Content2
    If Panel_Content2.ClientID = ExpandedClientID.Value Then
        Panel_Content2.Style.Clear()
    Else
        Panel_Content2.Style.Add("display", "none")
    End If
End Sub

 

And that's it, we are now several steps closer to dropping the AjaxControlToolkit from our code base Smile

Tags: , , , ,

AjaxControlToolkit | vs2010 | jQuery

1

DDD9 Community Developer Day at Microsoft Reading

by Jon 29. January 2011 19:24

Travelling home after another fantastic DDD; an annual UK development community held at Microsoft Reading.  A big thanks must go to all the organisers and speakers that have yet again made this a fantastic day. 

Some of the topics were a bit techy so I am using this blog to attempt solidify the notes I made.  If you see any mistakes or oversights please please please get back to me so I can rectify them. 

I managed to cover Liam's talk and the basics of the other talks, I had planned to do more but I have been ill this week.  I may try to fill it out with more details if I time this weekend, or if someone gets back to me with a suggestion.

Go Asynchronous With C# 5.0 - Liam Westley

Liam went through one of the headline new features that is coming in C# 5.0 (also in vb.net 5.0), which was announced at PDC 2010 last year.  The New async keyword and its sister keyword await, are two new keywords in the language that simplify the way we perform asynchronous operations. In this world of multi-core processors and responsive handheld devices we need to be able to do several things at the same time more efficiently without making an accidental mistake that brings your code crashing down.  Liam demonstrated the problem we face by offering three members of the audience hot drinks.  If you want to do three things at the same time, (make three hot drinks), there is a temptation for a developer to start up three threads, the analogy Liam made was this is like getting three kettles out and making three hot drinks at the same time.  Its not sensible, it uses too many resources and it will take you longer!  Its better to do it in a more controlled way, but in c# 4.0 (and other languages) the extra code needed to achieve this will add extra lines to your code that muddies the water hiding the detail of what we want to achieve.

Async and Await are two words that we will use to manage the complexity better, enable use to boil hot water and make drinks quicker without hiding the complexity involved in asking people what drinks they want.  The process of making three hot drinks is pretty simple so if we can describe it in a simple way but include markers to say how we are going to achieve this asynchronously we are onto a winner. 

The two new keywords means we are able to write asynchronous code but it looks like single threaded code in your source file.  By placing the Async and Await Keywords in the right places the dotnet compiler will take your essentially single threaded code and construct call backs in the right places at compilation!

Async – We use this keyword to mark a method, its a statement of intent to say we may be performing asynchronous operation.

Await – Await can only be used within a method that has already been marked with an Async keyword.  If you place the word Async before you call a method you want to be run asynchronously the compiler will ensure the code that is after the keyword will be executed on a Callback without you having to write any extra code.

The code looks amazing but there appear to be a couple of gotchas:

  • You have to be really careful not to use the word await in your method names, you need to check your naming conventions before you implement.
  • A method marked with the async keyword can only return void, task or Task<TResult>
  • The naming convention seems a little off, as await doesn’t wait.  It is a request to continue running on a callback
  • Exception handling looks a bit funky less than clear in some scenarios which could get confusing.

It looks fantastic, and I look forwards to using it but it almost needs a health warning because it so much easier to write asynchronous code, i can see that lots of people may start using the keywords everywhere. When they start getting weird exceptions they can’t fix there will be the temptation to swallow them.  Obviously this can happen today in our current callback centric world, but there is a smallish barrier to entry.  I’m looking forwards to seeing this in the framework, if the names will stick, and what if anything will change with the exceptions.  If you want to look at this now you can grab the CTP here, but be warned its not compatible with MVC3 or VS2010 SP1.  Liam mentioned that as this is a CTP we as developers have a chance to get back to MS to ask for features or changes we want to see in c# 5.

Monads! What are they and why should I care? - Mike Hadlow

Mike Hadlow is one clever bloke, I got to the end of the talk and I wasn’t even sure if the questions I had were valid.  I thought I knew what monads were by the end of the talk but looking at my notes its still not clear.  In summary most developers probably shouldn’t care unless they are really interested in it.  From what I understand monards are used all over the dotnet framework, LINQ, IEnumerable<T> by understanding the concept you will better understand what is going on under the seams.  I need to see this again, and probably again and do some sample coding to get my head round it before I can put together a sensible overview.

But it does beg a bigger question, does the average developer need to know what a monad is?  A developers job is to create software that solves a problem quickly and cheaply, it doesn’t really matter how this is done.  It goes back to my previous post on what is Lean.  The customer couldn’t care less if you know about monads, they don’t even want a piece of software, they just want there life to be easier/nicer.  If knowing monads helps developers achieve this; great.  Its one for my list of things to read about.

Functional Alchemy: Tricks to keep your C# DRY - Mark Rendle

DRY stands for Do Not Repeat yourself.  As a developer if you find yourself writing the same code, or even doing the same thing over and over again your doing something wrong.  Mark Rendle showed us some ways we can use Functional Tricks to reduce the amount of code we write and reduce repetition.  Mark made a great point that using an OO language is can be like using a Hammer to crack a nut, not everything is an object.  Mark then went through some code, I especially liked the functional catch and the cached dictionary looked useful, although the lock looked a little dangerous for my liking.

Again in my mind software development is getting something done as quickly and as simply as possible, not having to write the same line of code over and over again is an advantage, and I loved the extra readability some of the sample code added.

Is your code S.O.L.I.D ? - Nathan Gloyn

Nathan about to start his talkKind of, but it could be alot better.  I loved this talk, Nathan took a pretty dodgy asp.net project which had inline SQL and transformed it into a thing of beauty.  He showed how you can take any dotnet code and make it much better using SOLID principles.

SOLID is a set of principles about class design, they are principles to consider not rules to apply.  Each letter of SOLID stands for a different concept which is designed to remove the nasty ‘Design Smells’ that infect code bases.

Nasty Code Smells Nice SOLID Principle
  • Rigidity – Cant Change
    Fragility – one change will break other things
  • Viscosity – changes are too much work, and a dirty hack is preferable
  • Complexity – Makes it difficult to change in future
  • Repetition – Waste of time writing the same thing over and over again
  • No Opacity – lines are code are confusing, do different things
  • Single Responsibility – Each object has a single responsibility
  • Open/Closed – Software is open for extension closed for modification
  • Liskov substitution – objects can be swapped out for different reasons, ie testing, for different database back ends etc etc.
  • Interface Segregation – Lots of client interfaces are better rather than a single fat interface
  • Dependancy Inversion – Dependencies are turned on there head so objects are loosely coupled


After whistling through the concepts Nathan then dived into code taking a legacy application and applying each of the SOLID principles in turn to refactor the solution into a much cleaner, more testable manageable project.  Nathan covered alot in this presentation and I was glad I took notes so I could look into it further when I got home.  I’m looking forwards to going to the next talk that Nathan gives.

Enforcing Code ‘Beauty’ With StyleCop - Guy Smith-Ferrier

Unfortunately I made it to this session a little late, because I had got myself into a table tennis match on xbox kinect!  Unfortunately as soon as I made it to the session I found that StyleCop is of no use to our business because it doesn’t support vb.net.  A bit of a surprise as StyleCop is open source, might take a peek if I ever get any time!

Beginners Guide To Continuous Integration - Paul Stack

I have recently implemented TeamCity in our organisation, CI is life changing.  It fits in with the DRY principle, developers should be aiming to automate any repetitive tasks and for many organisations software Builds, Testing and Release take an inordinate length of time.  Paul covered the basics of what CI is, how you should pick a CI and did a quick demo, a nice taster session for anyone who hasn't thought about CI.  It didn’t cover anything really new for me but it was nice to see a different perspective., and I liked the presentation style.  I was set next to a guy who got really interested and ended up giving him a link to my blog so he could take look at my beginning TeamCity blog series.  I think this session interested alot of people; who just want to save time and .’. save money.  The advantages to CI are clear, reduced risk, reduced bugs better testing, faster release, you can take it to another level it has even been joked on twitter that ideally your CI system should order you a pizza if you break a build Smile with tongue out

Tags:

conference | ddd | development

Powered by BlogEngine.NET 2.0.0.36
Original Design by Laptop Geek, Adapted by onesoft, and finally some tiny tweaks by JonAlb