nopcommerce中文网

nopcommerce是国外asp.net领域一个高质量的b2c开源项目,基于EntityFramework和MVC开发,QQ群1:75272942(2000人超级群,已满) QQ群2:640322459

导航 - 搜索

教你一招 - nopcommerce如何启用redis缓存?

从nopcommerce3.7开始就支持redis缓存了,但是默认没有启用,启用步骤如下:
1、首先安装redis服务器(如果没有的话),参考网址 http://www.redis.net.cn/tutorial/3503.html
2、然后修改web.config如下:
<RedisCaching Enabled="true" ConnectionString="localhost:6379,allowAdmin=true" />
注意要启用allowAdmin=true,否则后台清理缓存的时候会报错。
3、刷新页面就可以了,在Redis Desktop Manager里面看下缓存数据吧。


分享是一种美。版权所有,转载请注明出处 http://www.nopchina.net/

Autofac怎么依赖注入静态方法

Autofac一般是通过Contrller的构造函数或者属性来注入,但是这有一个共同点就是调用这个类的方法一般都是实例方法,也就是要实例化这个类才能调用它的方法。但是如果它是一个静态方法我们又该怎么办呢?其实也很简单,下面我们就通过一个写日志的组件来介绍怎么实现ASP.NET MVC5类的静态方法的依赖注入。因为考虑到很多地方都要用到写日志这个方法,而且我们又不想每次调用都需要new一个对象,所以把调用方法封装成一些静态方法。

DependencyRegistrar.cs

  1. using Autofac;
  2. using Autofac.Integration.Mvc;
  3. using Lanhu.Services;
  4. using Lanhu.Services.MetionNowOrder;
  5. using Lanhu.Services.Member;
  6. using System.Web.Mvc;
  7. namespace Lanhu.Admin
  8. {
  9. public class DependencyRegistrar
  10. {
  11. public static void RegisterDependencies()
  12. {
  13. var builder = new ContainerBuilder();
  14. builder.RegisterControllers(typeof(MvcApplication).Assembly);
  15. builder.RegisterType<Log_UserLogonService>().As<ILog_UserLogon>().InstancePerLifetimeScope();
  16. builder.RegisterType<Log_UserOperateService>().As<ILog_UserOperate>().InstancePerLifetimeScope();
  17. //autofac 注册依赖
  18. IContainer container = builder.Build();
  19. DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  20.     }
  21.  }
  22. }

在App_Start事件中调用上面的会依赖注入代码:

  1. using Lanhu.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.Web.Optimization;
  8. using System.Web.Routing;
  9. namespace Lanhu.Admin
  10. {
  11. public class MvcApplication : System.Web.HttpApplication
  12. {
  13. protected void Application_Start()
  14. {
  15. AreaRegistration.RegisterAllAreas();
  16. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  17. RouteConfig.RegisterRoutes(RouteTable.Routes);
  18. BundleConfig.RegisterBundles(BundleTable.Bundles);
  19. DependencyRegistrar.RegisterDependencies();
  20. }
  21. }
  22. }

LogFacade.cs:

  1. using Lanhu.Model;
  2. using Lanhu.Services;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using System.Web.Mvc;
  10. namespace Lanhu.Admin.Infrastructure
  11. {
  12. public class LogFacade
  13. {
  14. public static bool AddLogonLog(MLog_UserLogon model)
  15. {
  16. var service = DependencyResolver.Current.GetService<ILog_UserLogon>();
  17. return service.Insert(model);
  18. }
  19. public static bool AddOperateLog(string info,bool isError=false)
  20. {
  21. var service = DependencyResolver.Current.GetService<ILog_UserOperate>();
  22. if (isError)
  23. model.ErrorMsg = info;
  24. else
  25. model.Msg = info;
  26. return service.Insert(model);
  27. }
  28. public static bool AddOperateLog(MLog_UserOperate model)
  29. {
  30. var service = DependencyResolver.Current.GetService<ILog_UserOperate>();
  31. return service.Insert(model);
  32. }
  33. }
  34. }

上面封装了三个静态方法,在方法里面通过DependencyResolver.Current.GetService从Ioc容器中获取相应类型的依赖对象。这个LogFacade使用外观模式,让调用显得很简单。

教你一招 - 如何在nopCommerce里面使用 Entity Framework (EF) Code-First Migrations(英)

