Category Archives: BundleConfig

[RESOLVED] Preventing Rendering jQuery source file in ASP.NET 4.5

Dear All,

I have a c# web forms project which I have attached the jquery source to the head tag of the master page without using Boundls. Since I have done it before, when I use validators, the application automatically attached another jquery file which is unavailable.

I have commented "BundleConfig.RegisterBundles(BundleTable.Bundles);" in application start but it does not affect.

Any idea how to do it?

Thanks

[RESOLVED] Delete Site.css in bundle visual studio 2012

Hello everyone, I just started using visual studio 2012 and I have a problem that is driving me crazy. I went to File > New> Web site and I created ASP.Net Web Form site. Visual Studio created many files for me. I don't like the default look and feel, so I want to use my own stylesheet. The problem is when I deleted Site.css, it threw me an error saying Site.css could not found. I believe Visual Studio created the bundle somewhere in my web application but no matter how many times I searched, I could not find any reference in my web application referencing Site.css at all. This is the bundle reference on my master page.

<webopt:BundleReference runat="server" Path="~/Content/css" />

Thanks. 

You should better use ASP.NET Empty Web Site. This template creates an ASP.NET website that includes a Web.config file but no other files. Use this project template when you do not require the functionality built into the standard.

Now you can do one thing is create a new website and copy it Site.css file and paste in you current project. Modify css and apply new style in site.css .. 

See Bundle.config file in your project

<styleBundle path="~/Content/css">
    <include path="~/Content/Site.css" />
</styleBundle>

You can point it to your custom css file.

Edited:

I rename site.css to site1.css and also modify bundle.config

<styleBundle path="~/Content/css">
    <include path="~/Content/Site1.css" />
</styleBundle>

and restart IIS express for changes to reflect .. It is working fine. and also i check by deleting it .. There is no error .. 

Just give following in header

<link rel="stylesheet" href="/Content/css?v=">
    Reload the page to get source for: http://localhost:8986/Content/css?v=
</link>

Regards

Hi asplearning,

Just find the file Bundle.config and comment out the line

<styleBundle path="~/Content/css">
    <include path="~/Content/Site.css" />
  </styleBundle>

Hope this helps.

Thanks,

Jatin

Yes I found that file. I deleted the line. Here is what currently have:

<styleBundle path="~/Content/css">
    <include path="~/Content/bootstrap.css" />
    <include path="~/Content/bootstrap-responsive.css" />
    <include path="~/Content/docs.css" />
    <include path="~/Content/prettyPhoto.css" />
  </styleBundle>

I did not reference site.css at all.

Thanks

Hello Nasser Malik, I used empty website before. The problem is I need to configure a lot of places in the webconfig file such as authentication and connection string and so on. Also I need to add library to my web application. How can I edit the bundle? I tried to edit the bundle.config and for some reasons, it just keeps asking for site.css. 

Thanks

Hi asplearning,

I have deleted Site.css  file and tried running the application it doesn't give any error to me. Means you have made some other changes apart from deleting the Site.css file.

Thanks,

Jatin

I will try to upload a video of what's going on. In the meantime, do you know what this error mean?

The element 'styleBundle' has incomplete content. List of possible elements expected: 'include'.

Thanks

Hi asplearning,

Do one thing just open New Website and just delete the Site.css file and do not change anything else. This should be working fine for you.

Thanks,

Jatin

Please check this video, did I do anything wrong?

http://screencast.com/t/juqTDtfhr

thanks

Hello Jatin, I did just that. Please check the video clip.

Thanks.

Hi asplearning,

Do one thing instead of Right Clicking and View in Browser.

Just Click on

 

and try running. Because I tried both ways and it is running.

Thanks,

Jatin

Hello Jatin, this bundle thing is driving me crazy. I have a question. Please take a look at the code below:

In Bundle.Config

