Tuesday, August 16, 2011

ASP.NET MVC 3 Section Helper Sitemap same Helper Codes

 
Section Html
 
@section Types {
    @{
        var menuTypes = Util.enumToList(typeof(MenuTypeEnum));
        <text><span>Цэсний төрөл: </span><select onchange="listMenu();" id="MenuTypeCode" class="select">
            @foreach(var mt in menuTypes) {
                <option value="@mt.Value">@mt.Text</option>
            }
        </select>
        </text>   
    }
}
 
Rozor Helper.cshtml in App_Code
 
@using System;
@using System.Collections.Generic;
@using System.Linq;
@using System.Web;
@using System.Web.Mvc;
@using System.Web.Mvc.Html;
@using System.Web.WebPages;

@functions {
   
    public MvcHtmlString RenderHtml()
    {
        return new MvcHtmlString("html");
    }
}

@helper SiteMap() {
       
    }
 
SiteMap Html Render
 
@{
   
    var topLevelNodes = SiteMap.RootNode.ChildNodes;
    <text><ul class="menu">
        @foreach (SiteMapNode node in topLevelNodes)
        {
            if (SiteMap.CurrentNode == node) {  
                <li class="selectedMenuItem"><a href="@node.Url">@node.Title</a></li>
            } else {
                <li><a href="@node.Url">@node.Title</a></li>
            }
        }
    </ul>
    </text>
}
 
 
Add Page Namespace
 
<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="CompanyName.ProjectName.Resources"/>
        </namespaces>
    </pages>
</system.web.webPages.razor>


Resource

 
public static class CommonHtmlExtensions
{
    public static object GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
    {
        return htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey);
    }

    public static object GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey, CultureInfo culture)
    {
        return htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey, culture);
    }

    public static object GetLocalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
    {
        return htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(classKey, resourceKey);
    }

    public static object GetLocalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey, CultureInfo culture)
    {
        return htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(classKey, resourceKey, culture);
    }

}

Monday, August 15, 2011

C# simples byte hash encrypt reflection formats

Byte or Int to HexString

Console.WriteLine(String.Format("{0:X}", 69));
            Console.WriteLine(((byte)69).ToString("x2").ToUpper());
            Console.ReadLine();

CreateInstance By reflection

ObjectHandle obj = AppDomain.CurrentDomain.CreateInstance("ClassLibrary1", "ClassLibrary1.Class1");
ClassLibrary1.Class1 c = (ClassLibrary1.Class1)obj.Unwrap();
c.name = "asdfasdf";

MD5 hash simple

public static String md5hash(String input)
        {
            MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
            byte[] bs = Encoding.ASCII.GetBytes(input);
            bs = x.ComputeHash(bs);
            StringBuilder s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToUpper());
            }
            return s.ToString();
        }

Encrypt simple

public static byte[] encrypt(byte[] content, byte[] key)
        {
            byte[] ret = new byte[content.Length];
            for (int i = 0, k = 0; i < ret.Length; i++, k++)
            {
                if (key.Length <= k) k = 0;
                ret[i] = (byte)(((int)content[i]) ^ ((int)key[k]));
            }
            return ret;
        }


Sunday, August 14, 2011

ASP.NET Membership service usage my own database with Entity framwork DbContext

ASP.NET -нэгэн шинэ технологи болох EntityFramwork ийн DbContext болон Membership Service ийг хэрхэн ашиглах вэ?
Эхлээд эхлээд өөрийн MVC 3 Project үүсгэ. Тэгээд өгөгдлийн сангаа DbContext ашиглан ( өмнөх сэдвүүдийг хараарай ) автоматаар үүсгэнэ. Дараа нь

