Solving Firebug’s “Unable to show styles”

November 8, 2009

I recently installed Firebug to debug some CSS problems, but the only CSS information I got was the message “Unable to show styles”. The link in the message to the FAQ was not very helpful, either.

Fortunately, this post by Ingo was, as it solved this problem.

The problem is caused by a couple of ancient files under the Mozilla Firefox directory belonging to an ancient version of DOM Inspector, which seem to have remained there since the earliest version 1.0x of Firefox, and are easily identifiable by the file date (in my case, the year 2005).

To solve the problem, uninstall Firebug, remove the offending files, restart Firefox and reinstall Firebug.

The files are:

components.ini
defaults.ini
chrome\inspector.jar
chrome\pipnss.jar
components\inspector.dll
components\inspector.xpt
components\inspector-cmdline.js
defaults\pref\inspector.js
extensions\Extensions.rdf
extensions\installed-extensions-processed.txt
res\platform-forms.css
res\builtin\platformHTMLBindings.xml
res\inspector\search-registry.rdf
res\inspector\viewer-registry.rdf

(list taken from above link, but as I said, you find the outdated files by their age)


Entity Designer opens edmx file only once, and other VS bugs

November 6, 2009

I found that Entity Designer in Visual Studio 2008 has some strange bugs.

→ One issue is that the installation of Visual Studio can open an .edmx file only once. Double-clicking on the edmx in the Solution Explorer after closing the file will simply expand and collapse the edmx node, but the file does not open. (Strangle, a fellow programmer never experienced this behavior on his machine).

But, I’m not alone, and somebody else already described a solution for the bug:

Right-click the edmx file, choose Open with… and select XML Editor to open the file. Close it, then the Entity Designer will open the next time (once).

→ Another issue is that VS freezes if you open the edmx in Entity Designer and navigate through it when the file is not checked out from TFS.

→ And then I wonder why, as Entity Designer implements auto-routing of foreign keys, it sometimes loses some connection points, and the connections/relations end somewhere in the diagram, instead of ending at the referencing entities, and the lines are criss-cross instead of horizontal or vertical.

→ And if you delete an entity from the diagram, the underlying object still remains in the edmx, and there is no way the Designer allows you to add the deleted entity. You either have to re-create it manually, which is cumbersome.

The solution I found was to rename the object in the database, execute Update Model so that Designer drops the object, rename the object back to its original name, and Update Model again.

→ And if you create a function mapping for a stored procedure, and define the return type as any of the entities, then the stored procedure needs to return a SELECT with the *mapped column names* instead of the original datamodel column names. In my opinion, this behavior breaks the concept of “mapping”.

→ And if you create a function mapping for a stored procedure with a SELECT that is not mappable to an entity, or returns no result or an integer result, you won’t find the mapped function in your C# code, because the generator does not create any code for it. The same is true for user defined SQL functions.

(Actually I found a solution for the missing stored procedure code generation, which I will post here soon)

Some of these issues can also be found on Connect. If you have a solution, please let me know.

Certain things will always remain a mystery to me ;)


Shared aspx and ascx Files in Visual Studio and TFS

November 5, 2009

In a Visual Studio (2008) project, we have two web applications that should share some aspx pages and ascx controls.

I found this tutorial Creating and Using User Control Libraries, which works in principal, but has left TFS integration out of the solution.

You start with two (or more) applications which have common elements. First create another Web Application Project and create a new folder named “shared” (or “common” or whatever your preferred name is).

The directory hierarchy under “shared” in the common project should be the same as expected by the referencing projects.

Now move the common files into this folder. Make sure you rename the namespace declarations in the moved files to the new web application’s namespace. Check the files in TFS.

Delete the copies of the common files from the referencing projects. After updating from TFS (Get Latest Version), make sure the files are really deleted in the file system. (I had several occurrences where deletions were not executing in the directories)

In the referencing projects, add as Pre-build event command line the following lines:

