Category Archives: ASP.Net MVC

ASP.Net MVC 5 Membership.GetUser() Issue

今天公司發佈了新的網站

由于沒有好好的做QA / 測試..
所以今天發現了很多的問題…
[如果他們一早聽我之前建議的做法..應該不用那麼失策的]

今天的其中一個問題是和 Asp.Net MembershipAsp.Net Identity有關的
自從Asp.Net MVC 5開始 Asp.netMembership 便用了 ASP.Net Identity 來取代
之前的 ASP.NET MembershipSimple Membership systems
ASP.NET MembershipSimple Membership systems便不能在ASP.Net MVC 5的網站上使用
ASP.Net Identity vs ASP.Net Membership system

所以公司的其中一位同事便將公司另一個網站的asp.net mvc3轉乘mvc5在他的電腦上測試是完全沒有問題的
當我們要把所有系統更新的時候把網站發放到伺服器上變出現了一個登入的問題在登入期間需要花一分半鐘才能進入主頁
公司的其中一個網絡顧問說是我們程式碼的問題..

但是我的同事卻說在他電腦上運行沒有問題
所以應該是網絡的問題
[作一些沒有意思的Argue]
最後因為覺得沒有意思浪費時間說誰對誰錯
所以我變進行了一個小小的除錯個步驟
發現應該是這個程式碼的問題

之後發現原來同事升級網頁的時候真的直接把Asp.Net MVC3 升級到 Asp.Net MVC5
但是沒有把所有和membership有相關的程式碼轉換成使用identity
所以當我在除錯模式是執行這個網頁是在membership這個功能花了很久才能執行下一段程式碼
解決方法十分簡單我們只需要把所有和membership相關的程式碼轉換成identity便可

解決方法
我們只需要把之前使用的 Membership.GetUser()
轉成 User.Identity 便可以了

E.G.
<pre>
string Username = Membership.GetUser().UserName;
</pre>
轉成
<pre>
string Username = HttpContext.Current.User.Identity.GetUserName();
</pre>

Hope you find it useful

How do you handle Javascript on ASP.Net MVC Website – ASP.Net MVC 5

最近開始再次學習ASP.Net MVC 5
科技推出得太快..很多東西都想學..
所以常常都被不同的東西分了心

開始寫ASP.Net MVC 5的時候..嘗試做cshtml上使用JQuery做一些東西
我的程式碼如下:
HTML

<h2 id="header">Javascript Section Demo - Failed</h2>

<div id="result">
    Original Div Content
    <p>
        Wait for Javascript to Load
    <p>
</div>

Javascript

   <script>
        $(document).ready(function () {
        $("#result").html("Javascript Excuted");
        $("#header").html("Javascript Section Demo - Success");
    });
</script>

誰不知..當我執行時出現了以下的錯誤..
Uncaught ReferenceError: $ is not defined
ASP.Net MVC - Uncaught ReferenceError: $ is not defined

Failed Demo:
http://sharechiwaimvccloud.apphb.com/JsDemo/MvcJsScriptInitSample

在想為什麼他認不了JQuery的呢?
原來ASP.Net MVC 新增了一個 SectionScripts的Tag
這個可以增加網頁的效能..
通常寫網頁的都建議把所有和Rendering沒有關係的程式碼都放在網頁的底部..
這可以令到網頁顯然得更快

解決方法
我們只要加所有和Javascript 相關係程式碼放進這個
Section scripts tag 內便可以了
E.G.


@section Scripts
{
    <script>
        $(document).ready(function () {
        $("#result").html("Javascript Excuted");
        $("#header").html("Javascript Section Demo - Success");
    });
</script>
}

Javascript working on ASP.Net MVC

Working Demo:
http://sharechiwaimvccloud.apphb.com/JsDemo/MvcJsScriptInitSample?isSuccess=true

Hope you find it useful

ASP.net MVC Session Time out

