Category Archives: Development

Hosting XAF ASP.NET Projects using Azure Web Sites

Azure Web Sites is a new offering from Microsoft under their Windows Azure cloud platform. It’s a scalable solution that allows you to host ASP.NET, PHP, and node.js projects. If your needs are basic, your sites – up to 10 of them – can be hosted for free*. If you need something like a custom domain, you’ll pay a bit more – currently about $8/mo. If you’d like a reserved instance, rather than shared, that will kick it up to around $70/mo. But you can run several of your web sites on that one reserved instance.
*bandwidth and database sold separately see site for details

The awesome thing is that you can start with the free setup, get up to 10 web sites going and, if your needs grow, scale your web sites up by simple dragging sliders in a web portal. It’s all very simple and straightforward and seems to work well.


One of the first things I tried with the free Azure Web Sites preview was hosting an eXpressApp Framework ASP.NET solution and database. While there are a few gotchas that came with publishing my XAF project to Azure Web Sites, most were the sort of issues you’d work through publishing an XAF ASP.NET project to any new server. However, there are some Azure-specific steps needed to work through some of these, which I’ll cover towards the end.

To get started, head to the Windows Azure homepage and sign up for Azure Web Sites. Afterwards, visit the Azure management portal. Note that after signing up for Azure Web Sites you’ll be treated to a nice new HTML5 UI for the Azure management portal (unfortunately the database management portal is still Silverlight).

Once you are in the management portal, click WEB SITES on the left, then click the NEW button at the bottom-left of the portal. Select the CREATE WITH DATABASE option (no I’m not yelling, the site is covered in caps).


You’ll need to give both your web site and database a name, and assign a login name and password for your database.


After the process completes, you’ll be left at the DASHBOARD screen for your new web site. On the right, under quick glance, click Download publish profile. This is the file you’ll use in Visual Studio to publish your XAF ASP.NET project. Next, click View connection strings and note the ADO.NET connection string for your Azure database instance.


As a final step in the Azure portal, scroll down the DASHBOARD page and click the link to your database under linked resources. Click the MANAGE button at the bottom of the portal. This should prompt you to add your current IP address to the firewall rules so that you can access the SQL database. Click YES.


This is necessary if you want to debug your application locally with the database hosted on Azure. Afterwards you can click NO to manage the database (we just needed the firewall rule added).

Next, if you haven’t already, you’ll want to download and install the Windows Azure SDK.

Now we can jump into Visual Studio and start the process of setting up the XAF ASP.NET project for hosting in Azure. First, double-click the WebApplication.cs file in the Web project. Select the Sql Connection and then edit its ConnectionString property, using the ADO.NET connection string from above. Make sure you use your real password as that will not be shown in the portal.


With the new connection string in place, and with the firewall rule added from the steps above, you should now be able to click Start to debug your XAF ASP.NET project, and successfully run against the new Azure database. This step will also create the destination database schema within the database hosted on Azure.

With these changes in place, right-click the Web project and click Publish. Click the Import button on the first screen and import the publishing profile you saved from the Azure portal.


Click Next through the wizard. On the final page you can click Start Preview to preview what will be published. Finally, click Publish.

Aaaand YSOD! Here’s where a bit of troubleshooting comes in. Some of this will be similar to publishing an ASP.NET XAF project to any host. Start by disabling Custom Errors in your web.config and Publish again.

Now you should see that the problem is that the DevExpress ExpressApp assemblies are not on the server.


Multi-select the DevExpress assemblies referenced by your Web project using CTRL or SHIFT. In the Properties Window, set Copy Local to True.


Go ahead and Publish again. Now, all of the DevExpress assemblies referenced by your project will be uploaded to Azure.

Aaaand YSOD! Even after setting all of the assemblies explicitly referenced by the ASP.NET project to Copy Local, there are missing ExpressApp assemblies.


Some assemblies – for instance DevExpress.ExpressApp.Security and DevExpress.ExpressApp.Objects – are not explicitly referenced by any of the XAF projects (mentioned to DevExpress here). While this may be addressed by DevExpress in a future update, in the meantime you’ll need to explicitly add any references with the Add Reference dialog, set Copy Local to true, Publish, and repeat on YSOD.

