2013年8月5日星期一

ASP.NET MVC 4使用技巧记录3:Twitter.Bootstrap安装和常用HtmlHelper

1. 安装Twitter.Bootstrap(于HTML,CSS,JAVASCRIPT的简洁灵活的流行前端框架及交互组件集)

PM> install-Package Twitter.Bootstrap.Less

PM> install-package dotless

 

2. 传递Pass Data从Controller到View

A. 可以使用public ViewDataDictionary ViewData { get; set; }

譬如:

in Controller:

ViewData["info"] = "Wrong Invitation Code!";

in View:

   @ViewData["info"] 

B. 也可以使用public Object ViewBag { get; }

譬如:

in Controller:

ViewBag.Message = "Wrong Invitation Code!";

in View:

   The message is @ViewBag.Message

C. 当然也可以使用Session

in Controller:

Session["info"] = “Wrong Invitation Code!”;

in View: 

@Session["info"]

 

3. 关于model 在 razor view中

需要在View中置顶声明model type:

@model MyNamespace.Models.MyModel

"model"是小写的m -- 用来指明具体的View要呈现的Model类型。也就是declares the model。

"Model"是大写M --当我们引用一个model对象时。也就是references the instantiation of the model。

 

4. 关于常用的HtmlHelper:

在System.Web.Mvc.Html中

具体参阅:

http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper

BeginForm()

BeginRouteForm() :根据URL路由规矩。

EndForm()

譬如:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {

   @Html.AntiForgeryToken()

   @Html.ValidationSummary(true)

   <fieldset>

       <legend>Log in Form</legend>
10
11        <ol>
12
13            <li>
14
15                @Html.LabelFor(m => m.UserName)
16
17                @Html.TextBoxFor(m => m.UserName)
18
19                @Html.ValidationMessageFor(m => m.UserName)
20
21            </li>
22
23            <li>
24
25                @Html.LabelFor(m => m.Password)
26
27                @Html.PasswordFor(m => m.Password)
28
29                @Html.ValidationMessageFor(m => m.Password)
30
31            </li>
32
33        </ol>
34
35        <input type="submit" value="Log in" />
36
37    </fieldset>
38
39  }
40

 

CheckBox() , CheckBoxFor()

譬如:

@Html.CheckBox( "MyCheckBox" , true , new { id="checkbox" } )

Hidden() , HiddenFor() 某个隐藏输入域,这种类型的输入元素实际上是隐藏的。这个不可见的表单元素的 value 属性保存了一个要提交给 Web 服务器的任意字符串。如果想要提交并非用户直接输入的数据的话,就是用这种类型的元素。

譬如:

@Html.Hidden( "Hidden" , "Hidden Value")
 
Password() , PasswordFor()   

譬如:

@Html.Password ( "Password" , 123456)

RadioButton() , RadioButtonFor()

譬如:

@Html.RadioButton ( "MyRadioButton" , "RadioValue" , true)

或者:

@Html.RadioButtonFor(m =>m.Position, "0", true) Employee

@Html.RadioButtonFor(m =>m.Position, "1", false) Manager

TextBox() , TextBoxFor()

譬如:

@Html.RadioButton ( "MyTextBox" , "TextValue" new { maxlength =100 })

DropDownList() , DropDownListFor()

譬如:

@HtmlDropDownList("List" , new SelectList( new int{1, 2, 3, 4 }))

ListBox() , ListBoxFor()

譬如:

@Html.ListBox ("List" , new SelectList(new string[]{ "apple" , "banana" , "orange" ,"mango"}))

TextArea() , TextAreaFor()

譬如:

@Html.TextArea("Message", new { rows=40, columns=40 })

LabelFor()

譬如:

@Html.LabelFor(m => m.Mobile)

TextBoxFor()

譬如:

@Html.TextBoxFor(m => m.Mobile)

ActionLink():超链接

譬如:

@Html.ActionLink ( "Links Name" , "New" , "Home" )

也就是在控制器Home上执行“New”方法

RouteLink(): 根据Route产生超链接 。

譬如:

@Html.RouteLink( "NewLink" , new { controller="Home" , action="New"} )

Html.partial(),是将视图内容直接生成一个字符串并返回。

譬如:

@Html.Partial("_LoginPartial") 

@Html.Partial("NavigateBarUserControl",Model)

RenderPartial() ,想对于Html.partial()而言,RenderPartial()直接输出至当前 HttpContext,性能较好。

譬如:

@Html.RenderPartial("Path/to/my/partial/view")

ValidationMessage() , ValidationMessageFor()

譬如:

@Html.ValidationMessageFor(m => m.Password)

2013年8月4日星期日

ASP.NET MVC 4使用技巧记录2: 如何进行Migrations和使用Simplemembership