在寫ASP.Net MVC 的程式時..常常發現 很快便會Session time out
很多時候在開發過程中.. 都可能要Debug..更改Stored procedure 或其他的東西..
很多時候都可能沒有按過頁面的連結超過20分鐘.. 過了二十多分鐘得再按下連結時..
便會出現登出發沒有顯示資料等等的情況..

這時候很大機會是Session timeout所導致的..

解決方法十分簡單..
只要在開發模式中的Web.config 修改一下 Session State timeout的時間便可以了
E.G.

Web.configSystem.web分支下 加入 或修改 “sessionState timeout” 的屬性 便可以了

  <system.web>
	  <sessionState timeout="60" />
</system.web>

Hope you find it useful

ASP.Net and Web Tool 2.2 Download

ASP.Net and Web Tool 2.2 終於Release 了

大家可以到以下網址下載/安裝
http://go.microsoft.com/fwlink/?LinkID=275131

新功能包括:

Tooling

  • Page Inspector
  • Editor
    • Support syntax highlighting for CoffeeScript, Mustache, Handlebars, and JsRender.
    • The HTML editor provides Intellisense for Knockout bindings.
    • LESS editing and compiler support to enable building dynamic CSS using LESS.
    • Paste JSON as a .NET class. Using this Special Paste command to paste JSON into a C# or VB.NET code file, and Visual Studio will automatically generate .NET classes inferred from the JSON.
  • Mobile Emulator support adds extensibility hooks so that third-party emulators can be installed as a VSIX. The installed emulators will show up in the F5 dropdown, so that developers can preview their websites on a variety of mobile devices. Read more about this feature in Scott Hanselman’s blog entry on the new BrowserStack integration with Visual Studio.

Web Publishing

  • Web site projects now have the same publishing experience as Web Application projects including publishing to Windows Azure Web Sites.
  • Selective publish – for one or more files you can perform the following actions (after publishing to a Web Deploy endpoint):
    • Publish selected files.
    • See the difference between a local file and a remote file.
    • Update the local file with the remote file or update the remote file with the local file.