1. ctrl + R дараад CMD г ажиллуулна.
2. > C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regsql.exe ажиллуул
3. Доорхи цонх гарч ирнэ.
4. Next
5. Next
За энд нэг зүйлийг хэлэхэд DemoUser гэсэн хэсэгт анхаарвал, анх MVC project үүсгэж байхад Web.config файл дотор default нэг connection үүсдэг. Түүний нэр нь aspnetdb гэсэн байдаг. Тэр connectionString г өөрийнхөөрөө дураараа солиж болно. Жишээ нь минийх нэг иймэрхүү::::
<connectionStrings>
    <clear/>
    <add name="MyDbContext"
         connectionString="data source=.;Database=MyDbName;User ID=sa;Password=password;Persist Security Info=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

Энэ зурган дээр орлуулт тавибал DemoUser -ний оронд MyDbName гэж бичих болно гэсэн үг.
Харин MyDbContext нэр бол class MyDbContext : DbContext {  } байх болно. Ингэж Entity FrameWork 4 тэй хамт Membership  Service тэй хамт ашиглах боломжтой болно.

  
6. Next
7. Next 
Энэ үед өгөгдлийн санд нэмэлт өөрчлөлт орно. Энэ нь өгөгдлийн санг Membership service д зориулан өөрчлөн шинэчиж байгаа.


8. үр дүнд нь сонгосон өгөгдлий сан доорхи маягийн бүтцээр шинэчлэгдсэн байх болно.

aspnet_Applications
aspnet_Membership - хэрэглэгч нэвтрэхтэй холбоотой мэдээлэл байна
aspnet_Paths
aspnet_PersonalizationAllUsers
aspnet_PersonalizationPerUser
aspnet_Profile         - энд програмчин өөрийн хүссэнээр property нэмж болно
aspnet_Roles           - эрхүүдийн мэдээлэл
aspnet_SchemaVersions
aspnet_Users               - Хэрэглэгчийн нэвтрэх нэр, нууцлагдсан Id
aspnet_UsersInRoles     - Эрхүүдэд хамаарах хэрэглэгчийг холбосон мэдээлэл бий
aspnet_WebEvent_Events

гэсэн Table үүд шинээр үүснэ.

9. үүсгэсэн MVC project ийнхоо Web.config дээр

<authentication mode="Forms" />
    <membership defaultProvider="SqlMembershipProvider" hashAlgorithmType="SHA1">
      <providers>
        <clear />
        <add
          type = "System.Web.Security.SqlMembershipProvider"
          name = "SqlMembershipProvider"
          connectionStringName = "MyDbContext"
          applicationName = "/"
          enablePasswordRetrieval = "false"       - нууц үгийг код дотор харах боломжгүй
          enablePasswordReset = "true"              - нууц үгийг шинэчилж болно
          requiresQuestionAndAnswer = "false" - бүртгүүлж байхад заавал нэхэхгүй
          requiresUniqueEmail = "true"               - майл хаягийг ялгаатай бүртгэнэ
          passwordFormat = "Hashed"                 - нууц үг нууцлэгдан орно ( Clear бол энгийн )
          maxInvalidPasswordAttempts = "5"
          minRequiredPasswordLength = "6"
          minRequiredNonalphanumericCharacters = "0" - нууц үгэнд тусгай тэмдэгт байхгүй
          passwordAttemptWindow = "10" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add type="System.Web.Profile.SqlProfileProvider"
             name="SqlProfileProvider"
             connectionStringName = "MyDbContext"
             applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="true" defaultProvider="SqlRoleProvider">
      <providers>
        <clear />
        <add type = "System.Web.Security.SqlRoleProvider"
             name = "SqlRoleProvider"
             connectionStringName = "MyDbContext"
             applicationName = "/" />
      </providers>
    </roleManager>
    <!--<authorization>
      <allow roles="SYSTEM,ADMIN,USER" />
      <deny users="*" />
    </authorization>-->

мөрүүдийг нэмж өгнө байвал хэрэггүй.

