Thursday, 20 December 2012

Turning you ASP.Net Hyperlinks into images buttons using CSS and jQuery

First of all I’m no big jQuery or CSS geek I know a little and I search the net Smile

I was building a site for a client who wanted Image buttons not text links and you should know me if you have read past posts I believe Dynamic Data is about changing as little as possible in the pages I like to do it all if possible using the Metadata, so I thought is there a way of doing this using pure CSS, there is sort of but you are still left with the text of the hyperlink, that is where jQuery came in, and then I thought I need to add a CSS class to each button and again jQuery came to my aid. so here we go.

Note: I am using the latest Web Essentials by Mads Kristensen and using LESS for my style sheets, you are really missing out if you have VS2012 and are not using this experimental add-in for VS2012.

Note: If you don't have VS2012 the you can use Mindscape’s Web Workbench which offers SASS, LESS and CoffeeScript

So the first job is to somehow automatically add the CSS class to each of the buttons that we want to swap to image button.

function NAC_ReplaceHyperLinkWithImageButton() {
// array of button commands/names to affect
var toMatch = ["Details", "Edit", "Delete", "Update", "Cancel", "Insert", "Select", "New"];
// commands/names to replace
var toReplace = { "New": "Insert" };
$(document).ready(function () {
$("TABLE.DDDetailsTable a, TABLE.DDGridView a")
.each(function () {
// get the inner text
var innerText = $(this).text();
if ($.inArray(innerText, toMatch) > -1) {

// do replacement of commands to Replace
var found = toReplace[innerText];
// check there is a match in the lookup table
if (typeof found !== "undefined")
innerText = found;

// get the embedded text
$(this).addClass(innerText);

// add a tooltip
$(this).attr('Title', innerText);

// remove the hyperlinks text
$(this).text('');
}
});
});
}
// run script
NAC_ReplaceHyperLinkWithImageButton();
// bind script to AJAX bits
Sys.Application.add_load(NAC_ReplaceHyperLinkWithImageButton);

Listing 1 – jQuery for the swap out

So first of all we have an array this contains ALL the button names (the display text) that we want to affect, next we hook into the jQuery Read event then we are selecting command buttons List, Details, Edit and ListDetails pages using these two selectors:

"TABLE.DDDetailsTable a, TABLE.DDGridView a"

after that I am using the jQuery inArray function to check if the buttons text is one we want to affect. Then having gotten the innerText form the hyperlink we add the CSS class, then finally we remove the text so only the icon will show.

jQuery is so cool mixed with CSS.

ReplaceHyperlinkWithIcons

Figure 1- hyperlinks replace with buttons

Now people say LESS is more and in this case it is.

table.DDGridView a.Cancel,
table.DDDetailsTable a.Cancel
{
    width: 20px;
    height: 20px;
    display: inline-block;
    background-repeat: no-repeat;
    background-position: center center;
    background-image: url('../images/Cancel.png');
}

    table.DDGridView a.Cancel:hover,
    table.DDDetailsTable a.Cancel:hover
    {
        background-image: url('../images/Cancel-h.png');
    }

        table.DDGridView a.Cancel:hover:active,
        table.DDDetailsTable a.Cancel:hover:active
        {
            background-image: url('../images/Cancel-a.png');
        }

    table.DDGridView a.Cancel.aspNetDisabled,
    table.DDDetailsTable a.Cancel.aspNetDisabled,
    table.DDGridView a.Cancel.aspNetDisabled:hover,
    table.DDDetailsTable a.Cancel.aspNetDisabled:hover,
    table.DDGridView a.Cancel.aspNetDisabled:active,
    table.DDDetailsTable a.Cancel.aspNetDisabled:active
    {
        background-image: url('../images/Cancel-d.png');
    }

Listing 2 – the CSS

above in Listing 2 is the CSS for the Edit button as you can see we cover hyperlinks with a CSS class of “Edit” and we have three states normal hover and active that is when we click. Now for the LESS

/* ==== button mixin ==== */
.Button (@Name)
{
a.@{Name}
{
width: 20px;
height: 20px;
display: inline-block;
background-repeat: no-repeat;
background-position: center center;

background-image: url('../images/@{Name}.png');

&:hover
{
background-image: url('../images/@{Name}-h.png');

&:active
{
background-image: url('../images/@{Name}-a.png');
}
}
// link fix
&.aspNetDisabled,
&.aspNetDisabled:hover,
&.aspNetDisabled:active
{
background-image: url('../images/@{Name}-d.png');
}
// link fix
}
}

table.DDGridView,
table.DDDetailsTable
{
.Button(Cancel);
.Button(Delete);
.Button(Details);
.Button(Edit);
.Button(Update);
.Button(New);
.Button(Select);
.Button(Insert);
}

Listing 3 – LESS

In Listing 3 we have a MIXIN called Button and we pass in the name of the button we want, no repeating the same code and if you need to add an extra button it’s easy.

The only thing left is for me to add this to NuGet as a simple to apply package and you are away.

Updated: Package now available from NuGet here Replace ASP.Net Hyperlink With Image Button You will need to add a reference in you master page to the CSS and the JavaScript files which will be added to the Style and Scripts folder respectively.

Adding the NuGet package to an existing Dynamic Data site

Right Click the “References” node of the Web Application Project

Adding NuGet Package

Figure 1 – Adding NuGet Package to Project

Find the “Replace Hyperlink With Image Button” NuGet Package

Figure 2 – Find the “Replace Hyperlink With Image Button” NuGet Package

AddingScriptToHead

Figure 3 – Add the Style sheet and jQuery references to the head of the Master page 

Note: the highlighted sections, you will need to add a ~/ and ../ to the start od the CSS and Script links.

AddScriptToEndOfMasterPage

Figure 4 – Add a script tag just before the end of the BODY tag

Note: you can add your scripts and Style sheets your own way with bundling and minifying this is just an example.

Happy coding.

V1.0.4 now on NuGet you disabled icons if a link’s Enabled property is set to “false”;

Replace Hyperlink With Disabled Icons

Hopefully no more changes now.

Warning another change: v1.0.8 now has better icons and supports disabled buttons including removing the onclick event of the Delete button.

Friday, 14 December 2012

ASP.NET and Web Tools 2012.2 (Release Candidate)

 

Scott Hanselman announced ASP.NET and Web Tools 2012.2 (Release Candidate) today and it’s great for the first time it’s easy to deploy a DD Web Application Project (WAP) site precompiled and un-editable it’s just a check box now.

So install the new tools (get them from here Download Page and Release notes)

Note: If you already have publish settings then VS2012 will import them but they need to be in the root of your site.