I've seen a lot of nopCommerce forums users asking how they can use Entity Framework (EF) Code-First Migrations to customize nopCommerce, add new fields and entites to the core. I actually use a lot of EF Migrations myself when doing nopCommerce customization projects, and I must say it helps a lot in the development.

Today, I'll share with you how you can do that in nopCommerce project! I'll be using nopCommerce 3.20 as an example, but you can easily apply the concept to other vesions!

Setting Up EF Migrations in nopCommerce Solution

The first thing you want to do is to enable migrations in your nopCommerce solution. So fire up nopCommerce in Visual Studio, look at Nop.Web project, and open Web.config. You need to add a connection string to your development database. Note that adding the connection string in Web.config doesn't affect how nopCommerce works, since nopCommerce doesn't look for connection string in Web.config.

EF Migrations in nopCommerce - Setup Web.config

Then, open NopObjectContext.cs in Nop.Data. Add a new constructor that points to the name of the connection string that you've just added in previous step. NOTE: replace Pro-nopCommerce with the name of your connection string.

EF Migrations in nopCommerce - Setup NopObjectContext.cs

The next step is to actually enable migrations in the project. If you have not already done so, bring up Package Manager Console. In the "Default Project" drop-down list, select Nop.Data as the project. Please also make sure Nop.Web is selected as the StartUp Project. Now, enter the command "enable-migrations" in Package Manager Console, and hit Enter! Visual Studio will generate a file named "Configurations.cs"; you can safely ignore it, but you need to keep it.

EF Migrations in nopCommerce - Enable migrations

The last step in EF Migrations setup is done by entering the command "add-migration InitialMigration -IgnoreChanges" in Package Manager Console. "InitialMigration" (highligted yellow) is the name you want to give the the current migration, and the "IgnoreChanges" handle is to tell EF Migrations that you want to leave out the current database as-is: that means you want EF to ignore all the existing tables so that no script is generated for the existing tables.

EF Migrations in nopCommerce - Initial Migration

As a result, you'll see a new .cs file generated by Visual Studio that correspond to the migration - InitialMigration - you've just added. If you look at the file, it essentially is a blank file, due to the fact that we used the -IgnoreChanges handle in previous step.

To actually save this migration over to the database, run the command "update-database" in Package Manager Console. Your database is now ready for actual EF Migration tasks!

EF Migrations in nopCommerce - Update Database

Adding a Migration and Updating the Database

Now, suppose we want to link up Blog and Products, where a Product can have multiple BlogPost that talk about the Product itself. We'll need a one-to-many relationship between Product and BlogPost.

In essence, what we need is a new ProductId field in BlogPost, and a ICollection<BlogPost> property in Product. The following screenshot sums up the update we should add to both Product.cs and BlogPost.cs (in Nop.Core project).

EF Migrations in nopCommerce - BlogPost.cs

EF Migrations in nopCommerce - Product.cs

Now you have the properties ready on your domain model, you also need to setup the configuration and tell Entity Framework how you want to format the parameter, for example the relationship, and whether a field is optional/required. Open BlogPostMap.cs in Nop.Data, and enter the following lines, where we tell EF to that Product (or ProductId) is an optional property (meaning it can have NULL as value), and a Product can have many BlogPost, and to use ProductId as the foreign key between BlogPost andProduct.

EF Migrations in nopCommerce - BlogPostMap

We now have enough information to instruct Entity Framework to generate the migration, so again, bring up Package Manager Console, and enter the command "add-migration AddProductToBlogPost".

EF Migrations in nopCommerce - Add Product To Blog Post

This command causes Visual Studio to generate a .cs file that looks like the following:

EF Migrations in nopCommerce - Generated Migration CS file

To actually generate the SQL script and update the database, run again the command "update-database" in Package Manager Console. Now, to verify that the database is updated correctly, open up BlogPost table in the database, and check that the new field, foreign key and etc are indeed added.

EF Migrations in nopCommerce - Verifying Database

Conclusion

Entity Framework Code-first Migration can be a very handy tool if you customize nopCommerce a lot. Like this you don't need to touch the database when you want to add new fields, tables and etc to the database. Everything can be done from the code!

Learn up the technique, and have fun coding!

翻译自:http://www.pronopcommerce.com/using-entity-framework-ef-code-first-migrations-in-nopcommerce-for-fast-customizations

nopcommerce 添加新表流程