<?xml version="1.0" encoding="utf-8" ?>
<bundles version="1.0">
  <styleBundle path="~/Content/css">
   
    <include path="~/assets/css/style.css" />
  </styleBundle>
  <styleBundle path="~/assets/css">
    <include path="~/assets/css/style.css" />
  </styleBundle>
  <styleBundle path="~/Content/themes/base/css">
    <include path="~/Content/themes/base/jquery.ui.core.css" />
    <include path="~/Content/themes/base/jquery.ui.resizable.css" />
    <include path="~/Content/themes/base/jquery.ui.selectable.css" />
    <include path="~/Content/themes/base/jquery.ui.accordion.css" />
    <include path="~/Content/themes/base/jquery.ui.autocomplete.css" />
    <include path="~/Content/themes/base/jquery.ui.button.css" />
    <include path="~/Content/themes/base/jquery.ui.dialog.css" />
    <include path="~/Content/themes/base/jquery.ui.slider.css" />
    <include path="~/Content/themes/base/jquery.ui.tabs.css" />
    <include path="~/Content/themes/base/jquery.ui.datepicker.css" />
    <include path="~/Content/themes/base/jquery.ui.progressbar.css" />
    <include path="~/Content/themes/base/jquery.ui.theme.css" />
  </styleBundle>
</bundles>

On my master page, this is how the bundle is referred:

<webopt:BundleReference runat="server" Path="~/Content/css" />
    <webopt:BundleReference runat="server" Path="~/assets/css" /> 

The problem is when I placed the style.css file in here:

 <styleBundle path="~/assets/css">
    <include path="~/assets/css/style.css" />
  </styleBundle>

the style sheet doesn't load. It said the file can't be found. When I place the style.css file in here:

 <styleBundle path="~/Content/css">   
    <include path="~/assets/css/style.css" />
  </styleBundle>

The css file is downloaded to the client just fine. I wonder what is causing this? It seems that "~/Content/css" is defined somewhere in my web application. Where is it located?

Thanks


Hi asplearning,

Have you created the folder named "assets" and then put the file in that folder.

Try this way.

Thanks,

Jatin

yes, the file is there. I am sure about that.

Thanks

Based on your path, I'm going to assume that you created an actual path called "Assets" that contains another folder called "CSS" and within that folder you have your Style.css file as seen below : 

The way that bundles actually function is they basically allow you to create a "virtual" folder of sorts, which is referenced by a specific path such as "~/Content/CSS" or "~/Assets/CSS" and you can include multiple files under one of these paths that will function as a "bundle", essentially storing all of the "included" files within a single accessible reference.

So, if your file structure matches the one demonstrated above, you would just need to revise your bundles.config to reference the appropriate file as seen below : 

<?xml version="1.0" encoding="utf-8" ?>
<bundles version="1.0">
  <styleBundle path="~/Assets/CSS">
    <include path="~/Assets/CSS/Style.css"></include>
  </styleBundle>
  <styleBundle path="~/Content/css">
    <include path="~/Content/Site.css" />
  </styleBundle>
  <styleBundle path="~/Content/themes/base/css">
    <include path="~/Content/themes/base/jquery.ui.core.css" />
    <include path="~/Content/themes/base/jquery.ui.resizable.css" />
    <include path="~/Content/themes/base/jquery.ui.selectable.css" />
    <include path="~/Content/themes/base/jquery.ui.accordion.css" />
    <include path="~/Content/themes/base/jquery.ui.autocomplete.css" />
    <include path="~/Content/themes/base/jquery.ui.button.css" />
    <include path="~/Content/themes/base/jquery.ui.dialog.css" />
    <include path="~/Content/themes/base/jquery.ui.slider.css" />
    <include path="~/Content/themes/base/jquery.ui.tabs.css" />
    <include path="~/Content/themes/base/jquery.ui.datepicker.css" />
    <include path="~/Content/themes/base/jquery.ui.progressbar.css" />
    <include path="~/Content/themes/base/jquery.ui.theme.css" />
  </styleBundle>
</bundles>

and then actually reference the newly created "Assets" bundle within your Master Page : 

<webopt:BundleReference runat="server" Path="~/Content/css" /> 
<webopt:BundleReference runat="server" Path="~/Assets/CSS" /> 

I just created this entire example on my local machine and it loaded the Style.css file just fine. If you feel that caching could possibly be an issue, you might try explicitly clearing the cache within your browser or try performing a hard-refresh using CTRL+F5 or SHIFT+F5.

Hello Rion, yes you are right. I do have the asset folder. Now through inspect elements I can see that the css file is downloaded just fine. Rion, please do me a favour. What if I have this structure in my folder:

http://screencast.com/t/DWjFbYGTvuAu

For some reason, I could not download the bootstrap to the machine and that's why things don't right on my page. 

Here is my bundle.config code:

<styleBundle path="~/assets/bootstrap/css">
    <include path="~/assets/bootstrap/css/bootstrap.min.css" />
  </styleBundle>
  <styleBundle path="~/assets/prettyPhoto/css">
     <include path="~/assets/pretyPhoto/css/prettyPhoto.css" />
  </styleBundle>
  <styleBundle path="~/assets/css">
    <include path="~/assets/css/flexslider.css" />
    <include path="~/assets/css/font-awesome.css" />
    <include path="~/assets/css/style.css" />
  </styleBundle>

Here is code on my master page

 <webopt:BundleReference ID="BundleReference1" runat="server" Path="~/assets/bootstrap/css" />
    <webopt:BundleReference ID="BundleReference2" runat="server" Path="~/assets/prettyPhoto/css" />
    <webopt:BundleReference runat="server" Path="~/assets/css" />

Thanks



If memory serves, I believe there is an issue with the .NET bundling mechanism not recognizing minified files.

Try switching your path to target the non-minified bootstrap.css file instead : 

<styleBundle path="~/assets/bootstrap/css">
    <include path="~/assets/bootstrap/css/bootstrap.css" />
</styleBundle>



Thanks Rion. Yes you are right. Now I change to bootstrap.css and it is working. How about the prettyPhoto.css? It still doesn't download. 

Here is the code:

<styleBundle path="~/bootstrap/css">
    <include path="~/assets/bootstrap/css/bootstrap.css" />
  </styleBundle>
  <styleBundle path="~/prettyPhoto/css">
     <include path="~/assets/pretyPhoto/css/prettyPhoto.css" />
  </styleBundle>

Here is how it is on master page

   <webopt:BundleReference ID="BundleReference1" runat="server" Path="~/bootstrap/css" />
    <webopt:BundleReference ID="BundleReference2" runat="server" Path="~/prettyPhoto/css" />

Bootstrap is working but prettyPhoto css file still doesn't download. Here is the structure of pretty photo

http://screencast.com/t/UfPhkhVIGU

Again thank you very much. 

Sorry my bad. I found it. Typo mistake. Pretty with two tt. Rion, since you fixed the problem with min.css, I have another question. So the bootstrap.min.css can't be used if I want to bundle?

Thanks

I believe that MVC handles bundling and minification on it's own (I would have to double-check) but it should automatically bundle and minify all of the files within a single bundle together when the bundle is created (this will only occur outside of an application running in debug mode).

It should automatically select your minified file I believe if you actually set your application into "Release" mode instead of "Debug" mode as well. You may want to take a look and read through the existing Bundling and Minification tutorial, which should answer some questions on the issue : 

Thank you very much Rion. 

Hello Rion, very sorry to come back and ask for your help again. I want to change my jquery script on the master page. Here is how it looks now:

<%--Framework scripts--%>
            <asp:ScriptReference Name="MsAjaxBundle" />
            <asp:ScriptReference Name="jquery" />
            <asp:ScriptReference Name="jquery.ui.combined" />
            <asp:ScriptReference Name="WebForms.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebForms.js" />
            <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebUIValidation.js" />
            <asp:ScriptReference Name="MenuStandards.js" Assembly="System.Web" Path="~/Scripts/WebForms/MenuStandards.js" />
            <asp:ScriptReference Name="GridView.js" Assembly="System.Web" Path="~/Scripts/WebForms/GridView.js" />
            <asp:ScriptReference Name="DetailsView.js" Assembly="System.Web" Path="~/Scripts/WebForms/DetailsView.js" />
            <asp:ScriptReference Name="TreeView.js" Assembly="System.Web" Path="~/Scripts/WebForms/TreeView.js" />
            <asp:ScriptReference Name="WebParts.js" Assembly="System.Web" Path="~/Scripts/WebForms/WebParts.js" />
            <asp:ScriptReference Name="Focus.js" Assembly="System.Web" Path="~/Scripts/WebForms/Focus.js" />
            <asp:ScriptReference Name="WebFormsBundle" />
            <%--Site scripts--%>

As you can see, the jquery part doesn't specify any path. How can I change that?

Thanks. 

Hi asplearning,

In your site master you will need to reference the Jquery script files located in your script folder within the project solution like so

<script src="/js/jquery-1.7.1.js" type="text/javascript"></script>

the src part of the above will differ depending on where your script files are located so it could be

<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>      

Now when it comes to using Jquery with in your page(s) you would do the following

<script type="text/javascript">

    $(document).ready(function () {
        // Do something here, reference controls etc
    });

</script>

or else the other way is:

you must add this code into Global.asax =>

protected void Application_Start(object sender, EventArgs e)
        {
            ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
            {
                Path = "~/scripts/jquery-2.0.2.min.js",
                DebugPath = "~/scripts/jquery-2.0.2.js",
                CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-2.0.2.min.js",
                CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-2.0.2.js"
            });
        }

then in your master page 

<form id="form1" runat="server" >
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Name="jquery" />
        </Scripts>
    </asp:ScriptManager>

in you content pages =>

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="test.test" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
           // ....
           
        });
    </script>

( if you dont have Global.asax you can add that this way ,right click on your project name -> Add->NewItem->Global Application Class )

(if you dont have script folder ,  you can get JQuery from Managed NuGet Package )

then

then will be create scripts folder in your project

Hope this helps.

Thanks,

Jatin






Hello Jatin, I checked the jquery file downloaded using inspect element in google chrome, I can see that the version downloaded is v1.7.1. What I am trying to understand is where is the reference to this file located in my web application? I tried to search but could not find it any where. Can I change this manually anywhere in my web application?

Thanks

I checked my global.asax, there is no script like the one you suggested. Was the script embedded somwhere? Here is my script on global.asax.

<%@ Application Language="VB" %>
<%@ Import Namespace="System.Web.Optimization" %>

<script runat="server">

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup
        BundleConfig.RegisterBundles(BundleTable.Bundles)
        AuthConfig.RegisterOpenAuth()
    End Sub

    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application shutdown
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs
    End Sub

</script>

Thanks

Hi asplearning,

The default packages that come with Visual Studio 2012 registers the names jquery and jquery.ui.combined with ScriptManager. Script Manager then replaces it with reference to the actual jquery Scripts in the CDN[if you set EnableCDN=true]. If you dont set this it will pick up from the directories you mentioned.

You can find more details here http://blogs.msdn.com/b/pranav_rastogi/archive/2012/09/21/asp-net-4-5-scriptmanager-improvements-in-webforms.aspx

If you do a view source of your webpage, you will see the references to the script.

Hope this helps.

Thanks,

Jatin

Hi asplearning,

There is also a scripts folder in the solution containing:

_references.js
jquery-1.7.1.intellisense.js
jquery-1.7.1.js
jquery-1.7.1.min.js
jquery-ui-1.8.20.js
jquery-ui-1.8.20.min.js
modernizer-2.5.3.js

And look into _references.js file

Hope this helps.

Thanks,

Jatin

I believe that this reference is actually integrated into .NET as mentioned in this article (the one that is referenced within new applications) and it automatically includes jQuery and jQueryUI templates by default : 

If you look within your packages.config file, you'll find the following references which refer to the packages that will have already established these references : 

<package id="AspNet.ScriptManager.jQuery" version="1.8.2" targetFramework="net45" />
<package id="AspNet.ScriptManager.jQuery.UI.Combined" version="1.8.24" targetFramework="net45" />
<package id="Microsoft.AspNet.ScriptManager.MSAjax" version="4.5.6" targetFramework="net45" />
<package id="Microsoft.AspNet.ScriptManager.WebForms" version="4.5.6" targetFramework="net45" />



Hello Rion, thanks. As you mentioned that it is included by default, is there a way I can change it? I do not want the client to download both jquery file. Here is my current structure for the jquery file that I want to use:

http://screencast.com/t/NVBegc4RpXl

And here is the structure by default from VS2012

http://screencast.com/t/vtyjWU4pMo

I want to update the reference and point it to jquery 1.8.2.min.js instead.

Thanks

Jatin, the _reference.js has the following code but they were all commented out.

/// <reference path="jquery-1.7.1.js" />
/// <reference path="jquery-ui-1.8.20.js" />
/// <reference path="modernizr-2.5.3.js" />

Thanks

 

Hi asplearning,

For updating the jQuery:

You can use NuGet

  1. right-click on your project in Solution Explorer
  2. click on "Manage NuGet Packages" in context menu
  3. type "jQuery" in the search box on the top right corner of the dialog box
  4. press Enter key and wait for results
  5. look for "jQuery" in the results, SELECT it and click "Install" button
  6. (after installation, you previous jquery and related files will be replaced with the latest ones)

Alternatively, you can create an Empty project and install the the nuget package(s) through the Package Manager Console. This can include ALL of the libraries that you default to.

PM> Install-Package jQuery