xcopy /s /y "$(SolutionDir)shared\*.ascx" "$(ProjectDir)"
xcopy /s /y "$(SolutionDir)shared\*.aspx" "$(ProjectDir)"

Adjust the path after $(SolutionDir) to match the path to the common project. You may also use $(ProjectDir) as base source path, and ..\ for parent directories.

Save the project, check in all pending changes, and build, which will execute the pre-build events, but will (most likely) fail, since you are still missing some files.

Next, use Project, Show All Files to display files in the Solution Explorer which are not part of the project.

Find the xcopied files, right-click each file individually and select Include in Project. This will add the ascx and aspx files in the project, and mark them Added in TFS.

Since we already have the files in TFS in the common project, and simply copy them into the referencing projects during build, we don’t want them in TFS in the referencing projects.

Select the added files in the Pending Changes window (i.e. all files except for the project file), right-click and execute Undo. Thus the files will not end up in TFS.

Check in the project file, and build.


oraddlscript: Solving ODP.Net version conflicts

November 4, 2009

I got feedback on oraddlscript that exceptions are raised due to incompatible versions of Oracle.DataAccess.dll. I could reproduce these exceptions on a non-development machine.

After installing Oracle Data Access Components (ODAC) 11.1.0.6.21 using the install command

install.bat all c:\oracle\odp odac

the problem was solved, and I could connect to the database server.

Oracle Data Access Components (ODAC) are available for download from Oracle here.


Profiling .Net Applications

November 1, 2009

I am working on replacing the current (ugly) SQL parser of dbscript by a nice grammar-based parser as outlined in previous posts. That part of the project has been idle for some months now, but it’s time to integrate a grammer-based parser.

During tests I found that the new parser takes several minutes to parse an SQL file, whereas the old one processed the same file within seconds. Where is this time spent?

Time to profile the code. There are a couple of .Net profilers around, also Microsoft also provides a product called CLR Profiler which can be downloaded here.

When you start the CLRProfiler.exe application, both a console window and a WinForm window open. (This may look unusual, but hey, it’s a developer tool, and it is the functionality that counts)

Click on Start Application to select the executable you want to profile. The application starts up and you perform the tasks to profile just as if you started the application directly. (It just takes a little longer than usual, because the profiler does its work in the background).

When you’re done, close the application. (You may also choose the profiler’s Kill Application button). The profiler will now compute its magic numbers while message “Progress loading (filename).log” is displayed. After computation has finished, a Summary window displays memory and garbage collection statistics.

Click on the Allocated bytes Histogram button, and find the classes with most objects instantiated during the run.

For my purposes, the View Function Graph command was the most useful. It shows the percentage of time spent by each called function relative to the calling function.

It is not obvious from the UI, but each box representing a function can be drilled down by double-clicking it, showing again the percentages of the sub functions. (My guess is that only functions of the same assembly are shown in one graph, and the drill-down is necessary to switch between assemblies).

Anyway, I like that tool, as it showed me in just two (!!) graphs where the code spent its time, and as it turned out, these were just debugging routines (create XML document, retrieve its OuterText property, write to Console).


Protecting SQL Server Data from Accidental Deletion

October 30, 2009

In nearly every project that I worked on in recent years, the database not only stores the data maintained by the application, but also describes (parts of) the application itself. If you ever had to implement a permission system which grants users to view or edit tables or open forms or execute functions, you already know that.

The resulting problem is that if the application relies on certain key data to be present and correct, accidental modification or deletion of that data usually causes the application to fail.

I try to show how to use triggers to prevent accidental data modification.

Prevent table data deletion

The simplest way to prevent data deletion is to have an INSTEAD OF DELETE trigger which does nothing, or simply raises an error:

CREATE TRIGGER [dbo].[Prevent_Foo_Delete]
    ON [dbo].[Foo]
    INSTEAD OF DELETE
AS
BEGIN
    SET NOCOUNT ON;
    RAISERROR('You cannot delete Foo',1,0);
END

If you really need to delete data, use the DISABLE TRIGGER (2005, 2008) and ENABLE TRIGGER (2005, 2008) commands.

