Rectangle 27 1

Why not use the ProductSummaryModel for binding instead of ProductViewModel. This way you can keep thing simple. Avoid nested bindings if you can. Also be sure you have using in the view as below, and the HttpPost attr. in the Controller

Public Class ProductController
Inherits Controller

' Main Action
Public Function Main() As ActionResult 
    Dim prdViewModel As ProductViewModel = New ProductViewModel       
    prdViewModel.ProductSummary = New ProductSummaryModel
    Return View("Main", prdViewModel)
End Function

' Partial Action
Public Function Add() As ActionResult 
    Dim prdViewModel As ProductViewModel = New ProductViewModel
    prdViewModel.ProductSummary = New ProductSummaryModel

    Return View("Add", prdViewModel)
End Function

'POST Action from Partial View
<HttpPost()> _
 Public Function AddItem(ByVal Model As ProductSummaryModel) As ActionResult ' Add Item into DB
   msgbox(Model.productPrice) ' Empty
End Function

End Class
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage(Of MvcApplication2.ProductViewModel)" %>

<asp:Content ID="manageTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Main Page
</asp:Content>

<asp:Content ID="manageContent" ContentPlaceHolderID="MainContent" runat="server">
    <%
        Html.RenderPartial("_Add", Model.ProductSummary)
     %>
</asp:Content>
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of MvcApplication2.ProductSummaryModel)" %>

<asp:Content ID="registerTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Register
</asp:Content>

<asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" runat="server">

    <% Using Html.BeginForm("AddItem", "Product")%>
        <%: Html.AntiForgeryToken() %>
        <tr>
            <td>Price: </td>
            <td><%: Html.TextBoxFor(Function(f) f.productPrice) %></td>
        </tr>
        <input type="submit" value="Register" />
    <% End Using%>
</asp:Content>
Public Class ProductSummaryModel

    Property productGUID As Integer
    Property productName As String
    Property productPrice As Double
    Property productSku As String
    Property categories As String()
    Property ShipsWithin As Nullable(Of Integer)
    <AllowHtml>
    Property productWebDescription As String
    Property ImageMainPath As String

End Class

Public Class ProductViewModel
    Public ProductSummary As ProductSummaryModel
End Class

Spock, This is how I was doing it before, Problem is...I have multiple TABS, and each TAB is a partial view Itself. Each Tab will contain its own ViewModel, and then I will send my main Model (ProductViewModel) to by DB, instead of passing multiple / Separate ViewModels.

In your Main View which has the partial view, use Inherits="System.Web.Mvc.ViewPage(Of MvcApplication2.ProductViewModel)". Your partial view use the above solution I posted. When you call this as a Partial view from the Main view, for example Html.RenderPartial("_YourProduceSummaryPartialView, Model.ProductSummaryModel"). And of course in your partial View @ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of MvcApplication2.ProductSummaryModel)" %>

Yes I did that, but now when I try to Post the Form and try to get the Values back, i am getting Object instance Error Message. this is how my Controller looks like: Public Function AddItem(ByVal Model As ProductViewModel) As ActionResult ' Add Item into DB MsgBox(Model.ProductSummary.productName)

asp.net mvc - MVC ViewModel not posting back - Stack Overflow

asp.net-mvc asp.net-mvc-4
Rectangle 27 58

I apologize in advance, this post strays a bit from what you asked, but all of this bubbled up when I read your question.

WebAPI Matching Semantic The matching semantic used by (the default routes in) WebAPI is fairly simple.

  • It matches the name of the action with the verb (verb = GET? look for method name starting with "get")
  • if a parameter is passed, the api seeks an action with a parameter

So in your code sample a GET request without a parameter matches the Get*( ) function without an parameters. A Get containing and ID looks for a Get***(int id).

Odd Names - Your get method can be named anything, so long as it starts with "get". So in the case of a widget controller you can name your functions GetStrawberry() and it will still be matched. Think of the matching as something like : methodname.StartsWith("Get")

Multiple Matching Methods - What happens if you have two Get methods with no parameters? GetStrawberry() and GetOrange(). As best I can tell, the function defined first (top of the file) in your code wins ...strange. This has the side effect of making some methods in your controller unreachable (at least with the default routes)....stranger.

NOTE : the beta behaved as above for 'matching multiple methods' - the RC & Release version is a bit more OCD. It throws an error if there are multiple potential matches. This change removes the confusion of multiple ambiguous matches. At the same time, it reduces our ability to mix REST and RPC style interfaces in the same controller, relying on the order & overlapping routes.

What to do? Well, WebAPI is new and consensus is still coalescing. The community seems to be reaching for REST principles quite a bit. Yet, not every API can or should be RESTful, some are more naturally expressed in an RPC style. REST & what people call REST seems to be the source of quite a bit of confusion, well at least to Roy Fielding.

As a pragmatist, i suspect that many API's will be 70% RESTful, with a smattering of RPC style methods. First, the the controller proliferation alone (given the webapi binding method) is going to drive developers bonkers. Second, WebAPI doesn't really have a built in way to create a nested structure of api paths (meaning: /api/controller/ is easy, but /api/CATEGORY/Sub-Category/Controller is doable, but a pain).

From my perspective, I would love to see the webAPI folder structure control the default API paths... meaning if I create a Category folder in my UI project then /api/Category would be the default path (something parallel to this MVC article).

What did I do? So, I had a few requirements: (1) to be able to use restful syntax in most case, (2) have some "namespace" separation of controllers (think sub-folders), (3) be able to call additional rpc-like methods when necessary. Implementing these requirements came down to clever routing.

// SEE NOTE AT END ABOUT DataToken change from RC to RTM

Route r;
r = routes.MapHttpRoute( name          : "Category1", 
                         routeTemplate : "api/Category1/{controller}/{id}", 
                         defaults      : new { id = RouteParameter.Optional } );
r.DataTokens["Namespaces"] = new string[] {" UI.Controllers.Category1"};

r = routes.MapHttpRoute( name          : "Category2", 
                         routeTemplate : "api/Category2/{controller}/{id}", 
                         defaults      : new { id = RouteParameter.Optional } );
r.DataTokens["Namespaces"] = new string[] {" UI.Controllers.Category2"};

routes.MapHttpRoute(     name          : "ApiAllowingBL", 
                         routeTemplate : "api/{controller}/{action}/{id}",
                         defaults      : new { id = RouteParameter.Optional } );

routes.MapHttpRoute(     name          : "DefaultApi",  
                         routeTemplate : "api/{controller}/{id}",           
                         defaults      : new { id = RouteParameter.Optional } );
  • The first two routes create "sub-folder" routes. I need to create a route for each sub-folder, but I limited myself to major categories, so I only end up with 3-10 of these. Notice how these routes add the Namespace data token, to restrict what classes are searched for a particular route. This corresponds nicely to the typical namespace setup as you add folders to a UI project.
  • The third route allows specific method names to be called (like traditional mvc). Since web API does away with action name in the URL, it's relatively easy to tell which calls want this route.
  • The last route entry is the default web api route. This catches any classes, particularly ones outside my 'sub-folders'.
/api/XXXX
  • I create a folder in my UI project(lets say Category1), and put api controllers within the folder.
  • Visual studio naturally sets class namespaces based on folder. So Widget1 in the Category1 folder gets a default namespace of UI.Category1.Widget1.
  • Naturally, I wanted api URLs to reflect the folder structure (/api/Category1/Widget). The first mapping you see above accomplishes that, by hard coding /api/Category1 into the route, then the namespace token restricts classes that will be searched for a matching controller.

NOTE: as of the release DataTokens are null by default. I'm not sure if this is a bug, or a feature. So I wrote a little helper method and added to my RouteConfig.cs file....

r.AddRouteToken("Namespaces", new string[] {"UI.Controllers.Category1"});