At this point, the ASP.NET XAF app should run properly hosted in Azure Web Sites.


But, there’s one last “gotcha” I want to cover, as trouble-shooting this is specific to Azure Web Sites. If you encounter the generic XAF ASP.NET error, you’ll need access to the XAF log to troubleshoot.


This may happen, for instance, if you make use of the HTML property editor in your ASP.NET solution and have not published all of the required assemblies.

To access the XAF log, go back to the Azure management portal. Click on the link under FTP HOSTNAME, which is in the quick glance column of the DASHBOARD.


You’ll be prompted for a username and password. You can get these by editing the PublishSettings file (downloaded above) in Notepad. Look for the userName and userPWD values after the FTP publishMode.

Once you’ve logged in, you’ll have full FTP access to both your sites and any logs. Navigate to site, then wwwroot. You should see an eXpressAppFramework.log file.


View the file’s contents, and search for “error occurred”. This will help you find XAF errors that occur that don’t cause a YSOD. This can and will happen for missing assembly references, such as DevExpress.SpellChecker.Core, if you use the HTML property editors.

With connection strings in place and all of the proper assemblies referenced and published, XAF ASP.NET projects run quite well in Azure Web Sites.


I’ve been using Azure Web Sites for a couple of months to host both my personal website and the website for Hip Shot and have been very pleased overall. And, if you don’t need a custom domain or a reserved instance, your web site hosting is free – bandwidth and database storage aside.

Emitting XtraScheduler Reminder XML


In a previous post I discussed how to generate the XML that the DevExpress XtraScheduler uses when persisting its appointment resource ID’s to a database. You can read that blog post here, and review the structure of the XtraScheduler data tables here.

In this post I’ll cover how to create the XML needed to persist XtraScheduler reminder information to a database. It’s pretty straight forward but not covered (yet) in the DevExpress documentation for the XtraScheduler control.

Again you’ll need a reference to the DevExpress.XtraScheduler.XML namespace. The classes you’ll be using are ReminderInfo and ReminderInfoContextElement. Here is an example of how to use ReminderInfo along with ReminderInfoContextElement:

        private string GetReminderInfoXML(DateTime? reminderDate, int? reminderMinutes)
        {
            ReminderInfo reminderInfo = new ReminderInfo();

            if (reminderDate != null)
            {
                reminderInfo.AlertTime = reminderDate.Value;
            }
            else if (reminderMinutes != null)
            {
                reminderInfo.TimeBeforeStart = new TimeSpan(0, reminderMinutes.Value, 0);
            }

            ReminderInfoContextElement element = new ReminderInfoContextElement(reminderInfo, DateSavingType.LocalTime);
            return element.ValueToString();
        }

I’ve also put together a small working example that you can download here.

UPDATE: There’s a real-world example of this technique you can find here. It is an open source project for transferring data from ExpressScheduler to XtraScheduler.

Using AutoMapper with Strongly-Typed DataRows

Over the years I’ve done a lot of work involving moving data in and out of databases. In most cases, this involves taking data from some form of data access object (DAO) and then copying it to a simple data transfer object (DTO) and vice-versa. I do this when working on web services or data synchronization utilities, and the practice can be tedious and repetitive. And, as with anything tedious and repetitive, it can introduce hard-to-spot bugs.

I was recently delighted to discover a very nice open source project called AutoMapper which handles these sorts of scenarios for you in a very simple manner. With only a couple of lines of code using static methods AutoMapper will copy the properties of a source object to a destination object (of different types) using very straight forward name mapping. AutoMapper also allows you to customize how each member of the source object is mapped (called projection), so you can do any necessary transformation in a very terse and easy-to-read manner.

That said, the first scenario where I wanted to make use of AutoMapper had me initially scratching my head: I had two strongly-typed datarows from different, but similar, databases and I wanted to copy the property values of one datarow to the other. I also wanted to make use of the .ForMember() and .MapFrom() methods to transform a few properties. While the mapping succeeded without error, the properties of my source row were copied to my destination row exactly, disregarding any custom mapping I provided.

