Umbraco 5: Get content from HiveManager using separate application

Written by Alex on . Posted in Uncategorized

This article will explain how to create an instance of HiveManager in a separate application (console windows application). HiveManager is a single point to access all data in Umbraco 5, when you are running already compiled web application of Umbraco 5 the HiveManager is already initialize but in case if you need to create an instance of HiveManager from another application you have to do some steps.

Creating instance of HiveManager from Console application

At the start you have to create console application (or any type of application you need) and reference all required libraries. The screenshot below shows which libraries are required to create instance of Hive, in my opinion it’s too much libraries.

image

 

The code to create Hive is very simple, but you have to prepare many helper classes before you can create it. below is the code to create HiveManager

IHiveManager hive = new HiveManager(new[]
    {
        new ProviderMappingGroup(
            "test",
            new WildcardUriMatch("content://"),
            singleReader,
            singleWriter,
            frameworkContext)
    }, frameworkContext);

To create all required instances you have to:

  • Create instance of FrameworkContext
  • Create instance of ProviderMetadata
  • Create instance of NhFactoryHelper
  • Create reader and writer providers
Full source code to create all helper classes available at the bottom of the post.

Loading content of your website in console application with Hive

After you have instance of Hive you have to get ReaderProvider and ask repository about all items or specific item. The code below shows how to iterate over all items and how to get item by Id

private static void Main(string[] args)
{
    var wrapper = new HiveManagerWrapper();
    IHiveManager hive = wrapper.GetHiveManager();

    IEnumerable<TypedEntity> allDocuments =
        hive.GetReader<IContentStore>().CreateReadonly()
        .Repositories.GetAll<TypedEntity>();
    foreach (TypedEntity entity in allDocuments)
    {
        foreach (TypedAttribute attribute in entity.Attributes)
        {
            foreach (var val in attribute.Values)
            {
                Console.WriteLine("{0}: {1}",
                attribute.AttributeDefinition.Name,
                val.Value);
            }
        }
    }

    Console.WriteLine();
    Console.WriteLine("----------------------------------------");

    Content mypage =
        hive.Query<Content, IContentStore>().SingleOrDefault(
            x => x.Id == new HiveId("content://p__nhibernate/v__guid/2c10d5d5bab2488a9af9a026000cadfc"));
    foreach (TypedAttribute attribute in mypage.Attributes)
    {
        Console.WriteLine("{0}: {1}",
        attribute.AttributeDefinition.Name,
        attribute.Values.FirstOrDefault());
    }
}

and after you run application you get content of the website

image

 

image

 

Source code of the test application

Msbuild file names naming convention

Written by Alex on . Posted in Uncategorized

There is no really documented naming convention for MSBuild files. One of the reason why Microsoft does not provide such convention because MsBuild files are just xml files and when you pass that files to MSBuild engine it can have any file name extension.

But there are some commonly used file names convention for MSBuild scripts:

.proj

This is generic file extension which can be applied to any msbuild file.

For example: myCoolProject.proj

Also when you run build with TFS the build scripts folder should contain file with the name TFSBuild.Proj which is some kind of hardcoded in TFS and by default TFS will call this file during build process.

.targets

Usually this file extension used for your targets, normally you have some re-usable targets which you can put in common folder and reference it from you .proj files.

For example: web-app-deployment.targets or database-deployment.targets

.props

Normally you will create environment specific properties or some common properties and you can give .props extension to the files. Usually this type of files contains just PropertyGroup and ItemGroup – nothing more.

For example UAT-Definition.props or Production-definition.props

.tasks

That types of files contains UsingTask elements – your custom tasks which you build in C# and imported into the main project.

A good example will be: Microsoft.Common.Tasks or MSBuild.ExtensionPack.tasks

.**proj

You can also find some language specific project files, for example .csproj – is a C# project file. Normally this msbuild files are done by visual studio, and you will not modify it too often.

.csproj C#
.vbproj VB.NET
.vcxproj Visual C++
.dbproj Database project
.fsproj F#
.pyproj IronPython
.rbproj IronRuby
.wixproj Windows Installer XML (WiX)
.vdproj Visual Studio Deployment Project
.isproj InstallShield
.pssproj PowerShell
.modelproj Modeling project
In case if you use Resharper, you can give .proj extension to all files to get good intellisence support. For example Production-definition.props.proj

How to use named query in NHibernate

Written by Alex on . Posted in Uncategorized

Most of the SQL queries are generated by Nhibernate and in fact developer does not need SQL knowledge at all. But in case if developer wants to create there own SQL query or use Stored procedure which contains some complex business logic he can use Nhibernate feature called “named query”.

What is Nhibernate named query