10. энэ блогийн өмнөх жишээнүүдийг хараарай ! Entity framwork DbContext той Membership зэрэг ажиллаж болно. Нэг зөвхөн хэрэглэгч нууцлалтай холбоотой асуудлыг, нөгөө нь өгөгдлөөр хангаж Model ийг агуулна.

public class InitializerMyDbContext : DropCreateDatabaseIfModelChanges<MyDbContext>
    {
        protected override void Seed(MyDbContext context)
        {
            base.Seed(context);
        }
    }

    public class MyDbContext : DbContext
    {
        public DbSet<ArtistInfo> ArtistInfoes { get; set; }
        public DbSet<AudioInfo> AudioInfoes { get; set; }
        public DbSet<ProductInfo> ProductInfoes { get; set; }
.....................
гэх мэт кодын хэсэг байж таараа

11. энэ бол хамгийн чухал хэсэг ( 9 ) дүгээрт бичсэн тохиргоор нь ASP.NET web ажиллах үед Membership.Provider - Class - г автоматаар дүүргэх ба шууд ашиглах боломжтой. За би програмистууддаа зориулж өөрийнхөө үүсгэсэн шууд ашиглаж болох Class г энд тавъя доорхи кодыг нэг бүрчлэн маш сайн хараарай

public class MembershipServiceHelper
    {
        private MembershipProvider Provider = null;

        public MembershipServiceHelper()
        {
// Membership.Provider системээр үүсгэгдсэн class
            Provider = Membership.Provider;
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email, bool isApproved)
        {
            InitRoot();
// Provider.ApplicationName = WebSites.Current.Name бол олон веб сайтад тус тусд нь захиран зарцуулах боломжийг олгох зорилготой зохиомол код. энгийн үед Provider.ApplicationName ийг өөрчлөх шаардлага бараг байдаггүй.
            Provider.ApplicationName = WebSites.Current.Name;
            if (isCreatedAnyUser(userName))
            {
                return MembershipCreateStatus.DuplicateUserName;
            }
            if (isCreatedAnyEmail(email))
            {
                return MembershipCreateStatus.DuplicateEmail;
            }
            MembershipCreateStatus status;
            MembershipUser user = Membership.CreateUser(userName, password, email, null, null, isApproved, out status);
            return status;
        }

        public bool ValidateUser(string userName, string password)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            return Membership.ValidateUser(userName, password);
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            MembershipUser user = Membership.GetUser(userName);
            return user.ChangePassword(oldPassword, newPassword);
        }

        public bool ResetPassword(string email, string question, string answer)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            MembershipUser user = Membership.GetUser(email);
            if (user.PasswordQuestion.Equals(question))
            {
                string newPassword = user.ResetPassword(answer);
                if (newPassword != null && newPassword.Length > 0)
                {
                    return resetPasswordSuccess(user, newPassword);
                }
            }
            return false;
        }

        public bool ResetPassword(string email)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            string userName = Membership.GetUserNameByEmail(email);
            if (userName != null && userName.Length > 0)
            {
                MembershipUser user = Membership.GetUser(userName);
                string newPassword = user.ResetPassword();
                if (newPassword != null && newPassword.Length > 0)
                {
                    return resetPasswordSuccess(user, newPassword);
                }
            }
            return false;
        }

        public bool UpdateUser(MembershipUser user)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            Membership.UpdateUser(user);
            return true;
        }

        public MembershipUser GetUser(string userName, bool isOnline)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            return Membership.GetUser(userName, isOnline);
        }

        public string GetUserName(string email)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            return Membership.GetUserNameByEmail(email);
        }
       
        private bool resetPasswordSuccess(MembershipUser user, string newPassword)
        {
            string body = string.Format(HtmlMailResources.ResetPassword, newPassword, WebSites.Current.FullName);

            string[] roles = Roles.GetRolesForUser(user.UserName);
            if (roles.Length == 0)
            {
                roles = new string[] { SystemConstants.DbSystemRole };
            }
            if (roles.Contains(SystemConstants.DbSystemRole)
                || roles.Contains(SystemConstants.DbAdminRole)
                || roles.Contains(SystemConstants.DbOperatorRole))
            {
                MailUtil.systemMailSend(user.Email, WebSites.Current.Name, body);
            }
            else
            {
                MailUtil.siteMailSend(user.Email, WebSites.Current.Name, body, null);
            }
            return true;
        }

        private bool InitRoot()
        {
            if (!isCreatedRootUser())
            {
                InitSystemRole();

                Provider.ApplicationName = WebSites.Current.Name;
                MembershipCreateStatus status;
                Membership.CreateUser(SystemConstants.DbSystemUser
                    , Membership.GeneratePassword(Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters)
                    , SystemConstants.RootUserEmail, ".", ".", false, out status);
                return (status == MembershipCreateStatus.Success);
            }
            return false;
        }

        private void InitSystemRole()
        {
            Provider.ApplicationName = WebSites.Current.Name;
            Roles.CreateRole(SystemConstants.DbSystemRole);
            Roles.CreateRole(SystemConstants.DbAdminRole);
            Roles.CreateRole(SystemConstants.DbOperatorRole);
            Roles.CreateRole(SystemConstants.DbUserRole);
            Roles.CreateRole(SystemConstants.DbClientRole);
        }

        private bool isCreatedAnyUser(string userName)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            return (Membership.GetUser(userName) != null);
        }

        private bool isCreatedRootUser()
        {
            Provider.ApplicationName = WebSites.Current.Name;
            return (Membership.GetUser(SystemConstants.DbSystemUser) != null);
        }

        private bool isCreatedAnyEmail(string email)
        {
            Provider.ApplicationName = WebSites.Current.Name;
            return (Membership.GetUserNameByEmail(email) != null);
        }
    }

