Monday, July 26, 2010

Adding a gallery to your .NET 4.0 application

After a frustrated user posted his troubles getting GSP to work in a .NET 4.0 application, I thought I would dig into it to see what was going on. I have step by step directions for Visual Studio 2008 in the Admin Guide, but it turns out they don’t quite work for Visual Studio 2010. I also felt I could improve upon the explanation that is in the Admin Guide, so I decided to completely rewrite it in this blog post. Eventually I will update the Admin Guide to include this information.

I will create a default .NET 4.0 web application and then add a gallery to it. These steps are largely the same for Visual Studio 2005 and 2008, too.

Download the sample application I created for this post. A couple notes: (1) Log in to the gallery with username Admin (password=111). (2) For demonstration purposes, it includes the latest release of the AJAX Control Toolkit, not the version that ships with GSP.

Integration strategies

First, let’s review the ways one can add a gallery into an existing ASP.NET app, in order from least coupled to most coupled:

1. Deploy the GSP support files and DLLs and don’t use assembly references – The contents of the gs directory are deployed to your server but not included as content files in your Visual Studio project. The GSP assemblies are deployed to the bin directory but not referenced by the project. The only parts of your project that are “aware” of GSP are: (1) App_GlobalResources contains the resource file GalleryServerPro.resx, (2) web.config contains the required GSP configuration, (3) the web page for the gallery contains a Register tag for the GSP user control and, of course, the Gallery user control itself.

The advantage of this approach are:

  1. You can add a gallery to your site without having to recompile it.
  2. You can update to new versions of GSP without having to recompile – just copy the new files to your server.
  3. Your Visual Studio project has minimal knowledge of GSP, which helps to keep things clean and allows you to focus on your application without thinking too much about GSP.

The disadvantages of this approach are:

  1. You cannot use the GSP API (which may be used in advanced customization scenarios).
  2. You no longer have your entire app contained within a single project, which makes management more difficult.
  3. You cannot use the built-in publishing functionality in Visual Studio to deploy your app. Well, not the GSP portion anyway.

This is the approach I use for the demo gallery on www.galleryserverpro.com.

2. Include the files as part of the Visual Studio solution, but don’t reference the GSP DLLs – Copy the gs directory and other files into your app and make them part of your solution/project. This is the method documented in the Admin Guide. It has the advantage of keeping everything organized in one project, which allows for simple source control and deployment, but tends to clutter up your app with GSP dependencies that can be a distraction.

3. Same as above, but also reference the GSP DLLs - Copy the files into your app and make them part of your solution/project. Add references to the GSP assemblies to make your app aware of GSP. This is required when you use the API in advanced scenarios (for example, if you want to create your own upload page and add media objects yourself). But doing this in .NET versions higher than 2.0 will often give you compile errors. They are all solvable without too much work, but they can be a hassle.

Step by step: Adding a gallery

Each strategy can be the right solution depending on your requirements. Unless you intend to use the GSP API, most developers will want to use the first or second technique.

Here are step by step directions for adding a gallery to an existing .NET 4.0 application using the first strategy. In this example, I’ll use Visual Studio 2010 Ultimate to add a gallery to a default ASP.NET application. Just for fun, I am using a Visual Basic project, which works great even though GSP is written in C#. I believe the steps are the same for all web-enabled versions of Visual Studio, including the free Express one.

Note: By default, Visual Studio creates pages that require compilation, but at the end of this post I’ll show how to create pages that don’t require compilation, thus providing you with the no-compile advantage I mentioned above.