An NHibernate named query is a native SQL queries or HQL queries which can be executed by Nhibernate and returned to developer as strongly typed object. Nhibernate named query can be both stored procedure and SQL (HQL) code.

How to map Nhibernate named query

Named queries can be defined in the same mapping (*.hbm.xml) files where you already have mapping for your classes or it can be located in separate .hbm.xml file where you can group a number of Nhibernate named queries.

Example of using Nhibernate named query

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="NHibernateNamedQuery.Entities" assembly="NHibernateNamedQuery">
  <class name="Person">
    <id name="Id" column="BusinessEntityID">
      <generator class="native"></generator>
    </id>
    <property name="FirstName"></property>
    <property name="LastName"></property>
  </class>

  <sql-query name="GetAllPersonsFromStoredProc">
    <return class="Person"></return>
    exec [dbo].[uspGetAllPersons]
  </sql-query>

  <sql-query name="GetAllPersonsSQLQuery">
    <return class="Person"></return>
    SELECT TOP(10) [BusinessEntityID], [FirstName], [LastName]
    FROM Person.Person
  </sql-query>

  <sql-query name="GetEmployeeById">
    <return class="Person"></return>
    exec [dbo].[uspLoadPersonById] @personId = :personId
  </sql-query>

  <sql-query name="GetEmployeeById2">
    <return class="Person"></return>
    exec [dbo].[uspLoadPersonById] ?
  </sql-query>

  <sql-query name="GetEmployeeById3">
    <return class="Person"></return>
    exec [dbo].[uspLoadPersonById] @personId = ?
  </sql-query>
</hibernate-mapping>

Code to load data from database with named query

Person p;
using (ISession s = GetSession())
{
    p = s.GetNamedQuery("GetEmployeeById")
    .SetParameter("personId", 293).UniqueResult<Person>();
}

Application execution results

-----------------SQL query----------------------------------------------
NHibernate: SELECT TOP(10) [BusinessEntityID], [FirstName], [LastName] FROM Person.Person
Id: 285 Name:Abbas, Syed
Id: 293 Name:Abel, Catherine
Id: 295 Name:Abercrombie, Kim
Id: 2170        Name:Abercrombie, Kim
Id: 38  Name:Abercrombie, Kim
Id: 211 Name:Abolrous, Hazem
Id: 2357        Name:Abolrous, Sam
Id: 297 Name:Acevedo, Humberto
Id: 291 Name:Achong, Gustavo
Id: 299 Name:Ackerman, Pilar
-----------------Stored Proc----------------------------------------------
NHibernate: exec [dbo].[uspGetAllPersons]
Id: 285 Name:Abbas, Syed
Id: 293 Name:Abel, Catherine
Id: 295 Name:Abercrombie, Kim
Id: 2170        Name:Abercrombie, Kim
Id: 38  Name:Abercrombie, Kim
Id: 211 Name:Abolrous, Hazem
Id: 2357        Name:Abolrous, Sam
Id: 297 Name:Acevedo, Humberto
Id: 291 Name:Achong, Gustavo
Id: 299 Name:Ackerman, Pilar
-----------------GetEmployeeById-----------------------------------------
NHibernate: exec [dbo].[uspLoadPersonById] @personId = @p0;@p0 = 293 [Type: Int32 (0)]
Id: 293 Name:Abel, Catherine
-----------------GetEmployeeById2---------------------------------------
NHibernate: exec [dbo].[uspLoadPersonById] @p0;@p0 = 293 [Type: Int32 (0)]
Id: 293 Name:Abel, Catherine
-----------------GetEmployeeById3-----------------------------------------
NHibernate: exec [dbo].[uspLoadPersonById] @personId = @p0;@p0 = 293 [Type: Int32 (0)]
Id: 293 Name:Abel, Catherine
Press any key to continue . . .

Download source code

Security Support Provider Interface (SSPI) authentication failed

Written by Alex on . Posted in Uncategorized

In case if application required to get some user related information from Active Directory (AD), for example user AD roles and retrieving this roles done with WCF services you can get the following exception

Exception:

Security Support Provider Interface (SSPI) authentication failed. The server may not be running in an account with identity ‘host/computer-name.domain’. If the server is running in a service account (Network Service for example), specify the account’s ServicePrincipalName as the identity in the EndpointAddress for the server. If the server is running in a user account, specify the account’s UserPrincipalName as the identity in the EndpointAddress for the server.

But if client application use IP address of the server instead of server name it works fine with no errors.

Solution:

There are two solution to fix exception

  1. Use server IP address instead of name
  2. Specify UserPrincipalName or ServicePrincipalName as suggested in exception message

The second is described in .NET 3.5 SP1 readme file as breaking changes

2.3.2.2 Breaking changes in the SspiNegotiatedOverTransport authentication mode