private static Route AddRouteToken(this Route r, string key, string[] values) {
  //change from RC to RTM ...datatokens is null
if (r.DataTokens == null) {
       r.DataTokens = new RouteValueDictionary();
    }
    r.DataTokens[key] = values;
    return r;
}

NOTE 2: even thought this is a WebAPI 1 post, as @Jamie_Ide points out in the comments the above solution doesn't work in WebAPI 2 because IHttpRoute.DataTokens has no setter. To get around this you can use a simple extension method like this:

private static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, string[] namespaceTokens)
{   
    HttpRouteValueDictionary    defaultsDictionary      = new HttpRouteValueDictionary(defaults);
    HttpRouteValueDictionary    constraintsDictionary   = new HttpRouteValueDictionary(constraints);
    IDictionary<string, object> tokens                  = new Dictionary<string, object>();
                                tokens.Add("Namespaces", namespaceTokens);

    IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: tokens, handler:null);
    routes.Add(name, route);

    return route;
}

Thanks EBarr, that's very helpful. Your solution at the end is a bit over my head, but the first part definitely answered my question, and I think the last part will be extremely useful to revisit after I've learned a bit more. I had suspected that there was some sort of comparison between a method name in your controller class and the http verbs, but until someone confirmed it and told me how it worked I didn't really believe my own suspicion. Thanks!

@AndrewBSchultz - glad to help. ..posting a bit better solution explanation.

if you would like to have urls broken into subfolders (or I have heard it referred to as 'by namespace') like localhost:xxxx/api/mySubfolder/myController and you are putting your controllers in subfolders under controllers you can use {path}. Example:---- file: MyProject\Controllers\Users\AdminUsersController.cs---- maps to uri: localhost:xxxx/api/Users/AdminUsers---- routing code: RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{path}/{controller}/{id}", defaults: new { id = RouteParameter.Optional });

In Web Api 2, IHttpRoute.DataTokens has no setter so this solution no longer works. I'm starting to get the hint that Web Api really does not want to accommodate this style of routing. You can always organize your controllers into folders, and you can define routes to access them, however they are still accessible via the default route and duplicate names will throw runtime exceptions.

asp.net mvc - How does a method in MVC WebApi map to an http verb? - S...

asp.net-mvc asp.net-mvc-routing asp.net-web-api
Rectangle 27 58

I apologize in advance, this post strays a bit from what you asked, but all of this bubbled up when I read your question.

WebAPI Matching Semantic The matching semantic used by (the default routes in) WebAPI is fairly simple.

  • It matches the name of the action with the verb (verb = GET? look for method name starting with "get")
  • if a parameter is passed, the api seeks an action with a parameter

So in your code sample a GET request without a parameter matches the Get*( ) function without an parameters. A Get containing and ID looks for a Get***(int id).

Odd Names - Your get method can be named anything, so long as it starts with "get". So in the case of a widget controller you can name your functions GetStrawberry() and it will still be matched. Think of the matching as something like : methodname.StartsWith("Get")

Multiple Matching Methods - What happens if you have two Get methods with no parameters? GetStrawberry() and GetOrange(). As best I can tell, the function defined first (top of the file) in your code wins ...strange. This has the side effect of making some methods in your controller unreachable (at least with the default routes)....stranger.

NOTE : the beta behaved as above for 'matching multiple methods' - the RC & Release version is a bit more OCD. It throws an error if there are multiple potential matches. This change removes the confusion of multiple ambiguous matches. At the same time, it reduces our ability to mix REST and RPC style interfaces in the same controller, relying on the order & overlapping routes.

What to do? Well, WebAPI is new and consensus is still coalescing. The community seems to be reaching for REST principles quite a bit. Yet, not every API can or should be RESTful, some are more naturally expressed in an RPC style. REST & what people call REST seems to be the source of quite a bit of confusion, well at least to Roy Fielding.

As a pragmatist, i suspect that many API's will be 70% RESTful, with a smattering of RPC style methods. First, the the controller proliferation alone (given the webapi binding method) is going to drive developers bonkers. Second, WebAPI doesn't really have a built in way to create a nested structure of api paths (meaning: /api/controller/ is easy, but /api/CATEGORY/Sub-Category/Controller is doable, but a pain).

From my perspective, I would love to see the webAPI folder structure control the default API paths... meaning if I create a Category folder in my UI project then /api/Category would be the default path (something parallel to this MVC article).

What did I do? So, I had a few requirements: (1) to be able to use restful syntax in most case, (2) have some "namespace" separation of controllers (think sub-folders), (3) be able to call additional rpc-like methods when necessary. Implementing these requirements came down to clever routing.

// SEE NOTE AT END ABOUT DataToken change from RC to RTM

Route r;
r = routes.MapHttpRoute( name          : "Category1", 
                         routeTemplate : "api/Category1/{controller}/{id}", 
                         defaults      : new { id = RouteParameter.Optional } );
r.DataTokens["Namespaces"] = new string[] {" UI.Controllers.Category1"};

r = routes.MapHttpRoute( name          : "Category2", 
                         routeTemplate : "api/Category2/{controller}/{id}", 
                         defaults      : new { id = RouteParameter.Optional } );
r.DataTokens["Namespaces"] = new string[] {" UI.Controllers.Category2"};

routes.MapHttpRoute(     name          : "ApiAllowingBL", 
                         routeTemplate : "api/{controller}/{action}/{id}",
                         defaults      : new { id = RouteParameter.Optional } );

routes.MapHttpRoute(     name          : "DefaultApi",  
                         routeTemplate : "api/{controller}/{id}",           
                         defaults      : new { id = RouteParameter.Optional } );
  • The first two routes create "sub-folder" routes. I need to create a route for each sub-folder, but I limited myself to major categories, so I only end up with 3-10 of these. Notice how these routes add the Namespace data token, to restrict what classes are searched for a particular route. This corresponds nicely to the typical namespace setup as you add folders to a UI project.
  • The third route allows specific method names to be called (like traditional mvc). Since web API does away with action name in the URL, it's relatively easy to tell which calls want this route.
  • The last route entry is the default web api route. This catches any classes, particularly ones outside my 'sub-folders'.
/api/XXXX
  • I create a folder in my UI project(lets say Category1), and put api controllers within the folder.
  • Visual studio naturally sets class namespaces based on folder. So Widget1 in the Category1 folder gets a default namespace of UI.Category1.Widget1.
  • Naturally, I wanted api URLs to reflect the folder structure (/api/Category1/Widget). The first mapping you see above accomplishes that, by hard coding /api/Category1 into the route, then the namespace token restricts classes that will be searched for a matching controller.

NOTE: as of the release DataTokens are null by default. I'm not sure if this is a bug, or a feature. So I wrote a little helper method and added to my RouteConfig.cs file....

r.AddRouteToken("Namespaces", new string[] {"UI.Controllers.Category1"});

private static Route AddRouteToken(this Route r, string key, string[] values) {
  //change from RC to RTM ...datatokens is null
if (r.DataTokens == null) {
       r.DataTokens = new RouteValueDictionary();
    }
    r.DataTokens[key] = values;
    return r;
}

NOTE 2: even thought this is a WebAPI 1 post, as @Jamie_Ide points out in the comments the above solution doesn't work in WebAPI 2 because IHttpRoute.DataTokens has no setter. To get around this you can use a simple extension method like this:

private static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, string[] namespaceTokens)
{   
    HttpRouteValueDictionary    defaultsDictionary      = new HttpRouteValueDictionary(defaults);
    HttpRouteValueDictionary    constraintsDictionary   = new HttpRouteValueDictionary(constraints);
    IDictionary<string, object> tokens                  = new Dictionary<string, object>();
                                tokens.Add("Namespaces", namespaceTokens);

    IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: tokens, handler:null);
    routes.Add(name, route);

    return route;
}