New Publish Wizard

Figure 1 - New Publish Wizard

Navigate to the Settings Tab and check the “Precompile during publishing” checkbox and then click “Configure”

Disabled Editable markup.

Figure 2 - Disabled Editable markup.

un-check the “Allow precompiled site to be updatable” checkbox and your pages will no look like this Figure 3 if someone tries to edit them Smile

Precompiled aspx page no uneditable

Figure 3 - Precompiled aspx page no un-editable

And finally in VS2012 you can set the build configuration in each Publish profile, this works without having to change the build configuration in you project.

Warning: This sadly does not work for Dynamic Data yet it testes OK you already deployed to a site as it uses the place holders, I’m looking into it hopefully there will be a simple fix.

Thursday, 30 August 2012

O2 has major fail

O2 have just blocked external access to smtp.o2.co.uk this means you cannot send e-mail from your mobile if you are no connected to an O2 network and if you are abroad you will only be able to send email via your data account.

For me this is a major fail I havrelayeded on this from O2 for as long as I have been with them. I will be moving from O2 and finding a solution to sending e-mail that no ISP or Mobile provider will be able to block.

RIP O2

Steve



Well news is O2 don't seem to know what the issue is I just got told by first level support that it was not accessable from outside O2's network? but it is again I suspect I was being given a line...

Steve

Saturday, 26 May 2012

Creating a Tabbed Entity Template using Wijmo Open for Juice UI

Wijmo Open for Juice UI is quite cool and offers an alternative to using Ajax Control Toolkit which is still cool but Wijmo Open for Juice UI supports IE6+, Firefox 3+, Safari 3+, and Chrome browsers which should mean everything works.

I started customising Entity Templates here Custom Entity Templates – Dynamic Data 4 I decided to take this a little further and create a Tabbed UI for editing really long forms, I have done this with the Ajax Control Toolkit but thought I like to have a jQuery UI version which brings theming to the table.

Creating the Entity Template

Wijmo tabs in action

Figure 1 – Wijmo tabs in action

<asp:Panel ID="Panel1" runat="server">
    <ul>
        <li><a href="#tabs-1">Nunc tincidunt</a></li>
        <li><a href="#tabs-2">Proin dolor</a></li>
        <li><a href="#tabs-3">Aenean lacinia</a></li>
    </ul>
    <div id="tabs-1">
        <p>
            Proin elit arcu, rutrum commodo, vehicula tempus...
</p>
</div> <div id="tabs-2"> <p> Morbi tincidunt, dui sit amet facilisis feugiat...
</p> </div> <div id="tabs-3"> <p> Mauris eleifend est et turpis. Duis id erat...
</p> </div> </asp:Panel> <wijmo:WijTabs ID="Tabs1" runat="server" TargetControlID="Panel1"> </wijmo:WijTabs>

Listing 1 – mark-up to create the Wijmo tabs

As you can see there are two blocks the UL and the DIVs the UO is used to create the tabs and each DIV matched an LI element and is shown when the tab is selected.

This is not quite as easy to render in an Entity Template as was the AJAX tabs because we need to render two sets of elements two the page, first the UL then the DIVs and we also need the IDs of the DIVs for link in the LIs. so we have to first create the DIVs so we can get each ones client ID then create the UL and add the hyperlinks.

protected override void OnLoad(EventArgs e)
{
    var groupAttribute = Table.GetAttribute<GroupNamesAttribute>();
    if (groupAttribute == null)
        throw new InvalidOperationException("A GroupsAttribute is required for AJAX tab group to work.");

    var row = new HtmlTableRow();
    var td = new HtmlTableCell();
    row.Controls.Add(td);
    this.Controls.Add(row);
    // create tab container to hold each children column
    var panel = new Panel();
    panel.ID = "tabContainer_" + Table.Name;

    // add a tab panel for each children table
    var unorderedList = new HtmlGenericControl("ul");

    // SortedList of tabs
    var tabs = new SortedList<String, HtmlGenericControl>();

    // add DIV for each group
    foreach (var gi in groupAttribute.Groups)
    {
        var groupName = gi.Value;

        var tabDiv = new HtmlGenericControl("div");
        tabDiv.ClientIDMode = ClientIDMode.Static;
        tabDiv.ID = String.Format("{0}-{1}", Table.Name, groupName).Replace(" ", "-");

        // get columns for this group
        var columns = from c in Table.GetScaffoldColumns(Mode, ContainerType)
                      where c.GetAttributeOrDefault<GroupAttribute>().Index == gi.Key
                      orderby c.GetAttributeOrDefault<DisplayAttribute>().GetOrder()
                      select c;

        // add table for this tabs fields
        var htmlTable = new HtmlTable();
        htmlTable.Attributes.Add("class", "DDDetailsTable");
        htmlTable.CellPadding = 6;
        htmlTable.Attributes.Add("Name", groupName);

        // add fields
        foreach (MetaColumn column in columns)
        {
            // new row
            var htmlRow = new HtmlTableRow();
            htmlTable.Controls.Add(htmlRow);

            // add header cell
            var tdHeader = new HtmlTableCell();
            tdHeader.Attributes.Add("class", "DDLightHeader");
            tdHeader.InnerText = column.DisplayName;
            // add cell to row
            htmlRow.Controls.Add(tdHeader);

            // add data cell
            var tdData = new HtmlTableCell();
            // get field template
            var dynamicControl = new DynamicControl() 
                { 
                    Mode = Mode,
                    DataField = column.Name, 
                    ValidationGroup = this.ValidationGroup 
                };
            // add field template to cell
            tdData.Controls.Add(dynamicControl);
            // add cell to row
            htmlRow.Controls.Add(tdData);
        }

        // add the DynamicControl to the tab panel
        tabDiv.Controls.Add(htmlTable);

        // add the tab to list
        tabs.Add(groupName, tabDiv);
    }

    foreach (var gi in groupAttribute.Groups)
    {
        var groupName = gi.Value;

        // new 'LI'
        var tabLi = new HtmlGenericControl("li");

        // new hyperlink
        var hyperlink = new Literal();
        hyperlink.Text = String.Format("<a href=\"#{0}\" >{1}</a>", tabs[groupName].ClientID, groupName);

        // add hyperlink to 'LI'
        tabLi.Controls.Add(hyperlink);

        // add LIs items to UL
        unorderedList.Controls.Add(tabLi);
    }

    // add UL to panel
    panel.Controls.Add(unorderedList);

    // add DIVs to panel
    foreach (var gi in groupAttribute.Groups)
    {
        var groupName = gi.Value;
        panel.Controls.Add(tabs[groupName]);
    }

    // add the panel to the page
    td.Controls.Add(panel);

    // associate the panel with the Wijmo tabs
    var wijmoTabs1 = new WijTabs()
        {
            ID = "wijmoTabs1",
            TargetControlID = panel.ID
        };

    // add Wijmo tabs to the page
    td.Controls.Add(wijmoTabs1);
}