MVC4 Simplemembership可以进行权限管理,很强大,我们也可以自己扩展数据库结构,它使用几个表:
  • 用户信息表UserProfile
  • 角色表webpages_Roles
  • webpages_Membership(用于存储Membership的信息内容)
  • 权限表webpages_Permission
  • 关系表webpages_PermissionsInRoles(用于存储角色的具体权限)
1. 建一个新的C# MVC4 Web Application在VS 2012,使用Internet Application的Project Template
2. 如果使用 Machine\SQLExpress,请确定Connection String in the web.config
在Web.Config中,在其“System.Web” 部分中加入:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
  <providers>
    <clear/>
    <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
  </providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
  <providers>
    <clear/>
10     <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
11   </providers>
12 </membership>
13
4. 在PM> enable-migrations
不要忘记在model中加入我们将要添加了元素譬如这里的Mobile,Company和Position
5. 会发现我们有Configuration.cs在Migrations文件夹中 
设置AutomaticMigrationsEnabled = true;
加入,譬如:
protected override void Seed(TestProject.Models.UsersContext context)
        {
            WebSecurity.InitializeDatabaseConnection(
                "DefaultConnection",
                "UserProfile",
                "UserId",
                "UserName", autoCreateTables: true);

            if (!Roles.RoleExists("Administrator"))
10                 Roles.CreateRole("Administrator");
11
12             if (!WebSecurity.UserExists("alex"))
13                 WebSecurity.CreateUserAndAccount(
14                     "uername",
15                     "password",
16                     new { Email = "username@gmail.com", Mobile = "+176", Company = "Company_A", Position = "0" }
17                     );
18
19             if (!Roles.GetRolesForUser("alex").Contains("Administrator"))
20                 Roles.AddUsersToRoles(new[] { "alex" }, new[] { "Administrator" });
21         }
22
6. 在PM> update-database -verbose
7.  Server Explorer → Data Connections,可以找到Tables,并可以在 SQL 中运行 update query 用于加入columns
8. PM> update-database -verbose
这就是整个migrations的过程。

具体使用请参考:
http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/

2013年7月31日星期三

ASP.NET MVC 4使用技巧记录1

很早就知道ASP.NET MVC但是一直没有机会使用。编过比较多的php程序,用过Yii framework。最近决定使用ASP.NET MVC来完成一个大的实验性项目。这里简单地记录一些我在自学和编程过程中学到的技巧。
1. 新建Project很简单,选择建立ASP.NET MVC就行了。选择Project Template我比较喜欢选择Basic,这样生成的Project的东西比较少,我们可以自己进行添加修改。
2. 新建SQL数据库也很容易,在Solution Explorer中选定App_Data文件夹,右击鼠标,选择Add-->New Item..然后可以选择例如SQL Server Compact 4.0 Local Database,给一个文件名,譬如MainDb.sdf
3. 新建Table,这需要我们先走App_Data文件夹中双击MainDb.sdf,然后会出现Server Explorer窗口,选择Tables,然右击鼠标右键Create就可以添加Table了。
4. 新建ADO.NET Entity Data Model,在Solution Explorer,右击鼠标,Add-->New Item..然后可以添加ADO.NET Entity Data Model,给一个Model名字,会出现一个Choose Model Contents,我们可以选择Generate from database,点击下一步,这时就可以和我们上面建立的MainDb.sdf相连。在接下来的窗口,Choose your Database Objects and Settings选择Tables,点击完成。同意Overwrite,这就完成了。
5. 添加Controller,这很简单,在Solution Explorer中选定Conrtroller文件夹,右击鼠标,选择Add-->New Item..然后添加Controller就OK了。可以选择不同的Template,我比较喜欢使用Empty MVC controller。
6. 添加View,在ASP.NET MVC里非常方便,只需要点击譬如HomeController.cs中的public ActionResult Index(),按鼠标右键点击Add View就行了。这里有一个小技巧,我们可以选择Use a layout or master page,在下拉菜单中可以选择_Layout.cshtml。
7. 新建一个Model,在Solution Explorer中选定Models文件夹,右击鼠标,选择Add-->New Item..,点击右边的Visual C#,然后选择Class,最后给定一个名字就行了,譬如UserModel.cs,这时候我们就可以在这个Model类中添加我们需要的属性。
8. 使用第三方库的方法,在Solution Explorer中选定我们的Project,右击鼠标,选择Manage NuGet Packages,我们就可以添加譬如Json.Net库。

2013年7月25日星期四

7月闲谈

7月份最大的领悟:花钱让专业人士去做他们的工作,不要吝啬而去自己干,虽然请别人来做会多花一些钱,但是其达到的质量和效果比我们自己实现好得多,我们也节约了大量的时间成本,这些浪费掉的时间我们大可以去做更具生产力的事情,也就是我们所擅长的事情,这个道理到现在才真正的体会。这个经验一定要切记,切记!

