Admin/CountryController.cs
using HiimelOyun.Core.Domain.Directory;
using HiimelOyun.Core.Infrastructure;
using HiimelOyun.Framework.Controllers;
using HiimelOyun.Services.Common;
using HiimelOyun.Services.Directory;
using HiimelOyun.Services.Localization;
using HiimelOyun.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using HiimelOyun.Core;
using HiimelOyun.Admin.Models.Directory;
using HiimelOyun.Core.Domain.Common;
namespace HiimelOyun.Admin.Controllers
{
[BorAdminAuthorize]
public class CountryController : BaseAdminController
{
private readonly ICountryManager _countryManager;
private readonly IStateProvinceManager _stateProvinceManager;
private readonly ILocalizationManager _localizationManager;
private readonly IAddressManager _addressManager;
private readonly ILocalizedEntityManager _localizedEntityManager;
private readonly ILanguageManager _languageManager;
private readonly AdminAreaSettingModel _adminAreaSettings;
public CountryController()
{
IEngine engine = EngineContext.Current;
_countryManager = engine.Resolve<ICountryManager>();
_stateProvinceManager = engine.Resolve<IStateProvinceManager>();
_localizationManager = engine.Resolve<ILocalizationManager>();
_addressManager = engine.Resolve<IAddressManager>();
_localizedEntityManager = engine.Resolve<ILocalizedEntityManager>();
_languageManager = engine.Resolve<ILanguageManager>();
_adminAreaSettings = engine.ResolveSettings<AdminAreaSettingModel>();
}
public ActionResult Index()
{
return View();
}
#region Countries
public ActionResult List()
{
ViewBag.AdminAreaSettings = _adminAreaSettings;
var countries = _countryManager.GetAllCountries(true);
var model = new GridModel<CountryInfo>
{
Data = countries.ToList(),
Total = countries.Count
};
return View(model);
}
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult CountryList(GridCommand command)
{
var countries = _countryManager.GetAllCountries(true);
var model = new GridModel<CountryInfo>
{
Data = countries.ToList(),
Total = countries.Count
};
return new JsonResult
{
Data = model
};
}
public ActionResult Create()
{
return View();
}
[HttpPost, ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
public ActionResult Create(CountryInfo country, bool continueEditing)
{
if (ModelState.IsValid)
{
_countryManager.InsertCountry(country);
SuccessNotification("Амжилттай хадгаллаа!");
return continueEditing ? RedirectToAction("Edit", new { id = country.Id }) : RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
return View(country);
}
public ActionResult Edit(int id)
{
var country = _countryManager.GetCountryById(id);
if (country == null) return RedirectToAction("List");
return View(country);
}
[HttpPost, ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
public ActionResult Edit(int id, FormCollection form, bool continueEditing)
{
var country = _countryManager.GetCountryById(id);
if (TryUpdateModel(country))
{
if (ModelState.IsValid)
{
_countryManager.UpdateCountry(country);
SuccessNotification("Амжилттай засварлалаа!");
return continueEditing ? RedirectToAction("Edit", new { id = country.Id }) : RedirectToAction("List");
}
}
return View(country);
}
[HttpPost]
public ActionResult Delete(int id)
{
var country = _countryManager.GetCountryById(id);
if (country == null) return RedirectToAction("List");
try
{
if (_addressManager.GetAddressTotalByCountryId(country.Id) > 0)
throw new BorException("The country can't be deleted. It has associated addresses");
_countryManager.DeleteCountry(country);
SuccessNotification(string.Format("{0} дугаартай мэдээлэл утслаа!", id));
return RedirectToAction("List");
}
catch (Exception exc)
{
ErrorNotification(exc);
return RedirectToAction("Edit", new { id = country.Id });
}
}
#endregion
#region States / provinces
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult States(int countryId, GridCommand command)
{
var states = _stateProvinceManager.GetStateProvincesByCountryId(countryId, true);
var model = new GridModel<StateProvinceInfo>
{
Data = states.ToList(),
Total = states.Count()
};
return new JsonResult
{
Data = model
};
}
//create
public ActionResult StateCreatePopup(int countryId)
{
var model = new StateProvinceModel();
model.CountryId = countryId;
return View(model);
}
[HttpPost]
public ActionResult StateCreatePopup(string btnId, string formId, StateProvinceModel model)
{
var country = _countryManager.GetCountryById(model.CountryId);
if (country == null) return RedirectToAction("List");
if (ModelState.IsValid)
{
var stateProvince = model.ToEntity<StateProvinceInfo>();
_stateProvinceManager.InsertStateProvince(stateProvince);
ViewBag.RefreshPage = true;
ViewBag.btnId = btnId;
ViewBag.formId = formId;
return View(model);
}
return View(model);
}
//edit
public ActionResult StateEditPopup(int id)
{
var stateProvince = _stateProvinceManager.GetStateProvinceById(id);
if (stateProvince == null) return RedirectToAction("List");
var model = stateProvince.ToModel<StateProvinceModel>();
return View(model);
}
[HttpPost]
public ActionResult StateEditPopup(string btnId, string formId, StateProvinceModel model)
{
var stateProvince = _stateProvinceManager.GetStateProvinceById(model.Id);
if (stateProvince == null) return RedirectToAction("List");
if (TryUpdateModel(stateProvince))
{
if (ModelState.IsValid)
{
_stateProvinceManager.UpdateStateProvince(stateProvince);
ViewBag.RefreshPage = true;
ViewBag.btnId = btnId;
ViewBag.formId = formId;
return View(model);
}
}
return View(model);
}
[GridAction(EnableCustomBinding = true)]
public ActionResult StateDelete(int id, GridCommand command)
{
var state = _stateProvinceManager.GetStateProvinceById(id);
if (state == null) throw new ArgumentException("No state found with the specified id");
if (_addressManager.GetAddressTotalByStateProvinceId(state.Id) > 0)
return Content("Мэдээлэл ашиглалтанд байгаа тул устгах боломжгүй!");
int countryId = state.CountryId;
_stateProvinceManager.DeleteStateProvince(state);
return States(countryId, command);
}
#endregion
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetStatesByCountryId(string countryId,
bool? addEmptyStateIfRequired, bool? addAsterisk)
{
//permission validation is not required here
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = _countryManager.GetCountryById(Convert.ToInt32(countryId));
var states = country != null
? _stateProvinceManager.GetStateProvincesByCountryId(true, false, country.Id, true).ToList()
: new List<StateProvinceInfo>();
var result = (from s in states select new { id = s.Id.ToString(), name = s.Name }).ToList();
if (addEmptyStateIfRequired.HasValue && addEmptyStateIfRequired.Value && result.Count == 0)
result.Insert(0, new { id = "0", name = MessageUtil.GetHtmlSelectFirstItem() });
else
{
if (result.Count == 0) result.Insert(0, new { id = "", name = MessageUtil.GetHtmlSelectEmptyItem() });
}
if (addAsterisk.HasValue && addAsterisk.Value)
result.Insert(0, new { id = "0", name = "*" });
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
CreateOrUpdate.cshtml
@model CountryInfo
@using Telerik.Web.Mvc.UI;
@Html.ValidationSummary(true)
@if (Model != null && Model.Id > 0)
{
Html.HiddenFor(model => model.Id);
}
@Html.Telerik().TabStrip().Name("country-edit").Items(x =>
{
x.Add().Text("Үндсэн мэдээлэл").Content(TabInfo().ToHtmlString()).Selected(true);
x.Add().Text("Аймаг/хот").Content(TabStates().ToHtmlString());
})
@helper TabInfo()
{
<table class="adminContent">
<tr>
<td class="adminTitle">
@Html.BorLabelFor(model => model.Name):
</td>
<td class="adminData">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</td>
</tr>
</table>
<table class="adminContent">
<tr>
<td class="adminTitle">
@Html.BorLabelFor(model => model.TwoLetterIsoCode):
</td>
<td class="adminData">
@Html.EditorFor(model => model.TwoLetterIsoCode)
@Html.ValidationMessageFor(model => model.TwoLetterIsoCode)
</td>
</tr>
<tr>
<td class="adminTitle">
@Html.BorLabelFor(model => model.ThreeLetterIsoCode):
</td>
<td class="adminData">
@Html.EditorFor(model => model.ThreeLetterIsoCode)
@Html.ValidationMessageFor(model => model.ThreeLetterIsoCode)
</td>
</tr>
<tr>
<td class="adminTitle">
@Html.BorLabelFor(model => model.NumericIsoCode):
</td>
<td class="adminData">
@Html.EditorFor(model => model.NumericIsoCode)
@Html.ValidationMessageFor(model => model.NumericIsoCode)
</td>
</tr>
<tr>
<td class="adminTitle">
@Html.BorLabelFor(model => model.DisplayOrder):
</td>
<td class="adminData">
@Html.EditorFor(model => model.DisplayOrder)
@Html.ValidationMessageFor(model => model.DisplayOrder)
</td>
</tr>
<tr>
<td class="adminTitle">
@Html.BorLabelFor(model => model.Published):
</td>
<td class="adminData">
@Html.EditorFor(model => model.Published)
@Html.ValidationMessageFor(model => model.Published)
</td>
</tr>
</table>
}
@helper TabStates()
{
if (Model.Id > 0)
{
<table class="adminContent">
<tr>
<td>
@(Html.Telerik().Grid<StateProvinceInfo>()
.Name("states-grid")
.DataKeys(x =>
{
x.Add(y => y.Id).RouteKey("Id");
})
.Columns(columns =>
{
columns.Bound(x => x.CentreName);
columns.Bound(x => x.Name);
columns.Bound(x => x.Abbreviation).Width(100);
columns.Bound(x => x.DisplayOrder).Width(100).Centered();
columns.Bound(x => x.IsCentre)
.Template(@<text>@Html.HintStateImageTag(item.IsCentre)</text>)
.ClientTemplate(string.Format(Html.HintStateImageTag(), "<#= IsCentre #>"))
.Centered()
.Width(100);
columns.Bound(x => x.IsWeather)
.Template(@<text>@Html.HintStateImageTag(item.IsWeather)</text>)
.ClientTemplate(string.Format(Html.HintStateImageTag(), "<#= IsWeather #>"))
.Centered()
.Width(100);
columns.Bound(x => x.Published)
.Template(@<text>@Html.HintStateImageTag(item.Published)</text>)
.ClientTemplate(string.Format(Html.HintStateImageTag(), "<#= Published #>"))
.Centered()
.Width(100);
columns.Bound(x => x.Id)
.Width(50)
.Centered()
.ClientTemplate("<input type='submit' value='Засах' onclick=\""
+ "javascript:OpenWindow('" + @Url.Action("StateEditPopup")
+ "/<#= Id #>?btnId=btnRefresh&formId=country-form', 800, 250, true); return false;\" class='t-button' />")
.Title("Засах");
columns.Command(commands =>
{
commands.Delete().Text("Устгах");
}).Title("Устгах").Width(50);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("States", "Country", new { countryId = Model.Id })
.Delete("StateDelete", "Country");
})
.ClientEvents(x => x.OnError("grid_onError"))
.EnableCustomBinding(true))
</td>
</tr>
<tr>
<td>
@{
var popupUrl = "javascript:OpenWindow('"
+ Url.Action("StateCreatePopup", "Country"
, new { countryId = Model.Id, btnId = "btnRefresh", formId = "country-form" })
+ "', 800, 250, true); return false;";
}
<input type="submit" id="btnAddNewState" name="btnAddNewState" value="Нэмэх"
onclick="@popupUrl" class="t-button" />
<input type="submit" id="btnRefresh" name="btnRefresh" style="display: none" />
<script type="text/javascript">
$(document).ready(function () {
$('#btnRefresh').click(function () {
var optionsGrid = $("#states-grid");
optionsGrid.data('tGrid').ajaxRequest();
return false;
});
});
</script>
</td>
</tr>
</table>
<script type="text/javascript">
function grid_onError(e) {
alert(e.XMLHttpRequest.responseText);
e.preventDefault();
}
</script>
}
else
{
@:Хадгалсаны дараа нэмэлт мэдээлэл дээр засвар хийх боломжтой болно.
}
}
HtmlExtensions.cs
public static class HtmlExtensions
{
public static string HintStateImageTag(this HtmlHelper helper)
{
return "<img alt=\"\" src=\""
+ ResolveUrl(helper, "~/Administration/Content/images/active-{0}.gif").ToHtmlString()
+ "\" />";
}
public static string HintStateImageTag(this HtmlHelper helper, bool value)
{
return "<img alt=\"\" src=\""
+ ResolveUrl(helper, "~/Administration/Content/images/active-" + value.ToString().ToLowerInvariant() + ".gif").ToHtmlString()
+ "\" />";
}
public static string HintStateImageUrl(this HtmlHelper helper, bool value)
{
return ResolveUrl(helper
, "~/Administration/Content/images/active-" + value.ToString().ToLowerInvariant() + ".gif").ToHtmlString();
}
public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
return MvcHtmlString.Create(urlHelper.Content(url));
}
public static MvcHtmlString Hint(this HtmlHelper helper, string value)
{
// Create tag builder
var builder = new TagBuilder("img");
// Add attributes
builder.MergeAttribute("src", ResolveUrl(helper, "~/Administration/Content/images/ico-help.gif").ToHtmlString());
builder.MergeAttribute("alt", value);
builder.MergeAttribute("title", value);
// Render tag
return MvcHtmlString.Create(builder.ToString());
}
public static MvcHtmlString DeleteConfirmation<T>(this HtmlHelper<T> helper, string buttonsSelector = null) where T : BaseBorEntityModel
{
return DeleteConfirmation<T>(helper, "", buttonsSelector);
}
public static MvcHtmlString DeleteConfirmation<T>(this HtmlHelper<T> helper, string actionName, string buttonsSelector = null) where T : BaseBorEntityModel
{
if (String.IsNullOrEmpty(actionName))
actionName = "Delete";
var modalId = MvcHtmlString.Create(helper.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation").ToHtmlString();
//there's an issue in Telerik (ScriptRegistrar.Current implemenation)
//it's a little hack to ensure ScriptRegistrar.Current is loaded
helper.Telerik();
#region Write click events for button, if supplied
if (!string.IsNullOrEmpty(buttonsSelector))
{
var textWriter = new StringWriter();
IClientSideObjectWriter objectWriter = new ClientSideObjectWriterFactory()
.Create(buttonsSelector, "click", textWriter);
objectWriter.Start();
textWriter.Write("function(e){e.preventDefault();openModalWindow(\"" + modalId + "\");}");
objectWriter.Complete();
var value = textWriter.ToString();
ScriptRegistrar.Current.OnDocumentReadyStatements.Add(value);
}
#endregion
var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = helper.ViewData.Model.Id,
ControllerName = helper.ViewContext.RouteData.GetRequiredString("controller"),
ActionName = actionName
};
var window = helper.Telerik().Window().Name(modalId)
.Title("Та мэдээллийг устгахдаа итгэлтэй байна уу?")
.Modal(true)
.Effects(x => x.Toggle())
.Resizable(x => x.Enabled(false))
.Buttons(x => x.Close())
.Visible(false)
.Content(helper.Partial("Delete", deleteConfirmationModel).ToHtmlString()).ToHtmlString();
return MvcHtmlString.Create(window);
}
public static MvcHtmlString BorLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool displayHint = true)
{
var result = new StringBuilder();
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var hintResource = string.Empty;
object value = null;
if (metadata.AdditionalValues.TryGetValue("Display", out value))
{
var resourceDisplayName = value as DisplayAttribute;
if (resourceDisplayName != null && displayHint)
{
hintResource = resourceDisplayName.Name;
}
}
if (string.IsNullOrEmpty(hintResource) && !string.IsNullOrEmpty(metadata.DisplayName) && metadata.IsRequired)
{
hintResource = metadata.DisplayName + "*";
}
result.Append(helper.Hint(hintResource).ToHtmlString());
result.Append(helper.LabelFor(expression, new { title = hintResource }));
return MvcHtmlString.Create(result.ToString());
}
public static MvcHtmlString RequiredHint(this HtmlHelper helper, string additionalText = null)
{
// Create tag builder
var builder = new TagBuilder("span");
builder.AddCssClass("required");
var innerText = "*";
//add additinal text if specified
if (!String.IsNullOrEmpty(additionalText))
innerText += " " + additionalText;
builder.SetInnerText(innerText);
// Render tag
return MvcHtmlString.Create(builder.ToString());
}
public static string FieldNameFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
return html.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
}
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
/// <summary>
/// Creates a days, months, years drop down list using an HTML select control.
/// The parameters represent the value of the "name" attribute on the select control.
/// </summary>
/// <param name="html">HTML helper</param>
/// <param name="dayName">"Name" attribute of the day drop down list.</param>
/// <param name="monthName">"Name" attribute of the month drop down list.</param>
/// <param name="yearName">"Name" attribute of the year drop down list.</param>
/// <param name="beginYear">Begin year</param>
/// <param name="endYear">End year</param>
/// <param name="selectedDay">Selected day</param>
/// <param name="selectedMonth">Selected month</param>
/// <param name="selectedYear">Selected year</param>
/// <param name="localizeLabels">Localize labels</param>
/// <returns></returns>
public static MvcHtmlString DatePickerDropDowns(this HtmlHelper html,
string dayName, string monthName, string yearName,
int? beginYear = null, int? endYear = null,
int? selectedDay = null, int? selectedMonth = null, int? selectedYear = null, bool localizeLabels = true)
{
var daysList = new TagBuilder("select");
var monthsList = new TagBuilder("select");
var yearsList = new TagBuilder("select");
daysList.Attributes.Add("name", dayName);
monthsList.Attributes.Add("name", monthName);
yearsList.Attributes.Add("name", yearName);
var days = new StringBuilder();
var months = new StringBuilder();
var years = new StringBuilder();
string dayLocale, monthLocale, yearLocale;
if (localizeLabels)
{
dayLocale = "Өдөр";
monthLocale = "Сар";
yearLocale = "Он";
}
else
{
dayLocale = "Day";
monthLocale = "Month";
yearLocale = "Year";
}
days.AppendFormat("<option value='{0}'>{1}</option>", "0", dayLocale);
for (int i = 1; i <= 31; i++)
days.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedDay.HasValue && selectedDay.Value == i) ? " selected=\"selected\"" : null);
months.AppendFormat("<option value='{0}'>{1}</option>", "0", monthLocale);
for (int i = 1; i <= 12; i++)
{
months.AppendFormat("<option value='{0}'{1}>{2}</option>",
i,
(selectedMonth.HasValue && selectedMonth.Value == i) ? " selected=\"selected\"" : null,
CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i));
}
years.AppendFormat("<option value='{0}'>{1}</option>", "0", yearLocale);
if (beginYear == null)
beginYear = DateTime.UtcNow.Year - 100;
if (endYear == null)
endYear = DateTime.UtcNow.Year;
for (int i = beginYear.Value; i <= endYear.Value; i++)
years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
(selectedYear.HasValue && selectedYear.Value == i) ? " selected=\"selected\"" : null);
daysList.InnerHtml = days.ToString();
monthsList.InnerHtml = months.ToString();
yearsList.InnerHtml = years.ToString();
return MvcHtmlString.Create(string.Concat(daysList, monthsList, yearsList));
}
public static MvcHtmlString Widget(this HtmlHelper helper, string widgetZone)
{
return helper.Action("WidgetsByZone", "Widget", new { widgetZone = widgetZone });
}
}
Wednesday, June 26, 2013
Monday, March 25, 2013
Entity framework Map : EntityTypeConfiguration auto add to DbContext
public class Customer
{
public int Id { get; set; }
...........................
}
public partial class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
this.ToTable("Customer");
this.HasKey(c => c.Id);
this.Property(u => u.Username).HasMaxLength(1000);
this.Property(u => u.Email).HasMaxLength(1000);
this.Property(u => u.Password);
this.Property(c => c.AdminComment);
this.Property(c => c.CheckoutAttributes);
this.Property(c => c.GiftCardCouponCodes);
this.Ignore(u => u.PasswordFormat);
this.Ignore(c => c.TaxDisplayType);
this.Ignore(c => c.VatNumberStatus);
this.HasOptional(c => c.Language)
.WithMany()
.HasForeignKey(c => c.LanguageId).WillCascadeOnDelete(false);
this.HasOptional(c => c.Currency)
.WithMany()
.HasForeignKey(c => c.CurrencyId).WillCascadeOnDelete(false);
this.HasMany(c => c.CustomerRoles)
.WithMany()
.Map(m => m.ToTable("Customer_CustomerRole_Mapping"));
this.HasOptional(c => c.Affiliate)
.WithMany()
.HasForeignKey(c => c.AffiliateId);
this.HasMany<Address>(c => c.Addresses)
.WithMany()
.Map(m => m.ToTable("CustomerAddresses"));
this.HasOptional<Address>(c => c.BillingAddress);
this.HasOptional<Address>(c => c.ShippingAddress);
this.HasOptional<Gift>(c => c.SelectedGift);
this.HasMany<Patient>(c => c.Patients)
.WithMany()
.Map(m => m.ToTable("CustomerPatients"));
}
}
public WebCmsDbContext() : base(EngineContext.Current.Resolve<DbSettingModel>().DataConnectionString)
{
//((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//dynamically load all configuration
//System.Type configType = typeof(LanguageMap); //any of your configuration classes here
//var typesToRegister = Assembly.GetAssembly(configType).GetTypes()
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null
&& type.BaseType.IsGenericType
&& type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
//...or do it manually below. For example,
//modelBuilder.Configurations.Add(new LanguageMap());
base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
automataar DbContext -ruu Entity class nemj bn. EntityTypeConfiguration<> ajiglaarai
...................................
{
public int Id { get; set; }
...........................
}
public partial class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
this.ToTable("Customer");
this.HasKey(c => c.Id);
this.Property(u => u.Username).HasMaxLength(1000);
this.Property(u => u.Email).HasMaxLength(1000);
this.Property(u => u.Password);
this.Property(c => c.AdminComment);
this.Property(c => c.CheckoutAttributes);
this.Property(c => c.GiftCardCouponCodes);
this.Ignore(u => u.PasswordFormat);
this.Ignore(c => c.TaxDisplayType);
this.Ignore(c => c.VatNumberStatus);
this.HasOptional(c => c.Language)
.WithMany()
.HasForeignKey(c => c.LanguageId).WillCascadeOnDelete(false);
this.HasOptional(c => c.Currency)
.WithMany()
.HasForeignKey(c => c.CurrencyId).WillCascadeOnDelete(false);
this.HasMany(c => c.CustomerRoles)
.WithMany()
.Map(m => m.ToTable("Customer_CustomerRole_Mapping"));
this.HasOptional(c => c.Affiliate)
.WithMany()
.HasForeignKey(c => c.AffiliateId);
this.HasMany<Address>(c => c.Addresses)
.WithMany()
.Map(m => m.ToTable("CustomerAddresses"));
this.HasOptional<Address>(c => c.BillingAddress);
this.HasOptional<Address>(c => c.ShippingAddress);
this.HasOptional<Gift>(c => c.SelectedGift);
this.HasMany<Patient>(c => c.Patients)
.WithMany()
.Map(m => m.ToTable("CustomerPatients"));
}
}
public WebCmsDbContext() : base(EngineContext.Current.Resolve<DbSettingModel>().DataConnectionString)
{
//((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//dynamically load all configuration
//System.Type configType = typeof(LanguageMap); //any of your configuration classes here
//var typesToRegister = Assembly.GetAssembly(configType).GetTypes()
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null
&& type.BaseType.IsGenericType
&& type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
//...or do it manually below. For example,
//modelBuilder.Configurations.Add(new LanguageMap());
base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
automataar DbContext -ruu Entity class nemj bn. EntityTypeConfiguration<> ajiglaarai
...................................
Tuesday, March 19, 2013
Silverlight sample contact page using MVVM
<UserControl x:Class="x.ViewPage.ContactPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL5"
xmlns:lib="clr-namespace:PrismEmpire.Lib.Tools"
x:Name="userControl"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="720">
<UserControl.Resources>
<lib:AIVisibilityConverter x:Key="VisibilityConverter"/>
<Style x:Key="ButtonStyle1" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Duration="0" To="#FF555555" Storyboard.TargetProperty="(Shape.Stroke).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle" d:IsOptimized="True"/>
<ColorAnimation Duration="0" To="#FF444444" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle" d:IsOptimized="True"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="rectangle" Fill="#FF333333" Stroke="#FF444444" StrokeThickness="2"/>
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="{TemplateBinding Content}" VerticalAlignment="Center" TextAlignment="Center" Foreground="#FF999999" FontSize="{TemplateBinding FontSize}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding Contact, Source={StaticResource Locator}}">
<TextBlock HorizontalAlignment="Center" Height="38" Margin="119,47,111,0" TextWrapping="Wrap" Text="Welcome to Prism Empire, thank you for your interest in our Business Solutions. Please fill in the form below and we will contact you within 24 hours." VerticalAlignment="Top" Width="490" Foreground="#FF999999" FontSize="12"/>
<TextBlock HorizontalAlignment="Center" Height="19" Margin="119,85,380,0" TextWrapping="Wrap" Text="Email: noreply@prismempire.com" VerticalAlignment="Top" Width="221" Foreground="White" FontSize="12"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,127,0,0" TextWrapping="Wrap" Text="Contact Name" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="28" Margin="119,10,0,0" TextWrapping="Wrap" Text="Contact Us" VerticalAlignment="Top" Width="207" Foreground="#FF999999" FontSize="24"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,162,0,0" TextWrapping="Wrap" Text="Phone Number" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,197,0,0" TextWrapping="Wrap" Text="Email" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,232,0,0" TextWrapping="Wrap" Text="Company" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,267,0,0" TextWrapping="Wrap" Text="Message" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBox x:Name="contactName" Text="{Binding Model.ContactName, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,123,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBlock Visibility="{Binding IsContactNameValid, Converter={StaticResource VisibilityConverter}, Mode=TwoWay}"
HorizontalAlignment="Left" Height="30" Margin="489,127,0,0" TextWrapping="Wrap" Text="Contact name is empty." VerticalAlignment="Top" Width="164" Foreground="Red"/>
<TextBox x:Name="phoneNumber" Text="{Binding Model.PhoneNumber, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,158,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="email" Text="{Binding Model.Email, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,193,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="companyName" Text="{Binding Model.CompanyName, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,228,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="message" Text="{Binding Model.Message, Mode=TwoWay}" HorizontalAlignment="Left" Height="57" Margin="242,263,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBlock Visibility="{Binding IsEmailValid, Converter={StaticResource VisibilityConverter}, Mode=TwoWay}"
HorizontalAlignment="Left" Height="30" Margin="489,197,0,0" TextWrapping="Wrap" Text="Email format is incorrect." VerticalAlignment="Top" Width="164" Foreground="Red"/>
<Button Content="Send" HorizontalAlignment="Left" Height="25" Margin="397,365,0,0" Style="{StaticResource ButtonStyle1}" VerticalAlignment="Top" Width="85">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand Command="{Binding SendCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button Content="Clear" HorizontalAlignment="Left" Height="25" Margin="307,365,0,0" Style="{StaticResource ButtonStyle1}" VerticalAlignment="Top" Width="85">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand
Command="{Binding Contact.ClearCommand, Source={StaticResource Locator}}"
CommandParameter="{Binding ElementName=userControl}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="242,325,0,0" TextWrapping="Wrap"
Text="{Binding IsSentMail, Mode=TwoWay}" VerticalAlignment="Top" Width="240" Foreground="White"/>
</Grid>
</UserControl>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL5"
xmlns:lib="clr-namespace:PrismEmpire.Lib.Tools"
x:Name="userControl"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="720">
<UserControl.Resources>
<lib:AIVisibilityConverter x:Key="VisibilityConverter"/>
<Style x:Key="ButtonStyle1" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Duration="0" To="#FF555555" Storyboard.TargetProperty="(Shape.Stroke).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle" d:IsOptimized="True"/>
<ColorAnimation Duration="0" To="#FF444444" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="rectangle" d:IsOptimized="True"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="rectangle" Fill="#FF333333" Stroke="#FF444444" StrokeThickness="2"/>
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="{TemplateBinding Content}" VerticalAlignment="Center" TextAlignment="Center" Foreground="#FF999999" FontSize="{TemplateBinding FontSize}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding Contact, Source={StaticResource Locator}}">
<TextBlock HorizontalAlignment="Center" Height="38" Margin="119,47,111,0" TextWrapping="Wrap" Text="Welcome to Prism Empire, thank you for your interest in our Business Solutions. Please fill in the form below and we will contact you within 24 hours." VerticalAlignment="Top" Width="490" Foreground="#FF999999" FontSize="12"/>
<TextBlock HorizontalAlignment="Center" Height="19" Margin="119,85,380,0" TextWrapping="Wrap" Text="Email: noreply@prismempire.com" VerticalAlignment="Top" Width="221" Foreground="White" FontSize="12"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,127,0,0" TextWrapping="Wrap" Text="Contact Name" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="28" Margin="119,10,0,0" TextWrapping="Wrap" Text="Contact Us" VerticalAlignment="Top" Width="207" Foreground="#FF999999" FontSize="24"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,162,0,0" TextWrapping="Wrap" Text="Phone Number" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,197,0,0" TextWrapping="Wrap" Text="Email" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,232,0,0" TextWrapping="Wrap" Text="Company" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="119,267,0,0" TextWrapping="Wrap" Text="Message" VerticalAlignment="Top" Width="164" Foreground="#FF999999"/>
<TextBox x:Name="contactName" Text="{Binding Model.ContactName, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,123,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBlock Visibility="{Binding IsContactNameValid, Converter={StaticResource VisibilityConverter}, Mode=TwoWay}"
HorizontalAlignment="Left" Height="30" Margin="489,127,0,0" TextWrapping="Wrap" Text="Contact name is empty." VerticalAlignment="Top" Width="164" Foreground="Red"/>
<TextBox x:Name="phoneNumber" Text="{Binding Model.PhoneNumber, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,158,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="email" Text="{Binding Model.Email, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,193,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="companyName" Text="{Binding Model.CompanyName, Mode=TwoWay}" HorizontalAlignment="Left" Height="25" Margin="242,228,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBox x:Name="message" Text="{Binding Model.Message, Mode=TwoWay}" HorizontalAlignment="Left" Height="57" Margin="242,263,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
<TextBlock Visibility="{Binding IsEmailValid, Converter={StaticResource VisibilityConverter}, Mode=TwoWay}"
HorizontalAlignment="Left" Height="30" Margin="489,197,0,0" TextWrapping="Wrap" Text="Email format is incorrect." VerticalAlignment="Top" Width="164" Foreground="Red"/>
<Button Content="Send" HorizontalAlignment="Left" Height="25" Margin="397,365,0,0" Style="{StaticResource ButtonStyle1}" VerticalAlignment="Top" Width="85">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand Command="{Binding SendCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button Content="Clear" HorizontalAlignment="Left" Height="25" Margin="307,365,0,0" Style="{StaticResource ButtonStyle1}" VerticalAlignment="Top" Width="85">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cmd:EventToCommand
Command="{Binding Contact.ClearCommand, Source={StaticResource Locator}}"
CommandParameter="{Binding ElementName=userControl}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<TextBlock HorizontalAlignment="Left" Height="30" Margin="242,325,0,0" TextWrapping="Wrap"
Text="{Binding IsSentMail, Mode=TwoWay}" VerticalAlignment="Top" Width="240" Foreground="White"/>
</Grid>
</UserControl>
Sunday, March 17, 2013
create database script from entity framework dbcontext
part 1
To set the auto drop and create you would do something like this...
To set the auto drop and create you would do something like this...
public class MyDbContext : DbContext
{
public IDbSet<Foo> Foos { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Database.SetInitializer(new MyDbContextInitializer());
base.OnModelCreating(modelBuilder);
}
}
public class MyDbContextInitializer : DropCreateDatabaseIfModelChanges<MyDbContext>
{
protected override void Seed(MyDbContext dbContext)
{
// seed data
base.Seed(dbContext);
}
}
part 2
You can create the tables yourself - the easiest way is:
IObjectContextAdapter adapter = (IObjectContextAdapter)context;
string script = adapter.ObjectContext.CreateDatabaseScript();
context.Database.ExecuteSqlCommand(script);
Where context is my EF 4.1 database context. Prior to this code I
drop all the tables (from the last time I created the db), and after
this I seed it with data.part 3
You need to add this to your Application_Start()
part 4
Database.SetInitializer(new MyDbContextContextInitializer());
var context = new MyDbContextContext();
context.Database.Initialize(true);
The last line forces the DB to createdpart 4
Better: add the initializer to the static constructor, like this:
public class MyDbContext : DbContext
{
static MyDbContext()
{
Database.SetInitializer(new MyDbContextContextInitializer());
}
}
Subscribe to:
Posts (Atom)