ASP.NET MVC Templates

  • The new Facebook Application template makes writing Facebook Canvas applications easy. In a few simple steps, you can create a Facebook application that gets data from a logged in user and integrates with their friends. The template includes a new library to take care of all the plumbing involved in building a Facebook app, including authentication, permissions, accessing Facebook data and more. For more information on using the Facebook Application template see http://go.microsoft.com/fwlink/?LinkID=269921.
  • A new Single Page Application MVC template allows developers to build interactive client-side web apps using HTML 5, CSS 3, and the popular Knockout and jQuery JavaScript libraries, on top of ASP.NET Web API. The template includes a “todo” list application that demonstrates common practices for building a JavaScript HTML5 application that uses a RESTful server API. You can read more at http://www.asp.net/single-page-application.
  • You can now create a VSIX that adds new templates to the ASP.NET MVC New Project dialog. Learn how here:http://go.microsoft.com/fwlink/?LinkId=275019
  • FixedDisplayModes package – MVC project templates have been updated to include the new ‘FixedDisplayModes’ NuGet package, which contains a workaround for a bug in MVC 4. For more information on the fix contained in the package, refer to this blog post (http://blogs.msdn.com/b/rickandy/archive/2012/09/17/asp-net-mvc-4-mobile-caching-bug-fixed.aspx) from the MVC team.

ASP.NET Web API

ASP.NET Web API has been enhanced with several new features:

  • ASP.NET Web API OData
  • ASP.NET Web API Tracing
  • ASP.NET Web API Help Page

ASP.NET Web API OData

ASP.NET Web API OData gives you the flexibility you need to build OData endpoints with rich business logic over any data source. With ASP.NET Web API OData you control the amount of OData semantics that you want to expose. ASP.NET Web API OData is included with the ASP.NET MVC 4 project templates and is also available from NuGet (http://www.nuget.org/packages/microsoft.aspnet.webapi.odata).

ASP.NET Web API OData currently supports the following features:

  • Enable OData query semantics by applying the [Queryable] attribute.
  • Easily validate OData queries and restrict the set of supported query options, operators and functions.
  • Parameter bind to ODataQueryOptions directly to get an abstract syntax tree representation of the query that can then be validated and applied to an IQueryable or IEnumerable.
  • Enable service-driven paging and next page link generation by specifying result limits on [Queryable] attribute.
  • Request an inlined count of the total number of matching resources using $inlinecount.
  • Control null propagation.
  • Any/All operators in $filter.
  • Infer an entity data model by convention or explicitly customize a model in a manner similar to Entity Framework Code-First.
  • Expose entity sets by deriving from EntitySetController.
  • Simple, customizable conventions for exposing navigation properties, manipulating links and implementing OData actions.
  • Simplified routing using the MapODataRoute extension method.
  • Support for versioning by exposing multiple EDM models.
  • Expose service document and $metadata so you can generate clients (.NET, Windows Phone, Windows Store, etc.) for your Web API.
  • Support for the OData Atom, JSON, and JSON verbose formats.
  • Create, update, partially update (PATCH) and delete entities.
  • Query and manipulate relationships between entities.
  • Create relationship links that wire up to your routes.
  • Complex types.
  • Entity Type Inheritance.
  • Collection properties.
  • Enums.
  • OData actions.
  • Built upon the same foundation as WCF Data Services, namely ODataLib (http://www.nuget.org/packages/microsoft.data.odata).

For more information on ASP.NET Web API OData see http://go.microsoft.com/fwlink/?LinkId=271141.

ASP.NET Web API Tracing

ASP.NET Web API Tracing integrates tracing data from your web APIs with .NET Tracing. It is now enabled by default in the Web API project template. Tracing data for your web APIs is sent to the Output window and is made available through IntelliTrace. ASP.NET Web API Tracing enables you to trace information about your Web API when hosted on Windows Azure through integration with Windows Azure Diagnostics. You can also install and enable ASP.NET Web API Tracing in any application using the ASP.NET Web API Tracing NuGet package (http://www.nuget.org/packages/microsoft.aspnet.webapi.tracing).

For more information on configuring and using ASP.NET Web API Tracing see http://go.microsoft.com/fwlink/?LinkID=269874.

ASP.NET Web API Help Page

The ASP.NET Web API Help Page is now included by default in the Web API project template. The ASP.NET Web API Help Page automatically generates documentation for web APIs including the HTTP endpoints, the supported HTTP methods, parameters and example request and response message payloads. Documentation is automatically pulled from comments in your code. You can also add the ASP.NET Web API Help Page to any application using the ASP.NET Web API Help Page NuGet package (http://www.nuget.org/packages/microsoft.aspnet.webapi.helppage).

For more information on setting up and customizing the ASP.NET Web API Help Page seehttp://go.microsoft.com/fwlink/?LinkId=271140.

ASP.NET SignalR

ASP.NET SignalR makes it simple to add real-time web capabilities to your ASP.NET application, using WebSockets if available and automatically falling back to other techniques when it isn’t.

For more information on using ASP.NET SignalR see http://go.microsoft.com/fwlink/?LinkId=271271.

ASP.NET Friendly URLs

ASP.NET FriendlyURLs makes it very easy for web forms developers to generate cleaner looking URLs(without the .aspx extension). It requires little to no configuration and can be used with existing ASP.NET v4.0 applications. The FriendlyURLs feature also makes it easier for developers to add mobile support to their applications, by supporting switching between desktop and mobile views.

For more information on installing and using ASP.NET Friendly URLs seehttp://www.hanselman.com/blog/IntroducingASPNETFriendlyUrlsCleanerURLsEasierRoutingAndMobileViewsForASPNET

有關新功能可以到以下URL 參考

http://www.asp.net/vnext/overview/fall-2012-update/aspnet-and-web-tools-20122-release-notes-rtw

Hope you find it useful

Asp.net website did not work on ie10 FIXED – 用戶使用IE10在不能登入ASP.Net 的網頁 SCRIPT5009P ‘__doPostBack’ is undefined

今天有客戶投訢當他們更新了他們的IEIE10之後 不能登入到公司的ASP.Net 網頁
之後我便去嘗試是客戶的電腦問題..還是真的是IE10的問題呢
當我便用IE10 去登入公司的網頁時… 在Developer ToolConsole上出現了以下的錯誤信息
SCRIPT5009P ‘__doPostBack’ is undefined
SCRIPT5009P '__doPostBack' is undefined

做了一會兒research 之後終生找到了解決方法

解決方法:
我們可以到以下的URL 去Request 這一個Hotfix
A hotfix is available for the ASP.NET browser definition files in the Microsoft .NET Framework 4.0
http://support.microsoft.com/kb/2600088

這個HotFix只可以在以下的系統上應用的
.NET Framework 4.0 – Windows XP, Windows 2003, Windows Vista, Windows Server 2008, Win7, Windows Server 2008 R2 (MSI)

按了”Hotfix Download Available“之後便會轉到另外一個頁面..
A hotfix is available for the ASP.NET browser definition files in the Microsoft .NET Framework 4.0
填上電郵..之後便會把Hotfix的Download Link發送到你的電郵..
 photo HotFix2600088.jpg
下載安裝後..需要從新啟動電腦才可以Apply這一個HotFix

Hope you find it useful

JQuery get number of items inside select list/ dropdownlist – 使用JQuery來取得在SelectList/ DropDownList上有多小個Item.

今天公司的ASP.Net MVC Website其中有一個Form 有很多Dynamic的 資料要取出
我們要依照不同的選擇顯示不同的內容..
其中一個情況是

當使用者選擇了一些內容後
另外的2個DropDownList會更新內容…
有時候因為資料沒有相符的關係..
不能Populate 其他的DropDownList
在這個情況下我們便要出示其他的資訊去提示用戶了

所以我們有需要看看怎樣取得DropDownList內有多小個Item

原本使用ASP.Net的話我們可以使用
C#

int NumberOfItems = ddl.Items.Count;

但是在ASP.Net MVC上我們便需要使用JQuery來實現了
假設我們的DropDownList 是這樣的
HTML

<select id="MinimumContractTerm" name="MinimumContractTerm" class="valid"><option value="1">1 month</option>
<option value="3">3 months</option>
<option value="6">6 months</option>
<option value="12">12 months - 1 Year</option>
<option value="24">24 months - 2 Year</option>
<option value="36">36 months - 3 Year</option>
<option value="48">48 months - 4 Year</option>
<option value="60">60 months - 5 Year</option>
</select>
<button id="btn_run" name="btn_run">Run</button>

我們可以使用以下的JQuery 方法來解決這個問題
Javascript

 $(document).ready(function () {
      $("#btn_run").click(function(){
          alert($("#MinimumContractTerm").length);
     });
});

Hope you find it useful

Visual Studio 2010 Could not load ASP.Net MVC Project – VS2010不能開啟ASP.Net MVC 的Project

今天同事開始學習寫ASP.Net MVC 3的Website
希望當我在放假時公司的網頁有Bugs或需要加新功能時
他也可以嘗試去解決問題

誰不知..當他從TFS 取後Project卻出現以下的錯誤信息
One or more projects in the solution were not loaded correctly. Please see te Output Windows for details
One or more projects in the solution were not loaded correctly. Please see te Output Windows for details

當我查看 “Output Windows/輸出視窗” 時出現了以下的信息
The project type is not supported by this installation.
The project type is not supported by this installation.
其他原因很簡單..
是因為他沒有在電腦上安裝ASP.Net MVC3的元件
解決方法:
大家可以到ASP.Net 的網頁上Download.
http://www.asp.net/mvc/mvc3
ASP.Net Website Download ASP.Net MVC
之後開啟安裝便可以了
Install ASP.Net MVC 3 via Web PI
Happy Coding