7月份另一个的领悟:若有可能产品一定要走高端,不要去走低端,中端。试着给用户提供更多的附加价值。其实仔细算一下,做高端的产品时候会极大的提高利润率,其实成本上升的幅度更不没有想象中的高,完全可控和可以承受。

7月份还有一个领悟:我刚刚把我主导开发的软件的70%都外包出去,我发现,其实只要掌握核心,掌控流程,其他都可以外包,这样做会大量的降低工作量,并提供生产效率。而且只要监控得当,产品的质量也会得到保证。

2013的六大目标已经实现了三个。另外三个在接下来的三个月也应该会实现。刚刚定了一个新的目标,希望也能在9月底前实现,还是要努力和靠一些运气。希望得到惊喜吧。

2013年6月30日星期日

JavaCV Installation and Using it in Eclipse

I always use C++ with OpenCV libs for coding the computer vision program, but I just find a nice library called JavaCV (wrapper classes used for openCV). It allows anyone to use OpenCV functions directly in desktop Java. Now I can write computer vision program with Java, great!

The links below is a basic guide to help anyone port their OpenCV code to JavaCV.
http://code.google.com/p/javacv/wiki/ConvertingOpenCV

Here I give a very short intro about how to set up JavaCV and use it.
A.
Download OpenCV-2.4.5.exe and javacv-0.5-bin.zip, from:
http://sourceforge.net/projects/opencvlibrary/files/
http://code.google.com/p/javacv/

B.
Install OpenCV-2.4.5
Extract javacv-0.5-bin.zip

C.
set the environment variables:
the user variables for you, such as:
CLASSPATH → D:\project\opencv\build\x86\vc10\lib;
PATH → D:\project\opencv\build\java\x86;D:\project\opencv\build\x86\vc10\bin

D.
Start Eclipse
create new java project →
click next →
1. add project to the build path
2. in Libraries tab → Add External JARs... → add javacv-bin\javacpp.jar, javacv-bin\javacpp.jar, javacv-bin\javacv-windows-x86.jar
3. in Order and Export tab → click all of these libraries we added
→ click finish
in the project → add a new class


E.
Copy the test code below, to run the test program, copy a img.jpg in the project folder:

import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;


public class test {
    /**
     * @param args
     */
10     public static void main(String[] args) {
11         IplImage img = cvLoadImage("tmp.jpg");
12         
13         cvShowImage("test image", img);
14         cvWaitKey();
15         cvReleaseImage(img);
16     }
17 }
18

F.
in the menu → Project → Build All → Run the project

2013年6月24日星期一

Using WordPress for our company’s website


I just switch to use the WordPress for our company’s website. WordPress is very easy to use and has an intuitive interface. I found that the time spent on formatting is greatly reduced.I choose 3 plugins and a beautiful theme for our site. Below is a short intro about them.
Plugins:
  • qTranslate
  • Contact Form 7
  • WP-Mail-SMTP
A: Setting of WP-Mail-SMTP
1. in WP-Mail-SMTP:
need to set:
  • From Email
  • From Name
set Mailer “Send all Wordpress email via SMTP”
2. in STMP Options
need to set:
  • SMTP Host
  • SMTP Port
  • Encryption → No encryption
  • Authentication → Yes: use SMTP authentication
  • Username: your mail username
  • Password: your mail password
B: Setting of Contact Form 7
Set your email-SMTP in the form field.

Copy this code and paste it into your post, page or text widget content.
For Example: [contact-form-7 id="48" title="Contact form 1"]

C: qTranslate
ignore message “qTranslate Services could not load OpenSSL!”
You can add Language in the setting page.
→ In the Widget Page of the WordPress add the qTranslate Language Chooser to the Header

Theme:
I choose Pinboard, cause it is a crafty and elegant theme powered by an advanced theme framework and grid system. It looks beautiful. It is also a Free Responsive WordPress Theme for the business or personal site. It is very easy to customize the site title & tagline, colors, header or background image, navigation and static front page. It also integriert the SEO tool.

2013年6月6日星期四

VS 2008编译strmbase.lib

最近写程序很少,因为有两个手下帮我写,一个星期编不超过8小时程序吧,但是写的东西很杂,Java,C++,Matlab等等。今天需要使用一个同事很早以前写的AVI2Grabber模块对Lagarith Lossless Avi Video读取,里面使用了strmbase.lib有关于DirectShow的东西。