Thanks EBarr, that's very helpful. Your solution at the end is a bit over my head, but the first part definitely answered my question, and I think the last part will be extremely useful to revisit after I've learned a bit more. I had suspected that there was some sort of comparison between a method name in your controller class and the http verbs, but until someone confirmed it and told me how it worked I didn't really believe my own suspicion. Thanks!

@AndrewBSchultz - glad to help. ..posting a bit better solution explanation.

if you would like to have urls broken into subfolders (or I have heard it referred to as 'by namespace') like localhost:xxxx/api/mySubfolder/myController and you are putting your controllers in subfolders under controllers you can use {path}. Example:---- file: MyProject\Controllers\Users\AdminUsersController.cs---- maps to uri: localhost:xxxx/api/Users/AdminUsers---- routing code: RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{path}/{controller}/{id}", defaults: new { id = RouteParameter.Optional });

In Web Api 2, IHttpRoute.DataTokens has no setter so this solution no longer works. I'm starting to get the hint that Web Api really does not want to accommodate this style of routing. You can always organize your controllers into folders, and you can define routes to access them, however they are still accessible via the default route and duplicate names will throw runtime exceptions.

asp.net mvc - How does a method in MVC WebApi map to an http verb? - S...

asp.net-mvc asp.net-mvc-routing asp.net-web-api
Rectangle 27 2

MvcSiteMapProvider already does most of the work for you. It keeps a cache of the hierarchical relationship between the nodes and also automatically looks up the current node on each request.

The only things you need to do are provide the node hierarchy (once per application start) and use the HTML helper for breadcrumbs, namely @Html.MvcSiteMap().SiteMapPath(). You can also optionally customize the URLs any way you like using routing.

Since you are likely dealing with database-driven data, you should use DynamicNodeProvider so new data will be automatically available in the SiteMap after it is added to the database.

First of all, your database should keep track of the parent-child relationship between categories. You can do that with a self-joining table.

| CategoryID  | ParentCategoryID  | Name           | UrlSegment     |
|-------------|-------------------|----------------|----------------|
| 1           | null              |       | category-1     |
| 2           | 1                 | 2     | category-2     |
| 3           | 2                 | 3     | category-3     |

Depending on where you put the categories in your web site, null should represent the parent node (usually it be the home page or a top-level category list page).

Then your products should be categorized. This gets more complicated if there is a many-to-many relationship between category and product because each node should have its own unique URL (even if it is just another link to the same product page). I won't go into details here, but using the canonical tag helper in conjunction with custom routing (possibly data-driven URLs) is the recommended approach. It is natural to add the category to the beginning of the product URL (which I show below) so you will have unique URLs for each category view of the product. Then you should add an additional flag in the database to keep track of the "primary" category, which can then be used to set the canonical key.

For the rest of this example, I will assume the product to category relationship is 1-to-1, but that is not how most e-commerce is done these days.

| ProductID   | CategoryID | Name           | UrlSegment     |
|-------------|------------|----------------|----------------|
| 1           | 3          | Prod1          | product-1      |
| 2           | 1          | Prod2          | product-2      |
| 3           | 2          | Prod3          | product-3      |

Next, the controllers are built to supply the dynamic category and product information. MvcSiteMapProvider uses the controller and action name.

Note that the exact way you get the product in your application depends on your design. This example uses CQS.

public class CategoryController : Controller
{
    private readonly IQueryProcessor queryProcessor;

    public CategoryController(IQueryProcessor queryProcessor)
    {
        if (queryProcessor == null)
            throw new ArgumentNullException("queryProcessor");

        this.queryProcessor = queryProcessor;
    }

    public ActionResult Index(int id)
    {
        var categoryDetails = this.queryProcessor.Execute(new GetCategoryDetailsQuery
        {
            CategoryId = id
        });

        return View(categoryDetails);
    }
}


public class ProductController : Controller
{
    private readonly IQueryProcessor queryProcessor;

    public ProductController(IQueryProcessor queryProcessor)
    {
        if (queryProcessor == null)
            throw new ArgumentNullException("queryProcessor");

        this.queryProcessor = queryProcessor;
    }

    public ActionResult Index(int id)
    {
        var productDetails = this.queryProcessor.Execute(new GetProductDetailsDataQuery
        {
            ProductId = id
        });

        return View(productDetails);
    }
}

For maintenance purposes, using separate category and product node providers may make things easier but it is not strictly necessary. In fact, you could provide all of your nodes with a single dynamic node provider.

public class CategoryDynamicNodeProvider : DynamicNodeProviderBase
{
    public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
    {
        var result = new List<DynamicNode>();

        using (var db = new MyEntities())
        {
            // Create a node for each category
            foreach (var category in db.Categories)
            {
                DynamicNode dynamicNode = new DynamicNode();

                // Key mapping
                dynamicNode.Key = "Category_" + category.CategoryID;

                // NOTE: parent category is defined as int?, so we need to check
                // whether it has a value. Note that you could use 0 instead if you want.
                dynamicNode.ParentKey = category.ParentCategoryID.HasValue ? "Category_" + category.ParentCategoryID.Value : "Home";

                // Add route values
                dynamicNode.Controller = "Category";
                dynamicNode.Action = "Index";
                dynamicNode.RouteValues.Add("id", category.CategoryID);

                // Set title
                dynamicNode.Title = category.Name;

                result.Add(dynamicNode);
            }
        }

        return result;
    }
}

public class ProductDynamicNodeProvider : DynamicNodeProviderBase
{
    public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
    {
        var result = new List<DynamicNode>();

        using (var db = new MyEntities())
        {
            // Create a node for each product
            foreach (var product in db.Products)
            {
                DynamicNode dynamicNode = new DynamicNode();

                // Key mapping
                dynamicNode.Key = "Product_" + product.ProductID;
                dynamicNode.ParentKey = "Category_" + product.CategoryID;

                // Add route values
                dynamicNode.Controller = "Product";
                dynamicNode.Action = "Index";
                dynamicNode.RouteValues.Add("id", product.ProductID);

                // Set title
                dynamicNode.Title = product.Name;

                result.Add(dynamicNode);
            }
        }

        return result;
    }
}

Alternatively, if you use DI you might consider implementing ISiteMapNodeProvider instead of dynamic node provider. It is a lower level abstraction that allows you to provide all of your nodes.

All that you need in your XML are static pages and dynamic node provider definition nodes. Note that you have already defined the parent-child relationship within the dynamic node providers, so there is no need to do it again here (although you could to make it more clear that products are nested within categories).

<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"
            xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd">

    <mvcSiteMapNode title="Home" controller="Home" action="Index">
        <mvcSiteMapNode title="Category Nodes" dynamicNodeProvider="MyNamespace.CategoryDynamicNodeProvider, MyAssembly" />
        <mvcSiteMapNode title="Product Nodes" dynamicNodeProvider="MyNamespace.ProductDynamicNodeProvider, MyAssembly" />
    </mvcSiteMapNode>
</mvcSiteMap>

Then it is just a matter of putting the SiteMapPath into your views. The simplest approach is just to add it to your _Layout.cshtml.

<div id="body">
    @RenderSection("featured", required: false)
    <section class="content-wrapper main-content clear-fix">
        @Html.MvcSiteMap().SiteMapPath()
        @RenderBody()
    </section>
</div>

Note that you can edit the templates (or create named templates) in the /Views/Shared/DisplayTemplates/ folder to customize the HTML that is output by the HTML helpers.

As I mentioned before, I recommend using data-driven routing when making data-driven pages. The primary reason for this is that I am a purist. Routing logic does not belong in the controller, so passing a slug to the controller is a messy solution.

Also, if you have a primary key to URL mapping, it means the routing is only cosmetic as far as the rest of the application is concerned. Keys are what drive the application (and the database) and URLs are what drive MVC. This makes managing URLs external to your application logic.