如果要在数据库中添加一个新的数据表,需要按照下面的步骤来完成.
一、数据库中添加数据表,比如nop_demo
二、在domain下添加nop_demo.cs
需要在目录Libraries\Nop.Core\Domain\下某个目录下添加相应的类,我在Catalog下添加nop_demo.cs;
三、在Mapping下添加map类
需要在目录Libraries\Nop.Data\Mapping\下某个目录下添加相应的类,我在Catalog下添加
nop_demoMap.cs;
四、添加IService.cs\Service.cs
需要在目录Libraries\Nop.Services\下某个目录下添加相应的类,我在Catalog下添加I
nop_demoService.cs和nop_demoService.cs 。
五、在DependencyRegistrar.cs中注册相应类型

需要在文件Presentation\Nop.Web\Infrastructure\DependencyRegistrar.cs中添加builder.RegisterType<nop_demoService>().As<Inop_demoService>().InstancePerHttpRequest();

六、添加相应model文件
需要在路径Presentation\Nop.Admin\Models\Catalog\下添加Nop_demoModel.cs

七、添加相应html文件
需要在路径Presentation\Nop.Admin\Views\Catalog\下添加Nop_demo.cshtml
八、添加domain与model的映射
 需要在文件Presentation\Nop.Admin\Infrastructure\AutoMapperStartupTask.cs 中添加相应的映射
Mapper.CreateMap<Nop_demo , Nop_demoModel>();
Mapper.CreateMap<Nop_demoModel, Nop_demo>();

版权声明:本文为博主原创文章,未经博主允许不得转载。

教你一招 - Misc类型插件的妙用(附带插件源码)

熟悉nopcommerce插件的朋友应该知道里面有一种Misc类型的插件,比如Nop.Plugin.Misc.WebServices和Nop.Plugin.Misc.FacebookShop,继承自接口IMiscPlugin,主要用来完成其他插件不能完成的工作,今天无意中发现这种插件还有个妙用,就是可以替换现有的页面,看来nopcommerce真的很博大。

例如我们进入后台促销管理 - 折扣管理,你会看到这个页面:



这个功能做的不太友好,没有搜索功能,如果数据比较多的话找起来会很吃力,怎么办?一般情况下我们会想到直接修改代码来增加搜索功能,但是这样会破坏nopcommerce的源程序,做nopcommerce二次开发的前提是尽可能的不修改它的架构,而是用插件和模板来实现自己的需求,这样方便以后升级。

然后我们会想到做个页面来替换这个页面从而达到我们的目的,这时候就会用到Misc类型的插件了,实际上我们就是在这个插件里面做了一个带搜索的折扣管理的页面,然后重要的是修改RouteProvider.cs里面的路由,如下:


这段代码的意思很明显就是移除默认的路由然后添加新的路由从而指向我们添加的这个页面,插件完成后后台安装再进入折扣管理页面你会看到如图所示的页面:


好了,其实还有很多的用途,盆友们自己研究吧!

源码下载:Nop.Plugin.Misc.DiscountAdminHelper.zip (170.9KB)

分享是一种美。版权所有,转载请注明出处 http://www.nopchina.net/

nopcommerce中tinymce编辑器的汉化及上传图片功能

nopcommerce后台编辑器使用了tinymce,默认不支持上传本地图片功能,这里简单说一下如何汉化和支持本地上传图片功能。

1. 如何汉化
首先在官网下载汉化包:tinymce_languages.zip (3.1KB)
解压后放到目录\Presentation\Nop.Web\Content\tinymce\langs,然后找到\Presentation\Nop.Web\Administration\Views\Shared\EditorTemplates\RichEditor.cshtml,这个view就是初始化tinymce的地方,在tinymce.init里面添加配置信息language: 'zh_CN',然后保存刷新页面就看到中文了。



2. 如何支持本地图片上传
找到文件\Presentation\Nop.Web\Administration\Views\Shared\EditorTemplates\RichEditor.cshtml,把其中的canUploadPictures = false;改为canUploadPictures = true; 保存刷新页面即可。



需要说明的是这个上传功能不够强大,如果需要强大的图片和文件管理功能可能需要在官网购买付费插件了,更多信息请查看:http://www.tinymce.com/

如何在nopcommerce3.3注册页面添加密码强度检查仪?

我刚刚完成了nopCommerce注册页面的密码强度检查仪,因为我觉得在电子商务交易平台,安全问题是非常重要的。在注册页面有必要添加一个密码强度检测仪,以便通知用户他们的密码是否足够强大。今天,大多数网站都使用这个密码强度计来检查密码的强度。