When WSHttpBinding, WS2007HttpBinding, or NetTcpBinding is used with SecurityMode = TransportWithMessageCredential and a client credential type of Windows, clients that previously authenticated to a service by using NTLM will now fail to authenticate, with the following error:

“System.ComponentModel.Win32Exception: Security Support Provider Interface (SSPI) authentication failed. The server may not be running in an account with identity ‘host/<hostname>’. If the server is running in a service account (Network Service for example), specify the account’s ServicePrincipalName as the identity in the EndpointAddress for the server. If the server is running in a user account, specify the account’s UserPrincipalName as the identity in the EndpointAddress for the server.”

The error appears when the service is running on an account that has an identity other than ‘host/<hostname>’. This issue also applies to CustomBindings, which specify the SspiNegotiatedOverTransport authentication mode.

To resolve this issue:

If possible, clients should be updated by using a UPN or SPN endpoint identity that specifies the identity of the service so that Kerberos authentication occurs. The following configuration snippet shows how to do this in the UPN case; the SPN case is similar, but the <servicePrincipalName> element is used instead.

<system.serviceModel>

      <client>

         <endpoint>

            <identity>

               <userPrincipalName value=”user@domain” />

            </identity>

          </endpoint>

     </client>

</system.serviceModel>

So to fix the problem just add

<userPrincipalName value=”user@domain” />

To identity of the endpoint – the value does not matter, it can be anything instead of “user” and “domain”

Show publish version in ClickOnce WPF or WinForms application

Written by Alex on . Posted in Uncategorized

When deploying ClickOnce application to the client, usually there is a requirement to display application version. It’s possible to hardcode application version in configuration file, or use assembly version. But when deploying ClickOnce application Visual studio can generate publish version and automatically increment revision every time you publish ClickOnce application.

So it’s better to use publish version as application version. But how to display publish version in ClickOnce application if publish version will be available only after publish is done? It’s very easy with System.Deployment namespace. Below is the C# code to display publish version in ClickOnce application.

if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) {
    System.Deployment.Application.ApplicationDeployment cd =
    System.Deployment.Application.ApplicationDeployment.CurrentDeployment;
    string publishVersion = cd.CurrentVersion;
    // show publish version in title or About box...
}
System.Deployment.Application namespace located in System.Deployment.dll which is not referenced by default, so do not forget to add reference to System.Deployment.dll
Also you always have to check IsNetworkDeployed property, because if it’s runs locally this property is false and CurrentDeployment will throw exception.

t-sql trim function

Written by Alex on . Posted in Uncategorized

I was surprised when found than SQL server 2005 and even 2008 R2 does not have support for trim function. Trim function is so simple and wide use function so I believed all programming languages support it. But instead Sql server has ltrim and rtrim function

  • ltrim – returns string after removing leading blank characters
  • rtrim – return string after removing trailing blank characters.

But using these two functions you can create trim function and use it in your t-sql code

t-sql trim function

You can create trim function for your database using this source code

CREATE FUNCTION [dbo].[trim] (@stringValue as nvarchar(max))
RETURNS nvarchar(max)
AS
BEGIN
    RETURN ltrim(rtrim(@stringValue));
END

t-sql trim inline code

One more option is to use inline code if for some reason you don’t want to create function

ltrim(rtrim(LastName)) + ', '
+ ltrim(rtrim(FirstName)) as 'Customer Name',

Font scale, pixels vs percent

Written by Alex on . Posted in Uncategorized

I use my PC every day, and often by the end of the day my eyes are tired, so while surfing the internet, I use my browser setting to set large font. And I hate websites where I can’t change font size.

You can’t change font size because it size uses pixels. The better idea is use percent to setup font size.

Using percent you can change font size using your browser setting, just use your mouse wheel with Ctrl key pressed.

There is a good Yahoo UI library to perform font reset and than set default fonts size with percent.

You can add two small css files (reset-fonts.css and base-min.css) to your project and than declare your font size with percent, like this


<style type="text/css">
    .pixelFont
    {
        font-size:14px;
    }

    .percentFont
    {
        font-size:108%;
    }
</style>

<p class="pixelFont">
Hello this is text with font size 14 pixels.
You can't resize this type of font.</p>

<p class="percentFont">
You can resize this font,
because it's size use percent.
Actually it's 108%</p>

Both fonts has the same size 14px with your default browser settings, but try to resize font size on the page with browser, and you will see than pixelFont are not resized in contrast to percentFont.

Eval vs Bind for ASP.NET

Written by Alex on . Posted in Uncategorized