Conditional deletion prevention

In this case, deletion should only be allowed under certain conditions. For example, we could allow to only delete single records:

CREATE TRIGGER [dbo].[Prevent_Foo_Multi_Delete]
   ON  [dbo].[Foo]
   INSTEAD OF DELETE
AS
BEGIN
    SET NOCOUNT ON;

    IF (SELECT COUNT(ID) FROM deleted) > 1
        RAISERROR('You can only delete a single Foo',1,0);
    ELSE
        DELETE Foo
        FROM Foo INNER JOIN deleted ON Foo.ID = deleted.ID

Similarly, one could prevent the deletion of detail records to only a single master record by writing

    IF (SELECT COUNT(DISTINCT BAR_ID) FROM deleted) > 1

Preventing Modifications

The same method can be used for UPDATE triggers. It may be, however, easier to define an ON UPDATE trigger to avoid rephrase the UPDATE statement in an INSTEAD OF trigger. In case of failure, we rollback the current transaction:

CREATE TRIGGER [dbo].[Prevent_Foo_Update]
   ON  [dbo].[Foo]
   FOR UPDATE
AS
BEGIN
      SET NOCOUNT ON;

      IF (SELECT COUNT(ID) FROM inserted) > 1 BEGIN
            ROLLBACK TRANSACTION
            RAISERROR('You can only modify 1 Foo',1,0);
      END
END

Preventing Truncation

These mechanisms prevent you from an accidental UPDATE or DELETE on all records (e.g. by a missing WHERE clause, or semicolon in front of the WHERE condition).

However, there is still the TRUNCATE TABLE command which deletes all data in a table and cannot be stopped by a DELETE trigger:

Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

The rescue shows in the preceding sentence:

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint

Simply have a table that references the tables to be protected:

CREATE TABLE Prevent_Truncate(
    Foo_ID INT REFERENCES Foo(ID),
    Bar_ID INT REFERENCES Bar(ID)
)

You only appreciate how valuable your data is once it’s lost ;)


Introducing oraddlscript

October 25, 2009

A recent question on StackOverflow inspired me to write a utility called oraddlscript:

How to generate scripts for Oracle schema objects, such as tables, procedures, etc.

The answers directed me to the DBMS_METADATA package (9i documentation, 10g documentation). The function DBMS_METADATA.GET_DDL is the functional equivalent of the MSSQL SMO library, which prompted me to adapt my command-line utility SMOscript to Oracle databases. Voilà, oraddlscript.

oraddlscript 0.14.3584.16268 (c) by devio.at 2009

    list and script databases and database objects.

    usage: oraddlscript [options] [command]

    options: (leading '-' or '/')

    -s server       TNS name or host name or host:port
    -svc service    service name (if host name is provided)
    -o owner        owner name

    -u username     username (default: integrated authentication)
    -p password     password (if -u is missing, password for sa)

    -f filename     output to file
    -F directory    output to directory

    -A              current ANSI codepage
    -O              ASCII
    -T              Unicode
    -U              UTF8

    commands:

    l               list objects
    s               script object/s (using dbms_meta.get*ddl)
    -xml            use dbms_meta.get*xml

    list object owners on server (implied by -s)
    list objects in database (implied by -s -o)
    script all objects (implied by -s -o -F/-f)

The command-line arguments are consistent with SMOscript, except for -d (database) which has been replaced by -o (owner name).

The list of objects is retrieved by querying DBA_OBJECTS, ALL_OBJECTS and USER_OBJECTS depending on which of the catalog views is accessible by the user specified by -u.

The package also contains a function GET_XML which is used to retrieve the XML representation of a database object.

The functions of oraddlscript are:

  • list usernames of object owners
  • list objects of specific owner
  • generate CREATE scripts of objects owned by specific user
  • generate XML files representing objects owned by specific user
  • generate one file per object or single file for all objects

Of course, logging and batch operations work just as previously described for SMOscript.

oraddlscript is available for download here.


Generating Table of Contents from WordPress Export

October 23, 2009