Here is an example:

            DestinationData.PersonDataTable destinationDataTable = new DestinationData.PersonDataTable();
            DestinationData.PersonRow destinationRow = destinationDataTable.NewPersonRow();

            AutoMapper.Mapper.CreateMap<SourceData.PersonRow, DestinationData.PersonRow>()
                //with this ForMember, every FirstName should be "First!"
                .ForMember(src => src.FirstName, opt => opt.MapFrom(src => "First!"));

            AutoMapper.Mapper.Map<SourceData.PersonRow, DestinationData.PersonRow>(sourceRow, destinationRow);

            Debug.Assert(destinationRow.FirstName.Equals("First!"), "datarow mapping failed");

After running into the issue, I created a sample illustrating the issue, hosted it on Github, reported the issue, and took a break from the issue.

Taking a break from an issue is almost always a great help for me. Once I started looking into the issue again, it was only a few minutes and logical steps before I realized what was going on. Being new to AutoMapper, I had made an assumption that was totally invalid: I assumed AutoMapper was only mapping my type’s properties, not ancestor properties. Once I started thinking along these lines the solution came quickly.

The ancestor DataRow class has an ItemArray public property. It’s an array of objects that provides direct access to the row’s values. AutoMapper was doing its job and doing it well. After copying over the individual, strongly-typed properties found in my DataRow implementations it was also copying the ItemArray property, which is why I always ended up with an exact copy of the source row without any custom mapping via .ForMember() and .MapFrom()!

The working code looks like this:

            DestinationData.PersonDataTable destinationDataTable = new DestinationData.PersonDataTable();
            DestinationData.PersonRow destinationRow = destinationDataTable.NewPersonRow();

            AutoMapper.Mapper.CreateMap<SourceData.PersonRow, DestinationData.PersonRow>()
                //with this ForMember, every FirstName should be "First!"
                .ForMember(src => src.FirstName, opt => opt.MapFrom(src => "First!"))

                //!!don't map property ItemArray from DataRow!!
                .ForMember(src => src.ItemArray, opt => opt.Ignore());

            AutoMapper.Mapper.Map<SourceData.PersonRow, DestinationData.PersonRow>(sourceRow, destinationRow);

            //!!this assertion will fail unless you use opt.Ignore() for ItemArray!!
            Debug.Assert(destinationRow.FirstName.Equals("First!"), "datarow mapping failed");

With the extra .ForMember() in place the issue with mapping goes away. I’m excited to be back on track with AutoMapper as it seems like a great tool for mapping objects to objects.

You can view the example project on Github here.

Emitting XtraScheduler Resource ID XML


I’ve recently been spending a bit of time directly accessing and manipulating the data that the DevExpress XtraScheduler emits when persisting its changes. You can read a bit about the structure of the data tables here and view the MSSQL schema here.

Most of the columns are relatively straight-forward, containing either strings or ordinal representations of enum values. However, the resource ID, reminder info, and recurrence info columns all contain specifically formatted XML strings. Luckily the DevExpress.XtraScheduler.XML namespace contains several helpful classes to assist in reading and writing these values.

In a previous blog post I discussed reading the resource ID’s stored by the VCL ExpressScheduler, returning them as a comma-delimited string. Given such a string called resources, in order to emit the proper XML you could do the following:

                string[] resourceArray = resources.Split(',');

                ResourceIdCollection idCollection = new ResourceIdCollection();
                foreach (string resourceID in resourceArray)
                {
                    idCollection.Add(int.Parse(resourceID));
                }

                AppointmentResourceIdCollectionContextElement element = new AppointmentResourceIdCollectionContextElement(idCollection);
                string xmlString = element.ValueToString();

With these few lines of code we have the necessary XML to access and store within the DB:

<ResourceIds>
  <ResourceId Type="System.Int32" Value="1"/>
  <ResourceId Type="System.Int32" Value="4"/>
</ResourceIds>

In a future post I’ll discuss emitting the XML representations of reminder and recurrence info as well.

UPDATE: There’s a real-world example of this technique you can find here. It is an open source project for transferring data from ExpressScheduler to XtraScheduler.

Accessing ExpressScheduler Resource Information from .NET

In a previous blog post I discussed how to access the recurrence information that the VCL ExpressScheduler stores in its DB from a .NET application. Reading and writing the recurrence information is possible from .NET given a knowledge of the struct layout that the Delphi control uses.