Note: If you already have an existing web app, skip to step # 3.

  1. Use Visual Studio 2010 to create a new ASP.NET 4.0 application using the ASP.NET Web Application template. Here I am using Visual Basic, but you can use another language.

    dotnet4_1

  2. The project will be created. In Solution Explorer, right click Default.aspx and choose View in Browser. The home page appears:

    dotnet4_2

  3. Okay! We have a working ASP.NET 4.0 app. Now we want to add a gallery to it. If you do not have an App_GlobalResources directory in your application, create one by using Visual Studio to right click the web project node in the Solution Explorer and choosing Add - Add ASP.NET Folder - App_GlobalResources. Similarly, add an App_Data folder if your project does not have one.

  4. Download the compiled version of Gallery Server Pro and extract the contents to a temporary directory. Use Windows Explorer to copy the following items:

    1. Copy the gs directory into your ASP.NET app. It should be at the same level as your other top-level directories, such as App_Data.
    2. Copy the contents of the bin directory into your bin directory.
    3. Copy GalleryServerPro.resx from App_GlobalResources into the same directory in your app.
    4. Copy galleryserverpro_data.sqlite from App_Data into the same directory in your app (not necessary if you use SQL Server).
    5. Copy web_4.0.config into the root of your app. Delete the existing web.config and rename web_4.0.config to web.config. NOTE: Your web.config may have settings you need to preserve, so you may need to manually merge the two instead.
  5. Create a new web page to hold the gallery. In this example, I created a page named Gallery.aspx from the Web Form Using Master Page template and then selected Site.Master for the master page. At the top of the page add a line to tell the page where the Gallery user control is defined:

    <%@ Register TagPrefix="gsp" Namespace="GalleryServerPro.Web" Assembly="GalleryServerPro.Web" %>

  6. Then add the user control somewhere in the body of the page:

    <gsp:Gallery ID="g" runat="server" />

  7. Compile the application. You will probably get the compilation error “Type ‘GalleryServerPro.Web.Gallery’ is not defined”, as seen here:

    dotnet4_3

  8. This error is not covered in the Admin Guide because it never happened under Visual Studio 2008. The reason for this error is because Visual Studio added a definition for the control in the page’s designer file and the compiler doesn’t know where the user control is defined. This doesn’t seem right to me - I would argue that it should know where it is because we explicitly defined it in the <%@ Register … /> tag.

  9. But no matter, because we can easily fix it. Double click the error to show the offending code:

    dotnet4_4

  10. Delete the line that is causing the error. As best I can tell there are no harmful consequences to removing it. The page will look like this when you are done:

    dotnet4_5

  11. Now compile the application. It should succeed. Right click the page and choose View in Browser. The page will appear with an empty gallery:

    dotnet4_6

  12. By default, no users are defined and the gallery is configured to use SQLite for data storage, so run the install wizard to set up the membership system and optionally configure SQL Server. In the web browser, add “?g=install” to the URL. The install wizard appears:

    dotnet4_7

  13. Step through the install wizard. When complete, you are redirected back to your gallery, which now includes a sample album and image. All done!

    dotnet4_8

Integrating with existing users

The integration example above assumes you are setting up a new set of users, but you might want the gallery to be integrated with your existing membership provider. After running the install wizard, open web.config and update the membership, role, and profile sections to point to the desired providers. GSP will use the default provider unless you specify a particular provider in the galleryserverpro.config settings membershipProviderName and roleProviderName.

After pointing web.config to your membership, you may get the following error:

dotnet4_9

This is happening because GSP doesn’t know what kind of security access any of your users have, so it assumes a “better safe than sorry” position and doesn’t let anybody in. To define the administrator, open the table gs_Role. GSP should have created a list of records in this table that mirror the roles in your role provider (if you don’t see any, try restarting the web app, which triggers the validation code that synchronizes the roles in gs_Role with the roles in your role provider). Pick the record that represents the system administrator role and set the AllowAdministerSite column to true. Then restart the app (or edit the album summary, which clears the role cache). Any users in this role should now have full administrative permission to the gallery. Now that you can log on as an administrator, you can use the normal GSP admin functions to define the security for the rest of the users.

No compile option

To add a gallery to your app without requiring compilation, remove the code behind file from the web page that contains the gallery user control. For example, in the example above, change the first line from this:

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Gallery.aspx.vb" Inherits="WebWithGsp.Gallery" %>

to this:

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" %>

After this change, the code behind files Gallery.aspx.vb and Gallery.aspx.designer.vb are no longer need and can be deleted.

An added benefit to this option is that you won’t be affected by the compile error we received above, since the designer file does not exist.

ASP.NET compatibility

Update 2010-08-03: Check out this blog post for more info.

If you look carefully at the screen shots, you will notice we lost the nice formatting of the menu after we added the gallery:

dotnet4_10

This is because the 4.0 version of web.config that ships with GSP is configured to render objects the pre-4.0 way. That is, the attribute controlRenderingCompatibilityVersion is set to 3.5:

<pages theme="" styleSheetTheme="" validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />

This is an application wide setting, so this causes the menu to render using tables (<table>) rather than list items (<li>), which breaks the CSS in the default ASP.NET application.

You can restore the formatting of the menu by setting the compatibility version to 4.0, or removing it altogether. After this change, it looks like this:

dotnet4_11

I specified 3.5 compatibility mode in web.config because I wanted to guarantee that everything worked the same in .NET 4.0. I am not sure it is required, though. In some very brief testing, I couldn’t find anything that was broken in 4.0 mode. It is possible that future releases will default to the native 4.0 rendering.

AJAX Control Toolkit