This is an implementation that allows you to map a set of data records to a single controller action. Each record has a separate virtual path (URL) that maps to a specific primary key.

This class is reusable so you can use it for multiple sets of data (typically one class per database table you wish to map).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

public class CachedRoute<TPrimaryKey> : RouteBase
{
    private readonly string cacheKey;
    private readonly string controller;
    private readonly string action;
    private readonly ICachedRouteDataProvider<TPrimaryKey> dataProvider;
    private readonly IRouteHandler handler;
    private object synclock = new object();

    public CachedRoute(string controller, string action, ICachedRouteDataProvider<TPrimaryKey> dataProvider)
        : this(controller, action, typeof(CachedRoute<TPrimaryKey>).Name + "_GetMap_" + controller + "_" + action, dataProvider, new MvcRouteHandler())
    {
    }

    public CachedRoute(string controller, string action, string cacheKey, ICachedRouteDataProvider<TPrimaryKey> dataProvider, IRouteHandler handler)
    {
        if (string.IsNullOrWhiteSpace(controller))
            throw new ArgumentNullException("controller");
        if (string.IsNullOrWhiteSpace(action))
            throw new ArgumentNullException("action");
        if (string.IsNullOrWhiteSpace(cacheKey))
            throw new ArgumentNullException("cacheKey");
        if (dataProvider == null)
            throw new ArgumentNullException("dataProvider");
        if (handler == null)
            throw new ArgumentNullException("handler");

        this.controller = controller;
        this.action = action;
        this.cacheKey = cacheKey;
        this.dataProvider = dataProvider;
        this.handler = handler;

        // Set Defaults
        CacheTimeoutInSeconds = 900;
    }

    public int CacheTimeoutInSeconds { get; set; }


    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        string requestPath = httpContext.Request.Path;
        if (!string.IsNullOrEmpty(requestPath))
        {
            // Trim the leading and trailing slash
            requestPath = requestPath.Trim('/'); 
        }

        TPrimaryKey id;

        //If this returns false, that means the URI did not match
        if (!this.GetMap(httpContext).TryGetValue(requestPath, out id))
        {
            return null;
        }

        var result = new RouteData(this, new MvcRouteHandler());

        result.Values["controller"] = this.controller;
        result.Values["action"] = this.action;
        result.Values["id"] = id;

        return result;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        TPrimaryKey id;
        object idObj;
        object controller;
        object action;

        if (!values.TryGetValue("id", out idObj))
        {
            return null;
        }

        id = SafeConvert<TPrimaryKey>(idObj);
        values.TryGetValue("controller", out controller);
        values.TryGetValue("action", out action);

        // The logic here should be the inverse of the logic in 
        // GetRouteData(). So, we match the same controller, action, and id.
        // If we had additional route values there, we would take them all 
        // into consideration during this step.
        if (action.Equals(this.action) && controller.Equals(this.controller))
        {
            // The 'OrDefault' case returns the default value of the type you're 
            // iterating over. For value types, it will be a new instance of that type. 
            // Since KeyValuePair<TKey, TValue> is a value type (i.e. a struct), 
            // the 'OrDefault' case will not result in a null-reference exception. 
            // Since TKey here is string, the .Key of that new instance will be null.
            var virtualPath = GetMap(requestContext.HttpContext).FirstOrDefault(x => x.Value.Equals(id)).Key;
            if (!string.IsNullOrEmpty(virtualPath))
            {
                return new VirtualPathData(this, virtualPath);
            }
        }

        return null;
    }

    private IDictionary<string, TPrimaryKey> GetMap(HttpContextBase httpContext)
    {
        IDictionary<string, TPrimaryKey> map;
        var cache = httpContext.Cache;
        map = cache[this.cacheKey] as IDictionary<string, TPrimaryKey>;
        if (map == null)
        {
            lock (synclock)
            {
                map = cache[this.cacheKey] as IDictionary<string, TPrimaryKey>;
                if (map == null)
                {
                    map = this.dataProvider.GetVirtualPathToIdMap(httpContext);
                    cache[this.cacheKey] = map;
                }
            }
        }
        return map;
    }

    private static T SafeConvert<T>(object obj)
    {
        if (typeof(T).Equals(typeof(Guid)))
        {
            if (obj.GetType() == typeof(string))
            {
                return (T)(object)new Guid(obj.ToString());
            }
            return (T)(object)Guid.Empty;
        }
        return (T)Convert.ChangeType(obj, typeof(T));
    }
}
ICachedRouteDataProvider<TPrimaryKey>
public interface ICachedRouteDataProvider<TPrimaryKey>
{
    IDictionary<string, TPrimaryKey> GetVirtualPathToIdMap(HttpContextBase httpContext);
}

Here is an implementation of the above interface to provide categories to the CachedRoute.

public class CategoryCachedRouteDataProvider : ICachedRouteDataProvider<int>
{
    private readonly ICategorySlugBuilder categorySlugBuilder;

    public CategoryCachedRouteDataProvider(ICategorySlugBuilder categorySlugBuilder)
    {
        if (categorySlugBuilder == null)
            throw new ArgumentNullException("categorySlugBuilder");
        this.categorySlugBuilder = categorySlugBuilder;
    }

    public IDictionary<string, int> GetVirtualPathToIdMap(HttpContextBase httpContext)
    {
        var slugs = this.categorySlugBuilder.GetCategorySlugs(httpContext.Items);
        return slugs.ToDictionary(k => k.Slug, e => e.CategoryID);
    }
}