研究了一下才发现strmbase.lib并不在MS配的SDK \lib. 需要自己编译一个。

  • 下载并安装Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1
  • 安装后,可以在C:\Program Files\Microsoft SDKs\Windows\v7.0\Samples\multimedia\directshow\baseclasses找到baseclasses.sln,然后用VS 2008打开。
  • 用VS2008在Release下进行编译(编译模式“Debug” 改成 “Release”),可以在C:\Program Files\Microsoft SDKs\Windows\v7.0\Samples\multimedia\directshow\baseclasses\Release得到我们需要的strmbase.lib。

2013年5月28日星期二

5月随笔

还是保持每个月一篇博客的速度。虽然非常忙,最为自豪的是5月读了至少20本书。最近坚持培养两个看似简单但不容易坚持的习惯,一是先做最重要的工作,二是把每一项工作都做成“流程”,最简单譬如写信,打电话,做计划表。最近的工作成果和效率大大的提高。最大的错误就是不犯错误,我尝试了很多不同的工作和任务,同时也犯了一些错误,但是收获很大。


无止境地提高自己的技术和知识非常重要,争取成为自己的领域的专家,就会建立出个人“品牌”。当同事关于这个领域的问题的时候,先想到的肯定是你这个“品牌”。要舍得花时间,花精力来培养人才,当他们可以当起工作的时候,最大的收益者,还是你自己。


今年我开始管理两个员工,两个半职的助理,我最近更多的工作是给他们安排编程研究任务,管理没有标准答案,但是我在这半年中积累了不少经验。以下是一些经验的总结:
1. 给他们顶任务目标,而且目标应当是可见,最好是可测的。
2. 有效沟通,建立信任。
3. 坚持互惠原则,承诺/一致性原则。

 

前不久看了《工作禅》一书,里面有很多有趣,发人深思的良言,这里做一个简单摘要,作为这篇随笔的结语。

如果你有100分的能力,那么在对外发挥时要掌握好火候,只崭露80分即可。这是人生得以惬意而过的良策。你对当前不对盘的工作的苦恼与憎恶其实是来源于你的野心。怀着一种玩乐的轻松心情去应对工作,不仅能激发你的创造性思维,还能消除你在面对上司时的紧张感。无论何时,都要有一颗洒脱之心。少些打工心态,多点儿事业心。

2013年4月17日星期三

4月随笔

德国的春天终于来了,春暖花开,上个星期去了汉诺威工业展,收获很大,有了一些新的计划,认识了一些合作伙伴。

我发现我的做事情的行动力越来越好,因为我身边有拖延症的人太多,如果我也拖延的话,那什么事也做不完。每天居然可以完成了很多事情,譬如今天来说,早上帮同事做ppt的图表,回信,中午开会关于一个合作的实验项目,下午和一家离办公室20公里外的小公司谈合作,然后和朋友研究商业计划,晚上接老婆回家,回家后做晚餐,打两个电话,写信,编程,还看了一集美剧,然后继续帮同事做ppt里的图,做了一个小时信息和数据分析整理,现在写博客。

被拒绝,被拒绝,继续被拒绝,做生意,创业很难。学会接受拒绝,学会销售绝对是创业中的重中之重。

很多看起来复杂的,不可执行的事情,如果把问题分解开,一个个小问题进行分析,层层推敲,常常可以找到解决方案,最重要的是有一个团队进行讨论分析。

很多不重要的事情,其实也要想到就做,或记入下来有时间就做,这样会减少很多麻烦。有时候把一些工作外包出去,也要有一定的方式去控制这些工作的进展,设计一个模式,可以有效的简易地控制外包出的工作,譬如使用文档驱动与控制工作的进程。

2013年3月18日星期一

生产力的低谷

虽然工作很多但是最近真是我生产力的低谷,工作上没有兴奋,让人充满力量和期待的感觉。计划很多进度很慢。深入某个领域去调查,很难,很难。
最近进行了很多讨论,很多的计划,试着去寻找问题,毕竟创业就是


“The essence of a startup lies in the process of discovering a problem shared by many people and trying to solve it.”). (本话原文http://tomtunguz.com/the-value-of-startup-research)


在生产力的低谷,干不了很多“正事”,一直在思考公司产品新规划。
什么是真正的产品(看到一篇文章很符合我的思考,比我想得完善http://coolshell.cn/articles/7617.html


真正的产品应该是有一个端到端的一个解决方案
真正的产品应该是有价值的。这种价值表现在——你可以从中获得有价值的内容,并且你也可以通过他创造对你有价值的东西。
真正的产品应该是和社会有交互并能自我进化的
真正的产品应该是体现品质的。所谓有品质的意思是,你能从使用这个产品中获得一种感觉,一种档次的提升的感觉。


下个月汉诺威的工业展也许是不错的活动,可以开开眼界,看看在我脑中的我们的产品和现实世界的差距。