Listing 2 – the main code for the Entity Template

26-05-2012 12-13-50

Figure 2 – the finished Wijmo Tabs EntityTemplate

To setup you will need to have the Attributes and the Advanced Field Template Factory these are in the sample project. I will be putting on NuGet along with my other bits and pieces hopefully soon.

public static void RegisterRoutes(RouteCollection routes)
{
    // add new entity template factory that works with single files also
    DefaultModel.EntityTemplateFactory 
        = new AdvancedEntityTemplateFactory();

    DefaultModel.RegisterContext(typeof(Models.NorthwindEntities), 
        new ContextConfiguration() { ScaffoldAllTables = true });

    routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
    {
        Constraints = new RouteValueDictionary(new 
        { 
            action = "List|Details|Edit|Insert" 
        }),
        Model = DefaultModel
    });
}

Listing 3 – setting up the project Global.asax.cs

[MetadataTypeAttribute(typeof(Employee.EmployeeMetadata))]
[EntityUIHint("WijmoTabs")]
[GroupNames("Personal","Company","Address")]
public partial class Employee
{
    internal sealed class EmployeeMetadata
    {
        public int EmployeeID { get; set; }

        [Group(0)]
        [Display(Order = 0)]
        public string Title { get; set; }
        [Group(0)]
        [Display(Order = 1)]
        public string TitleOfCourtesy { get; set; }
        [Group(0)]
        [Display(Order = 2)]
        public string FirstName { get; set; }
        [Group(0)]
        [Display(Order = 3)]
        public string LastName { get; set; }
        [Group(0)]
        [Display(Order = 4)]
        public Nullable<DateTime> BirthDate { get; set; }
        [Group(0)]
        [Display(Order = 5)]
        public string Extension { get; set; }
        [Group(0)]
        [Display(Order = 6)]
        public byte[] Photo { get; set; }
        [Group(0)]
        [Display(Order = 7)]
        public string HomePhone { get; set; }

        [Group(1)]
        [Display(Order = 8)]
        public Nullable<DateTime> HireDate { get; set; }
        [Group(1)]
        [Display(Order = 9)]
        public Employee Manager { get; set; }
        [Group(1)]
        [Display(Order = 10)]
        public Nullable<int> ReportsTo { get; set; }
        [Group(1)]
        [Display(Order = 10)]
        public EntityCollection<Employee> Staff { get; set; }
        [Group(1)]
        [Display(Order = 11)]
        public EntityCollection<Order> Orders { get; set; }
        [Group(1)]
        [Display(Order = 12)]
        public EntityCollection<Territory> Territories { get; set; }
        [Group(1)]
        [Display(Order = 13)]
        public string Notes { get; set; }

        [Group(2)]
        [Display(Order = 14)]
        public string Address { get; set; }
        [Group(2)]
        [Display(Order = 15)]
        public string City { get; set; }
        [Group(2)]
        [Display(Order = 16)]
        public string PostalCode { get; set; }
        [Group(2)]
        [Display(Order = 17)]
        public string Region { get; set; }
        [Group(2)]
        [Display(Order = 18)]
        public string Country { get; set; }

        [Display(AutoGenerateField = false)]
        public string PhotoPath { get; set; }
    }
}

Listing 4 – Sample Metadata

You will also need NuGet and add the Wijmo Open for Juice UI to your project.

Get Wijmo Open for Juice UI from NuGet

Later I will add all the features that you get with jQuery UI such as tab sorting and alignment see the online Juice Explorer for all the features.

Just for good measure I have added the Wijmo Accordion to the project

Wijmo Accordian Entity Termplate

Figure 3 – Wijmo Accordion Entity Template

You can of course get even more by getting Studio for Studio for ASP.NET Wijmo from ComponentOne this is the best thing for ASP.Net I have seem come out for a while Open-mouthed smile as everyone else seems to be concentrating on either pure client or MVC Sad smile

Download from my sky drive WijmoTabs.zip

Wednesday, 22 February 2012

Using SQL Server View in Visual Studio LightSwitch 2011

There are two issue resulting from SQL Server Views in VS LightSwitch 2011 inferred keys;

  1. Columns appearing as key that you do not want  to be inferred as keys.
  2. Forcing columns to be keys that are not inferred as keys.

You will see the results of these issues with SQL Server Views in different ways for me there were two forms:

  1. Strange Paging on child grids, you may see less row than are set on the pager i.e. page size was set to 10 but on pages you see 5, 6, 7 rows or more.
  2. Single item per page.
  3. Single item returned when there should be many.

Removing Inferred Columns

View from Northwind

Figure 1 – View from Northwind

As you can see in Figure 1 view from the Northwind database as imported in to LightSwitch you can see there are two columns that may cause you problems.

To take these out of the inferred key on this view we can apply a CAST see below:

CAST(dbo.Products.Discontinued AS BIT)
CAST(dbo.Categories.CategoryName AS NVARCHAR(15))

Adding CAST to Column

Figure 2 – Adding CAST to Column

So when we “Update Datasource” we get what we see in Figure 3

View after “Update Datasource”

Figure 3 – View after “Update Datasource”

Now we have remove the two offending columns from the inferred keys.

Forcing Columns to be Inferred

Here we need to do the opposite and the function we use for that is ISNULL (Transact-SQL) for this sample we will add the Supplier and Customer ID’s to the inferred keys, here the replacement value I am using is 0 because the two columns are INT but if a column was NVARCHAR(50) then the cast would be ISNULL(TextColumn, N‘’)

ISNULL(dbo.Products.SupplierID, 0)
ISNULL(dbo.Products.CategoryID, 0)

In Figure 4 we can see the result;

After Including the Supplier and Customer IDs in the Inferred Keys

Figure 4 – After Including the Supplier and Customer IDs in the Inferred Keys

Conclusion

This way you can for the keys you want to used in your view, there will be a small hit in the queries for using either of these techniques in your queries but hopefully not too much of a hit.

Note: These view may or may not have issues, but I have had various problems in LightSwitch relating both issues and used one the two techniques to override the default behaviour.
Note: Also I did not come up with these methods they are scattered around the LightSwitch Forums but for my own use and easy reference I have added them here.

Monday, 20 February 2012

Love Telerik Open Access ORM