And this is an implementation that provides product URLs (complete with categories, although you could omit that if you don't need it).

public class ProductCachedRouteDataProvider : ICachedRouteDataProvider<int>
{
    private readonly ICategorySlugBuilder categorySlugBuilder;

    public ProductCachedRouteDataProvider(ICategorySlugBuilder categorySlugBuilder)
    {
        if (categorySlugBuilder == null)
            throw new ArgumentNullException("categorySlugBuilder");
        this.categorySlugBuilder = categorySlugBuilder;
    }

    public IDictionary<string, int> GetVirtualPathToIdMap(HttpContextBase httpContext)
    {
        var slugs = this.categorySlugBuilder.GetCategorySlugs(httpContext.Items);
        var result = new Dictionary<string, int>();

        using (var db = new ApplicationDbContext())
        {
            foreach (var product in db.Products)
            {
                int id = product.ProductID;
                string categorySlug = slugs
                    .Where(x => x.CategoryID.Equals(product.CategoryID))
                    .Select(x => x.Slug)
                    .FirstOrDefault();
                string slug = string.IsNullOrEmpty(categorySlug) ?
                    product.UrlSegment :
                    categorySlug + "/" + product.UrlSegment;

                result.Add(slug, id);
            }
        }
        return result;
    }
}

This is the service that converts the category URL segments into URL slugs. It looks up the parent categories from the category database data and appends them to the beginning of the slug.

There is a little extra responsibility added here (which I probably wouldn't do in a production project) that adds request caching because this logic is used by both the CategoryCachedRouteDataProvider and ProductCachedRouteDataProvider. I combined it here for brevity.

public interface ICategorySlugBuilder
{
    IEnumerable<CategorySlug> GetCategorySlugs(IDictionary cache);
}

public class CategorySlugBuilder : ICategorySlugBuilder
{
    public IEnumerable<CategorySlug> GetCategorySlugs(IDictionary requestCache)
    {
        string key = "__CategorySlugs";
        var categorySlugs = requestCache[key];
        if (categorySlugs == null)
        {
            categorySlugs = BuildCategorySlugs();
            requestCache[key] = categorySlugs;
        }
        return (IEnumerable<CategorySlug>)categorySlugs;
    }

    private IEnumerable<CategorySlug> BuildCategorySlugs()
    {
        var categorySegments = GetCategorySegments();
        var result = new List<CategorySlug>();

        foreach (var categorySegment in categorySegments)
        {
            var map = new CategorySlug();
            map.CategoryID = categorySegment.CategoryID;
            map.Slug = this.BuildSlug(categorySegment, categorySegments);

            result.Add(map);
        }

        return result;
    }

    private string BuildSlug(CategoryUrlSegment categorySegment, IEnumerable<CategoryUrlSegment> categorySegments)
    {
        string slug = categorySegment.UrlSegment;
        if (categorySegment.ParentCategoryID.HasValue)
        {
            var segments = new List<string>();
            CategoryUrlSegment currentSegment = categorySegment;

            do
            {
                segments.Insert(0, currentSegment.UrlSegment);

                currentSegment =
                    currentSegment.ParentCategoryID.HasValue ?
                    categorySegments.Where(x => x.CategoryID == currentSegment.ParentCategoryID.Value).FirstOrDefault() :
                    null;

            } while (currentSegment != null);

            slug = string.Join("/", segments);
        }
        return slug;
    }

    private IEnumerable<CategoryUrlSegment> GetCategorySegments()
    {
        using (var db = new ApplicationDbContext())
        {
            return db.Categories.Select(
                c => new CategoryUrlSegment
                {
                    CategoryID = c.CategoryID,
                    ParentCategoryID = c.ParentCategoryID,
                    UrlSegment = c.UrlSegment
                }).ToArray();
        }
    }
}

public class CategorySlug
{
    public int CategoryID { get; set; }
    public string Slug { get; set; }
}

public class CategoryUrlSegment
{
    public int CategoryID { get; set; }
    public int? ParentCategoryID { get; set; }
    public string UrlSegment { get; set; }
}
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add("Categories", new CachedRoute<int>(
            controller: "Category", 
            action: "Index", 
            dataProvider: new CategoryCachedRouteDataProvider(new CategorySlugBuilder())));

        routes.Add("Products", new CachedRoute<int>(
            controller: "Product",
            action: "Index",
            dataProvider: new ProductCachedRouteDataProvider(new CategorySlugBuilder())));

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Now, if you use the following code in a controller action or view:

var product1 = Url.Action("Index", "Product", new { id = 1 });
product1
/category-1/category-2/category-3/product-1

And if you enter this URL into the browser, it will call the ProductController.Index action and pass it id 1. When the view returns, the breadcrumb is

Home >  > 2 > 3 > Prod1

You could still improve things, such as adding cache busting for the route URLs, and adding paging to the categories (although these days most sites go with infinite scroll rather than paging), but this should give you a good starting point.

Sorry, I have just seen your answer. It is amazing! I have many things to read and learn before make it in my project!

I don't understand why all articles about dynamicNodeprovider proposes to foreach ALL products from DB to create breadcrumbs. I have more than 5k products and this requires about 1 minute build list of nodes. Performance of my website has gone down after implementation this way.. Is there another way to create dynamyc nodes? For example per request decides who should be a parent for a node?

Dynamic nodes (despite the name) are cached at application startup, so all of them need to be loaded at that point. There is a more scalable option - preservedRouteParameters. But it is also more complicated to use, and nodes that use it only appear in bread crumbs (not on menus or for the XML sitemap endpoint). So basically if you go this route it is up to you to disable the XML sitemap and roll your own based on the same product data. See the demos linked from the post

I read about cache, and i decide to check it. I just put a breakpoint in the ProductDynamicNodeProvider method and I was surprised to see it called again after 3-5 minutes of application's work!

c# - asp net MVC 5 SiteMap - build breadcrumb to another controller - ...

c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5
Rectangle 27 1374

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}
new A() { ... }

Mind that you can also import a static nested class directly, i.e. you could do (at the top of the file): import OuterClass.StaticNestedClass; then reference the class just as OuterClass.

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

So What is the use of private static nested class? I think we can't instantiate it from out side like OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

@Ilya Kogan: I meant that I know we can access parent's class fields static or non-static (if the child class is non-static class) i have utilized their features couple of times, but I was wondering that what kind of memory model they follow? does OOP concepts cover them as a separate concept? if not where they really fit in within OOP. Seems like a friend class to me :)

@martin, I know I am coming to this thread incredibly late but: It is your variable, a, that is a static field of the class, A. That does not mean the anonymous class created by 'new A() { int t() { return 2; } }' is static any more than if I simply assigned any other object to the static field, a, as in: class B { static void main(string s) {A.a = new A()}} (A & B in same package) This doesn't make A a static class. The phrase "static context," in the reference cited in the thread you linked to, is incredibly vague. In fact, this was noted in many of the comments in that thread.

Java inner class and static nested class - Stack Overflow

java inner-classes
Rectangle 27 1368

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}
new A() { ... }

Mind that you can also import a static nested class directly, i.e. you could do (at the top of the file): import OuterClass.StaticNestedClass; then reference the class just as OuterClass.

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

So What is the use of private static nested class? I think we can't instantiate it from out side like OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

@Ilya Kogan: I meant that I know we can access parent's class fields static or non-static (if the child class is non-static class) i have utilized their features couple of times, but I was wondering that what kind of memory model they follow? does OOP concepts cover them as a separate concept? if not where they really fit in within OOP. Seems like a friend class to me :)

@martin, I know I am coming to this thread incredibly late but: It is your variable, a, that is a static field of the class, A. That does not mean the anonymous class created by 'new A() { int t() { return 2; } }' is static any more than if I simply assigned any other object to the static field, a, as in: class B { static void main(string s) {A.a = new A()}} (A & B in same package) This doesn't make A a static class. The phrase "static context," in the reference cited in the thread you linked to, is incredibly vague. In fact, this was noted in many of the comments in that thread.

Java inner class and static nested class - Stack Overflow

java inner-classes
Rectangle 27 1365

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

class A {
  int t() { return 1; }
  static A a =  new A() { int t() { return 2; } };
}
new A() { ... }

Mind that you can also import a static nested class directly, i.e. you could do (at the top of the file): import OuterClass.StaticNestedClass; then reference the class just as OuterClass.

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

So What is the use of private static nested class? I think we can't instantiate it from out side like OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

@Ilya Kogan: I meant that I know we can access parent's class fields static or non-static (if the child class is non-static class) i have utilized their features couple of times, but I was wondering that what kind of memory model they follow? does OOP concepts cover them as a separate concept? if not where they really fit in within OOP. Seems like a friend class to me :)

@martin, I know I am coming to this thread incredibly late but: It is your variable, a, that is a static field of the class, A. That does not mean the anonymous class created by 'new A() { int t() { return 2; } }' is static any more than if I simply assigned any other object to the static field, a, as in: class B { static void main(string s) {A.a = new A()}} (A & B in same package) This doesn't make A a static class. The phrase "static context," in the reference cited in the thread you linked to, is incredibly vague. In fact, this was noted in many of the comments in that thread.

Java inner class and static nested class - Stack Overflow

java inner-classes
Rectangle 27 474

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

In common parlance, the terms "nested" and "inner" are used interchangeably by most programmers, but I'll use the correct term "nested class" which covers both inner and static.

Classes can be nested ad infinitum, e.g. class A can contain class B which contains class C which contains class D, etc. However, more than one level of class nesting is rare, as it is generally bad design.

There are three reasons you might create a nested class:

  • organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won't be used in any other context
  • access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).
  • convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context

four kinds of nested class in Java

  • static class: declared as a static member of another class
  • inner class: declared as an instance member of another class
  • local inner class: declared inside an instance method of another class
  • anonymous inner class: like a local inner class, but written as an expression which returns a one-off object

Let me elaborate in more details.

Static classes are the easiest kind to understand because they have nothing to do with instances of the containing class.