12. За одоо энэ class ийг ашигласан Controller - ийн кодыг доор тавъя
default аар үүсгэсэн AccountController -г жаахан өөрчлөөд өөртөө зориулаад нэг иймэрхүү::::

MembershipServiceHelper helper = new MembershipServiceHelper();
        //Cms1DbContextHelper helper = Cms1DbContextHelper.Current;
// би хуучин AuthenticationService ашиглаж байлаа харин одоо Membership service ашиглаж байгаа.

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordModel model, string returnUrl)
        {
            if (helper.ResetPassword(model.Email))
            {
                ViewBag.Status = "OK";
                return View("~/Views/Admin/Login/ResetPassword.cshtml");
                //Redirect("~/Admin/Login/ResetPassword");
            }
            else
            {
                ModelState.AddModelError("", "Хэрэглэгчийн нэр майл хаягаа зөв оруулна уу.");
                return View("~/Views/Admin/Login/ForgetPassword.cshtml");
            }
        }

        [HttpPost]
        public ActionResult Login(LogOnModel model, string Return_Url)
        {
            if (ModelState.IsValid)
            {
                if (helper.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(Return_Url) && Return_Url.Length > 1 && Return_Url.StartsWith("/")
                        && !Return_Url.StartsWith("//") && !Return_Url.StartsWith("/\\"))
                    {
                        return Redirect(Return_Url);
                    }
                    else
                    {
                        return Redirect("~/Admin/Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Хэрэглэгчийн нэр эсвэл нууц үг буруу байна.");
                    return View("~/Views/Admin/Login/Index.cshtml");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string Return_Url)
        {
            if (ModelState.IsValid)
            {
                if (helper.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(Return_Url) && Return_Url.Length > 1 && Return_Url.StartsWith("/")
                        && !Return_Url.StartsWith("//") && !Return_Url.StartsWith("/\\"))
                    {
                        return Redirect(Return_Url);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Хэрэглэгчийн нэр эсвэл нууц үг буруу байна.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

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

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                createStatus = helper.CreateUser(model.UserName, model.Password, model.Email, false);
               
                if (createStatus == MembershipCreateStatus.Success)
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = helper.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = helper.ChangePassword(currentUser.UserName, model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Хуучин нүүц үг буруу эсвэл шинэ нууц үг буруу алдаатай байна.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


ДҮГНЭЛТ

Хамгийн гол нь сонгосон өгөгдлийн сангаа Membership Service аар баяжуулаад Web.config оо түүнд зориулж жаахан өөрчлөөд бараг болж байгаа. Web.config тэр хэсгийг сайн ойлговол гар код бичихэд хялбар байх болно. За амжилт

Sunday, August 7, 2011

ASP net mail send simple method

to is email@example.com
subj is hi or hello
obj is html or string

WebSites.SystemEmailSetting.Email бол зохиомол class ба myemail@gmail.com
чухал хэсэг нь доорх мөрөнд бий. gmail.com ийн өөрийнхөө account ийг ашиглан майл илгээхийн тулд нууц үгээ энд оруулна.Timeout aa шалгаад send. Миний жишээнд smtp.gmail.com майл гаргах порт нь 587 байна.

 new System.Net.NetworkCredential(WebSites.SystemEmailSetting.Email, WebSites.SystemEmailSetting.Password);

public static bool systemMailSend(string to, string subj, string obj)
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.To.Add(new System.Net.Mail.MailAddress(to));
            mail.From = new System.Net.Mail.MailAddress(WebSites.SystemEmailSetting.Email);
            mail.Subject = subj;
            mail.Body = obj;
            mail.IsBodyHtml = true;

            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Port = WebSites.SystemEmailSetting.Port;//587;//465;
            client.Host = WebSites.SystemEmailSetting.Host;//"smtp.gmail.com";//"smtp.googlemail.com";
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential(WebSites.SystemEmailSetting.Email, WebSites.SystemEmailSetting.Password);
            client.Timeout = 600000;//10min
            client.Send(mail);

            return true;
        }

Saturday, August 6, 2011

Jquery Selector with attribute description

Friday, August 5, 2011

ASP.NET MVC 2 project With Entityframework Model simple

ASP.NET MVC2 project үүсгээд доорхи кодыг Register.aspx дээр солиж тавиад ажиллуулаарай.
доорх код нь Jquery UI ашигласан хялбар $._DatePicker функц бичсэн байгаа ашиглахгүй байж болно гэхдээ энэ жишээн дээр DateTime төрлийн утгыг бас харуулж байгаа.
WebSiteRender ( Зохиомол Class ) програмчлалд хэрэгтэй WebSite ийн мэдээллийг агуулдаг.

<script type = "text/javascript">

 $(function() {
    $._DatePicker = function() {
        var method = null;
        var dformat = null;
        if (arguments.length == 3) {
            if (typeof arguments[2] == 'function') {
                method = arguments[2];
            } else {
                dformat = arguments[2];
            }
        }
        if (arguments.length == 4) {
            dformat = arguments[2];
            method = arguments[3];
        }
        if (arguments.length == 2 && typeof arguments[1] == 'function') {
            method = arguments[1];
        }

        $(arguments[0]).datepicker({
            showOn: "both",
            buttonImage: "<%: WebSiteRender.Current.FullName %>/Scripts/jquery/images/calendar.gif",
            buttonImageOnly: true,
            showOtherMonths: true,
            selectOtherMonths: true,
            changeMonth: true,
            changeYear: true,
            onSelect: method,
            dateFormat: dformat == null ? DEFAULT_DATE_FORMAT : dformat
        });
        //$("#" + $.datepicker._mainDivId).css("font-size", "77%");
        if (arguments.length == 2 && typeof arguments[1] == 'string') {
            $(arguments[0]).val(arguments[1]);
        }
        if (arguments.length == 3 && typeof arguments[1] == 'string') {
            $(arguments[0]).val(arguments[1]);
        }
    };
});
</script>



// RegisterModel class ийг бусдад хэрэг болох үүднээс жаахан өөрчилсөн байгаа
<%: Html.LabelFor(m => m.UserName) %> бичиглэл нь Inherits="System.Web.Mvc.ViewPage<RegisterModel>" %> кодтой холбоотой ба Тухайн хуудасны Өгөгдөл хадгалах Model class д утга олгогдсон өгөгдлийг CAST хийж
(Model==RegisterModel as m) гэсэн үг бөгөөд
Html.LabelFor(m => m.UserName) код нь моделийн талбарыг Html код болгоно.


Мөн 
<%: Html.DropDownListFor(m => m.SexType
                    , new SelectList(RegisterModel.SexTypes, "Value", "Text")
                    , "[ None ]") %>
код нь <select></select> html бичиглэл үүсгэх зорилготой функц юм.
RegisterModel.SexTypes нь анх Controller дуудагдах үед static member т утга оноосон олонлог.
m.SexType нь RegisterModel.SexTypes.Value утгыг авна.

Анх AccountController.Register() дуудагдахад RegisterModel нь null байна.
дарааа нь хадгалах үед Register(RegisterModel model) нь дүүргэгдэнэ.


Register.aspx

<%@ Page Language="C#" MasterPageFile="../Site.Master" Inherits="System.Web.Mvc.ViewPage<RegisterModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Register</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Create a New Account</h2>
    <p>
        Use the form below to create a new account.
    </p>
    <p>
        Passwords are required to be a minimum of <%: ViewData["PasswordLength"] %> characters in length.
    </p>

    <% using (Html.BeginForm()) { %>
        <%: Html.ValidationSummary(true, "Хадгалахад алдаа гарлаа!")
// Html.ValidationMessageFor(m => m.UserName) гэх мэт алдааны бусад мэдээлэл дээрх кодны доор (яг энд) харагдана
%>
        <div>
            <fieldset>
                <legend>Account Information</legend>
               
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.UserName) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.UserName) %>
                    <%: Html.ValidationMessageFor(m => m.UserName) %>
                </div>
               
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.Email) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.Email) %>
                    <%: Html.ValidationMessageFor(m => m.Email) %>
                </div>
               
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.Password) %>
                </div>
                <div class="editor-field">
                    <%: Html.PasswordFor(m => m.Password) %>
                    <%: Html.ValidationMessageFor(m => m.Password) %>
                </div>
               
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.ConfirmPassword) %>
                </div>
                <div class="editor-field">
                    <%: Html.PasswordFor(m => m.ConfirmPassword) %>
                    <%: Html.ValidationMessageFor(m => m.ConfirmPassword) %>
                </div>
               
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.LastName) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.LastName) %>
                    <%: Html.ValidationMessageFor(m => m.LastName) %>
                </div>
               
                <div class="editor-label">
                    <%: Html.LabelFor(m => m.FirstName) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.FirstName) %>
                    <%: Html.ValidationMessageFor(m => m.FirstName) %>
                </div>

                <div class="editor-label">
                    <%: Html.LabelFor(m => m.SexType) %>
                </div>
                <div class="editor-field">
                    <%: Html.DropDownListFor(m => m.SexType
                    , new SelectList(RegisterModel.SexTypes, "Value", "Text")
                    , "[ None ]") %>
                    <%: Html.ValidationMessageFor(m => m.SexType) %>
                </div>

                <div class="editor-label">
                    <%: Html.LabelFor(m => m.BirthDay) %>
                </div>
                <div class="editor-field">
                    <%: Html.TextBox("BirthDay", Model.BirthDay)%>
                    <%: Html.ValidationMessageFor(m => m.BirthDay) %>
                    <script type="text/javascript">
                        $(function () {
                            $._DatePicker("#BirthDay");
                        });
                        </script>
                </div>

                <p>
                    <input type="submit" value="Register" />
                </p>
            </fieldset>
        </div>
    <% } %>
