The simplest way to create hosted apps across platforms and devices GitHub
Rust – the Ultimate Programming Language?
What makes a good programming language? Syntax? Compiler? Tools and ecosystem? It is tempting to say “all of that” but in that case, why there are so many different programming languages? All these components are very important but they alone can’t make the language “good”. One of essential things is the purpose — like languages for rapid development, or development of distributed algorithms, or general purpose for high-level and low-level applications, or easy to learn, or safe to use and so on.
زمانی که درخواستی به سمت یک Action پارامتر دار ارسال میشود، قسمت ActionInvoker قبل از فراخوانی اکشن مربوطه، به دنبال Model Binder مناسبی برای دادههای پارامترها میگردد و در صورت یافت نشدن، از ModelBinder پیش فرض ASP.NET MVC استفاده میکند.
اما وظیفهی ModelBinder چیست ؟
ModelBinder دادههای ارسال شده از مرورگر را که توسط درخواستهای HTTP (کوئری استرینگها و یا دادههای همراه با فرمها ) ارسال شده است، تبدیل به دادههای قابل فهم برای پارامترها میکند.
به عبارتی ModelBinder وظیفه تبدیل دادههای ارسال شده از سمت مرورگر به اشیاء NET. را دارد.
فرض کنید ما مدلی به شکل زیر داریم :
public class CustomerInfo { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } }
فیلد آخر برای ذخیرهی تاریخ تولد مشتری استفاده میشود. که View مربوط به آن به شکل زیر خواهد بود :
همانطور که میبینید تایپ کردن تاریخ به این صورت (1/1/2009 12:00:00 AM) ، هم زیاد جالب نیست و هم کمی مشکل است. به همین دلیل برخی سایتها از سه قسمت جدا برای گرفتن روز ، ماه و سال استفاده میکنند و در نهایت آنها را با یکدیگر ترکیب میکنند.
در این مثال ما نیز میخواهیم تاریخ را به صورت زیر دریافت و پس از تبدیل آن به تاریخ میلادی، آن را به کاربر نمایش دهیم :
اما هنگام ارسال فرم به صورت بالا ، ModelBinder توانایی تبدیل این سه ورودی (روز ، ماه و سال) به فیلد BirthDate موجود در کلاس CustomerInfo را ندارد. به همین خاطر ما باید یک ModelBinder متناسب با نیاز خود را طراحی کنیم.
برای ایجاد یک ModelBinder سفارشی نیاز است که از کلاس IModelBinder ارثبری و متد BindModel آن را پیاده سازی کنیم.
ساختار این اینترفیس به شکل زیر است :
public interface IModelBinder { object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext); }
متد BindModel حاوی 2 پارامتر است :
ControllerContext : حاوی اطلاعاتی در مورد درخواست http جاری
ModelBindingContext : این کلاس حاوی یک property به نام Model است که حاوی ارجاعی به مدلی که همکنون قصد پردازشش آن را دارد.
با توجه به موارد بالا کلاس ما به شکل زیر خواهد بود :
using System; using System.Web; using System.Web.Mvc; using ModelBinderExample.Models; using Persia; namespace ModelBinderExample.CustomModelBinder { // Article written for www.dotnettips.info public class CustomerInfoModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { HttpRequestBase request = controllerContext.HttpContext.Request; string firstName = request.Form.Get("FirstName"); string lastName = request.Form.Get("LastName"); DateTime birthDate = this.GetMiladiDate(request); return new CustomerInfo() { FirstName = firstName, LastName = lastName, BirthDate = birthDate }; } private DateTime GetMiladiDate(HttpRequestBase request) { int day = int.Parse(request.Form.Get("Day")); int month = int.Parse(request.Form.Get("Month")); int years = int.Parse(request.Form.Get("Years")); //Convert shamsi to miladi return Persia.Calendar.ConvertToGregorian(years, month, day, DateType.Gerigorian); } } }
در کد بالا ایتدا موارد ارسال شده را دریافت میکنیم و توسط متد ()GetMiladiDate تاریخ دریافتی از کاربر که به صورت روز، ماه و سال میباشد را تبدیل به میلادی میکنیم و سپس در قالب یک شی customerInfo آنها را برگشت میدهیم.
نکته : جهت تبدیل تاریخ شمسی به میلادی از کتابخانهی Persia کمک گرفته شده است که در فایل پیوستی قرار داده شده.
کار ایجاد یک ModelBinder سفارشی تمام شده و حال نیاز است کلاس را در فایل Global.asax در قسمت ()Application_start ثبت کنیم به شکل زیر :
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //Register New ModelBinder ModelBinders.Binders.Add(typeof(CustomerInfo), new CustomerInfoModelBinder()); }
و برای استفاده از این ModelBinder ، ما باید به کنترلر اطلاع دهیم که میخواهیم از چه نوع Binding استفاده کنیم به همین دلیل از attribute زیر برای انجام این کار استفاده میکنیم:
[HttpPost] public ActionResult Create([ModelBinder(typeof (CustomerInfoModelBinder))] CustomerInfo customerInfo) { if (ModelState.IsValid) { ViewBag.FirstName = customerInfo.FirstName; ViewBag.LastName = customerInfo.LastName; ViewBag.BirthDate = customerInfo.BirthDate; } return View(); }
پروژه پیوستی : ModelBinder-Example.zip
نظرات مطالب
سری آموزشی PRISM
Mike Taulty آدم خیلی فعالی در این زمینه هستش ، من خیلی پادکست ازش دیدم در همه زمینه ها ، و از شما هم بابت لینک مفیدتون نهایت تشکر رو دارم ، به امید موفقیت روزافزون شما ، من یکی از خواننده گان ثابت وبلاگ شما هستم!
اشتراکها
Live Charts برای WPF
اشتراکها
Cheatsheet سیستم GIT
- Validate arguments from events.
- Validate inputs and results from JS interop calls.
- Avoid using (or validate beforehand) user input for .NET to JS interop calls.
- Prevent the client from allocating an unbound amount of memory.
- Data within the component.
-
DotNetObject
references returned to the client. - Guard against multiple dispatches.
- Cancel long-running operations when the component is disposed.
- Avoid events that produce large amounts of data.
- Avoid using user input as part of calls to NavigationManager.NavigateTo and validate user input for URLs against a set of allowed origins first if unavoidable.
- Don't make authorization decisions based on the state of the UI but only from component state.
- Consider using Content Security Policy (CSP) to protect against XSS attacks.
- Consider using CSP and X-Frame-Options to protect against click-jacking.
- Ensure CORS settings are appropriate when enabling CORS or explicitly disable CORS for Blazor apps.
- Test to ensure that the server-side limits for the Blazor app provide an acceptable user experience without unacceptable levels of risk.
قبل شروع این قسمت بد نیست با یک سری از وبلاگهای اعضای تیم Oslo آشنا شویم:
در ادامهی مثال قسمت قبل، اکنون میخواهیم entity جدیدی به نام Project را به مدل اضافه کنیم:
//mschema to define a Project type
type Project
{
ProjectID : Integer64 = AutoNumber();
ProjectName : Text#25;
ConectionStringSource : Text;
ConectionStringDestination : Text;
DateCompared: DateTime;
Comment: Text?;
ProjectOwner: ApplicationUser;
} where identity ProjectID;
//this will define a SQL foreign key relationship
ProjectCollection : Project* where item.ProjectOwner in ApplicationUserCollection;
set xact_abort on;
go
begin transaction;
go
set ansi_nulls on;
go
create schema [Test1];
go
create table [Test1].[ApplicationUserCollection]
(
[UserID] bigint not null identity,
[FirstName] nvarchar(max) null,
[LastName] nvarchar(25) not null,
[Password] nvarchar(10) not null,
constraint [PK_ApplicationUserCollection] primary key clustered ([UserID])
);
go
create table [Test1].[ProjectCollection]
(
[ProjectID] bigint not null identity,
[Comment] nvarchar(max) null,
[ConectionStringDestination] nvarchar(max) not null,
[ConectionStringSource] nvarchar(max) not null,
[DateCompared] datetime2 not null,
[ProjectName] nvarchar(25) not null,
[ProjectOwner] bigint not null,
constraint [PK_ProjectCollection] primary key clustered ([ProjectID]),
constraint [FK_ProjectCollection_ProjectOwner_Test1_ApplicationUserCollection] foreign key ([ProjectOwner]) references [Test1].[ApplicationUserCollection] ([UserID])
);
go
insert into [Test1].[ApplicationUserCollection] ([FirstName], [LastName], [Password])
values (N'user1', N'name1', N'1@34')
;
insert into [Test1].[ApplicationUserCollection] ([FirstName], [LastName], [Password])
values (N'user2', N'name2', N'123@4')
;
insert into [Test1].[ApplicationUserCollection] ([FirstName], [LastName], [Password])
values (N'user3', N'name3', N'56#2')
;
insert into [Test1].[ApplicationUserCollection] ([FirstName], [LastName], [Password])
values (N'user4', N'name4', N'789@5')
;
go
commit transaction;
Go
نکته:
جهت آشنایی با انواع دادههای مجاز در زبان M میتوان به مستندات رسمی آن مراجعه نمود:
The "Oslo" Modeling Language Specification
اکنون قصد داریم همانند مثال قسمت قبل، تعدادی رکورد آزمایشی را برای این جدول تعریف کنیم:
ProjectCollection
{
Project1{
ProjectName = "My Project 1",
ConectionStringSource = "Data Source=.;Initial Catalog=MyDB1;Integrated Security=True;",
ConectionStringDestination = "Data Source=.;Initial Catalog=MyDB2;Integrated Security=True;",
Comment="Project Comment",
DateCompared=2009-01-01T00:00:00,
ProjectOwner=ApplicationUserCollection.User1 //direct ref to User1 (FK)
},
Project2{
ProjectName = "My Project 2",
ConectionStringSource = "Data Source=.;Initial Catalog=MyDB1;Integrated Security=True;",
ConectionStringDestination = "Data Source=.;Initial Catalog=MyDB2;Integrated Security=True;",
Comment="Project Comment",
DateCompared=2009-01-01T00:00:00,
ProjectOwner=ApplicationUserCollection.User2 //direct ref to User2 (FK)
}
}
ادامه دارد ...