A static class is a class declared as a static member of another class. Just like other static members, such a class is really just a hanger on that uses the containing class as its namespace, e.g. the class Goat declared as a static member of class Rhino in the package pizza is known by the name pizza.Rhino.Goat.

Frankly, static classes are a pretty worthless feature because classes are already divided into namespaces by packages. The only real conceivable reason to create a static class is that such a class has access to its containing class's private static members, but I find this to be a pretty lame justification for the static class feature to exist.

An inner class is a class declared as a non-static member of another class:

package pizza;

public class Rhino {

    public class Goat {
        ...
    }

    private void jerry() {
        Goat g = new Goat();
    }
}

Like with a static class, the inner class is known as qualified by its containing class name, pizza.Rhino.Goat, but inside the containing class, it can be known by its simple name. However, every instance of an inner class is tied to a particular instance of its containing class: above, the Goat created in jerry, is implicitly tied to the Rhino instance this in jerry. Otherwise, we make the associated Rhino instance explicit when we instantiate Goat:

Rhino rhino = new Rhino();
Rhino.Goat goat = rhino.new Goat();

(Notice you refer to the inner type as just Goat in the weird new syntax: Java infers the containing type from the rhino part. And, yes new rhino.Goat() would have made more sense to me too.)

So what does this gain us? Well, the inner class instance has access to the instance members of the containing class instance. These enclosing instance members are referred to inside the inner class via just their simple names, not via this (this in the inner class refers to the inner class instance, not the associated containing class instance):

public class Rhino {

    private String barry;

    public class Goat {
        public void colin() {
            System.out.println(barry);
        }
    }
}

In the inner class, you can refer to this of the containing class as Rhino.this, and you can use this to refer to its members, e.g. Rhino.this.barry.

A local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).

Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)

If a local inner class is declared in an instance method, an instantiation of the inner class is tied to the instance held by the containing method's this at the time of the instance's creation, and so the containing class's instance members are accessible like in an instance inner class. A local inner class is instantiated simply via its name, e.g. local inner class Cat is instantiated as new Cat(), not new this.Cat() as you might expect.

An anonymous inner class is a syntactically convenient way of writing a local inner class. Most commonly, a local inner class is instantiated at most just once each time its containing method is run. It would be nice, then, if we could combine the local inner class definition and its single instantiation into one convenient syntax form, and it would also be nice if we didn't have to think up a name for the class (the fewer unhelpful names your code contains, the better). An anonymous inner class allows both these things:

new *ParentClassName*(*constructorArgs*) {*members*}

This is an expression returning a new instance of an unnamed class which extends ParentClassName. You cannot supply your own constructor; rather, one is implicitly supplied which simply calls the super constructor, so the arguments supplied must fit the super constructor. (If the parent contains multiple constructors, the simplest one is called, simplest as determined by a rather complex set of rules not worth bothering to learn in detail--just pay attention to what NetBeans or Eclipse tell you.)

new *InterfaceName*() {*members*}

Such a declaration creates a new instance of an unnamed class which extends Object and implements InterfaceName. Again, you cannot supply your own constructor; in this case, Java implicitly supplies a no-arg, do-nothing constructor (so there will never be constructor arguments in this case).

Even though you can't give an anonymous inner class a constructor, you can still do any setup you want using an initializer block (a {} block placed outside any method).

Be clear that an anonymous inner class is simply a less flexible way of creating a local inner class with one instance. If you want a local inner class which implements multiple interfaces or which implements interfaces while extending some class other than Object or which specifies its own constructor, you're stuck creating a regular named local inner class.

Great story, thanks. It has one mistake though. You can access the fields of an outer class from an instance inner class by Rhino.this.variableName .

While you can't provide your own constructor for anonymous inner classes, you can use double brace initialisation. c2.com/cgi/wiki?DoubleBraceInitialization

Great explanation, but I disagree with static inner classes being worthless. See rwhansen.blogspot.com/2007/07/ for a great variation of the builder pattern that depends heavily on the use of static inner classes.

I also disagree that static inner class is worthless: if you want an enum in the inner class you'll have to make the inner class static.

Private static nested classes are also quite useful: you want to have them, but you do not want to expose them. Like Entry<T> in a LinkedList<T>, or AsyncTasks inside an Activity (Android), etc...

Java inner class and static nested class - Stack Overflow

java inner-classes
Rectangle 27 469

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

In common parlance, the terms "nested" and "inner" are used interchangeably by most programmers, but I'll use the correct term "nested class" which covers both inner and static.

Classes can be nested ad infinitum, e.g. class A can contain class B which contains class C which contains class D, etc. However, more than one level of class nesting is rare, as it is generally bad design.

There are three reasons you might create a nested class:

  • organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won't be used in any other context
  • access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).
  • convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context

four kinds of nested class in Java

  • static class: declared as a static member of another class
  • inner class: declared as an instance member of another class
  • local inner class: declared inside an instance method of another class
  • anonymous inner class: like a local inner class, but written as an expression which returns a one-off object

Let me elaborate in more details.

Static classes are the easiest kind to understand because they have nothing to do with instances of the containing class.

A static class is a class declared as a static member of another class. Just like other static members, such a class is really just a hanger on that uses the containing class as its namespace, e.g. the class Goat declared as a static member of class Rhino in the package pizza is known by the name pizza.Rhino.Goat.

Frankly, static classes are a pretty worthless feature because classes are already divided into namespaces by packages. The only real conceivable reason to create a static class is that such a class has access to its containing class's private static members, but I find this to be a pretty lame justification for the static class feature to exist.

An inner class is a class declared as a non-static member of another class:

package pizza;

public class Rhino {

    public class Goat {
        ...
    }

    private void jerry() {
        Goat g = new Goat();
    }
}

Like with a static class, the inner class is known as qualified by its containing class name, pizza.Rhino.Goat, but inside the containing class, it can be known by its simple name. However, every instance of an inner class is tied to a particular instance of its containing class: above, the Goat created in jerry, is implicitly tied to the Rhino instance this in jerry. Otherwise, we make the associated Rhino instance explicit when we instantiate Goat:

Rhino rhino = new Rhino();
Rhino.Goat goat = rhino.new Goat();

(Notice you refer to the inner type as just Goat in the weird new syntax: Java infers the containing type from the rhino part. And, yes new rhino.Goat() would have made more sense to me too.)

So what does this gain us? Well, the inner class instance has access to the instance members of the containing class instance. These enclosing instance members are referred to inside the inner class via just their simple names, not via this (this in the inner class refers to the inner class instance, not the associated containing class instance):

public class Rhino {

    private String barry;

    public class Goat {
        public void colin() {
            System.out.println(barry);
        }
    }
}

In the inner class, you can refer to this of the containing class as Rhino.this, and you can use this to refer to its members, e.g. Rhino.this.barry.

A local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).

Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)

If a local inner class is declared in an instance method, an instantiation of the inner class is tied to the instance held by the containing method's this at the time of the instance's creation, and so the containing class's instance members are accessible like in an instance inner class. A local inner class is instantiated simply via its name, e.g. local inner class Cat is instantiated as new Cat(), not new this.Cat() as you might expect.

An anonymous inner class is a syntactically convenient way of writing a local inner class. Most commonly, a local inner class is instantiated at most just once each time its containing method is run. It would be nice, then, if we could combine the local inner class definition and its single instantiation into one convenient syntax form, and it would also be nice if we didn't have to think up a name for the class (the fewer unhelpful names your code contains, the better). An anonymous inner class allows both these things:

new *ParentClassName*(*constructorArgs*) {*members*}

