Monday, 12 August 2013

Umbraco get media id from url

Working with umbraco 6 is great fun.

I am working with images and needed to access image before is served to public.
Hope my solution will  save you some time.

Here is solution


var path = HttpContext.Current.Request.Path.ToLower();

// filter requests that we know are not relevant
if (!path.StartsWith("/media/") || path.StartsWith("/media/temp/") || path.Contains("_thumb.")) return;


// access medisa service
Umbraco.Core.Services.MediaService ms = new Umbraco.Core.Services.MediaService(new Umbraco.Core.Persistence.RepositoryFactory()); 
var item = ms.GetMediaByPath(path);

Monday, 5 August 2013

Adding typescript minified scripts into bundles.

Problem:

I want to add TypeScript generated minified files into bundle configuration.

By default, minified files are excluded.


Solution:
I need to add custom implementation of ignore list in order to manage ignore list. I do not change any configuration of typescripts generated files, but add custom code.

See implementation below:


 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

public class BundleConfig
    {

   public static void AddDefaultIgnorePatterns(IgnoreList ignoreList)
        {
            ignoreList.Clear();
            ignoreList.Ignore("*.min.css", OptimizationMode.WhenDisabled);
        }

        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            AddDefaultIgnorePatterns(bundles.IgnoreList);

            bundles.Add(new ScriptBundle("~/bundles/site")
                .Include("~/Scripts/Site.min.js",
                         "~/Scripts/Test2.min.js"));
        }
}


Wednesday, 31 July 2013

Clear all objects from database

Today I have been working on web deploy solution, and needed to clear databse.
Drop database does not work for me, because the files still hang around. And I want to reuse the implementation for every build I do. This solution come from the need of regular deploy, from my build server.


I need to clear:
  1. Stored procedures if any
  2. Foreign keys
  3. Primary key constaints
  4. Tables

My implementation works with only [dbo] schema, but you can specify the block for each chema you need.

Original source for this you can find of course on Stack overflow

My modification is make sure that database name is specified for every schema, in order to satisfy DB admins, that in case of selecting wrong schmea, the implementation does not remove everything.

Now SQL:


IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'HomeSite')
BEGIN

    /* ====================================================*/
    /*           Drop all non-system stored procs          */
    /* ====================================================*/
        
        /* Drop all non-system stored procs */
        DECLARE @StoredProcName VARCHAR(128)
        DECLARE @StoredProcSQL VARCHAR(254)

        SELECT @StoredProcName = (SELECT TOP 1 [name] FROM HomeSite..sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

        WHILE @StoredProcName is not null
        BEGIN
            SELECT @StoredProcSQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@StoredProcName) +']'
            EXEC (@StoredProcSQL)
            PRINT 'Dropped Procedure: ' + @StoredProcName
            SELECT @StoredProcName = (SELECT TOP 1 [name] FROM HomeSite..sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @StoredProcName ORDER BY [name])
        
        END
        
    /* ====================================================*/
    /*           Drop all Foreign Key constraints          */
    /* ====================================================*/        
        
        DECLARE @ForeignKeyName VARCHAR(128)
        DECLARE @ForeignKeyConstraint VARCHAR(254)
        DECLARE @ForeignKeySQL VARCHAR(254)

        SELECT @ForeignKeyName = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

        WHILE @ForeignKeyName is not null
        BEGIN
            SELECT @ForeignKeyConstraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @ForeignKeyName ORDER BY CONSTRAINT_NAME)
            WHILE @ForeignKeyConstraint IS NOT NULL
            BEGIN
                SELECT @ForeignKeySQL = 'ALTER TABLE [dbo].[' + RTRIM(@ForeignKeyName) +'] DROP CONSTRAINT [' + RTRIM(@ForeignKeyConstraint) +']'
                EXEC (@ForeignKeySQL)
                PRINT 'Dropped FK Constraint: ' + @ForeignKeyConstraint + ' on ' + @ForeignKeyName
                SELECT @ForeignKeyConstraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @ForeignKeyConstraint AND TABLE_NAME = @ForeignKeyName ORDER BY CONSTRAINT_NAME)
            END
        SELECT @ForeignKeyName = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
        END
    
    /* ====================================================*/
    /*           Drop all Primary Key constraints          */
    /* ====================================================*/
    
        DECLARE @PrimaryKeyName VARCHAR(128)
        DECLARE @PrimaryKeyConstraint VARCHAR(254)
        DECLARE @PrimaryKeySQL VARCHAR(254)

        SELECT @PrimaryKeyName = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

        WHILE @PrimaryKeyName IS NOT NULL
        BEGIN
            SELECT @PrimaryKeyConstraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @PrimaryKeyName ORDER BY CONSTRAINT_NAME)
            WHILE @PrimaryKeyConstraint is not null
            BEGIN
                SELECT @PrimaryKeySQL = 'ALTER TABLE [dbo].[' + RTRIM(@PrimaryKeyName) +'] DROP CONSTRAINT [' + RTRIM(@PrimaryKeyConstraint)+']'
                EXEC (@PrimaryKeySQL)
                PRINT 'Dropped PK Constraint: ' + @PrimaryKeyConstraint + ' on ' + @PrimaryKeyName
                SELECT @PrimaryKeyConstraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @PrimaryKeyConstraint AND TABLE_NAME = @PrimaryKeyName ORDER BY CONSTRAINT_NAME)
            END
        SELECT @PrimaryKeyName = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
        END
        
    
        
    /* ====================================================*/
    /*           Finally drop all tables                           */
    /* ====================================================*/
        DECLARE @TableName VARCHAR(128)
        DECLARE @TableSQL VARCHAR(254)

        SELECT @TableName = (SELECT TOP 1 [name] FROM HomeSite..sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

        WHILE @TableName IS NOT NULL
        BEGIN
            SELECT @TableSQL = 'DROP TABLE [dbo].[' + RTRIM(@TableName) +']'
            EXEC (@TableSQL)
            PRINT 'Dropped Table: ' + @TableName
            SELECT @TableName = (SELECT TOP 1 [name] FROM HomeSite..sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @TableName ORDER BY [name])
        END    
    
END
GO

Monday, 29 July 2013

TFS versioning

I have found following guid, but not wrote it. All credit goes to author on link below.

source:
http://tfsbuildextensions.codeplex.com/wikipage?title=Build%20and%20Assembly%20versioning%20%28alternate%20to%20above%20using%20SDC%20Tasks%29&referringTitle=Home



Description

Incrementing the build number, and versioning the assemblies, is a simple process with the help of the Microsoft SDC Tasks (http://www.codeplex.com/sdctasks). There are two aspects to versioning a Build in TFS, first is versioning the TFS Build number and the second is versioning the assemblies in the build. Both of these are reasonable simple to do.

Usage

The first thing to do is place the SDC tasks assembly on your team build server. I found the easiest way of doing this, and to allow different builds to use different versions, was to add the assembly to the build folder in TFS along with the tasks definition file.

The top of the Tasks file will need to be customised to match your environment by supplying, or ensuring, that the taskspath property is set correctly, for me changing the property group to the following worked.

  <PropertyGroup>
    <BuildPath Condition="'$(BuildPath)'==''">$(MSBuildProjectDirectory)\</BuildPath>
    <TasksPath Condition="Exists('$(BuildPath)\Microsoft.Sdc.Tasks.dll')">$(BuildPath)\</TasksPath>
  </PropertyGroup>


You will also need to include the tasks file in your project file by adding the following line to your .proj file.

<Import Project="$(MSBuildProjectDirectory)\Microsoft.Sdc.Common.tasks" />


Now you can customise the version numbers.

1. TFS Build Number.

TFS provides a ''BuildNumberOverrideTarget'' which should be used to modify the build number. This is the appropriate place to load and configure the build number for the entire solution by outputing a ''BuildNumber'' property.

In my solution I load the version number using the SDC's VersionNumber.Update command. To keep track of the Version number and to ensure they are always unique I keep the version.xml used by the task in Source control and check it in and out of TFS using the TF command line. This can be seen in the scripts below. (the structure of the Version.XML file can be found on the SDC codeplex site, see link below.)

TFS will then use this build number for the build rather than its built in one. 


2. Versioning the assemblies.

Once you have a build number you usually want to adjust the AssemblyInfo.cs files to match the build number. 

I do this by creating my own target ''VersionAssemblies'' which I attach as a dependency to the Team build ''AfterGet'' target. The process is simple... first collect all the AssemblyInfo.cs files into an item group and then use the SDC File.Replace task to do a regular expression search and replace all the assembly version lines to the new build number.

Source

Information on the tasks used to accomplish this script can be found on the http://www.codeplex.com/sdctasks

Full credit also to the numerous blog articles I can't remember reading that pointed me the right direction for desiging this receipe.

Script

<PropertyGroup>
    <TfCommand>&quot;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\tf.exe&quot;</TfCommand>
</PropertyGroup>
<Target Name="BuildNumberOverrideTarget" DependsOnTargets="CoreInitializeWorkspace">
    <!-- First get and check out the version files.-->
    <Exec Command="$(TfCommand) get /force /noprompt &quot;$(MSBuildProjectDirectory)\version.xml&quot;"
          ContinueOnError="true" />
    <Exec Command="$(TfCommand) checkout &quot;$(MSBuildProjectDirectory)\version.xml&quot;"
          ContinueOnError="true"/>

    <!-- Now update the version number -->
    <VersionNumber.Update VersionNumberConfigFileLocation="$(MSBuildProjectDirectory)\version.xml"
                          SkipSourceControl="true">
      <Output TaskParameter="VersionNumber" PropertyName="BuildNumber" />
    </VersionNumber.Update>

    <!-- Now check the version file back in. -->
    <Exec Command="$(TfCommand) checkin /override:&quot;Automated&quot; /comment:&quot;Update Version number $(BuildNumber)&quot; /noprompt &quot;$(MSBuildProjectDirectory)\version.xml&quot;"
          ContinueOnError="false"/>

</Target>

<!-- This target is called after Team build gets all the source files from TFS. -->
<Target Name="AfterGet" DependsOnTargets="VersionAssemblies" />

<Target Name="VersionAssemblies">
     <!-- Get the Assembly Info files.-->
     <CreateItem Include="$(SolutionRoot)\Source\**\AssemblyInfo.cs;">
          <Output TaskParameter="Include" ItemName="AssemblyInfos"/>
     </CreateItem>

     <!-- Update the version numbers -->
     <File.Replace Path="%(AssemblyInfos.FullPath)" NewValue="AssemblyVersion(&quot;$(BuildNumber)&quot;)" regularExpression="AssemblyVersion\(\&quot;(\d+.\d+.\d+.\d+)\&quot;\)" ignoreCase="true" />

</Target>

Notes

  1. By making the BuildNumberOverrideTarget depend on CoreInitializeWorkspace the build is forced to initilize the workspace before the buildnumber target. This makes it possible (as long as the full path is used) for the version.xml to be checked in and out of TFS the first time the build is run. (Which was a problem with the previous version.)
  2. The ''AssemblyVersion'' line in the AssemblyInfo.cs files must exist for it to be found and replaced. This shouldn't usually be a problem as it usually does exists anyway.

Tuesday, 23 July 2013

Fake EF DbSets example

I have need to create data for my db context for my tests when testing PageHits.


Code for implementation:


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace TestHelpers
{
    /// <summary>
    /// Create fake db set for testing db sets.
    /// </summary>
    /// <typeparam name="T">Pass ojbect to cereate DbContext fake.</typeparam>
    public class FakeDbSet<T> : IDbSet<T> where T : class
    {
        private HashSet<T> _data;

        public FakeDbSet()
        {
            _data = new HashSet<T>();
        }

        public virtual T Find(params object[] keyValues)
        {
            throw new NotImplementedException();
        }


        public Task<T> FindAsync(CancellationToken cancellationToken, params object[] keyValues)
        {
            throw new NotImplementedException();
        }

        public T Add(T item)
        {
            _data.Add(item);
            return item;
        }

        public T Remove(T item)
        {
            _data.Remove(item);
            return item;
        }

        public T Attach(T item)
        {
            _data.Add(item);
            return item;
        }

        public void Detach(T item)
        {
            _data.Remove(item);
        }

        Type IQueryable.ElementType
        {
            get { return _data.AsQueryable().ElementType; }
        }

        Expression IQueryable.Expression
        {
            get { return _data.AsQueryable().Expression; }
        }

        IQueryProvider IQueryable.Provider
        {
            get { return _data.AsQueryable().Provider; }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _data.GetEnumerator();
        }

        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return _data.GetEnumerator();
        }

        public T Create()
        {
            return Activator.CreateInstance<T>();
        }

        public ObservableCollection<T> Local
        {
            get { return new ObservableCollection<T>(_data); }
        }

        public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T
        {
            return Activator.CreateInstance<TDerivedEntity>();
        }

        DbLocalView<T> IDbSet<T>.Local
        {
            get { throw new NotImplementedException(); }
        }
    }
}

Now we have to modify our Context:


  public partial class DataContext : DbContext, DataContext
    {
        static DataContext()
        {
            Database.SetInitializer<DataContext>(null);
        }

        public DataContext()
            : base("Name=DataContext")
        {
        }

        public IDbSet<PageHit> PageHits { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new PageHitMap());
        }
    }