From there, save it as a new template, and whenever you create a new project, simply run the following terminal command before starting work.

PM> Update-Package

more info on Update-Package

Hope this helps.

Thanks,

Jatin


If you want to manually remove these references, you can simply right-click on your Project within the Solution Explorer and select the "Manage NuGet Packages" option and then choose to remove the following package : 

  • AspNet.ScriptManager.jQuery.UI.Combined
  • AspNet.ScriptManager.jQuery

which should look something like this : 


After removing these, you'll want to create another Script Bundle that explicitly targets your other scripts within your BundleConfig.cs file :

//Adding a Script Reference to your File
bundles.Add(new ScriptBundle("~/bundles/jQuery").Include("~/Assets/JS/jquery-1.8.2.js"));

and then simply reference this within your Master Page :

<asp:PlaceHolder runat="server">     
          <%: Scripts.Render("~/bundles/jQuery") %>
          <%: Scripts.Render("~/bundles/modernizr") %>
</asp:PlaceHolder>  

Your reference is in dll AspNet.ScriptManager.jQuery.dll .. Check bin folder. Packages.config files tell you which assembly is installed .. It would be 

<package id="AspNet.ScriptManager.jQuery" version="1.7.1" targetFramework="net45" />

So if you want to update get the new dll by NuGet .. 

http://www.nuget.org/packages/AspNet.ScriptManager.jQuery/

Regards. 

Sorry to be a pain. So in nutshell, there is no easy that I can go and change the reference path right? Like Path="~/example/..."? If so I think Rion and Jatin solution is the best way for me for now. 

Thanks a lot for your reply. 

[RESOLVED] Webform Masterpages and CSSJS file paths

In .net 4.5,  have there been any improvements in masterpages and including CSS/javascript files?  I am talking about when you have a masterpage in the root that includes references to CSS files and Javascript files and when you use the masterpage on a file inside a subfolder and that link is not relative.  I know about the resolveurl method, but was wondering if there are any improvements in the latest release?  What approach do most people use to get around this problem?

In 4.5 framework still the same methodology can be implemented.However, you might be interested in Bundling mechanism. It can be very useful when you have multiple/many css files and javascript file references required in your ASP.NET website.

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time.  Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) This feature makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve the page load  performance.

Here are some links on articles that you may find useful:

I would prefer to easily understand this; is to create a New > Project > Web > ASP.NET Web form application and look at the master page and code in App_Start folder where you will find BundleConfig.cs/.vb

hope it helps./.

Use ResolveUrl to refer the files like : src = '<%= ResolveUrl("~/folder/file.js") %>'

When you use this method to import the stylesheets,  the design gui in VS doesn't show any of the styles anymore since the code isn't being rendered.  This makes it a little weird when developing.

oh, interesting.  I guess that .net handles the CSS references automatically so that the resolveurl isn't necessary. 

The Minification and Bundling is going to work a bit different but will resolve all of the appropriate URLs that it needs and when it comes to explicit references usually the ResolveUrl() approach is going to be the safest to ensure that your items can be accessed properly. You'll need to be careful if you contain any references within your CSS files however, as they are going to be accessed relative to the location of the CSS file itself.

If you ever encounter any issues with it not working properly or if a file is not being loaded correctly, try using the Developer Tools (F12) through your browser and checking for any errors within the Console (this is one of the best methods of resolving issues like these).

[RESOLVED] Seed data problem

why  i can't seed data to be added to the database (The seed function dosn't excute) please help me?

this is the code

1-Global.asax:

namespace AlshamyShop
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Initialize the product database.
            Database.SetInitializer(new ProductDatabaseInitializer());
            //Database.SetInitializer<ProductContext>(new ProductDatabaseInitializer());
        }
    }
}

2-ProductContext is :

namespace AlshamyShop.Models
{
  public class ProductContext : DbContext
  {
    public ProductContext()
      : base("AlshamyShop")
    {
    }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
    //public DbSet<CartItem> ShoppingCartItems { get; set; }
    //public DbSet<Order> Orders { get; set; }
    //public DbSet<OrderDetail> OrderDetails { get; set; }
  }
}

3-ProductDatabaseInitializer is :

namespace AlshamyShop.Models
{
  public class ProductDatabaseInitializer : DropCreateDatabaseIfModelChanges<ProductContext>
  {
    protected override void Seed(ProductContext context)
    {
      GetCategories().ForEach(c => context.Categories.Add(c));
      GetProducts().ForEach(p => context.Products.Add(p));
    }