为什么一个密码强度计如此重要?
- 拥有一个强密码来保护我们的,因为我们每天都在网上共享个人信息
- 拥有一个强密码来保护我们,如信用卡信息,社会保障,银行帐号,密码#S等敏感信息

如何建立一个强大的密码?
- 一个强大的密码至少有8个字符
- 一个强大的密码应该有特殊字符
- 一个强大的密码应该有字母和数字
- 一个强大的密码应该有小写字母和大写字母

提示:
- 请在至少2个月更改一次密码的做法。
- 避免使用正确的拼写。例如:你应该使用“ef4t”代替单词“effort”。

现在,是时候看代码了:

1) 在nopCommerce代码,注册页面在以下位置:
根目录\Views\Customer\ Register.cshtml   <-- 打开这个文件

2) 在代码中找到这里:
<div class="form-fields">
                    <div class="inputs">
                        @Html.LabelFor(model => model.Password, new { }, ":")
                        @Html.EditorFor(model => model.Password)
                        @Html.RequiredHint()
                        @Html.ValidationMessageFor(model => model.Password)
                    </div>
                    <div class="inputs">
                        @Html.LabelFor(model => model.ConfirmPassword, new { }, ":")
                        @Html.EditorFor(model => model.ConfirmPassword)
                        @Html.RequiredHint()
                        @Html.ValidationMessageFor(model => model.ConfirmPassword)
                    </div>
                    @if (Model.DisplayCaptcha)
                    {
                        <div class="captcha-box">
                            @Html.Raw(Html.GenerateCaptcha())
                        </div>
                    }
                </div>

3) 在这种情况下,我们需要添加javascript,jQuery和CSS。因此,为了做到这一点,我们将在我们的“Register.cshtml”页面中添加这样的代码:
<script type='text/javascript'>
    $(function () {
        // This applies the Strength checking plug-in to your particular element
        $('#Password').strength({ strengthButtonText: "" });
        // Fixup your Required indicator (inserts it explicitly after your password element)
        $('.required-indicator').insertAfter($("#Password"));
    });
</script>
注: 这里的 $('#Password') 将引用密码输入字段。

4) 我们还需要添加相应的JQuery插件(如果存在jquery插件就不需要添加了):
<!-- Example jQuery -->
<script type="text/javascript" src="http://www.StrivingProgrammers.com/ScriptFiles_Extras/js/jquery.min.js"></script>

<!-- Strength.js -->
<script type="text/javascript" src="http://www.StrivingProgrammers.com/ScriptFiles_Extras/js/strength.js"></script>
注: "strength.js" 这个文件里面定义什么是弱,中,强密码。根据您的要求,如果你愿意你可以修改它。

5) 现在,我们将增加CSS样式:
<style type='text/css'>
    .strength_meter, .strength_meter * {
        display: inline;
    }
</style>
6) 到这里 - 你可以下载这个页面的源代码了Register.cshtml: RegisterPageCode.zip (2.9KB)

P.S. 此代码经过测试,适用于nopCommerce3.30版本

注: 在nopCommerce,您可以通过将定义的最小长度的密码:
Administration > Configuration > Settings > All settings 
找到: "customersettings.passwordminlength" 并且修改它的值

希望对你有所帮助...
翻译自:http://www.strivingprogrammers.com/Blog/post/Lavish-Kumar/29/Steps-to-add-password-strength-meter-in-nopCommerce-3-30-register-page/

nopcommerce里面的@Html.Widget("home_page_top") 是什么?

很多朋友在修改模板的时候看到很多类似@Html.Widget("xxx")的东西,这里简单介绍一下流程:

比如@Html.Widget("home_page_top"),首先要知道Html.Widget是什么,这是Html的一个扩展方法,位于Nop.Web.Framework\HtmlExtensions.cs

public static MvcHtmlString Widget(this HtmlHelper helper, string widgetZone)
 {
       return helper.Action("WidgetsByZone", "Widget", new { widgetZone = widgetZone });
 }


可以看到这里面调用的是action,找到WidgetController下面的WidgetsByZone,这是一个child action(不懂的百度一下),读一下代码,就能了解这个方法就是通过反射获取到实现接口IWidgetPlugin并且GetWidgetZones()包含home_page_top的插件的列表,然后创建一个model传递给试图:

[ChildActionOnly]
        public ActionResult WidgetsByZone(string widgetZone)
        {
            //model
            var model = new List<RenderWidgetModel>();

            var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _storeContext.CurrentStore.Id);
            foreach (var widget in widgets)
            {
                var widgetModel = new RenderWidgetModel();

                string actionName;
                string controllerName;
                RouteValueDictionary routeValues;
                widget.GetDisplayWidgetRoute(widgetZone, out actionName, out controllerName, out routeValues);
                widgetModel.ActionName = actionName;
                widgetModel.ControllerName = controllerName;
                widgetModel.RouteValues = routeValues;

                model.Add(widgetModel);
            }

            return PartialView(model);
        }

 

打开试图Widget\WidgetsByZone.cshtml:

@model List<RenderWidgetModel>
@using Nop.Web.Models.Cms;
@foreach (var widget in Model)
{
    @Html.Action(widget.ActionName, widget.ControllerName, widget.RouteValues)
}


这个试图的目的就是循环输出html,具体输出的内容在插件里面实现的,比如插件Nop.Plugin.Widgets.NivoSlider里面有个NivoSliderPlugin,这类插件必须继承自BasePlugin,和IWidgetPlugin,里面的方法GetDisplayWidgetRoute就是用于返回显示这个插件内容的action的信息,WidgetsNivoSliderController.cs里面的public ActionResult PublicInfo(string widgetZone)就是这个插件具体输出的内容,大体流程就是这样了。

教你一招 - 如何给nopcommerce增加一个类似admin的area

asp.net mvc里面的area是什么,点击这里查看

 如果在nopcommerce里面加入类似admin的area,步骤如下:

1、新建一个mvc空项目MvcApplication1,位置放在\Nop.Web下面,添加一个类MvcApplicationAreaRegistration.cs用于注册area,内容如下:

using System.Web.Mvc;

namespace MvcApplication1
{
    public class MvcApplicationAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "MvcApplication1";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "MvcApplication1_default",
                "MvcApplication1/{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", area = "MvcApplication1", id = "" },
                new[] { "MvcApplication1.Controllers" }
            );
        }
    }
}
2、修改MvcApplication1/Views/_ViewStart.cshtml,内容如下:
@{
    Layout = "~/MvcApplication1/Views/Shared/_Layout.cshtml";
}
如果不修改的话会提示找不到view的。
3、添加一个HomeController和对应的视图,这里不再详细说明。
4、修改MvcApplication1输出路径,改为:..\bin\,要不然是找不到dll的。
5、删除Global.asax文件,删除web.config里面不需要的内容,可参考admin下面的config文件。
6、最后关键一步,修改Nop.Web.Framework\Themes\ThemeableVirtualPathProviderViewEngine.cs的方法GetPath,添加如下内容:
if (!string.IsNullOrEmpty(areaName) && areaName.Equals("mvcApplication1", StringComparison.InvariantCultureIgnoreCase))
            {
                //admin area does not support mobile devices
                if (mobile)
                {
                    searchedLocations = new string[0];
                    return string.Empty;
                }
                var newLocations = areaLocations.ToList();
                newLocations.Insert(0, "~/MvcApplication1//Views/{1}/{0}.cshtml");
                newLocations.Insert(0, "~/MvcApplication1//Views/{1}/{0}.vbhtml");
                newLocations.Insert(0, "~/MvcApplication1//Views/Shared/{0}.cshtml");
                newLocations.Insert(0, "~/MvcApplication1//Views/Shared/{0}.vbhtml");
                areaLocations = newLocations.ToArray();
            }
重新编译测试一下吧,地址http://localhost:2619/MvcApplication1/Home。

 

 

 

 

教你一招 - 如何给nopcommerce做一套自己的主题

nopcommerce拥有一套不错的模板机制,可以让你快速的做一套属于自己的主题。\Presentation\Nop.Web下面有个Themes文件夹,这里面就是放主题的地方,每个主题对应一个文件夹,每个主题文件夹下面都有一个theme.config文件,这个文件定义了该主题的一些基本信息。Content文件夹放的样式、图片、脚本等资源文件,Views文件夹放的是试图,nopcommerce会默认先读取这个里面的view,如果找不到就去根目录下面的Views里面找,我的作法是直接把根目录下面的Views文件夹复制过来,需要哪个就修改哪个,然后就是修改样式了,nopcommerce有一列、两列、三列显示,你可以参考一些国内的商城系统(注:你可以使用google浏览器或者火狐浏览器能很方便的看到每一块的具体样式,能很快的抄过来。。。),这里就不多说了。

这里分享了几个简单的主题:查看