Just watched the Q1 2012 “What’s New in Data Tools – OpenAccess ORM” and they now have a a Dynamic Data Wizard see screen show of the slide.

DD Wizard in Telerik OpenAccess ORM

Find it here Telrik OpenAccess ORM, Note this works with Most Databases and all Free databases Open-mouthed smile

This is cool!

Monday, 13 February 2012

Basic Auditing for Dynamic Data with Entity Framework 4.x

This is my first article of 2012 and I thought I had published an article on this previously but apparently not Crying face so I will now rectify that oversight.

The first this we need out audit fields, these are added to every entity we need to audit, next we need an Interface to allow us to fine entities with Audit fields.

AuditFields

Figure 1 – Audit Fields

public interface IAuditable
{
String CreatedByUserID { get; set; }
String CreatedDateTime { get; set; }
String UpdatedByUserID { get; set; }
String UpdatedDateTime { get; set; }
}

Listing 1 – IAuditable interface

We then need to add this to each entity that will be audited, this is just applied to you metadata classes on the Partial Class NOT the buddy class.

[MetadataType(typeof(AppAlterMetadata))]
public partial class AppAlter : IAuditable
{
internal class AppAlterMetadata
{
public Object ID { get; set; }

// other field deleted for brevety

// auditing fields
public Object CreatedByUserID { get; set; }
public Object CreatedDateTime { get; set; }
public Object UpdatedByUserID { get; set; }
public Object UpdatedDateTime { get; set; }
}
}

Listing 2 – the interface applied to each entity that requires auditing

Now for the code that does the auditing automatically,

public partial class MyEntities
{
/// <summary>
/// Called when [context created].
/// </summary>
partial void OnContextCreated()
{
// Register the handler for the SavingChanges event.
this.SavingChanges += new EventHandler(context_SavingChanges);
}


/// <summary>
/// Handles the SavingChanges event of the context control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private static void context_SavingChanges(object sender, EventArgs e)
{
var objects = ((ObjectContext)sender).ObjectStateManager;

// handle auditing
AuditingHelperUtility.ProcessAuditFields(objects.GetObjectStateEntries(EntityState.Added));
AuditingHelperUtility.ProcessAuditFields(objects.GetObjectStateEntries(EntityState.Modified), InsertMode: false);
}


/// <summary>
/// Auditing helper utility class
/// </summary>
internal static class AuditingHelperUtility
{
internal static void ProcessAuditFields(IEnumerable<Object> list, bool InsertMode = true)
{
foreach (ObjectStateEntry item in list)
{
var appUserID = GetUserId();
// deal with insert and update entities
var auditEntity = item.Entity as IAuditable;
if (auditEntity != null)
{

if (InsertMode)
{
auditEntity.CreatedByUserID = appUserID;
auditEntity.CreatedDateTime = DateTime.Now;
}

auditEntity.UpdatedByUserID = appUserID;
auditEntity.UpdatedDateTime = DateTime.Now;
}

}
}
}


public static String GetUserId()
{
return System.Web.HttpContext.Current.User.Identity.Name;
}
}

Listing 3 – the Audit code

Lets break this down into three sections

Section 1

Here we wire-up the SavingChanges handler in the OnContextCreated() partial method to do this we first need to create a partial class from out entities for you look in the EDMX code behind file you will see something like this;

EFClasses

Figure 2 – Entities classes

so we add a new class to the the project, make sure it has the same namespace as the EDMX code behind file (this is pretty much the same as for out metadata classes) and then we add the partial class same as the MyEntities (this will be the name you gave it when creating but it is there in the code behind you can’t miss it) class, see Listing 3.

The method is wired up with this line of code:

this.SavingChanges += new EventHandler(context_SavingChanges);

Section 2

Now in the context_SavingChanges method we simply get the ObjectStateManager  which has all the objects that are being added, updated and deleted, here we are only interested in the Added and Modified items. All we do is call our helper with each collection of objects.

Section 3

Looking at Listing 3 you will see the AuditingHelperUtility and it’s ProcessAuditFields method, here we first of all cast the each entity to the IAuditable interface and check for null if it isn't then set the appropriate properties and exit.

Finally

This can be expanded to cover many different requirements, I have maintained a separate audit table using this method with the addition of a little reflection.

Friday, 21 October 2011

Axialis Software Ribbon & Toolbar Stock Icons - Basic Set Offer

are offering 30%-off discount to my readers for their new Windows Ribbon & Toolbars Stock Icons Basic Set, they are provided in sizes 48x48, 32x32, 24x42, 16x16, different states (normal, hot, disabled) and RGBA / RGB color depths. Called "Basic", the first set contains 1108 unique icons. Including all sizes and derivatives, more that 29,000 images are provided.

Get the offer here

This offer will last 30 days up to Nov 20:

These look great and will be ideal for Visual Studio LightSwitch 2011 toolbars

Share this post :

Monday, 8 August 2011

Visual Studio LightSwitch 2011 Arrives (Yes, I know it arrived a while ago!)

Well I have finally had the time to indulge in Visual Studio LightSwitch 2011 RTM (henceforth LS), and it brings to Silverlight development what Dynamic Data (henceforth DD) brought to Web Forms with bells on.

It’s faster to develop an app with LS than it is with DD and that’s a fact. I decided to develop an app that I had need to run my little company but had been putting off for the last two years for lack of time. You know how a builder always has work to do on his own home never completed, well no more with LS I built it in just over one day see Figure 1.

My App in one day

Figure 1 – My App in one day

All I have to add is the Invoice report which I am going to use DevExpress – XtraReports for Light Switch

And the good news is that most of the Silverlight control venders are jumping in there with everything from How to add our controls to custom installs for LS;

And there are tones of starter kits on Visual Studio Gallery.

The forums are very active;

Blogs I’ve found so far;

I don’t expect this is an exhaustive list but it’s very encouraging and I will be joining the band waggon and build some of my own extensions and of course blog about it here.

P.S. I have not left DD this is just some new fun that will certainly compliment DD

P.P.S. I still have loads of stuff to put on NuGet so keep an eye on me here.

Wednesday, 13 July 2011

Monday, 4 July 2011

Custom Field Templates On NuGet

In this article I am going to build some custom field templates;

  1. File Upload field template
  2. Image Upload field template
  3. Image Select field template
  4. Date picker field template

CustomFieldTemplates

Figure 1 – Our proposed field templates

So first of all we need specify what we want each to do.