GSP ships with version 1.0.10920 of the AJAX Control Toolkit, which is the most recent version of the toolkit that is compatible with .NET 2.0. If you want to use later versions in your app, GSP will work with it, but you must update web.config so that GSP uses the desired version rather than looking in vain for the one it was compiled against. Open web.config and add this line just before the final </configuration> element:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="AjaxControlToolkit" publicKeyToken="28f01b0e84b6d53e" />
      <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="4.1.40412.0" />
     </dependentAssembly>
  </assemblyBinding>
</runtime>

Update the newVersion attribute as needed to reflect the version of your AjaxControlToolkit.dll.

MVC apps

GSP is a webforms application, which is very different than the MVC pattern recently introduced by Microsoft. Generally speaking, webforms and MVC functionality don’t belong in the same application and can give you trouble if you try.

Having said that, it *is* possible to add a gallery to an MVC app. I actually did it for a customer not long ago. Here are the key lessons I learned:

  • The gallery user control must be added to a webforms page, not an MVC one.

  • I added a line to global.asax to tell the routing system to ignore paths to the webforms page. In my case, I put the webform (an .aspx page containing the Gallery user control) in a directory named Webforms and then added this line to global.asax: routes.IgnoreRoute("Webforms/{*pathInfo}");

  • The javascript on the Rearrange objects page failed until I set controlRenderingCompatibilityVersion to “3.5” in web.config.

  • Getting MVC and webform pages to share the same master page is difficult. I actually had to define a top level master page Root.Master that inherited from System.Web.UI.MasterPage. In this page I put the main layout. Then I created two child master pages – one was called Mvc.Master and it inherited System.Web.Mvc.ViewMasterPage; the other was called Webform.Master and it inherited from System.Web.UI.MasterPage. Both child pages used Root.Master as its own master page, and served as essentially empty containers for the web pages. All MVC pages used Mvc.Master; webforms used Webform.Master. A big problem with this approach is that the top level master page cannot use any MVC code. And if you add something to Mvc.Master, you must duplicate it in Webform.Master. This is a fragile approach that might create maintainability issues down the road, but I couldn’t come up with anything better. An alternative was to create identical master pages – one for MVC and one for webforms, but that is obviously not ideal.

Tuesday, July 6, 2010

Turning a lemon into lemonade: Multiple galleries in a single web application

A clash between DotNetNuke portals and Gallery Server Pro architecture

Back in March I released an alpha build to a few select users for a new DotNetNuke module version of Gallery Server Pro. At the time I thought I was nearly done. Well, it turns out that DotNetNuke has one feature that conflicted with GSP’s architecture: Multiple Portals. And I’ve been working to resolve this ever since.

Portals are a concept in DNN where a single web application can have one or more mini-web sites that appear – to the outside world – as if they are separate applications. They can even have different URLs: www.p1.site.com, www.p2.site.com, etc. For example, a user navigating to www.p1.site.com would see a site that looks completely different than www.p2.site.com. It can have a different theme, different content, and even different users, but behind the scenes it is a single web application connecting to a single database.

My alpha testers noticed that the GSP module worked fine EXCEPT that media objects were shared across multiple portals. Not cool - Each portal must have its own set of media objects and its own administration settings. At first I thought – no big deal – GSP already has the concept of a gallery – all I need to do is create a unique gallery for each portal.

The problem, however, was that the Gallery ID was specified in galleryserverpro.config, and there is only one of those per web application. I had to figure out how to manage multiple galleries within *one* application. There was no way to shoehorn the config file to support multiple galleries unless I radically changed its structure. Even then, an administrator updating a setting in one portal would cause the entire application pool to recycle, since that is how the ASP.NET configuration system works. Something big had to change.

Refactoring gallery settings to the database

In the end, I abandoned the galleryserverpro.config file and moved everything into the database. There are now five new tables:

gs_GallerySetting – Stores most of the items in the <core> section of galleryserverpro.config, such as ShowErrorDetails and MediaObjectPath. The column FKGalleryId is a foreign key to gs_Gallery, so each gallery gets its own set of settings.

gs_AppSetting – It made sense to keep a few items from galleryserverpro.config at the application level, and these are stored here. It has just a few records that apply to all galleries, such as JQueryScriptPath and ProductKey.

gs_BrowserTemplate – These are the HTML templates from galleryserverpro.config.

gs_MimeType – This is a read-only list of all MIME types.

gs_MimeTypeGallery – This stores whether each MIME type is enabled or disabled for a gallery.

These changes were applied to the source code trunk, meaning it affects the main release of GSP in addition to the DotNetNuke branch.