However, if you want to read the resource information that ExpressScheduler stores in its DB from .NET, this requires using a Delphi DLL. This is because the Delphi scheduler control stores the resource ID’s for appointments in a single field but in multiple formats depending on the appointment. For instance, if the appointment has only one associated resource, its resource ID will be stored as a Delphi variant. However, the value will be stored as a Delphi variant array of variants if the appointment is associated with multiple resources.

Luckily, both Delphi and .NET make it straight-forward to interoperate between them and DevExpress has a simple utility method we can use to simplify things as well.

Start off with a new Delphi DLL project by clicking File>New>Other in Delphi XE2. On the New Items dialob, select Delphi Projects followed by Dynamic-link Library.


Start by adding both Variants and cxSchedulerStorage to the uses clause of the DPR. Then, add the following exported method to the DPR:

procedure ResourceIDBlobToString(const AResourceID: PByteArray; out AResult: PByteArray); export; stdcall;

var
  ResourceIDVar: Variant;
begin
  ResourceIDVar := cxFieldValueToVariant(AnsiString(AResourceID));
  if VarIsArray(ResourceIDVar) then
    AResult := PByteArray(VarArrayToArrayStr(ResourceIDVar))
  else
    //the cast to AnsiString below is necessary or a Unicode string will sneak in and gum up the works
    AResult := PByteArray(AnsiString(VarToStr(ResourceIDVar)));
end;

exports ResourceIDBlobToString;

This method uses the cxFieldValueToVariant utility method found in cxSchedulerStorage to translate the string representation of the field value to a Delphi variant. We then use VarIsArray to test if the variant is an array. If it is not, we simply return the variant as a string. If the variant is a variant array, we will use the following method to parse it:

//input is a variant array of strings
//output is a comma delimited string composed of the members of the input array
function VarArrayToArrayStr(const ResourceIDArray: Variant): AnsiString;
var
  I: Integer;
begin
  Result := '';
  for I := VarArrayLowBound(ResourceIDArray, 1) to VarArrayHighBound(ResourceIDArray, 1) do
  begin
    if Result <> '' then
      Result := Result + ',';
    Result := Result + VarToStr(ResourceIDArray[I]);
  end;
end;

This simple function iterates through the variant array using VarArrayLowBound and VarArrayHighBound, building up a comma-delimited list of the resource ID’s.

And that’s it for the Delphi DLL.

Next we’ll create a new C# WinForms solution to test out our DLL. Click File>New>Project and select a Windows Forms Application.


I’ll skip the data access code as it’s straight-forward. The interesting bit here is the DllImport attribute we’ll use to call our Delphi DLL:

[DllImport("ExpressSchedulerInterop.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
static extern void ResourceIDBlobToString([MarshalAs(UnmanagedType.AnsiBStr)] string resourceID, [Out, MarshalAs(UnmanagedType.AnsiBStr)] out string result);

With this method defined properly, the following code can be used to read the resource data from the DB in C#:

string result = null;
ResourceIDBlobToString((string)reader["ResourceID"], out result);

You can download a Delphi scheduler app here, the Delphi scheduler interop project here, and the C# example data reader here.

UPDATE: I updated the code in this Blog post, along with the interop Delphi project source, to address a bug when using Unicode versions of Delphi. A cast to AnsiString is necessary or only the first character in the resource ID will be returned.

UPDATE #2: There’s a real-world example of this technique you can find here. It is an open source project for transferring data from ExpressScheduler to XtraScheduler.

Using the XAF Scheduler Module with Domain Components

It had been a while since I last looked at XAF from DevExpress, and since then the new Domain Components technology has been released in version 11.2. I decided to take a look at this new technology recently and see how exactly to make use of it.

The technology itself looks very promising, but makes using some of XAF’s modules require a little extra effort in some cases. This post will go over how to use the combination of Domain Components with the SchedulerWindowsFormsModule, which takes several steps beyond those required when using normal Domain Objects.

Start off by creating a new XAF Cross-Platform Application solution.


As with any XAF based project, build the solution first so that type information is available to the XAF model editor.

Expand the WinForms (Win) application project in the Solution Explorer and double-click WinApplication.cs. Side-note: on this designer you can select the Sql Connection and edit the connection string if necessary.

Locate the SchedulerWindowsFormsModule in the XAF Modules category of the Toolbox and drag to the Modules window in WinApplication.cs


Next, in the Solution Explorer, expand the common module project and double-click Module.cs. Under Exported Types, expand Referenced assemblies and then DevExpress.Persistent.Base.vXX.Y. Right-click IPersistentRecurrentEvent (the DC we’ll be using) and click Use Type In Application


Build the solution. This is necessary so that the newly included types are available in the model editors.

So far, this is very similar to using the Domain Objects. The exception being that we’ve included the Domain Component interfaces rather than the Domain Object classes (Event, Resource).

Now, right-click the Module.cs designer and click View Code. Add the following code:

        public override void Setup(XafApplication application)
        {
            base.Setup(application);

            //register scheduling Domain Components
            XafTypesInfo.Instance.RegisterEntity("Event", typeof(DomainComponents.Common.IPersistentRecurrentEvent));
            XafTypesInfo.Instance.RegisterEntity("Resource", typeof(DomainComponents.Common.IPersistentResource));
        }

This code is necessary with Domain Components to register the interfaces with XAF.

Next we’ll need to make some modifications to the model so that the scheduler user interface elements are displayed. These steps are taken care of automatically when using the Event Domain Object. Right-click the common module project in the Solution Explorer and click Open Model Editor.


Expand NavigationItems. Then, right-click Items, go to Add, and then NavigationItem.


Select the new navigation item and, on the right, under View, select IPersistentRecurrentEvent_ListView. If you do not see IPeristentRecurrentEvent_ListView, close the model editor, rebuild, and try again.


Back in the model editor tree, expand Views, followed by DomainComponents.Common, IPersistentRecurrentEvent_DetailView, Layout, Main, and finally SimpleEditors. Select IPersistentEvent and, on the right, change Caption to Event.


Again in the model editor tree, above Layout, expand Items. Find and delete the AppointmentId and Pattern items (normally hidden by the built in Event Domain Object).


And now run the WinForms project.


You can download the sample project here.

Windows Phone 8 Details Leak

Steve Troughton-Smith happened upon a copy of the Windows Phone 8 SDK and noted these details on his Twitter account:

  • Thanks to WinPRT, Windows Phone 8 Developer Preview is able to support a significant subset of the Windows 8 SDK
  • In addition to native development, Direct3D® is being added to the family of Windows Phone technologies
  • New APIs [] include a new map control powered by Nokia maps and a wallet API for storing payment methods and enabling NFC-based payments.
  • Unfortunately for HTML developers, HTML-based phone apps are not a supported app model in Windows Phone 8 Developer Preview.
  • Windows Phone 8 Developer Preview only supports Direct3D, not the entire DirectX runtime
  • The DirectX feature level supported in Windows Phone 8 Developer Preview is level 9_3
  • Talks continue with key [game] middleware vendors but we are not able to announce any middleware compatibility with [WP8] just yet.
  • Windows Phone 8 Developer Preview supports hot-swappable SD cards, and provide read-only API access to user content stored on them.
  • Marketplace developers have API access to the Windows Phone 8 Developer Preview Bluetooth stack, courtesy of WinPRT.
  • The Windows Phone map system is being upgraded to Nokia Maps, which features beautiful cartography, […] a new 3-D mode…

Interesting stuff! If you don’t already follow Steve on Twitter I highly recommend it. He’s always sharing great new info on tons of mobile platforms.

Update: This post goes into more detail on the leak of the SDK itself and the differences between the Windows 8 RT API and Windows Phone 8 API.

Registering Missing Data Providers with Visual Studio 2012

In using the preview releases of Visual Studio 2012, something that eventually became a stumbling block was missing .NET data providers in the IDE. The .NET components themselves can be manually registered in the toolbox, but if you want tooling support (for instance for strongly-typed datasets or EF) you need the data provider registered in the IDE.

At first I switched back to Visual Studio 2010 to do these specific tasks. One of the great features of Visual Studio 2012 is its file compatibility (project round-tripping) with Visual Studio 2010. However, after a few times of doing this I decided there had to be a better way.

I tried Googling around a bit, but most of the references I found were for how component developers can register their own data providers with the IDE. For me, though, the problem was getting data providers installed that don’t yet have support for the next version of Visual Studio.

My next intuition was to search the registry. So, I fired up regedit, accepting that lovely UAC prompt, and searched for the name of one of the data providers that was registered in Visual Studio 2010 but not Visual Studio 2012 – in my case Advantage Database Server.


In the end there were four relevant results in the following locations:

HKEY_LOCAL_MACHINESOFTWAREMicrosoftVisualStudio10.0DataProviders
HKEY_LOCAL_MACHINESOFTWAREMicrosoftVisualStudio10.0DataSources
HKEY_CURRENT_USERSoftwareMicrosoftVisualStudio10.0_ConfigDataProviders
HKEY_CURRENT_USERSoftwareMicrosoftVisualStudio10.0_ConfigDataSources

Under each of these keys are another series of keys with GUID names. Selecting a GUID key will show the details of the data provider (or data source) on the right.


So, to get this single data source & provider registered in the Visual Studio 2012 IDE, I ended up locating the four specific keys to my missing data source & provider (all had the same GUID name, but in each of the above locations), and exporting those registry entries to .reg files with the right-click context menu.


Then, I edited those four .reg files in Notepad, changing any references from “VisualStudio10.0″ to “VisualStudio11.0″. Finally, after saving, I double-clicked each of the four .reg files, accepting the small army of dialogs, and fired up Visual Studio 2012. Adding a new data source showed that the data providers were now registered and working.


I may end up writing a little utility for doing this with the ability to target any version of Visual Studio but, until then, the above steps are pretty simple (if not a little manual).

Update: Thanks to user ieaglle for pointing out that the HKLM paths will be different if you are running a 64-bit edition of Windows. The paths are:

HKEY_LOCAL_MACHINESOFTWAREWow6432NodeMicrosoftVisualStudio10.0DataProviders
HKEY_LOCAL_MACHINESOFTWAREWow6432NodeMicrosoftVisualStudio10.0DataSources

Update #2: Thanks again to user ieaglle for pointing out that additional keys must be taken into consideration for SQLite. The paths are:

HKEY_CURRENT_USERSoftwareMicrosoftVisualStudio10.0_ConfigPackages
HKEY_CURRENT_USERSoftwareMicrosoftVisualStudio10.0_ConfigServices

Adding Some Style to the VCL TileControl

In my previous post in the DevExpress VCL TileControl I laid out the basics of getting a Metro-inspired application functional. However, while the result definitely had function, it was a little short on “form”.

When using the VCL TileControl, odds are you will also want a Metro-inspired skin for your application. While the ExpressSkins Library does not currently ship with any Metro-inspired skins, the RealtorWorld demo that ships with the DevExpress VCL TileControl includes two such skins: MetroBlack and MetroWhite.

Making use of these skins in your own Metro-inspired VCL application is a cinch.

To get started, copy the two SKINRES files from the following path to your own application’s working directory:

C:Program FilesDeveloper Express.VCLExpressTile ControlDemosData

Next, locate the TdxSkinController component on the Tool Palette and add it to Form1 of the TileControlSample project created in my previous post. You can download the source to that project here.


Add a FormCreate handler to Form1 with the following code:

procedure TForm1.FormCreate(Sender: TObject);
begin
  dxTileControl1.LookAndFeel.NativeStyle := False; //so skins take affect
  dxSkinController1.SkinName := 'UserSkin'; //so we can load a .skinres
  dxSkinsUserSkinLoadFromFile('MetroBlack.skinres');
end;

And that’s all it takes to give our sample a dark, Metro-inspired skin.


Replace the reference to MetroBlack.skinres with MetroWhite.skinres in order to use the lighter Metro-inspired skin.

You can download the updated Delphi sample here.

Hip Shot Update Brings Improved Diabetes Support

Version 1.2 of Hip Shot is now available in the Apple App Store. This update incudes the following:

  • You can now track medicine, doses, and carbs with Hip Shot
  • You can build a medication list with default dosages, and also flag a medicine as default
  • Settings are now synchronized between devices using iCloud

With this update, Hip Shot’s feature set is expanding to make the app more useful to those who suffer from illnesses other from Multiple Sclerosis, such as Diabetes.


You can see a video showing some of these new features here.