File Upload Field Template Requirements
  • Be able to upload and file type (PDF, ZIP, DOC, XLS etc.).
  • Restrict types to be uploaded.
  • access uploaded file via hyperlink (enable or disable this).
  • Store in folder in site.
  • Replace old file if new file replaces it during edit (you would need to maintain deleting items using some business logic as the field template is not called during the deletion process).
Image Upload Field Template Requirements
  • Be able to upload and image type (jpeg, gif, png, etc.).
  • Restrict which image types can be uploaded (i.e. restricts to jpeg or png etc.).
  • Store in folder in site.
  • Replace old file if new file replaces it during edit (you would need to maintain deleting items using some business logic as the field template is not called during the deletion process).
Image Select Field Template Requirements
  • Choose from a set of images .
  • Use images a folder in site.
Ajax Date picker
  • Select a date using a popup date picker from the Ajax Control toolkit.

At another time we will do one based on the jQuery UI date picker.

Building the Field Templates

We could just pass the information we want using the UIHint attribute and it’s control parameters collection but there is no design time intellisense, so we will build an attribute that all three field template can use. We will call it the Upload attribute it will need to store the following information;

  • Folder to store images
  • Folder to store file icons
  • Size to display Icon or Image (Height and Width)
  • Whether to display an hyperlink or not.
  • Acceptable file type for image and file upload.
  • Image extension for icons.
The Upload Attribute
/// <summary>
/// Upload attribute defines values for the upload
/// field templates
/// </summary>
/// <remarks></remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class UploadAttribute : Attribute
{
    #region Properties
    /// <summary>
    /// Gets or sets the height to display the image, 
    /// if only one of the two dimensions are specified
    /// then the aspect ration will be retained.
    /// </summary>
    /// <value>The height.</value>
    /// <remarks></remarks>
    public int Height { get; set; }

    /// <summary>
    /// Gets or sets the width to display the image, 
    /// if only one of the two dimensions are specified
    /// then the aspect ration will be retained.
    /// </summary>
    /// <value>The width.</value>
    /// <remarks></remarks>
    public int Width { get; set; }

    /// <summary>
    /// Gets or sets the uploads folder.
    /// </summary>
    /// <value>The uploads folder.</value>
    /// <remarks></remarks>
    public String UploadFolder { get; set; }

    /// <summary>
    /// Gets or sets the icons folder.
    /// </summary>
    /// <value>The icons folder.</value>
    /// <remarks></remarks>
    public String ImagesFolder { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether [show hyperlink].
    /// </summary>
    /// <value><c>true</c> if [show hyperlink]; otherwise, <c>false</c>.</value>
    /// <remarks></remarks>
    public Boolean ShowHyperlink { get; set; }

    /// <summary>
    /// Gets or sets the file types.
    /// </summary>
    /// <value>The file types.</value>
    /// <remarks></remarks>
    public String[] FileTypes { get; set; }

    /// <summary>
    /// Gets or sets the image extension.
    /// </summary>
    /// <value>The image extension.</value>
    /// <remarks></remarks>
    public String ImageExtension { get; set; }
    #endregion

    /// <summary>
    /// Initializes a new instance of the <see cref="T:System.Attribute"/> class
    /// setting the Height to 50 and the folder to "~/images".
    /// </summary>
    /// <remarks></remarks>
    public UploadAttribute()
    {
        // set a default value of 50 and constrain aspect ratio.
        Height = 50;
        // set default images folder
        UploadFolder = "~/images";
    }
}

Listing 1 – Upload Attribute

The attribute in Listing 1 handles all the properties we want so we can build each of the field templates.

Upload File Field Template

To start off expand the DynamicData folder to see the FieldTemplate folder and right click and choose Add->New Item… you can now choose “Dynamic Data Field” (this will create a new field template pretty much the same as the Text field template) enter the name “UploadFile” and you will see your new blank field template.

Dynamic Data Field

Figure 2 – Dynamic Data Field

I have decided that I want nothing to show apart form the File Upload control until there is a file uploaded

WithoutData WithData
Figure 3 – Insert mode Figure 4 – Edit mode
In Figures 2 & 3 we can see both modes we only see an image and link/text when data is already present. So I have put the mark-up for this in a place holder.
<asp:PlaceHolder 
    ID="PlaceHolder1" 
    runat="server" 
    Visible="false">
    <asp:Image ID="Image1" runat="server" />&nbsp;
    <asp:Label ID="Label1" runat="server" Text="<%# FieldValueString %>" />
    <asp:HyperLink ID="HyperLink1" runat="server"><%# FieldValueString %></asp:HyperLink>
</asp:PlaceHolder><br />
<asp:FileUpload 
    ID="FileUpload1" 
    runat="server" 
    CssClass="DDTextBox" 
    Width="150px"/>

Listing 2 – Upload File field template mark-up

Next we remove the current validators and replace with a custom validator.

<asp:CustomValidator 
    ID="CustomValidator1" 
    runat="server" 
    ControlToValidate="FileUpload1" 
    onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>

Listing 4 – Custom validator

In the code behind we need to setup the validator and the fileupload

protected void Page_Load(object sender, EventArgs e)
{
    CustomValidator1.Text = "*";
    SetUpValidator(CustomValidator1);

    // get attributes
    uploadAttribute = MetadataAttributes.GetAttribute<UploadAttribute>();
    if (uploadAttribute == null)
    {
        // no attribute thrw an error
        throw new InvalidOperationException("FileUpload must have valid uploadAttribute applied");
    }
    else
    {
        // add tooltip describing what file types can be uploaded.
        FileUpload1.ToolTip = String.Format("Upload {0} files", uploadAttribute.FileTypes.ToCsvString());
    }
}

Listing 5 – Page_Load

Here we setup the custom validator and get the Upload attribute, if the attribute is missing we throw an InvalidOperationException and if the attribute is there we set the FileUpload’s tooltip to a helpful message.

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (FileUpload1.HasFile)
    {
        // get files name
        var fileName = FileUpload1.FileName;

        // get files extension without the dot
        String fileExtension = FileUpload1.GetFileExtension();

        // check file has an allowed file extension
        if (!uploadAttribute.FileTypes.Contains(fileExtension))
        {
            args.IsValid = false;
            CustomValidator1.ErrorMessage = String.Format("{0} is not a valid upload file type (only {1} are supported).",
                FileUpload1.FileName, 
                uploadAttribute.FileTypes.ToCsvString());
        }
    }
    else if (Column.IsRequired && String.IsNullOrEmpty(Label1.Text))
    {
        args.IsValid = false;
        CustomValidator1.ErrorMessage = Column.RequiredErrorMessage;
    }
}

Listing 6 – CustomValidator1_ServerValidate method