With these changes, the next version of GSP will support multiple, distinct sets of media objects within a single web application. Each set – called a gallery – has its own settings, users and roles. From the user’s perspective, the media objects are completely isolated from each other, although a site administrator can move or copy objects between galleries. And the galleryserverpro.config file has been confined to the dustbins of history.

A quick note about users and roles: GSP continues to use the membership and role provider model. This model enforces a unique set of user and role names across the entire application. That means that once a user is created, that username cannot be created again in other galleries. You can, however, *share* users and roles across galleries. For example, you can assign user ‘Bob’ to have view permission in gallery 1, write permission in gallery 2, and no permission whatsoever in gallery 3.

I used the phrase “turning lemon into lemonade” in the title because this was not something I wanted to spend three months working on, nor do I think this is a feature that regular GSP users are clamoring for. I would have rather spent this time adding tagging support, improving the upload experience, or just about any of the one hundred items on my to-do list.

Making lemonade

However, it turns out there are significant benefits to this change. One of my favorites is that the application pool no longer recycles when you update a setting. Now you can edit a setting without affecting any in-progress uploads or synchronizations.

Plus, more complex scenarios suddenly become possible:

  • You want to have one gallery for staging and another for production. Media objects are first added to the staging area, where they are organized and prepped. When they are ready to be deployed, they can be moved or copied to the production gallery.
  • You have departments in your company that should each have their own gallery. Each gallery should have its own administrator and can have its own settings, such as user accounts, watermark, permissions, etc. Rather than setting up and maintaining multiple web applications, this can now be handled in a single app.
  • You have media files in multiple locations you want to expose, such as D:\Pictures and D:\Video.
  • You want to set up a gallery for each member of your family. Each person is a mini-administrator for their area and can't edit another person's media objects, yet everything is contained within a single web application and database.
  • You want some images to be 640x480 and others to be smaller (or larger).
  • You want to have a watermark applied to one set of images but another set should have no watermark, and all images are to be accessible to anonymous users. Or you have different watermarks that should be applied to different sets of images.
  • You want to provide a user with different gallery-wide permissions. For example, user 'Bob' should be a gallery administrator for one set of objects, but have edit-only permission for another set.
  • You want to allow some users to upload any file type of any size, but others should only be able to upload .JPEG's that are less than 5 MB.

Gallery administration

To accommodate this change, the concept of a “gallery administrator” has been introduced. A gallery administrator can change settings for a particular gallery but has no rights to other galleries. She can add users and roles, but those accounts are restricted to the current gallery.

The previous concept of a site administrator remains. The site administrator has complete access to all galleries.

Creating multiple galleries

The desired gallery is now specified on the Gallery user control defined in the web page. For example, the Gallery definition in default.aspx now looks like this:

<gsp:Gallery ID="g" runat="server" GalleryId="1" />

To create a second gallery, just add a new ASPX page and specify a new gallery ID:

<gsp:Gallery ID="g" runat="server" GalleryId="2" />

The first time you load this page, GSP will automatically create the gallery and a default set of gallery settings. One of the first things you may want to do is check the media object path to ensure it is at a unique location. You *can* use the same media object path in multiple galleries, but note that updating an object in one gallery does not update the database record associated with the other gallery.

Example: Create a staging gallery

To create a staging gallery where you can prep objects before pushing them to the production gallery, copy default.aspx to create a second ASPX page called gallerystaging.aspx. Change the gallery ID to a new value (such as 2). Open this page in your browser – you don’t need to run the install wizard or compile any source code. Log in with any account with ‘Allow site administration’ permission and configure the settings as desired, such as disabling anonymous access and changing the media object file path. Synchronize or add your media objects and organize them as you wish.

I’ll assume the original page default.aspx is your production gallery. While in your staging gallery, use the move/copy function to transfer the items to the production gallery. Voila! You have just deployed your items to production.

Roadmap

My priority is to get a beta version of the DotNetNuke module released as soon as possible. There are still some odds and ends to take care of, like how to implement licensing, but hopefully nothing significant. If I didn’t have any distractions, I think it would be ready within a few weeks. But my development time has been split to support a few customers, and it is unclear how much time will be devoted to them in the coming weeks.

My best guess is that I will have the DotNetNuke beta out by the end of August. That should be followed relatively quickly with the release of GSP 2.4, which contains the multiple gallery feature I am talking about here, some bug fixes, and some great new properties on the Gallery user control that website integrators will love. I will also try to squeeze in some high-value, easy-to-implement feature requests.

Once the DotNetNuke module and 2.4 is out, I plan to implement those top features requests you have:

  • Tagging
  • Better upload experience – especially the ability to upload a compressed version of an image rather than the original
  • Extract video thumbnails
  • Advanced sorting
  • Much more…