When you start working with ASP.NET sometimes it’s difficult to understand what is the difference between Eval and Bind for data binding controls in ASP.NET. If you just need to display data on the screen from DataSource it’s enough to use Eval. It’s something like read-only method from DataSource. But if you need to edit data inside of Grid you have to use Bind method. Because it provides two way binding you can read data from DataSource and you can write data back. Usually you have to use this methods if you need to quickly develop some WebPages and display and edit data from one table or simple view. If you try to edit some row in Data Grid and want to make some changes in code behind class in OnUdpdating event, data with Eval method will not be available instead of Bind method.

<asp:GridView ID="GridView1" runat="server" CssClass="dataGrid"
   DataSourceID="SqlDataSource1" AllowPaging="True" AutoGenerateColumns="false"
  OnRowDeleting="grid_onRowDeleting" OnRowUpdating="GridView1_OnRowUpdating"
    AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
  PageSize="20" GridLines="None" Width="99%">
   <AlternatingRowStyle CssClass="odd" />
   <Columns>

       <asp:TemplateField HeaderText="App Id">
           <ItemTemplate>
               <asp:Label ID="lbl" runat="server" Text='<%#Bind("APP_ID") %>'></asp:Label>
           </ItemTemplate>
       </asp:TemplateField>

      <asp:TemplateField HeaderText="App name">
           <ItemTemplate>
               <%#Eval("APPLICATION_NAME")%>
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>
protected void GridView1_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
   // if APP_ID in the grid bind with Eval method, it will be exception below
   // But if you use Bind instead of Eval it will be ok.
   rowToUpdate = e.NewValues["APP_ID"];
}

How to install Mac OS X Snow Leopard on VirtualBox under Windows 7 x64

Written by Alex on . Posted in Uncategorized

This guide explains how to install Mac OS X Snow Leopard on VirtualBox working under Windows 7 x64 Ultimate.

Configuration of my PC

  • laptop Asus G2S.
  • 4GB RAM
  • two core processor
  • VirtualBox 2.3.8
  • Mac OS X Snow Leopard 10.6 (boot image file)

my-pc

Steps to install Mac OS X Snow Leopard on VirtualBox

Dowload Mac OS X image

You need image of Mac OS. You can buy it or download from internet. The image usualy have extension .dng – it’s Mac analog for .iso extension on Windows.

Convert dng file to iso file

Unfortunately VirtualBox does not understand .dng file extension and you have to convert it to .iso. There is a great tool dng2img which you can use to convert dng to iso. It’s free and small.

convert-dng-to-iso

Create virtual machine at Virtualbox

To create new virtual machine in VirtualBox press New button and follow the steps in wizard. Below is the screenshots from my PC. Select at least 1.5 Gb RAM for Virual Machine.   

create-new-vmram-for-vmvm-created

Add boot image for Virtual Machine

After you have created Virtual Machine go to settings and under Storage add Mac OS X image file as a second boot device.

mac-os-boot-imagevm-settings

Modifing Mac OS X Virtual Machine setting

To install Mac OS X to VirtualBox you need to modify configuration file in text editor. Configuration files is just XML files. Close VirtualBox. Open in text editor file

c:\Users\\.VirtualBox\Machines\<virtual-machine>\<virtual-machine>.xml at my PC this path is c:\Users\Alexander\.VirtualBox\Machines\Mac OS X Snow Leopard\Mac OS X Snow Leopard.xml

Add the following lines to <extradata> section of xml file

<ExtraDataItem name="VBoxInternal2/EfiBootArgs" value=" "/>
<ExtraDataItem name="VBoxInternal2/SmcDeviceKey"
    value="ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"/>

Close and save file. Now you can start VirtualBox and Run Virtual image of Mac OS X.

xml-settings-modification 

Installation of Mac OS X Snow Leopard on VirtualBox

Now you are ready to install Mac OS X Snow Leopard. After you run Virtual Machine installation should start. After than you need to create disc where you want to install Mac OS. Open Disk Utility under Utilities menu. Select the virtual disk and click Erase. Close it and you can now install OSX.

mac-os-x-start-installationmac-os-installation-step-1mac-os-x-disk-utilityerase-discmac-os-x-ready-to-installmac-os-x-installation-finished

How to run multiple instances of console application

Written by Alex on . Posted in Uncategorized

Sometimes developer need to quickly simulate high load to server with concurrent connections, and one of the ways to do it create console application which will connect to server and make some calls. Below is very simple but helpful technic how to create a number of instances of console application with cmd script. 

So to run multiple instances of the same application can be done with cmd file. Create runme.cmd file with the following content

REM running multiple instances of notepad application
start cmd /c c:\myApp\loadTestConsoleApp.exe
start cmd /c c:\myApp\loadTestConsoleApp.exe
start cmd /c c:\myApp\loadTestConsoleApp.exe 

Replace the name of the application to your name and control number of instances by adding or removing lines in cmd file. When you run the cmd script it will open separate console window for each instance of application.