</asp:Content>





Register(), Register(RegisterModel model) бичлэг нь <% using (Html.BeginForm()) { %> кодтой холбоотой ба анх хуудас дуудагдаж байхад model == null байх нь мэдээж учир Register() method ажиллаж, өгөгдөл хадгалах үед model == RegisterModel дүүргэгдэж Register(RegisterModel model) method дуудагдана. Хэрэв Register(RegisterModel model) оос өөр функц ажиллуулах бол Html.BeginForm("SaveUser", "AccountController", "POST") гэх мэтчилэн өөрчилж болно.



Миний хувьд Ria Service ( Domain Service Class  ) өгөгдөл ашигладаг учир түүнтэй зохицдог Хэрэглэгчийн нэвтрэхтэй холбоотой нууцлалыг хангах доорх AuthenticationService маягийн кодыг ашигласан байна


 AuthenticationDbContextHelper.cs


public class AuthenticationDbContextHelper
    {
        public static readonly AuthenticationDbContextHelper Current = new AuthenticationDbContextHelper();
      
        private MyDbContext db = new MyDbContext();
      
        private static readonly string RootEmail = "boroo_c@yahoo.com";
      


        public bool ValidateUser(string username, string password)
        {
            return this.db.UserInfoes.Any(u => u.Name == username && u.Password == password);
        }

        public bool ValidateUser(string email, string username, string password)
        {
            return this.db.UserInfoes.Any(u => u.Email == email && u.Name == username && u.Password == password);
        }

        public UserInfo GetUser()
        {
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                return this.GetUser(User.Identity.Name);
            }
            return null;
        }

        private UserInfo GetUser(string userName)
        {
            return this.db.UserInfoes.FirstOrDefault(u => u.Name == userName);
        }

        private UserInfo GetUser(string userName, string email)
        {
            return this.db.UserInfoes.FirstOrDefault(u => u.Name == userName && u.Email == email);
        }

        private UserInfo GetSingleUser(string email)
        {
            return this.db.UserInfoes.FirstOrDefault(u => u.Email == email);
        }

        private bool createRootUser(string email)
        {
            UserInfo root = new UserInfo();
            root.LastName = "";
            root.FirstName = "System User";
            root.Name = SystemConstants.DbSystemUser;
            root.Password = Util.STR(SystemConstants.DbPasswordMinLength);
            root.Email = email;
            root.BirthDay = new DateTime(1986, 4, 12);
            root.SexTypeCode = (short)SexTypeEnum.male;
            root.SiteId = 0;
            root.DbRoles = SystemConstants.DbSystemRole;
            root.IsActive = true;
            root.Modified = root.Created = DateTime.Now;
            root.ModifiedId = root.CreatedId = 0;
            root.ModifiedName = root.CreatedName = ".";

            this.db.UserInfoes.Add(root);
            this.db.SaveChanges();
            return true;
        }

        private void InitRoot()
        {
            if (!isCreatedRootUser())
            {
                createRootUser(RootEmail);
            }
        }

        public UserInfo Login(string userName, string password, bool isPersistent, string customData)
        {
            InitRoot();

            if (this.ValidateUser(userName, password))
            {
                UserInfo user = this.GetUser(userName);

                System.Web.HttpContext.Current.Session[SystemSessionKeys.UserId] = user.Id;
                System.Web.HttpContext.Current.Session[SystemSessionKeys.UserName] = user.Name;
                System.Web.HttpContext.Current.Session[SystemSessionKeys.UserEmail] = user.Email;
                System.Web.HttpContext.Current.Session[SystemSessionKeys.UserLastName] = user.LastName;
                System.Web.HttpContext.Current.Session[SystemSessionKeys.UserFirstName] = user.FirstName;
                System.Web.HttpContext.Current.Session[SystemSessionKeys.UserRole] = user.DbRoles;

                FormsAuthentication.SetAuthCookie(userName, isPersistent);
                return this.GetUser(userName);
            }
            return null;
        }

        public bool RegisterUser(string userData)
        {
            InitRoot();

            if (userData == null) return false;
            UserInfo user = Util.DeserializeX<UserInfo>(userData);

            if (isCreatedAnyUser(user.Name))
            {
                return false;
            }

            IQueryable<UserInfo> query = this.db.UserInfoes.Where(u => u.Name.Equals(user.Name));
            List<UserInfo> list = query.ToList<UserInfo>();
            if (list.Count > 0) return false;

            this.db.UserInfoes.Add(user);
            this.db.SaveChanges();
            return true;
        }

        public void UpdateUser(UserInfo user)
        {
            this.db.UserInfoes.Attach(user);
            this.db.SaveChanges();
        }

        public UserInfo Logout()
        {
            FormsAuthentication.SignOut();

            System.Web.HttpContext.Current.Session[SystemSessionKeys.UserId] = null;
            System.Web.HttpContext.Current.Session[SystemSessionKeys.UserName] = string.Empty;
            System.Web.HttpContext.Current.Session[SystemSessionKeys.UserEmail] = string.Empty;
            System.Web.HttpContext.Current.Session[SystemSessionKeys.UserLastName] = string.Empty;
            System.Web.HttpContext.Current.Session[SystemSessionKeys.UserFirstName] = string.Empty;
            System.Web.HttpContext.Current.Session[SystemSessionKeys.UserRole] = string.Empty;

            return null;
        }

        public bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            UserInfo user = GetUser(username);
            if (user.Password.Equals(oldPassword))
            {
                user.Password = newPassword;
                this.db.SaveChanges();
                return true;
            }
            return false;
        }

        public bool ResetPassword(string username, string email)
        {
            InitRoot();

            string sPassword = Util.STR(SystemConstants.DbPasswordMinLength);
            UserInfo user = null;
            try
            {
                user = GetUser(username, email);
            }
            catch { return false; }
            if (user != null)
            {
                user.Password = sPassword;
                this.db.SaveChanges();

                string body = string.Format(HtmlMailResources.ResetPassword, sPassword, WebSites.Current.FullName);
                if (user.Roles.Contains(SystemConstants.DbSystemRole))
                {
                    MailUtil.systemMailSend(email, WebSites.Current.Name, body);
                }
                else
                {
                    MailUtil.siteMailSend(email, WebSites.Current.Name, body, null);
                }

                return true;
            }
            return false;
        }

        public bool isCreatedAnyUser(string userName)
        {
            return this.db.UserInfoes.Any(u => u.Name == userName && u.SiteId == WebSites.Current.Id);
        }

        public bool isCreatedRootUser()
        {
            return this.db.UserInfoes.Any(u => u.Name == SystemConstants.DbSystemUser && u.SiteId == WebSites.Current.Id);
        }
    }
AccountController.cs
 
AuthenticationDbContextHelper _auth;
//// **************************************
        //// URL: /Account/Register
        //// **************************************

        public ActionResult Register()
        {
            Model.MetaTitle = "Register";
            ViewData["PasswordLength"] = 6;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                UserInfo userInfo = new UserInfo();
                userInfo.Name = model.UserName;
                userInfo.Password = model.Password;
                userInfo.Email = model.Email;
                userInfo.FirstName = model.FirstName;
                userInfo.LastName = model.LastName;
                userInfo.BirthDay = model.BirthDay;
                SexTypeEnum ste = (SexTypeEnum)Enum.Parse(typeof(SexTypeEnum), model.SexType);
                userInfo.SexTypeCode = (short)ste;
                userInfo.Roles = new List<string>();
                userInfo.IsActive = 0;
                FillRequiredFields_Date6_SiteId(userInfo);

                string userData = DataManager.SerializeX(userInfo);
                if (_auth.RegisterUser(userData))
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "error");
                    //AccountValidation.ErrorCodeToString(createStatus)
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = 6;
            return View(model);
        }