    private static List<Category> GetCategories()
    {
      var categories = new List<Category> {
                new Category
                {
                    CategoryID = 1,
                    CategoryName = "Cars"
                },
                new Category
                {
                    CategoryID = 2,
                    CategoryName = "Planes"
                },
                new Category
                {
                    CategoryID = 3,
                    CategoryName = "Trucks"
                },
                new Category
                {
                    CategoryID = 4,
                    CategoryName = "Boats"
                },
                new Category
                {
                    CategoryID = 5,
                    CategoryName = "Rockets"
                },
            };

      return categories;
    }

    private static List<Product> GetProducts()
    {
      var products = new List<Product> {
                new Product
                {
                    ProductID = 1,
                    ProductName = "Convertible Car",
                    Description = "This convertible car is fast! The engine is powered by a neutrino based battery (not included)." +
                                  "Power it up and let it go!",
                    ImagePath="carconvert.png",
                    UnitPrice = 22.50,
                    CategoryID = 1
               },
                new Product
                {
                    ProductID = 2,
                    ProductName = "Old-time Car",
                    Description = "There's nothing old about this toy car, except it's looks. Compatible with other old toy cars.",
                    ImagePath="carearly.png",
                    UnitPrice = 15.95,
                     CategoryID = 1
               },
                new Product
                {
                    ProductID = 3,
                    ProductName = "Fast Car",
                    Description = "Yes this car is fast, but it also floats in water.",
                    ImagePath="carfast.png",
                    UnitPrice = 32.99,
                    CategoryID = 1
                },
                new Product
                {
                    ProductID = 4,
                    ProductName = "Super Fast Car",
                    Description = "Use this super fast car to entertain guests. Lights and doors work!",
                    ImagePath="carfaster.png",
                    UnitPrice = 8.95,
                    CategoryID = 1
                },
                new Product
                {
                    ProductID = 5,
                    ProductName = "Old Style Racer",
                    Description = "This old style racer can fly (with user assistance). Gravity controls flight duration." +
                                  "No batteries required.",
                    ImagePath="carracer.png",
                    UnitPrice = 34.95,
                    CategoryID = 1
                },
                new Product
                {
                    ProductID = 6,
                    ProductName = "Ace Plane",
                    Description = "Authentic airplane toy. Features realistic color and details.",
                    ImagePath="planeace.png",
                    UnitPrice = 95.00,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 7,
                    ProductName = "Glider",
                    Description = "This fun glider is made from real balsa wood. Some assembly required.",
                    ImagePath="planeglider.png",
                    UnitPrice = 4.95,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 8,
                    ProductName = "Paper Plane",
                    Description = "This paper plane is like no other paper plane. Some folding required.",
                    ImagePath="planepaper.png",
                    UnitPrice = 2.95,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 9,
                    ProductName = "Propeller Plane",
                    Description = "Rubber band powered plane features two wheels.",
                    ImagePath="planeprop.png",
                    UnitPrice = 32.95,
                    CategoryID = 2
                },
                new Product
                {
                    ProductID = 10,
                    ProductName = "Early Truck",
                    Description = "This toy truck has a real gas powered engine. Requires regular tune ups.",
                    ImagePath="truckearly.png",
                    UnitPrice = 15.00,
                    CategoryID = 3
                },
                new Product
                {
                    ProductID = 11,
                    ProductName = "Fire Truck",
                    Description = "You will have endless fun with this one quarter sized fire truck.",
                    ImagePath="truckfire.png",
                    UnitPrice = 26.00,
                    CategoryID = 3
                },
                new Product
                {
                    ProductID = 12,
                    ProductName = "Big Truck",
                    Description = "This fun toy truck can be used to tow other trucks that are not as big.",
                    ImagePath="truckbig.png",
                    UnitPrice = 29.00,
                    CategoryID = 3
                },
                new Product
                {
                    ProductID = 13,
                    ProductName = "Big Ship",
                    Description = "Is it a boat or a ship. Let this floating vehicle decide by using its " +
                                  "artifically intelligent computer brain!",
                    ImagePath="boatbig.png",
                    UnitPrice = 95.00,
                    CategoryID = 4
                },
                new Product
                {
                    ProductID = 14,
                    ProductName = "Paper Boat",
                    Description = "Floating fun for all! This toy boat can be assembled in seconds. Floats for minutes!" +
                                  "Some folding required.",
                    ImagePath="boatpaper.png",
                    UnitPrice = 4.95,
                    CategoryID = 4
                },
                new Product
                {
                    ProductID = 15,
                    ProductName = "Sail Boat",
                    Description = "Put this fun toy sail boat in the water and let it go!",
                    ImagePath="boatsail.png",
                    UnitPrice = 42.95,
                    CategoryID = 4
                },
                new Product
                {
                    ProductID = 16,
                    ProductName = "Rocket",
                    Description = "This fun rocket will travel up to a height of 200 feet.",
                    ImagePath="rocket.png",
                    UnitPrice = 122.95,
                    CategoryID = 5
                }
            };

      return products;
    }
  }
}