Listing 6 is the Custom validator method here all we are concerned with is making sure we have a valid file to upload, so we check the file type via its file extension and if it matched one from out Upload attribute the file can be uploaded but if not we invalidate the page and add a custom error to our Custom validator. Also if the field is a required field then we check to see if there is a file present either from an edit or from the FileUpload control.

protected override void OnDataBinding(EventArgs e)
{
    base.OnDataBinding(e);

    //check if field has a value
    if (FieldValue == null)
        return;

    // when there is already a value in the FieldValue
    // then show the icon and label/hyperlink
    PlaceHolder1.Visible = true;

    // get the file extension
    String extension = FieldValueString.GetFileExtension();

    if (uploadAttribute.ShowHyperlink)
    {
        Label1.Visible = false;
        // open in new window
        HyperLink1.Target = "_blank";
        HyperLink1.Text = FieldValueString.GetFileNameTitle();
        HyperLink1.NavigateUrl = VirtualPathUtility.AppendTrailingSlash(uploadAttribute.UploadFolder) + FieldValueString;
    }
    else
    {
        HyperLink1.Visible = false;
        Label1.Text = FieldValueString;
    }

    // show the icon
    if (!String.IsNullOrEmpty(extension))
    {
        // set the file type image
        if (!String.IsNullOrEmpty(uploadAttribute.ImagesFolder))
        {
            // get file type image from folder specified in
            Image1.ImageUrl = String.Format("{0}{1}.{2}",
                VirtualPathUtility.AppendTrailingSlash(uploadAttribute.ImagesFolder),
                extension,
                uploadAttribute.ImageExtension);
        }

        Image1.AlternateText = extension + " file";

        // set width
        if (uploadAttribute.Width > 0)
            Image1.Width = uploadAttribute.Width;

        // set height
        if (uploadAttribute.Height > 0)
            Image1.Height = uploadAttribute.Height;
    }
    else
    {
        // if file has no extension then hide image
        Image1.Visible = false;
    }
}

Listing 7 – OnDataBinding event

In the OnDataBinding event Listing 7 we first of all check to see if the FieldValue is null if it is we just return. If it’s not null then we show the place holder. New we have to determine if we are showing an Hyperlink or a Label for the name of the file. And lastly we check to see if we can show a icon to represent the uploaded file type.

Note: The OnDataBinding event is the only place where we have access to the FieldValue in the field template code behind.
protected override void ExtractValues(IOrderedDictionary dictionary)
{
    // make sure file is valid
    if (FileUpload1.HasFile && Page.IsValid)
    {
        // make sure we have the folder to upload the file to
        var uploadFolder = Server.MapPath(VirtualPathUtility.AppendTrailingSlash(uploadAttribute.UploadFolder));
        if(!Directory.Exists(uploadFolder))
            Directory.CreateDirectory(uploadFolder);

        // upload the file
        FileUpload1.SaveAs(uploadFolder + FileUpload1.FileName);

        // update the field with the filename
        dictionary[Column.Name] = ConvertEditedValue(FileUpload1.FileName);
    }
}

Listing 8 – ExtractValues method

We make sure we have a file to upload and the there was no error from the custom validator, check that the upload folder exists and create it if not. We then save the file to the upload folder and update the data field.

Upload Image Field Template
// show the uploaded image
Image1.ImageUrl = String.Format("{0}{1}", 
    VirtualPathUtility.AppendTrailingSlash(uploadAttribute.UploadFolder), 
    FieldValueString);

// add alternate text
Image1.AlternateText = FieldValueString.GetFileNameTitle();

Listing 9 – OnDataBinding event

There only a few minor differences between UploadImage and UploadFile and they are in the section that displays the icon, in the UploadImage instead of displaying an Icon representing the file type we display the actual image.

Select Image Field Template

Here we are using a RadioButtonList and most of the work is done in the Page_Load Listing 10

protected void Page_Load(object sender, EventArgs e)
{
    // get attributes
    var uploadAttribute = MetadataAttributes.GetAttribute<UploadAttribute>();
    if (uploadAttribute == null)
        throw new InvalidOperationException("FileUpload must have valid uploadAttribute applied");

    SetUpValidator(RequiredFieldValidator1);
    SetUpValidator(DynamicValidator1);

    // if no images folder return
    var dirInfo = new DirectoryInfo(Server.MapPath(uploadAttribute.ImagesFolder));
    if (!dirInfo.Exists)
    {
        RadioButtonList1.Visible = false;
        return;
    }

    if (RadioButtonList1.Items.Count == 0)
    {
        // get a list of images in the ImageUrlAttribute folder
        var imagesFolder = ResolveUrl(uploadAttribute.ImagesFolder);
        var files = dirInfo.GetFiles(String.Format("*.{0}", uploadAttribute.ImageExtension));

        foreach (FileInfo file in files)
        {
            // size image to uploadAttribute
            var imgString = new StringBuilder();

            imgString.Append(
                String.Format("<img src='{0}' alt='{1}' ",
                    imagesFolder + file.Name,
                    file.Name.GetFileNameTitle()
               ));

            if (uploadAttribute.Width > 0)
                imgString.Append(String.Format("width='{0}' ", uploadAttribute.Width));

            if (uploadAttribute.Height > 0)
                imgString.Append(String.Format("height='{0}' ", uploadAttribute.Height));

            imgString.Append(" />");

            // embed image in the radio button
            var listItem = new ListItem(imgString.ToString(), file.Name);
            listItem.Attributes.Add("title", file.Name.GetFileNameTitle());

            this.RadioButtonList1.Items.Add(listItem);
        }
    }
}

Listing 10 – Page_Load

Here we get a list of file filtered by the file extension supplied by the Upload attribute the we populate the RadioButtonList with this list. it get a little clever as we add some html mark-up into the Text value of each ListItem added to the RadioButtonList showing the Image to choice.

Note: Setting the images folder up you will need to place your selection of images for the user to choose from into the folder and name them appropriately as the file name will be used for the tool tip and be stored in the DB as the value for the selection.
Date Picker  Field Template

All I have done here is add an Ajax Control Toolkit CalendarExtender to the page and set it up.

<asp:TextBox 
    ID="TextBox1" 
    runat="server" 
    CssClass="DDTextBox" 
    Text="<%# FieldValueEditString %>" 
    Columns="20">
</asp:TextBox>
<ajaxToolkit:CalendarExtender 
    ID="TextBox1_CalendarExtender" 
    runat="server" 
    Enabled="True"
    TargetControlID="TextBox1">
</ajaxToolkit:CalendarExtender>

Listing 11 – Date with Calendar Extender

private readonly static String DATE_FORMAT = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern

protected void Page_Load(object sender, EventArgs e)
{
    TextBox1_CalendarExtender.Format = DATE_FORMAT;
    TextBox1.ToolTip = Column.Description;

    SetUpValidator(RequiredFieldValidator1);
    SetUpValidator(RegularExpressionValidator1);
    SetUpValidator(DynamicValidator1);
    SetUpCustomValidator(DateValidator);
}

Listign 12 – Page_Load

All I’ve had to do is make sure the CalendarExtender matches the localised date time format, we now get a nice data picker.

Sample Metadata
[MetadataTypeAttribute(typeof(File.FileMetadata))]
public partial class File
{
    internal sealed class FileMetadata
    {
        public int ID { get; set; }
        public string Description { get; set; }

        [Upload(
            FileTypes = new String[] { "doc", "xls" },
            UploadFolder = "~/FileUploads/",
            ImagesFolder = "~/images/",
            ShowHyperlink = true,
            ImageExtension = "png",
            Height = 30)]
        [UIHint("UploadFile")]
        public string FileName { get; set; }

        [Upload(
            FileTypes = new String[] { "png", "jpg", "jpeg" },
            UploadFolder = "~/ImageUploads/",
            ShowHyperlink = true,
            ImageExtension = "png",
            Height = 30)]
        [UIHint("UploadImage")]
        public string ImageName { get; set; }

        [Upload(
            ImagesFolder = "~/ImageSelection/",
            ImageExtension = "png",
            Height = 30)]
        [UIHint("SelectImage")]
        public string Selection { get; set; }

        [DataType(DataType.Date)]
        public DateTime DateCreated { get; set; }

    }
}

Listing 13 – sample metadata

Download NuGet Package

Dynamic Data Custom Field Templates - 1.0

Tuesday, 28 June 2011

Autocomplete ForeignKey Field Template Now on NuGet

I have just added the ForeignKey field template based on the old Futures Autocomplete filter to NuGet at NotAClue.DynamicData.AutocompleteForeignKey 

NotAClue.DynamicData.AutocompleteForeignKeySample

Autocomplete in action

All you need is to add a UIHint attribute to the to set the field template,

Note: only works on Foreign Key columns

you can als0 set the number of characters you need to type before autocomplete kicks in.

[UIHint("Autocomplete", null, "MinimumPrefixLength",2)]
public Supplier Supplier { get; set; }

By setting the MinimumPrefixLength in the UIHint’s ControlParameters.

Monday, 27 June 2011

My Classic Cascading Filters and Field Templates on NuGet

I’ve just released my classic Cascading Filters and Field Templates on NuGet for ease of install supports both Entity Framework and Linq to SQL.

DynamicDataCascade100x100

Dynamic Data Filters and Field Templates

Sample Metadata
[MetadataTypeAttribute(typeof(Vehicle.VehicleMetadata))]
public partial class Vehicle
{
    internal sealed class VehicleMetadata
    {
        public int Id { get; set; }
        public int ManufacturerId { get; set; }
        public int VehicleTypeId { get; set; }
        public int ModelId { get; set; }
        public int StyleId { get; set; }

        [Display(Order = 0)]
        public String Name { get; set; }

        /// <summary>
        /// Note for cascade to work correctly
        /// fields must be in cascade order Parent->Child
        /// </summary>
        [FilterUIHint("CascadingForeignKey")]
        [UIHint("CascadingForeignKey")]
        [Filter(Order = 0)]
        [Display(Order = 1)]
        public Manufacturer Manufacturer { get; set; }

        [FilterUIHint("CascadingForeignKey")]
        [UIHint("CascadingForeignKey")]
        [Cascade("Manufacturer")]
        [Filter(Order = 1)]
        [Display(Order = 2)]
        public VehicleType VehicleType { get; set; }

        [FilterUIHint("CascadingForeignKey")]
        [UIHint("CascadingForeignKey")]
        [Cascade("VehicleType")]
        [Filter(Order = 2)]
        [Display(Order = 3)]
        public Model Model { get; set; }

        [FilterUIHint("CascadingForeignKey")]
        [UIHint("CascadingForeignKey")]
        [Cascade("Model")]
        [Filter(Order = 3)]
        [Display(Order = 4)]
        public Style Style { get; set; }

    }
}
Note: For cascading to work each child must follow in order Parent->Child note the Ordering of both filters and fields to facilitate the cascade.

Next up are hierarchical cascade field templates

Thursday, 23 June 2011

Links to Sample Down :(

It would appear that Live.com have done some reorganisation of my SkyDrive for me Disappointed smile and now ALL the links to my samples are broken, you can see my public folder here Public

Sorry for this but it is out of my control.

Anyway on a positive note I plan to have all my old samples update to .Net 4 and on NuGet as we go forward, I will post a pole with a list of proposed samples to get a vote what people want most.

Wednesday, 22 June 2011

Filter NuGet Package updated

Thirteen Dynamic Data Custom Filters has been updated to Dynamic Data 15 Custom Filters and the PackageId is now “DynamicData.CustomFilters”, makes more sense than “DynamicData.ThirteenFilters” especially it now had 15 filters instead of 13.

I have added

  • GreaterThanOrEqual
  • LessThanOrEqual
Sample Metadata
[MetadataTypeAttribute(typeof(Product.ProductMetadata))]
public partial class Product
{
    internal sealed class ProductMetadata
    {
        [FilterUIHint("MultiForeignKey")]
        public Category Category { get; set; }

        public Nullable<int> CategoryID { get; set; }

        public bool Discontinued { get; set; }

        public EntityCollection<Order_Detail> Order_Details { get; set; }

        public int ProductID { get; set; }

        public string ProductName { get; set; }

        public string QuantityPerUnit { get; set; }

        public Nullable<short> ReorderLevel { get; set; }

        public Supplier Supplier { get; set; }

        public Nullable<int> SupplierID { get; set; }

        [FilterUIHint("GreaterThanOrEqual")]
        public Nullable<decimal> UnitPrice { get; set; }

        [FilterUIHint("LessThanOrEqual")]
        public Nullable<short> UnitsInStock { get; set; }

        public Nullable<short> UnitsOnOrder { get; set; }
    }
}

Much fun I expect there will be more soon.

Tuesday, 21 June 2011

More NuGet

I have just put up the the first instalment of my Dynamic Data Extensions this version (V1.0) we have

  • HideColumnIn attribute see A New Way To Do Column Generation in Dynamic Data 4
  • ShowColumnOnlyIn attribute does what it says on the tin shows column in particular page templates
  • Filter attribute (I have only implemented the Order property as yet) this allows you to set the filter order.

Dynamic Data Extensions

Dynamic Data Extensions

Search for DynamicData.Extensions on NuGet

Example Metadata

[MetadataTypeAttribute(typeof(Order.OrderMetadata))]
public partial class Order
{
    internal sealed class OrderMetadata
    {
        public string CustomerID { get; set; }
        public Nullable<int> EmployeeID { get; set; }
        public Nullable<int> ShipVia { get; set; }

        [ShowColumnOnlyIn(PageTemplate.List)]
        [ScaffoldColumn(true)]
        public int OrderID { get; set; }

        public Nullable<DateTime> OrderDate { get; set; }

        [HideColumnIn(PageTemplate.List | PageTemplate.Insert)]
        public Nullable<DateTime> RequiredDate { get; set; }

        [HideColumnIn(PageTemplate.List | PageTemplate.Insert)]
        public Nullable<DateTime> ShippedDate { get; set; }
        public Nullable<decimal> Freight { get; set; }
        public string ShipName { get; set; }
        public string ShipAddress { get; set; }
        public string ShipCity { get; set; }
        public string ShipCountry { get; set; }
        public string ShipRegion { get; set; }
        public string ShipPostalCode { get; set; }

        [Filter(Order=2)]
        public Customer Customer { get; set; }
        [Filter(Order = 1)]
        public Employee Employee { get; set; }
        [Filter(Order = 3)]
        public Shipper Shipper { get; set; }

        public EntityCollection<Order_Detail> Order_Details { get; set; }
    }
}

Here you can see all three custom attributes in action.

  • The HideColumnInAttribute hides columns in page templates (note the use of the ‘|’ OR operator to allows multiple pages to be selected.
  • The ShowColumnOnlyInAttribute does the opposite and only shows columns in selected pages.
  • The FilterAttribute here sets the order to display the filters on the list page (Note there are other properties on Filter that are not yet implemented).

Next up on NuGet are both of my original cascade and my hierarchical cascading field templates.

Friday, 10 June 2011

A Second NuGet Package for Dynamic Data

Dynamic Data 15 Custom Filters is now on NuGet  this package add thirteen filters to your Web Application Project see Five Cool Filters for Dynamic Data 4 I have added some more filters to that list;

  • AutoComplete – is ForeignKey filter but pre-filters results by what users has typed in.
  • Contains – equivalent to T-SQL LIKE ‘%text%’
  • DateFrom – All Dates greater than or equal to the selected date.
  • DateRange – A range of dates
  • DateTo – Less than or equal to the selected date.
  • EndsWith – Ends with entered text.
  • GreaterThan – Greater than entered value
  • LessThan – Less than entered value
  • MultiForeignKey – allows multiple ForeignKey values to be selected.
  • Range – a range of values
  • StartWith – Starts with entered text.
  • Where – is equal to entered text
  • WhereDropdownList – a dropdown list of values from column to filter by.

This has a few more exciting bits that NuGet offers Dependencies and Framework Assembly References

Dependencies, here this package there is dependency upon Ajax Control Toolkit

<dependencies>
    <dependency id="AjaxControlToolkit" version="4.1.50508" />
</dependencies>

Framework Assembly References – is requirement for an assembly reference from the GAC

<frameworkAssemblies>
    <frameworkAssembly assemblyName="System.Data.Entity" targetFramework="net40" />
</frameworkAssemblies>

This give great flexibility without resorting to PowerShell.

NuGet truly is awesome!

NuGet for Dynamic Data – First Package

I have just added my first NuGet package, and you may no know what NuGet is? so what is NuGet it’s a Package management add on for Visual Studio 2010 and above (maybe more as it is integrated with Windows PowerShell).

Install NuGet

Figure 1 – Install NuGet

See Installing NuGet and then you will need NuGet.exe Command Line and or NuGet Package Explorer v1.1 this is the GUI version (and unlike Scott Hanselman I like the GUI and try to avoid the DOS as much as possible I’m with Phil Haack on that see NuGet In Depth: Empowering Open Source on the .NET Platform on Channel9) and can do a lot of what the command line tool does.

You can get loads on information on NuGet Docs.

OK so I’m going to assume your all setup and ready to go.

Creating the Package

NuGet has some Package Conventions and we should follow them (I’ll not explain them just go and have a read as documentation can be updated from time to time) for out package lets first of all look at what we want to package.

For this Package I want to package up Scott Hunter’s old Sample for Displaying Images from the Database using Dynamic Data (DBImage) and it’s update Sample for Displaying Images Updated + Screencast note the latest version of this is in the old Dynamic Data Futures VS2008 SP1 RTM for DD 3.51 SP1.

Embedded image field template

Figure 2 – Embedded image field template

This consists of several parts;

  • Read-Only field template
  • Edit field template
  • Image Format attribute
  • Linq extension methods
  • Image http handler.
  • Web.Config settings

I have decided to keep things simple for out first NuGet Package and all the above will go into one package some of the above could be shared and as such we could spilt it between several packages and have dependencies but we will keep it simple for now.

so to build our package there are some things we need to know like where do we put our files;

Package folder structure

Figure 3 – Simple Package folder structure

As you can see I have broken the folder structure into three parts, the first part is quite simple, it’s the readme file which will give basic information about the package.

Content (files to be copied on install)

Here you can have three types of file;

The “.transform” files transform web.config or app.config files by adding/merging their content with the project’s configuration file.

While the “.pp” files are files that are transformed as they are copied to the project in the same folder structure they have in the package. These files are a little more complex than the configuration files, as they have Visual Studio project properties in the code and these are used to transform the code files during install ((see Configuration File and Source Code Transformations and the Specifying Source Code Transformations section for more info).

Lib Folder

This folder contains any DLLs that are required, not that the “net40” subfolder this indicates that the DLL supports .Net 4 you could have several version that support different versions of the .Net framework here we will just support .Net 4.

Next

Note this is just the basic of where you need to put files for your package to work.

now we have out files ready in a folder structure we need to create our “nuspec” file, this is an XML file containing details (the manifest) about the package you can manually create this or you can use NuGet Package Explorer to create this see Using A GUI (Package Explorer) to build packages once created you can manually edit the “nuspec” file manually if you like.

You then place your “nuspec” file in the root of the package folder structure or if you follow Using A GUI (Package Explorer) to build packages you can add them directly.

Once done you just publish and it works!

Next steps

The real power come with PowerShell scripts see Scaffolding – ASP.NET, NuGet, Entity Framework Code First and More with Steve Sanderson he shows what you can really do.

I am going to add more complex post here as I discover new and interesting feature of NuGet.