WordPress implements an Export function which allows bloggers to download the contents of their blog as a single XML file.

In a previous post I described an XSLT file to convert the exported XML into a single HTML file. A click on an article’s title displayed the whole article using a little JavaScript and CSS.

This time, I wanted to create an HTML table of contents displaying all the blog’s categories. Upon selection of a category, only the posting titles of that category should be displayed. The titles link to the original blog articles.

The new XSLT is available for download here.

Applied to this blog, the generated Table of Contents is here.


dbscript New Version 0.99

October 20, 2009

The latest version 0.99 of dbscript has been released today providing new functionality and a couple of fixes.

Data diagrams looked a bit distorted if the data model contained circular foreign key constraints. I sketched the problem in my article on cycle detection, and the data diagram now excludes circular foreign keys in the calculation of the tables’ positions.

Comparison results can be restricted to “scopes”, such as new objects only, dropped objects only, etc. This makes it easier to generate schema migration scripts without dropping objects, for example.

Documentation Generators provide a preview to the generated content, and the generated XML now contains the project and project version identifiers to enable linking and referencing in the generator’s output.

Scripting a table in the object’s Generate/Create page now includes all constraints and indexes. (The project version script always included child objects). The same applies to object comparisons of tables, so that changes to indexes etc are easily identifiable.

New Functions

Besides generating .png data diagrams, dbscript now has the capability to generate data diagrams for Dia, an open-source diagrammer. The layout routine is the same as for png’s, but the output is Dia’s native XML format. Generating for Dia means that developers can freely layout and edit the diagram according to their needs, and export it to other formats. I described this feature earlier, and included samples.

Schema comparison is one basic feature of dbscript, and the new version compares multiple versions in one operation. After defining which schema versions to compare, you get a comparison matrix showing the number of differences between any two versions.

If the selected versions are versions of the same schema at different points of time, the comparison timeline shows each object ever changing in any of the versions, along with an indicator of the change.

Within a project, you can define Branches (as known from version control systems) and assign project versions to a branch. This alone would not be too overwhelming, but branches are a precondition of the update notification system, which I will describe in a future post.

The latest version of dbscript is available for download here.

Please leave comments and feedback.


Get Absolute URL of ASP.Net Application

October 19, 2009

In one of my web projects, I needed to pass the name of a specific URL inside the application to another application. So the first task was: how do I find the absolute URL of an ASP.Net application’s root directory.

I tried ResolveClientUrl, which, according to MSDN, returns

A fully qualified URL to the specified resource suitable for use on the browser

As I was expecting an absolute URL from this description, it turned out, it doesn’t. (There also seems to be a terminological confusion between a Fully Qualified Domain Name, and Absolute and Relative URLs)

Both ResolveUrl and ResolveClientUrl create URLs relative to the page’s URL or the application root, but no absolute URL.

Fortunately, I found this entry on geekpedia, which provided a solution (that I was very close to develop on my own ;) )

public string FullyQualifiedApplicationPath
{
  get
  {
    //Return variable declaration
    string appPath = null;

    //Getting the current context of HTTP request
    HttpContext context = HttpContext.Current;

    //Checking the current context content
    if (context != null)
    {
      //Formatting the fully qualified website url/name
      appPath = string.Format("{0}://{1}{2}{3}",
        context.Request.Url.Scheme,
        context.Request.Url.Host,
        context.Request.Url.Port == 80
          ? string.Empty : ":" + context.Request.Url.Port,
        context.Request.ApplicationPath);
    }
    if (!appPath.EndsWith("/"))
      appPath += "/";
    return appPath;
  }
}

Of course, if you are inside a Page’s context, this reduced version is sufficient

string appPath = string.Format("{0}://{1}{2}{3}",
  context.Request.Url.Scheme,
  context.Request.Url.Host,
  context.Request.Url.Port == 80
    ? string.Empty : ":" + context.Request.Url.Port,
  context.Request.ApplicationPath);
if (!appPath.EndsWith("/"))
  appPath += "/";