4-web.config is:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-AlshamyShop-20140210065734.mdf;Initial Catalog=aspnet-AlshamyShop-20140210065734;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <!--<add name="AlshamyShop" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\AlshamyShop.mdf;Initial Catalog=aspnet-AlshamyShop-20140210065734;Integrated Security=True"
    providerName="System.Data.SqlClient" />-->
  </connectionStrings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
    <membership>
      <providers>
        <!--
          ASP.NET Membership is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
        <clear />
      </providers>
    </membership>
    <profile>
      <providers>
        <!--
          ASP.NET Membership Profile is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
        <clear />
      </providers>
    </profile>
    <roleManager>
      <!--
            ASP.NET Membership Role is disabled in this template. Please visit the following link http://go.microsoft.com/fwlink/?LinkId=301889 to learn about the ASP.NET Membership support in this template
        -->
      <providers>
        <clear />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

haitham alshamy

(The seed function dosn't excute)

Are you sure this is true?  It looks like your Seed method does not persist the changes to the database.  Try adding:

context.SaveChanges();

But if in fact the Seed method is not executed, then it may be that you are not querying the database.

I add context.savechanges() but it dosn't work when i add breakpoint on function Seed ithis breakpont dosn't trigger

Hi,

So far as I know, the Application_Start()event in Global.asax will execute the database operations you’ll define in the
ProductDatabaseInitializerclass which we’ll create in the next step.So please refer to check if the Application_Start() event has been ran.

For more informaiton, please refer to the links below:

http://www.codeproject.com/Articles/315708/Entity-Framework-Code-First-Data-Initializers

http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-no-magic-walkthrough.aspx

Hope it's useful for you.

Best Regards,

Michelle Ge

the Application_Start() event normaly without any problem but Seed function dosn't ran

As I said the Seed() method will only execute if you query the database and if your model has changed.  It does not execute just because the Application_Start() executes.

[RESOLVED] How to routes.MapPageRoute() to route non-existing path to a working path

I'm in my 2nd day now and I still couldn't figure out how to make this work.  I'm using Web Application having both WebForm and Razor webpages, .NET framework 4.5.1.

In html script like <style type="text/css" rel="stylesheet" href="rCss/global1.css" />, it would sent out https://www.foo.com/rCss/global1.css.   But the physical filepath is ~/Webpages/Css/global1.css .

With the routing I used, routes.MapPageRoute("Css","rCss/{file}","~Webpage/css/{file}"); I still get a 404 not found error in web browser.

So, what did I do wrong?  Thanks...

Hi,

  

fletchsod

I'm in my 2nd day now and I still couldn't figure out how to make this work.  I'm using Web Application having both WebForm and Razor webpages, .NET framework 4.5.1.

In html script like <style type="text/css" rel="stylesheet" href="rCss/global1.css" />, it would sent out https://www.foo.com/rCss/global1.css.   But the physical filepath is ~/Webpages/Css/global1.css .

With the routing I used, routes.MapPageRoute("Css","rCss/{file}","~Webpage/css/{file}"); I still get a 404 not found error in web browser.

Refer to the following example:

        private void RoutingData(RouteCollection routeCollection)
        {
            routeCollection.MapPageRoute("Css", "rCss/global", "~/Webpage/CSS/site.css"); 
        }

Spify the Path correctly.

  protected void Application_Start()
        {
            RoutingData(RouteTable.Routes);//CALL IT AT THE TOP

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

Call the RoutingData at before any other code in Application_Start.

For more reference:

http://forums.asp.net/t/1990476.aspx?How+to+use+MapPageRoute

http://weblogs.asp.net/scottgu/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series

Hope it helps!

Best Regards!