This is an expression returning a new instance of an unnamed class which extends ParentClassName. You cannot supply your own constructor; rather, one is implicitly supplied which simply calls the super constructor, so the arguments supplied must fit the super constructor. (If the parent contains multiple constructors, the simplest one is called, simplest as determined by a rather complex set of rules not worth bothering to learn in detail--just pay attention to what NetBeans or Eclipse tell you.)

new *InterfaceName*() {*members*}

Such a declaration creates a new instance of an unnamed class which extends Object and implements InterfaceName. Again, you cannot supply your own constructor; in this case, Java implicitly supplies a no-arg, do-nothing constructor (so there will never be constructor arguments in this case).

Even though you can't give an anonymous inner class a constructor, you can still do any setup you want using an initializer block (a {} block placed outside any method).

Be clear that an anonymous inner class is simply a less flexible way of creating a local inner class with one instance. If you want a local inner class which implements multiple interfaces or which implements interfaces while extending some class other than Object or which specifies its own constructor, you're stuck creating a regular named local inner class.

Great story, thanks. It has one mistake though. You can access the fields of an outer class from an instance inner class by Rhino.this.variableName .

While you can't provide your own constructor for anonymous inner classes, you can use double brace initialisation. c2.com/cgi/wiki?DoubleBraceInitialization

Great explanation, but I disagree with static inner classes being worthless. See rwhansen.blogspot.com/2007/07/ for a great variation of the builder pattern that depends heavily on the use of static inner classes.

I also disagree that static inner class is worthless: if you want an enum in the inner class you'll have to make the inner class static.

Private static nested classes are also quite useful: you want to have them, but you do not want to expose them. Like Entry<T> in a LinkedList<T>, or AsyncTasks inside an Activity (Android), etc...

Java inner class and static nested class - Stack Overflow

java inner-classes
Rectangle 27 468

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

In common parlance, the terms "nested" and "inner" are used interchangeably by most programmers, but I'll use the correct term "nested class" which covers both inner and static.

Classes can be nested ad infinitum, e.g. class A can contain class B which contains class C which contains class D, etc. However, more than one level of class nesting is rare, as it is generally bad design.

There are three reasons you might create a nested class:

  • organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won't be used in any other context
  • access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).
  • convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context

four kinds of nested class in Java

  • static class: declared as a static member of another class
  • inner class: declared as an instance member of another class
  • local inner class: declared inside an instance method of another class
  • anonymous inner class: like a local inner class, but written as an expression which returns a one-off object

Let me elaborate in more details.

Static classes are the easiest kind to understand because they have nothing to do with instances of the containing class.

A static class is a class declared as a static member of another class. Just like other static members, such a class is really just a hanger on that uses the containing class as its namespace, e.g. the class Goat declared as a static member of class Rhino in the package pizza is known by the name pizza.Rhino.Goat.

Frankly, static classes are a pretty worthless feature because classes are already divided into namespaces by packages. The only real conceivable reason to create a static class is that such a class has access to its containing class's private static members, but I find this to be a pretty lame justification for the static class feature to exist.

An inner class is a class declared as a non-static member of another class:

package pizza;

public class Rhino {

    public class Goat {
        ...
    }

    private void jerry() {
        Goat g = new Goat();
    }
}

Like with a static class, the inner class is known as qualified by its containing class name, pizza.Rhino.Goat, but inside the containing class, it can be known by its simple name. However, every instance of an inner class is tied to a particular instance of its containing class: above, the Goat created in jerry, is implicitly tied to the Rhino instance this in jerry. Otherwise, we make the associated Rhino instance explicit when we instantiate Goat:

Rhino rhino = new Rhino();
Rhino.Goat goat = rhino.new Goat();

(Notice you refer to the inner type as just Goat in the weird new syntax: Java infers the containing type from the rhino part. And, yes new rhino.Goat() would have made more sense to me too.)

So what does this gain us? Well, the inner class instance has access to the instance members of the containing class instance. These enclosing instance members are referred to inside the inner class via just their simple names, not via this (this in the inner class refers to the inner class instance, not the associated containing class instance):

public class Rhino {

    private String barry;

    public class Goat {
        public void colin() {
            System.out.println(barry);
        }
    }
}

In the inner class, you can refer to this of the containing class as Rhino.this, and you can use this to refer to its members, e.g. Rhino.this.barry.

A local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).

Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)

If a local inner class is declared in an instance method, an instantiation of the inner class is tied to the instance held by the containing method's this at the time of the instance's creation, and so the containing class's instance members are accessible like in an instance inner class. A local inner class is instantiated simply via its name, e.g. local inner class Cat is instantiated as new Cat(), not new this.Cat() as you might expect.

An anonymous inner class is a syntactically convenient way of writing a local inner class. Most commonly, a local inner class is instantiated at most just once each time its containing method is run. It would be nice, then, if we could combine the local inner class definition and its single instantiation into one convenient syntax form, and it would also be nice if we didn't have to think up a name for the class (the fewer unhelpful names your code contains, the better). An anonymous inner class allows both these things:

new *ParentClassName*(*constructorArgs*) {*members*}

This is an expression returning a new instance of an unnamed class which extends ParentClassName. You cannot supply your own constructor; rather, one is implicitly supplied which simply calls the super constructor, so the arguments supplied must fit the super constructor. (If the parent contains multiple constructors, the simplest one is called, simplest as determined by a rather complex set of rules not worth bothering to learn in detail--just pay attention to what NetBeans or Eclipse tell you.)

new *InterfaceName*() {*members*}

Such a declaration creates a new instance of an unnamed class which extends Object and implements InterfaceName. Again, you cannot supply your own constructor; in this case, Java implicitly supplies a no-arg, do-nothing constructor (so there will never be constructor arguments in this case).

Even though you can't give an anonymous inner class a constructor, you can still do any setup you want using an initializer block (a {} block placed outside any method).

Be clear that an anonymous inner class is simply a less flexible way of creating a local inner class with one instance. If you want a local inner class which implements multiple interfaces or which implements interfaces while extending some class other than Object or which specifies its own constructor, you're stuck creating a regular named local inner class.

Great story, thanks. It has one mistake though. You can access the fields of an outer class from an instance inner class by Rhino.this.variableName .

While you can't provide your own constructor for anonymous inner classes, you can use double brace initialisation. c2.com/cgi/wiki?DoubleBraceInitialization

Great explanation, but I disagree with static inner classes being worthless. See rwhansen.blogspot.com/2007/07/ for a great variation of the builder pattern that depends heavily on the use of static inner classes.

I also disagree that static inner class is worthless: if you want an enum in the inner class you'll have to make the inner class static.

Private static nested classes are also quite useful: you want to have them, but you do not want to expose them. Like Entry<T> in a LinkedList<T>, or AsyncTasks inside an Activity (Android), etc...

Java inner class and static nested class - Stack Overflow

java inner-classes
Rectangle 27 2

So you're retrieving all the categories correctly, but they aren't displaying correctly. Your problem is that you're looping through all the categories and you aren't correctly outputting the relevant sub categories to the parents. I don't know what your data structure is like, but you must have a foreign key type field somewhere that you can check.

Here's an example of how it should work:

<?php foreach ($categories as $cat) : ?>
    <tr>
       <td><?php echo $cat->name ?></td>
       <td><?php echo $cat->description ?></td>
    </tr>
    <?php foreach($sub_categories as $sub_category) : ?>
        <?php 
        // if this sub_category doesn't belong to the current parent, skip it
        if($sub_category['parent_id'] != $cat['category_id'])
            continue; 
        ?>
        <tr>
            <td><?php echo $sub_category->name ?></td>
            <td><?php echo $sub_category->description ?></td>
        </tr>
    <?php endforeach; ?>
<?php endforeach; ?>

Of course, the better way to do this would be to obtain your data in the correct structure to begin with, e.g. nested array Parent => array(parent_data, Children => array(children_data)).

php - Nested sub category right under parent category in codeigniter -...

