برای برسی بیشتر لطفا کد قسمت کانفیگ Mapping و همچنین کلاسهاتون رو بنویسید.
ویژگی های پیشرفته ی AutoMapper - قسمت دوم
برای برسی بیشتر لطفا کد قسمت کانفیگ Mapping و همچنین کلاسهاتون رو بنویسید.
var dataTable = new DataTable("SalaryList"); dataTable.Columns.Add("User", typeof (string)); dataTable.Columns.Add("Month", typeof (int)); dataTable.Columns.Add("Salary", typeof (decimal)); var rnd = new Random(); for (var i = 0; i < 200; i++) dataTable.Rows.Add("User " + i, rnd.Next(1, 12), rnd.Next(400, 2000));
public class SalaryList { public string User { set; get; } public int Month { set; get; } public decimal Salary { set; get; } }
var salaryList = AutoMapper.Mapper.DynamicMap<IDataReader, List<SalaryList>>(dataTable.CreateDataReader());
var anonymousObject = new { User = "User 1", Month = 1, Salary = 100000 }; var salary = Mapper.DynamicMap<SalaryList>(anonymousObject);
var anonymousList = new[] { new { User = "User 1", Month = 1, Salary = 100000 }, new { User = "User 2", Month = 1, Salary = 300000 } }; var salaryList = anonymousList.Select(item => Mapper.DynamicMap<SalaryList>(item)).ToList();
public interface ICustomerService { string Code { get; set; } string Name { get; set; } }
var anonymousObject = new { Code = "111", Name = "Test 1" }; var result = Mapper.DynamicMap<ICustomerService>(anonymousObject);
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Web.Mvc; using System.Web.Security; namespace OpenIDExample.Models { #region Models public class ChangePasswordModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [ValidatePasswordLength] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class LogOnModel { [Display(Name = "OpenID")] public string OpenID { get; set; } [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterModel { [Display(Name = "OpenID")] public string OpenID { get; set; } [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [ValidatePasswordLength] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } #endregion Models #region Services // The FormsAuthentication type is sealed and contains static members, so it is difficult to // unit test code that calls its members. The interface and helper class below demonstrate // how to create an abstract wrapper around such a type in order to make the AccountController // code unit testable. public interface IMembershipService { int MinPasswordLength { get; } bool ValidateUser(string userName, string password); MembershipCreateStatus CreateUser(string userName, string password, string email, string OpenID); bool ChangePassword(string userName, string oldPassword, string newPassword); MembershipUser GetUser(string OpenID); } public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } public AccountMembershipService(MembershipProvider provider) { _provider = provider ?? Membership.Provider; } public int MinPasswordLength { get { return _provider.MinRequiredPasswordLength; } } public bool ValidateUser(string userName, string password) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password"); return _provider.ValidateUser(userName, password); } public Guid StringToGUID(string value) { // Create a new instance of the MD5CryptoServiceProvider object. MD5 md5Hasher = MD5.Create(); // Convert the input string to a byte array and compute the hash. byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value)); return new Guid(data); } public MembershipCreateStatus CreateUser(string userName, string password, string email, string OpenID) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password"); if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email"); MembershipCreateStatus status; _provider.CreateUser(userName, password, email, null, null, true, StringToGUID(OpenID), out status); return status; } public MembershipUser GetUser(string OpenID) { return _provider.GetUser(StringToGUID(OpenID), true); } public bool ChangePassword(string userName, string oldPassword, string newPassword) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword"); if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword"); // The underlying ChangePassword() will throw an exception rather // than return false in certain failure scenarios. try { MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */); return currentUser.ChangePassword(oldPassword, newPassword); } catch (ArgumentException) { return false; } catch (MembershipPasswordException) { return false; } } public MembershipCreateStatus CreateUser(string userName, string password, string email) { throw new NotImplementedException(); } } public interface IFormsAuthenticationService { void SignIn(string userName, bool createPersistentCookie); void SignOut(); } public class FormsAuthenticationService : IFormsAuthenticationService { public void SignIn(string userName, bool createPersistentCookie) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } public void SignOut() { FormsAuthentication.SignOut(); } } #endregion Services #region Validation public static class AccountValidation { public static string ErrorCodeToString(MembershipCreateStatus createStatus) { // See http://go.microsoft.com/fwlink/?LinkID=177550 for // a full list of status codes. switch (createStatus) { case MembershipCreateStatus.DuplicateUserName: return "Username already exists. Please enter a different user name."; case MembershipCreateStatus.DuplicateEmail: return "A username for that e-mail address already exists. Please enter a different e-mail address."; case MembershipCreateStatus.InvalidPassword: return "The password provided is invalid. Please enter a valid password value."; case MembershipCreateStatus.InvalidEmail: return "The e-mail address provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidAnswer: return "The password retrieval answer provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidQuestion: return "The password retrieval question provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidUserName: return "The user name provided is invalid. Please check the value and try again."; case MembershipCreateStatus.ProviderError: return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; case MembershipCreateStatus.UserRejected: return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; default: return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; } } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable { private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long."; private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength; public ValidatePasswordLengthAttribute() : base(_defaultErrorMessage) { } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _minCharacters); } public override bool IsValid(object value) { string valueAsString = value as string; return (valueAsString != null && valueAsString.Length >= _minCharacters); } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { return new[]{ new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue) }; } } #endregion Validation }
using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; using OpenIDExample.Models; namespace OpenIDExample.Controllers { public class AccountController : Controller { private static OpenIdRelyingParty openid = new OpenIdRelyingParty(); public IFormsAuthenticationService FormsService { get; set; } public IMembershipService MembershipService { get; set; } protected override void Initialize(RequestContext requestContext) { if (FormsService == null) { FormsService = new FormsAuthenticationService(); } if (MembershipService == null) { MembershipService = new AccountMembershipService(); } base.Initialize(requestContext); } // ************************************** // URL: /Account/LogOn // ************************************** public ActionResult LogOn() { return View(); } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { FormsService.SignIn(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); } // ************************************** // URL: /Account/LogOff // ************************************** public ActionResult LogOff() { FormsService.SignOut(); return RedirectToAction("Index", "Home"); } // ************************************** // URL: /Account/Register // ************************************** public ActionResult Register(string OpenID) { ViewBag.PasswordLength = MembershipService.MinPasswordLength; ViewBag.OpenID = OpenID; return View(); } [HttpPost] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.OpenID); if (createStatus == MembershipCreateStatus.Success) { FormsService.SignIn(model.UserName, false /* createPersistentCookie */); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form ViewBag.PasswordLength = MembershipService.MinPasswordLength; return View(model); } // ************************************** // URL: /Account/ChangePassword // ************************************** [Authorize] public ActionResult ChangePassword() { ViewBag.PasswordLength = MembershipService.MinPasswordLength; return View(); } [Authorize] [HttpPost] public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form ViewBag.PasswordLength = MembershipService.MinPasswordLength; return View(model); } // ************************************** // URL: /Account/ChangePasswordSuccess // ************************************** public ActionResult ChangePasswordSuccess() { return View(); } [ValidateInput(false)] public ActionResult Authenticate(string returnUrl) { var response = openid.GetResponse(); if (response == null) { //Let us submit the request to OpenID provider Identifier id; if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) { try { var request = openid.CreateRequest(Request.Form["openid_identifier"]); return request.RedirectingResponse.AsActionResult(); } catch (ProtocolException ex) { ViewBag.Message = ex.Message; return View("LogOn"); } } ViewBag.Message = "Invalid identifier"; return View("LogOn"); } //Let us check the response switch (response.Status) { case AuthenticationStatus.Authenticated: LogOnModel lm = new LogOnModel(); lm.OpenID = response.ClaimedIdentifier; //check if user exist MembershipUser user = MembershipService.GetUser(lm.OpenID); if (user != null) { lm.UserName = user.UserName; FormsService.SignIn(user.UserName, false); } return View("LogOn", lm); case AuthenticationStatus.Canceled: ViewBag.Message = "Canceled at provider"; return View("LogOn"); case AuthenticationStatus.Failed: ViewBag.Message = response.Exception.Message; return View("LogOn"); } return new EmptyResult(); } } }
@model OpenIDExample.Models.LogOnModel @{ ViewBag.Title = "Log On"; } <h2> Log On</h2> <p> Please enter your username and password. @Html.ActionLink("Register", "Register") if you don't have an account. </p> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <form action="Authenticate?ReturnUrl=@HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"])" method="post" id="openid_form"> <input type="hidden" name="action" value="verify" /> <div> <fieldset> <legend>Login using OpenID</legend> <div class="openid_choice"> <p> Please click your account provider:</p> <div id="openid_btns"> </div> </div> <div id="openid_input_area"> @Html.TextBox("openid_identifier") <input type="submit" value="Log On" /> </div> <noscript> <p> OpenID is service that allows you to log-on to many different websites using a single indentity. Find out <a href="http://openid.net/what/">more about OpenID</a> and <a href="http://openid.net/get/">how to get an OpenID enabled account</a>.</p> </noscript> <div> @if (Model != null) { if (String.IsNullOrEmpty(Model.UserName)) { <div class="editor-label"> @Html.LabelFor(model => model.OpenID) </div> <div class="editor-field"> @Html.DisplayFor(model => model.OpenID) </div> <p class="button"> @Html.ActionLink("New User ,Register", "Register", new { OpenID = Model.OpenID }) </p> } else { //user exist <p class="buttonGreen"> <a href="@Url.Action("Index", "Home")">Welcome , @Model.UserName, Continue..." </a> </p> } } </div> </fieldset> </div> </form> @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") @using (Html.BeginForm()) { <div> <fieldset> <legend>Or Login Normally</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.Password) </div> <div class="editor-field"> @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password) </div> <div class="editor-label"> @Html.CheckBoxFor(m => m.RememberMe) @Html.LabelFor(m => m.RememberMe) </div> <p> <input type="submit" value="Log On" /> </p> </fieldset> </div> }
<authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication>
با سلام و احترام
ممنون از پاسخ شما
این تست کرده بودم میتونید خالی نبودن متغیر فوق ببینید اینم فیلدهای اصلی این کلاس
#region Properties /// <summary> /// Gets or sets the product variant identifier /// </summary> public int ProductVariantId { get; set; } /// <summary> /// Gets or sets the product identifier /// </summary> public int ProductId { get; set; } /// <summary> /// Gets or sets the name /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the SKU /// </summary> public string SKU { get; set; } /// <summary> /// Gets or sets the description /// </summary> public string Description { get; set; } /// <summary> /// Gets or sets the admin comment /// </summary> public string AdminComment { get; set; } /// <summary> /// Gets or sets the manufacturer part number /// </summary> public string ManufacturerPartNumber { get; set; } /// <summary> /// Gets or sets a value indicating whether the product variant is gift card /// </summary> public bool IsGiftCard { get; set; } /// <summary> /// Gets or sets the gift card type /// </summary> public int GiftCardType { get; set; } /// <summary> /// Gets or sets a value indicating whether the product variant is download /// </summary> public bool IsDownload { get; set; } /// <summary> /// Gets or sets the download identifier /// </summary> public int DownloadId { get; set; } /// <summary> /// Gets or sets a value indicating whether this downloadable product can be downloaded unlimited number of times /// </summary> public bool UnlimitedDownloads { get; set; } /// <summary> /// Gets or sets the maximum number of downloads /// </summary> public int MaxNumberOfDownloads { get; set; } /// <summary> /// Gets or sets the number of days during customers keeps access to the file. /// </summary> public int? DownloadExpirationDays { get; set; } /// <summary> /// Gets or sets the download activation type /// </summary> public int DownloadActivationType { get; set; } /// <summary> /// Gets or sets a value indicating whether the product variant has a sample download file /// </summary> public bool HasSampleDownload { get; set; } /// <summary> /// Gets or sets the sample download identifier /// </summary> public int SampleDownloadId { get; set; } /// <summary> /// Gets or sets a value indicating whether the product has user agreement /// </summary> public bool HasUserAgreement { get; set; } /// <summary> /// Gets or sets the text of license agreement /// </summary> public string UserAgreementText { get; set; } /// <summary> /// Gets or sets a value indicating whether the product variant is recurring /// </summary> public bool IsRecurring { get; set; } /// <summary> /// Gets or sets the cycle length /// </summary> public int CycleLength { get; set; } /// <summary> /// Gets or sets the cycle period /// </summary> public int CyclePeriod { get; set; } /// <summary> /// Gets or sets the total cycles /// </summary> public int TotalCycles { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity is ship enabled /// </summary> public bool IsShipEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity is free shipping /// </summary> public bool IsFreeShipping { get; set; } /// <summary> /// Gets or sets the additional shipping charge /// </summary> public decimal AdditionalShippingCharge { get; set; } /// <summary> /// Gets or sets a value indicating whether the product variant is marked as tax exempt /// </summary> public bool IsTaxExempt { get; set; } /// <summary> /// Gets or sets the tax category identifier /// </summary> public int TaxCategoryId { get; set; } /// <summary> /// Gets or sets a value indicating how to manage inventory /// </summary> public int ManageInventory { get; set; } /// <summary> /// Gets or sets the stock quantity /// </summary> public int StockQuantity { get; set; } /// <summary> /// Gets or sets a value indicating whether to display stock availability /// </summary> public bool DisplayStockAvailability { get; set; } /// <summary> /// Gets or sets a value indicating whether to display stock quantity /// </summary> public bool DisplayStockQuantity { get; set; } /// <summary> /// Gets or sets the minimum stock quantity /// </summary> public int MinStockQuantity { get; set; } /// <summary> /// Gets or sets the low stock activity identifier /// </summary> public int LowStockActivityId { get; set; } /// <summary> /// Gets or sets the quantity when admin should be notified /// </summary> public int NotifyAdminForQuantityBelow { get; set; } /// <summary> /// Gets or sets a value indicating whether to allow orders when out of stock /// </summary> public int Backorders { get; set; } /// <summary> /// Gets or sets the order minimum quantity /// </summary> public int OrderMinimumQuantity { get; set; } /// <summary> /// Gets or sets the order maximum quantity /// </summary> public int OrderMaximumQuantity { get; set; } /// <summary> /// Gets or sets the warehouse identifier /// </summary> public int WarehouseId { get; set; } /// <summary> /// Gets or sets a value indicating whether to disable buy button /// </summary> public bool DisableBuyButton { get; set; } /// <summary> /// Gets or sets a value indicating whether to show "Call for Pricing" or "Call for quote" instead of price /// </summary> public bool CallForPrice { get; set; } /// <summary> /// Gets or sets the price /// </summary> public decimal Price { get; set; } /// <summary> /// Gets or sets the old price /// </summary> public decimal OldPrice { get; set; } /// <summary> /// Gets or sets the product cost /// </summary> public decimal ProductCost { get; set; } /// <summary> /// Gets or sets a value indicating whether a customer enters price /// </summary> public bool CustomerEntersPrice { get; set; } /// <summary> /// Gets or sets the minimum price entered by a customer /// </summary> public decimal MinimumCustomerEnteredPrice { get; set; } /// <summary> /// Gets or sets the maximum price entered by a customer /// </summary> public decimal MaximumCustomerEnteredPrice { get; set; } /// <summary> /// Gets or sets the weight /// </summary> public decimal Weight { get; set; } /// <summary> /// Gets or sets the length /// </summary> public decimal Length { get; set; } /// <summary> /// Gets or sets the width /// </summary> public decimal Width { get; set; } /// <summary> /// Gets or sets the height /// </summary> public decimal Height { get; set; } /// <summary> /// Gets or sets the picture identifier /// </summary> public int PictureId { get; set; } /// <summary> /// Gets or sets the available start date and time /// </summary> public DateTime? AvailableStartDateTime { get; set; } /// <summary> /// Gets or sets the shipped end date and time /// </summary> public DateTime? AvailableEndDateTime { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity is published /// </summary> public bool Published { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity has been deleted /// </summary> public bool Deleted { get; set; } /// <summary> /// Gets or sets the display order /// </summary> public int DisplayOrder { get; set; } /// <summary> /// Gets or sets the date and time of instance creation /// </summary> public DateTime CreatedOn { get; set; } /// <summary> /// Gets or sets the date and time of instance update /// </summary> public DateTime UpdatedOn { get; set; } /// <summary> /// Gets or sets CouponCreated /// </summary> public bool? CouponetCreated { get; set; } /// <summary> /// Gets or sets the date and time of CouponCreated /// </summary> public DateTime? CouponetCreatedOn { get; set; } #endregion
یک نکتهی تکمیلی: روش طراحی binding دو طرفه در Blazor SSR
در نکتهی قبل عنوان شد که مقدمات طراحی binding دو طرفه، داشتن حداقل سه خاصیت زیر در یک کامپوننت سفارشی است:
[Parameter] public T? Value { set; get; } [Parameter] public EventCallback<T?> ValueChanged { get; set; } [Parameter] public Expression<Func<T?>> ValueExpression { get; set; } = default!;
اگر این خواص را به کامپوننتهای توکار خود Blazor متصل کنیم (مانند InputBox آن و مابقی آنها)، نیازی به کدنویسی بیشتری ندارند و کار میکنند. اما اگر قرار است از یک input سادهی Html ای استفاده کنیم، نیاز است ValueChanged آنرا اینبار در متد OnInitialized فراخوانی کنیم؛ چون در زمان post-back به سرور است که مقدار آن در اختیار مصرف کنندهی کامپوننت قرار میگیرد. این مورد، مهمترین تفاوت نحوهی طراحی binding دوطرفه در Blazor SSR با مابقی حالات و نگارشهای Blazor است.
بررسی وقوع post-back به سرور به دو روش زیر میسر است:
الف) بررسی کنیم که آیا HttpPost ای رخدادهاست؟ سپس در همین لحظه، متد ValueChanged.InvokeAsync را فراخوانی کنیم:
[CascadingParameter] internal HttpContext HttpContext { set; get; } = null!; protected override void OnInitialized() { base.OnInitialized(); if (HttpContext.IsPostRequest()) { SetValueCallback(Value); } } private void SetValueCallback(string value) { if (!ValueChanged.HasDelegate) { return; } _ = ValueChanged.InvokeAsync(value); }
در این مثال نحوهی فعالسازی ارسال اطلاعات از یک کامپوننت سفارشی را به مصرف کنندهی آن ملاحظه میکنید. اینکار در قسمت OnInitialized و فقط در صورت ارسال اطلاعات به سمت سرور، فعال خواهد شد.
ب) میتوان در قسمت OnInitialized، بررسی کرد که آیا درخواست جاری به همراه اطلاعات یک فرم ارسال شدهی به سمت سرور است یا خیر؟ روش کار به صورت زیر است:
protected override void OnInitialized() { base.OnInitialized(); if (HttpContext.Request.HasFormContentType && HttpContext.Request.Form.TryGetValue(ValueField.HtmlFieldName, out var data)) { SetValueCallback(data.ToString()); } }
در اینجا از ValueField.HtmlFieldName که در نکتهی قبلی معرفی BlazorHtmlField به آن اشاره شد، جهت یافتن نام واقعی فیلد ورودی، استفاده شدهاست.
public static class IoCWrapper { public static void RunAndDispose(Action action) { try { action(); } finally { // اگر در درخواست وب بودیم، به صورت خودکار در پایان کار همه چیز تمام میشود if (!HttpContextLifecycle.HasContext()) { new HybridLifecycle().FindCache(null).DisposeAndClear(); } } } public static T GetInstance<T>() { return SmObjectFactory.Container.GetInstance<T>(); } }
public override void Run() { IoCWrapper.RunAndDispose(() => { var draftsService = IoCWrapper.GetInstance<IBlogPostDraftsService>(); draftsService.RunConvertDraftsToPostsJob(); }); }