Thursday, November 5, 2009

Format Blogger Source Code

Just in case anyone is wondering, I use the following utility for formatting source code in my blog posts.

http://formatmysourcecode.blogspot.com/

Mucho thanks to that guy for setting it up.

Sql Server - Execute multiple scripts from a master script

I was fiddling about with Sql Server Management Studio today trying to come up with a way to setup a master .sql script that would call numerous other scripts. What I landed on was the sqlcmd command line utility. I'd have liked to have run this from the query editor itself, however the option that presented itself there was a stored proc named xp_cmdshell. I didn't feel like messing around with my security settings locally (it's apparently turned off by default for security concerns) and figured it would be an issue with the remote host as well, so I went ahead with sqlcmd instead.

Basically, I set up a simple batch script I called dbCreate.bat and put the following commands in it:
sqlcmd -E -dMyDatabaseName -iDBCreateAll.sql
pause

The -E argument tells the script to use your local machine's permissions. You'll need to change this for operations on a remote host. I'll provide a reference page in the links at the end of this article. The "-d" option allows you to specify the database context you want to work with. It's like including the "USE " option in your script itself. The -i argument tells sqlcmd what script you want to call. I didn't need a full path reference in this case because it uses relative paths and my batch file is in the same directory as the scripts I'm calling. The last piece here is the "pause" instruction. This is simply a command line instruction that awaits a user hitting a key before moving on. This would allow you to view the output from calling the batch file before the window disappears if you double-click the file rather than run it from an open command shell.

The last part to running a list of scripts from one master sql file is the contents of the master sql file itself.

--DBCreateAll.sql

:On Error Exit

PRINT 'CREATING DATABASE...'

:r .\DBCreate.sql

PRINT 'FINISHED CREATING DATABASE...'

PRINT 'LOADING DATA...'

:r .\DBDataLoad.sql

PRINT 'FINISHED LOADING DATA...'

PRINT 'FINISHED SETTING UP DATABASE'

It's pretty self explanatory, but basically your batch file calls the immediately following filename. The sqlcmd utility interprets the :r as an instruction to add the text from the referenced sql file to the statement cache for execution.

So that about covers it! Now you have a method to separate your scripts and still run them all in Sql Server.

Reference

Thursday, July 23, 2009

Vertical Centering with CSS

I've got a secret for many of you out there. You may have perused the CSS Zen Gardens of the internet in awe-stricken hope, looking for the answer to one very simple, yet extremely elusive concept... how to get your text et. al. to center vertically with cascading style sheets. First, let me say I spent a good number of hours tinkering about in the belief that I was missing just one simple point about how elements work together in HTML. No, I wasn't missing one simple point. The point, as it turns out, is that the W3C Consortium neglected to include vertical alignment capabilities for their block level elements. Don't believe me? Check out this page straight from the horse's mouth about vertically centering text and other goodies.
W3C - Centering Things

Yeah, I was a bit underwhelmed myself too. You actually have to change the display mode over to table. See, unlike other block-level elements, tables DO have vertical centering capabilities and so the workaround is to gleefully turn your DIVs, Ps, H1s, etc., etc. into TABLE wannabes. So there you have it. There is no out of the box method for vertically centering block elements in HTML via CSS without changing their display type or performing one of the other myriad CSS-kung-fu moves.

Thursday, July 9, 2009

Microsoft .NET Code Generation Error with MySQL

Sometimes in tech you're forced to combine technologies that don't always seem naturally well-matched. This is especially true when you're hosting company offers one database technology, but not another, and when the natural scripting language partner to that database is slower than than the other competing language. So that brings me to running a MySQL database with ASP.NET 2.0/3.0 running the front end. Creating a simple web-based database application is pretty trivial, but even in those cases you can run into issues with unclear solutions.
        As I was putting together a simple web application with asp.net and mysql, I ran into a mysterious and misleading error that went something like:
Failed to generate code. Exception of type 'System.Data.Design.InternalException' was thrown.

        Oddly enough, the error pointed to the first line of my DAL DataSet.xsd where the XML declaration resides. It turns out, this is not a parsing error at all, but rather an issue with the .NET compiler being unable to auto-generate the C# code from the DataSet's XML. The reason being, it couldn't find the appropriate DbProviderFactory. The solution was pretty simple in the end. All I had to do was add the following SQL DB Provider to my web.config and I was on my way.


<system.data>
<DbProviderFactories>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net
Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory,
MySql.Data, Version=6.0.4.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D" />
</DbProviderFactories>
</system.data>

Tuesday, April 28, 2009

.NET TableAdapter - connectionString fails for 'xxxx\ASPNET'

While working on getting an application copied from my development environment over to IIS for production testing I ran into an interesting database error.
System.Data.SqlClient.SqlException: Cannot open database "xxYourDBNameHerexx" requested by the login. The login failed.
Login failed for user 'xxComputerNamexx\ASPNET'.

My first thought was that I had wiped out a necessary database login or user when I accidentally wiped them all out the other day (you'll see how I recovered from this in another post), but it was much simpler to correct. There's a parameter in the connectionString, "Integrated Security" that's set to true when you create your TableAdapters in Visual Web Developer. This tells your application to login to SQL Server using the current logged in user's credentials, which seems to be those of IIS for a web application. From MSDN says this of the Integrated Security setting:
When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.

Simply change the value to false and then supply a username and password like so:

connectionString="Data Source=YOUR-COMPUTER\SQLEXPRESS;Initial Catalog=YourDBNameHere;Integrated Security=False;User ID=YourUserName;Password=YourPassword"


References:








Friday, March 27, 2009

.NET Ajax - Using Sys.Component.create and $create

I recently spent some time getting intimate with the .NET Ajax library v1.0 and found the documentation for Sys.Component.create and $create particularly ambiguous, so I've decided to talk about it here to help other developers facing similar problems. First I'd like to again clarify that for backwards compatibility with the .NET 2.0 app I'm working with I've been using .NET Ajax 1.0 as opposed to the newer 2.0 version.

The doc's provide a similar example in all cases:

$create(MyControl, {id: 'c1', visible: true}, {click: showValue}, null, $get('button1'));

This would be fine, however I've referred to four Microsoft doc sources on the 'create' method and there are two main issues:
  1. The "id" property cannot be set on a Sys.UI.Control object, rather only on a Component or Behavior.
  2. The fourth argument's syntax, references, is never thoroughly explained. This is true even in the newest version of the docs.
It appears that the example is actually a mashup of instantiations for two object types, Sys.Component and Sys.UI.Control.

Issue 1:
If you try to set the id property on a Control object you'll get a JavaScript exception thrown along the lines of:
Error: Sys.InvalidOperationException: The id property can't be set on this object.
You can set the id property without issue on Component objects and I believe Behavior objects as well.

Issue 2:
For the other issue I will simply describe the existing documentation further, since something left incomplete cannot exactly be dubbed wrong. The MS documentation describes the references parameter as follows:
(Optional) A JSON object that describes the properties that are references to other components.

I was also able to turn up some documentation that describes the references parameter a bit further, but is still not quite enough to be useful, http://www.asp.net/AJAX/Documentation/Live/tutorials/CreatingCustomClientControlsTutorial.aspx:
An optional JSON object that contains references to associated components, passed as component name/ID pairs.

The components referred to here are other JavaScript objects created with the $create() method. So if you create an object A and set its id to 'c1', you can create an object B and then refer to object A by passing a property in the references parameter with 'c1' as the value. The undocumented mystery here is that the $create() method will extrapolate an object reference out of the id string value you supply. Figuring this out is made even more difficult when you are seemingly unable to set the id value in the first place if it's a Control (see issue 1). The main question here to answer is what should be passed as an id, a DOM id or object id? When using a Sys.Component object, there is not a corresponding DOM element associated with it and so you must specify an id during object instantiation, which is the id you will refer to for references. When using a Sys.UI.Control object, the id will derive from the required associated DOM element and this is the id value to pass in the references list. Below I've included a really simple example demonstrating the use of the references parameter to refer to another .NET Ajax component.

//------------------
// ContentManager.js
//------------------

/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("ContentManager");

ContentManager.TestA = function() {
ContentManager.TestA.initializeBase(this);

this._othercontrol = null;
}

ContentManager.TestA.prototype = {
show: function() {
alert('TestA show function called.\nthis._id: ' + this._id + '\nthis.get_id(): ' + this.get_id());
},
set_othercontrol: function(val) {
this._othercontrol = val;
},
get_othercontrol: function() {
return this._othercontrol;
},
getUsed: function(arg) {
alert("TestA getUsed called, passed this val: " + arg);
}
}

ContentManager.TestA.registerClass('ContentManager.TestA', Sys.Component);

ContentManager.TestB = function(a) {
ContentManager.TestB.initializeBase(this, [a]);

this._othercontrol = null;
}

ContentManager.TestB.prototype = {
show: function() {
alert('TestB show function called.\nthis._id: ' + this._id + '\nthis.get_id(): ' + this.get_id());
},
set_othercontrol: function(val) {
this._othercontrol = val;
},
get_othercontrol: function() {
return this._othercontrol;
},
useOtherControl: function() {
this._othercontrol.getUsed("Passed from TestB!");
},
getUsed: function(arg) {
alert("TestB getUsed called, passed this val: " + arg);
}
}

ContentManager.TestB.registerClass('ContentManager.TestB', Sys.UI.Control);


ContentManager.TestC = function(a) {
ContentManager.TestC.initializeBase(this, [a]);

this._othercontrol = null;
}

ContentManager.TestC.prototype = {
show: function() {
alert('TestC show function called.\nthis._id: ' + this._id + '\nthis.get_id(): ' + this.get_id());
},
set_othercontrol: function(val) {
this._othercontrol = val;
},
get_othercontrol: function() {
return this._othercontrol;
},
useOtherControl: function() {
this._othercontrol.getUsed("Passed from TestC!");
}
}

ContentManager.TestC.registerClass('ContentManager.TestC', Sys.UI.Control);

// Notify the ScriptManager that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();



//--------------
// AJAXTest.aspx
//--------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AJAXTest.aspx.cs" Inherits="management_AJAXTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Test</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/ContentManager.js" />
</Scripts>
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" Text="Button1" />
<asp:Button ID="Button2" runat="server" Text="Button2" />
<script type="text/javascript">
var app = Sys.Application;
app.add_load(applicationLoadHandler);

function applicationLoadHandler() {
// instantiate a component
var aCtrl = $create(ContentManager.TestA, { id: 'controla' });
// instantiate a control
var bCtrl = $create(ContentManager.TestB, null, null, { othercontrol: 'controla' }, $get('Button1'));
// instantiate a control
var cCtrl = $create(ContentManager.TestC, null, null, { othercontrol: 'Button1' }, $get('Button2'));

// Display alert message from TestA, TestB, and TestC
aCtrl.show();
bCtrl.show();
cCtrl.show();

// Display alert message from TestA (aCtrl var) via TestB (bCtrl var) property referencing TestA.
bCtrl.get_othercontrol().show();
// Display alert message from TestB via TestC property referencing TestB, 'Button2'.
cCtrl.get_othercontrol().show();

// Display alert message calling TestB function that uses TestA behind the scenes.
bCtrl.useOtherControl();
cCtrl.useOtherControl();
}
</script>
</form>
</body>
</html>

Running the example will give you a simple page with two buttons that pops up three alert messages on page load. In a real circumstance it would probably make more sense if I applied these alerts via some onclick handler function, but it gets the point across.

Cheers,
Mike

References: