Injecting services into entities
Entities with async construction
- Created entity is NOT immediately usable.
- Entity code now generally needs safety code to throw if not fully initialised
I built this a while ago; others may find it handy.
It's a small library focussing primarily on syntax sugar for C#
kwd.CoreUtil v1.1.0: Git / Nuget
The main code is a set of extensions to make working with FileInfo and DirectoryInfo more natural.
In addition there are some other utilities for strings and file streams.
Originally the design was to restrict this to ONLY depend on standard .NET Core packages.
But more recently I stumbled onto System.IO.Abstractions; since the package is lite, and provides significant benefit; I've take it as a dependency
I've finally got Team City to run on Azure with the built-in database. But I was having terrible trouble getting my unit tests (MSTest) to run.
The error: 'Could not load file or assembly Autofac ...'
Every thing looked fine. Local build / test worked like a dream. NuGet packages loaded. CI build log showed Autofac was nu-get downloaded, and build success... I even fell back to RDP to build-box and run tests; again, success.
I used a simple short-hand to tell team city where the test assembly was: src/core.tests/**/*.tests.dll. This was (unexpected, by me at least) picking up both
The fix is simple, just use a more exact setting in Team City src/core.tests/bin/Debug/*.tests.dll
Recently I needed to create a link to edit a content item in Orchard. Orchard uses a url like http://mysite/Home/Admin/Contents/Edit/123, where the id corresponds to the content item id.
My first thought was to hand-craft the url, replacing the content id as needed. But I found a better way: use the item's meta-data. Firstly inject the orchard IContentManager as usual, then call IContentManager.GetItemMetadata() The returned ContentItemMetadata contains MVC route's, for my particular case, EditorRouteValues had all the data I needed.
In my exploration of Orchard, I am continually finding myself having to dive into the code to work out how to do things. So here is 'how' I finally stumbled on the meta data solution.
Firstly I knew the Content Control Wrapper performed some 'magic' which added a link to a content item's edit.
Alas so-far I have no special trick for getting from a feature to the code that implements it. But eventually I found Orchard.Core/Contents/ControlWrapper.cs which implements the feature as a IShapeTableProvider. In here we see Content is wrapped with a Content_ControlWrapper shape.
Since nothing particularly enlightening is happening, I went to the view for the shape: Orchard.Core/Views/Content.ControlWrapper.cshtml. In the view the Html.ItemEditLinkWithReturnUrl() caught my eye.
This ItemEditLinkWithReturnUrl() is an extension, tracked down to Orchard.Framework/Mvc/Html/ContentItemExtensions.cs
Navigating to find the core ItemEditLink helper, bingo, I found how the content item meta-data is used for route values.
While working on a module for Orchard CMS I ran into some problems trying to glue async (Task) based code with (classic) synchronous code.
Here's the set-up:TheMoveDb uses Tasks, so I don't have to wait around for across-the-wire calls. MovieInfo uses Tasks, and integrates with orchard services. AdminController uses normal Action methods.
Being a TDD developer, all the pieces looked fine. But as soon as I put it together... splat.
It all starts with a deadlock (doesn't it always!). A quick google gets to Stephen Cleary (via SO) Don't Block on Async Code and Async and Await Armed with this I now at-least understand the problem.
Alas, at least in Orchard 1.6, async controllers are a no-go. It took a fair bit of searching, I finally found an SO article describing the problem. So (for now) I've settled on a sync / async solution.
Putting it all together:There was one last gotcha; anything after the await in MovieInfo service executes on its own thread. So no access to orchard services (such as WorkContext etc). To get around this I just had to take care to no need the 'orchard friendly' thread context after the await.
To avoid the spin-up time on an Azure role, I use the IIS Application Initialization (formally warm-up) module. The module is available by default for IIS8, so it's easier if you can run your azure role on Server 2012 (osFamily=3).
The step-by-step instructions describe how to configure the module for use. Using this along side an article on programmatic configuring azure app pool settings, I've got enough pieces to create a RoleEntryPoint for the task.
You will also need to (find) and include a reference to the Microsoft.Web.Administration assembly. Oh, and in addition to configuring the module, be sure to set the IIS IdleTimeout to 0 (zero).
Putting it all together:Many developers that I work with avoid working with msbuild. This is a shame, since a little msbuild knowledge can go a long way. Here are some tips to help others leverage msbuild along with VStudio
Both extensions are common for MSBuild files. So which to use? I use the following to help clarify a MSBuild files purpose:
A great way to leverage msbuild with your normal visual studio (.csproj) project, is to edit the .csproj and import a corresponding .targets file. As a convention, I name the import after the .csproj file, as an example; for a project MyApp.csproj I use a MyApp.targets import. Simply add the following in your .csproj file:
<Import Project="$(MSBuildThisFileName).targets" Condition="Exists('$(MSBuildThisFileName).targets')" />
After importing, you can now make interesting extensions to the build process using the BeforeTargets and AfterTargets attributes
As of VStudio 2012, I can edit my custom MyApp.targets and, without re-loading the MyApp.csproj the changes take effect.
As your MSBuild project get more complex, you may find (like me) that it can help to use a kind of 2-Target approach. In such cases I try and use a Short name for outer; descriptive name for inner style.
My reasoning is that I use an 'outer' Task from the command line, wehere I want a short easier-to-type name. Whilst, when building the task(s) I want more descriptive names, for future-maintainability. For example, I might have a task makeHelp that calls an internall task AddItemsFromAdditionalPaths.
To help modularize, use the MSBuild task to 'call' an external project. In the child task, define an Output attribute, and assign a resulting item list to it. Now in the caller (parent) task simply assign the items using TargetOutputs.
MSBuid is surprisingly easy to extend. There are 2 well known extension libraries: MSBuild Extension Pack and MSBuild Community Tasks. If neither suite, its really easy to just create your own.
As another option, you can also inline a task (MSBuild in-line task). But I would recommend NOT doing this. A task is easier to understand when written as a C# class, rahter than in-line.
Just as I like to extend my .csproj using a .targets file. It can also be useful to go the other way and build a .proj that imports your .csproj
The Visual Studio IDE is great for maintaining source files, and content files and other files in your project. You can use the UI to visually add and organize project files.
On occasion I take advantage of this using a MyApp.proj MSBuild project that imports MyApp.csproj. This way I can build targets that have access to ItemGroup's such as @(Compile) and @(Content)
Property Functions can be used to manipulate a property, the string manipulation is one of the more useful capabilities. Unfortunately the syntax is verbose, and can be challenging to read, so I tend to limit to simpler uses.
One of the more useful tricks, is to use property functions with item meta-data. To do this 'convert' meta-data to a string, and use it e.g
$([System.String]::new('%(RelativeDir)')).Replace('Stub', '$(OutPath)')
Metadata can be a clean way to extend an existing ItemGroup, allowing Tasks to alter how they behave. I prefer to use metadata over creating 'working' ItemGroups. If I find myself creating an ItemGroup just for a Task, e.g
<ItemGroup>
<LogFilesToArchive />
<ItemGroup>
I prefer
<ItemGroup>
<LogFiles Include="">
<archive>$(oldFiles)</archive>
</LogFiles>
</ItemGroup>
Using meta-data does have a down-side; you need to ensure all Items have the meta-data otherwise msbuild complains. To solve this use a ItemDefinistionGroup, or update the items with:
<ItemGroup>
<LogFiles Include="@(LogFiles)">
<archive></archive>
<LogFiles>
</ItemGroup>
VStudio uses DependsOn metadata to nest one item under another (like web.config and web.debug.config). You can do this for your own files. For example if you use partials, edit the .csproj to group all the files under one.
VStudio has a number of well-known item groups, such as @(Compile) and @(Content).
If you edit the .csproj, you can manually add items to these ItemGroups. It can be a faster / easier way to add items, rather then using the UI. I've even use recursive includes to add tree's of files to particular itemgroup's.
//http://orchard.codeplex.com/discussions/255594 //User controllable display name. var displayName = String.Empty; if(WorkContext.CurrentUser != null) { dynamic user = WorkContext.CurrentUser.ContentItem; if(user.ProfilePart != null && user.ProfilePart.Has(typeof(object), "DisplayName") && user.ProfilePart.DisplayName.Value is string) { displayName = user.ProfilePart.DisplayName.Value.Trim(); } if(String.IsNullOrWhiteSpace(displayName)) { displayName = WorkContext.CurrentUser.UserName; } }
<system.webServer> <.other.> <rewrite> <rules> <rule name="HostName" enabled="true" stopProcessing="false"> <match url="(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="YOUR\.SERVICENAME\.cloudapp\.net" /> </conditions> <action type="Redirect" url="{MapSSL:{HTTPS}}/YOURHOSTNAME/{R:1}"/> </rule> </rules> <rewriteMaps> <rewriteMap name="MapSSL" defaultValue="OFF"> <add key="ON" value="https://" /> <add key="OFF" value="http://" /> </rewriteMap> </rewriteMaps> </rewrite> </system.webServer>
Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...