php codeigniter
Rectangle 27 2

Nested sub-categories appear as nested directories in the URI

That didn't work. The individual posts work fine with both the category and sub-category in the URL (ie: faroutmagazine.co.uk/wp/music/track-of-the-day/) but the sub-category archive still doesn't display: faroutmagazine.co.uk/wp/music/track-of-the-day

This won't work. You just get the same category in the URL twice.

Wordpress - Show parent category AND subcategory name in subcategory a...

wordpress wordpress-plugin wordpress-theming
Rectangle 27 1

The problem, I belive, is that you are binding the categories array to the bars selection, like this:

bars.selectAll("rect").data(categories)

As far as I can see (whithout a running demo) categories is an array with only four values (one for each category).

You have to go one step 'deeper' in your nested data structure.

To draw a set of bars for each category you would need to iterate over categories and bind the values array that contains the actual values to the selection.

categories.each(function (category) {
    var klass = category.name;
    bars.selectAll("rect ." + klass)
        .data(category.values)
        .enter()
        .append("rect")
        .attr("class", klass)
        .attr("width", barWidth)
        .attr("x", function (d, i) { /* omitted */})
        .attr("y", function (d) { return yScale(d.rate); })
        .attr("height", function (d) { return h - yScale(d.rate); });
  });

Instead of the above code, think about drawing the bars just like you do with the lines. Like this:

var bars = svg.selectAll(".barGroup")
    .data(categories)
    .enter()
    .append("g")
    .attr("class", function (d) { return lineClass(d.name) + "Bar barGroup"; })
    .attr("transform", function (d, i) {
        var x = i > 1 ? xScale.rangeBand() / 2 : 0;
        return "translate(" + x + ",0)";
    })
    .selectAll('rect')
    .data(function (d) { return d.values; })
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("width", barWidth)
    .attr("x", function (d, i) { return xScale(d.date); })
    .attr("y", function (d, i) { return yScale(d.rate); })
    .attr("height", function (d) { return h - yScale(d.rate); });

Yes, Doktorn, that is exactly what I want to do access one step 'deeper' into the structure. This solution is probably correct. Unfortunately, this project is a bit old and I found a workaround for it, so I have to do some reconstruction of where I was at in December to test it. I'm unable to do so now, but will get stuck into it tomorrow (Australian time).

@Dotkom I changed your categories.each to categories.forEach to get around an error but otherwise ran this as is. It's appending all 36 rectangles into each of the rangeBands i.e. there is a bar for each of the 36 datapoints in July's position, another 36 in August's and so on. There's an example of it here:

javascript - d3 accessing nested data in grouped bar chart - Stack Ove...

javascript csv d3.js nested grouping
Rectangle 27 3

Thinking out loud here, but perhaps it would be helpful to view some attributes (like Red, Yellow and Green) as 'tags' instead of 'categories' and handle them with separate logic. That would let you keep the Nested Set model and avoid unnecessary duplication. Plus, it would allow you to keep your categories simpler.

It's all in how you think about the information. Categories are just another way of representing attributes. I understand your example was just for illustrative purposes, but if you're going to categorize fruit by color, why would you not also categorize meat the same way, i.e., white meat and red meat? Most likely you would not. So my point is it's probably not necessary to categorize fruit by color, either.

Instead, some attributes are better represented in other ways. In fact, in its simplest form, it could be recorded as a column in the 'food' table labeled 'color'. Or, if it's a very common attribute and you find yourself duplicating the value significantly, it could be split off to a separate table named 'color' and mapped to each food item from a third table. Of course, the more abstract approach would be to generalize the table as 'tags' and include each color as an individual tag that can then be mapped to any food item. Then you can map any number of tags (colors) to any number of food items, giving you a true many-to-many relationship and freeing up your category designations to be more generalized as well.

I know there's ongoing debate about whether tags are categories or categories are tags, etc., but this appears to be one instance in which they could be complimentary and create a more abstract and robust system that's easier to manage.

I had the same thought, not sure if I have missed some of the possible consequences but kinda makes sense to think of colors as tags.

database - Hierarchical Data - Nested Set Model: MySql - Stack Overflo...

mysql database database-design relational-database database-schema
Rectangle 27 3

Before you create a hierarchical category model in your database, take a look at this article which explains the problems and the solution (using nested sets).

To summarize, using a simple parent_category_id doesn't scale very well and you'll have a hard time writing performant SQL queries. The answer is to use nested sets which make you visualize your many-to-many category model as sets which are nested inside other sets.

It should be worth pointing out that the "multiple categories" idea is basically how "tagging" works. With the exception that, in "tagging", we allow any product to have many categories. By allowing any product to be in many categories, you allow the customer the full ability to filter their search by starting where they believe they need to start. It could be clicking on "airplanes", then "wood", then "turbojet engine" (or whatever). Or they could start their search with Wood, and get the same result.

This will give you the greatest flexibility, and the customer will enjoy a better UX, yet still allow you to maintain the hierarchy structure. So, while the quoted answer suggests letting categories be M:N to categories, my suggestion is to allow products to have M:N categories instead.

categories will have a natural hierarchy

but

I should also note that this doesn't prevent strict hierarchy either. You could much easily enforce hierarchy in the code where necessary (ex. only showing the categories "cars", "airplanes", and "boats" on your initial page). It just moves the "strctness" to your business logic, which might make it better in the long run.

php - Database Structure Advice Needed - Stack Overflow

php mysql database database-design
Rectangle 27 1

The solution here is to get all the data you need and create an array of categories, each one containing its own sub categories. And use this object in the nested ng-repeats.

ng-repeat="category in documents.categories"

In the outer ng-repeat and:

ng-repeat="service in category.subCategories"

In the Controller I build the category.subCategories in the following way:

documentsFactory
  .getCategories() // Get categories
  .then(function(response) { // Extract them from the response
    return response.data.subCategory;
  })
  .then(getSubcategories) // For every catgory, get its own subcategory
  .then(function(categories) { // Add categories to the $scope
    self.categories = categories;
  });
getSubcategories
function getSubcategories(categories) {
  console.log(categories)
  var retrievSubcategories = categories.map(function(category) { // Create a promise to get the subcategories for every category
    return documentsFactory
      .getServicesByCategory(category.name) // Get the subcategories for the given category
      .then(function(response) {
        category.subCategories = response.data.documents; // Add subgategories to the category
        return category;
      });
  });
  return $q.all(retrievSubcategories) // Return a promise resolve only when all the subcategories for every category are retrieved
}

javascript - Using function with ng-repeat causing infinite digest loo...

javascript angularjs promise angularjs-ng-repeat angular-promise
Rectangle 27 1

If I were you I'd used model ProjectCategoryBeloning, that will be "between" Project and Category: has_many instead of has_many_and_belongs_to. To link Project to Category, I would use nested attributes on the ui in the form of the project. For autocompletion of the categories there is a good jquery.ui: https://jqueryui.com/autocomplete/ that you can use with AJAX.

javascript - Rails select with suggestions and remote data - Stack Ove...

javascript jquery ruby-on-rails ruby-on-rails-4
Rectangle 27 0

No wonder you cannot wrap your head around the problem. There is a formal language theory regarding formal languages. Noam Chomsky described four categories of the languages -- known as Chomsky hierarchy. Regular expressions are capable do describe the easies category of the languages -- the regular languages. However, languages with nested paired structures are outside of regular languages, and they cannot be described/accepted by regular expressions.

One kind of the parsers that are the most easily implemented are the ones based on recursive call of functions that parse elements of the language.

@Cyborgx37: Well, but then the regular expression engine is given a bit different name -- to emphasise it does something more than usual regular expression. Anyway, I did not check heavily, but Python re module does not support the recursive extension.

python - Regex to extract nested patterns - Stack Overflow

python regex python-3.x