แสดงบทความที่มีป้ายกำกับ MVC 4 แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ MVC 4 แสดงบทความทั้งหมด

วันศุกร์ที่ 1 พฤศจิกายน พ.ศ. 2556

System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to

[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Users\xxxx\AppData\Local\Temp\Temporary ASP.NET Files\root\fe4980a2\10ea1996\assembly\dl3\33a3ac9e\f6af08a0_f8d6ce01\System.Web.WebPages.Razor.dll'.
This happen today when I use Nuget upgrade my MVC 4 asp.net 4.5 to last version on 1 November 2013 but can't get my project run normally after upgrade.
Normally look like I got System.Web.Razor version 3.0.0.0 but my web still use version 2.0.0.0 so I try to fix this
first change in root web.config by this
from
    <appSettings>
        <add key="webpages:Version" value="2.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="PreserveLoginUrl" value="true" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
to
    <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="PreserveLoginUrl" value="true" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
from
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
            </dependentAssembly>
to
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>

change in web.config in ~/Views/
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>
to
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>

from
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
to
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

from
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <controls>
                <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
            </controls>
        </pages>
to
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <controls>
                <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
            </controls>
        </pages>

now I can run my project with no problem (for now...)
Update...
yes i can build and run but intellisense not work anymore  look like i need Visual Studio 2003 for this job done.

วันจันทร์ที่ 29 กรกฎาคม พ.ศ. 2556

Disable SimpleMembership in MVC 4

Today I need to use simple membership in web.config but SimpleMembership in MVC 4 is not simple.

First u need to custom Web.config like this
        <authentication mode="Forms">
            <forms loginUrl="~/Account/Login" timeout="2880" >
                <credentials passwordFormat="Clear">
                    <user name="test" password="test"/>
                </credentials>
            </forms>
        </authentication>

add this to AppSettings
<add key="enableSimpleMembership" value="false"/>

and in AccountController disable InitializeSimpleMembership
//[InitializeSimpleMembership]

now for Login use this for realy simple life.

        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login( LoginModel model, string returnUrl )
        {
            //if (ModelState.IsValid && WebSecurity.Login( model.UserName, model.Password, persistCookie: model.RememberMe ))
            //{
            //    return RedirectToLocal( returnUrl );
            //}
            if (!ValidateLogOn( model.UserName, model.Password ))
                return View( model );

            FormsAuthentication.SetAuthCookie( model.UserName, model.RememberMe );

            if (!String.IsNullOrEmpty( returnUrl ))
                return Redirect( returnUrl );
            else
                return RedirectToAction( "LogOn" );

            //// If we got this far, something failed, redisplay form
            //ModelState.AddModelError( "", "The user name or password provided is incorrect." );
            //return View( model );
        }

        //Add Custom Validate for validate user and pass in Web.config
        private bool ValidateLogOn( string userName, string passWord )
        {
            if (string.IsNullOrEmpty( userName ))
                ModelState.AddModelError( "username", "User name required" );

            if (string.IsNullOrEmpty( passWord ))
                ModelState.AddModelError( "password", "Password required" );

            if (ModelState.IsValid && !FormsAuthentication.Authenticate( userName, passWord ))
                ModelState.AddModelError( "_FORM", "Wrong user name or password" );

            return ModelState.IsValid;
        }
        //End Custom Validate

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //WebSecurity.Logout();

            //return RedirectToAction( "Index", "Home" );

            FormsAuthentication.SignOut();
            return RedirectToAction( "LogOn" );
        }

วันจันทร์ที่ 1 กรกฎาคม พ.ศ. 2556

Integrate NLog in my MVC 4

use Nuget to get NLog to your MVC
current version is 2.0.1.2 ad 1/7/2555 (d/m/yyyy)

create file NLog.config and input this

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
    <variable name="appName" value="MOTEWorkflow" />
    <targets>
        <target name="console" xsi:type="ColoredConsole"
          layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
        <target name="file" xsi:type="File" fileName="${basedir}/Logs/rrLog.log"
          layout="${date}: ${message}" />
    </targets>
    <rules>
        <logger name="*" minlevel="Info" writeTo="file" />
    </rules>
</nlog>

then when need log use like this

NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
logger.Error( "Test Error" );

this is simple but more configuration and details can be found here.
https://github.com/NLog/NLog/wiki

วันพฤหัสบดีที่ 27 มิถุนายน พ.ศ. 2556

Install YAF (Yet Another .NET Forum) in subfolder of MVC

You will got error from the start but with this step will make you pass.
1. add <remove namespace="..."/> in yaf  web.config line 72 for not conflict with MVC
            <namespaces>
                <remove namespace="System.Web.Mvc.Html"/>
                <remove namespace="System.Web.Mvc"/>
                <remove namespace="System.Web.Optimization"/>
                <remove namespace="System.Web.Mvc.Ajax"/>
                <remove namespace="System.Web.Helpers"/>
                <add namespace="YAF.Core"/>
                <add namespace="YAF.Controls"/>
                <add namespace="YAF.Utils"/>
                <add namespace="YAF.Types.Interfaces"/>
                <add namespace="YAF.Types"/>
            </namespaces>
2. Go to folder u can install normally now.

วันพฤหัสบดีที่ 23 พฤษภาคม พ.ศ. 2556

C# Ajax.ActionLink How to Add Onclick for confirm or validate.

I try to insert onclick or @onclick in html attribute but it don't work.
so I try research and found this

@Ajax.ActionLink("Done", "ActionName", 
    new AjaxOptions 
    { 
        OnBegin = "return ConfirmDone()", 
        UpdateTargetId = "MyContainerId" 
    })
@Ajax.ActionLink("Done", "ActionName", 
    new AjaxOptions 
    { 
        Confirm= "Are you sure you want to do this?", 
        UpdateTargetId = "MyContainerId" 
    })
With this i can add function validate on begin or add confirm before click from Ajax Option.

ref: http://stackoverflow.com/questions/9604942/asp-net-mvc3-ajax-actionlink-conditional-confirmation-dialog-box

วันอังคารที่ 13 พฤศจิกายน พ.ศ. 2555

MVC4 IIS 6 and error occurred while establishing a connection to SQL Server


I use MVC 4 with My Custom Membership controller can test normally in my Localhost but when upload to Server it show when go to page that need authorize

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)


I don't use any ms sql in this project so this error is wild. After  check on my code that use sql connection name "DefaultConnection" I found in 2 place
AccountModels.cs in Models
InitializeSimpleMembershipAttribute.cs in Filters
so I don't use InitializeSimpleMembershipAttribute in any place so I chnage

AccountModels.cs in line 14,15
public UsersContext()
            : base( "DefaultConnection" )
to 
public UsersContext()
            : base( "MyDBConnection" )

and now it work fine.

Hope this help.