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
...................................

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>

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...
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()
 Database.SetInitializer(new MyDbContextContextInitializer());
 var context = new MyDbContextContext();
 context.Database.Initialize(true);
The last line forces the DB to created

part 4

Better: add the initializer to the static constructor, like this:
public class MyDbContext : DbContext 
{
    static MyDbContext()
    {
        Database.SetInitializer(new MyDbContextContextInitializer());
    }
}

Sample Validating Controls in Silverlight

Validating Controls in Silverlight

If ever you have done validation of form controls in ASP.NET or Desktop applications then validating controls in Silverlight will be easy to get to grips with.  Unfortunately there are no controls in Silverlight that perform validation, maybe Microsoft will release some at some point but for now we have a few tips for validating and a simple example Registration Form with basic validation.




Our example Silverlight registration dialog
<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:liquid="clr-namespace:Liquid;assembly=Liquid"
    Width="400" Height="300">
    <Canvas>
        <Rectangle Width="330" Height="170" RadiusX="7" RadiusY="7" Fill="#44888888" />

        <Rectangle Canvas.Left="2" Canvas.Top="2" Width="326" Height="166" RadiusX="5" RadiusY="5" StrokeThickness="2" Stroke="#888888">
            <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <GradientStop Color="#ffdfdfdf" Offset="0.0" />
                    <GradientStop Color="#fff8f8f8" Offset="0.7" />
                    <GradientStop Color="#ffeeeeee" Offset="1.0" />
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        
        <Rectangle Canvas.Left="5" Canvas.Top="5" Width="320" Height="21" StrokeThickness="0.5" Stroke="#7A8295" RadiusX="3" RadiusY="3">
            <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                    <GradientStop Color="#626C88" Offset="0.0" />
                    <GradientStop Color="#393F4D" Offset="0.5" />
                    <GradientStop Color="#151516" Offset="0.5" />
                    <GradientStop Color="#3C476F" Offset="1.0" />
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        
        <TextBlock Text="Username:" Canvas.Left="10" Canvas.Top="35" />
        <TextBox x:Name="newUsername" Canvas.Left="120" Canvas.Top="32" Width="200" TabIndex="0" />
        <TextBlock Text="Email:" Canvas.Left="10" Canvas.Top="65" />
        <TextBox x:Name="newEmail" Canvas.Left="120" Canvas.Top="62" Width="200" TabIndex="1" />
        <TextBlock Text="Password:" Canvas.Left="10" Canvas.Top="95" />
        <TextBox x:Name="newPassword" Canvas.Left="120" Canvas.Top="92" Width="200" TabIndex="2" />

        <HyperlinkButton x:Name="registerHelp" Canvas.Left="10" Canvas.Top="146" NavigateUri="help.aspx" Content="Problems Registering?" />
        <TextBlock x:Name="registerStatus" Canvas.Left="10" Canvas.Top="121" Foreground="Red" FontSize="10" FontWeight="Bold" />

        <Button Canvas.Left="200" Canvas.Top="133" Width="50" Content="Cancel" Click="RegisterCancel_Click" />
        <Button x:Name="registerRegister" Canvas.Left="260" Canvas.Top="133" Width="60" Content="Register" Click="Register_Click" />
    </Canvas>
</UserControl>

code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void RegisterCancel_Click(object sender, RoutedEventArgs e)
        {
            // Registration has been cancelled. Handle this here
        }

        private void Register_Click(object sender, RoutedEventArgs e)
        {
            // Clear the status text
            registerStatus.Text = "";

            if (newPassword.Text.Length == 0)
            {
                // No password entered
                registerStatus.Text = "Enter a password.";
                newPassword.Focus();
            }
            if (newEmail.Text.Length == 0)
            {
                // No email address entered
                registerStatus.Text = "Enter an email.";
                newEmail.Focus();
            }
            else if (!Regex.IsMatch(newEmail.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
            {
                // An invalid email format was entered
                registerStatus.Text = "Enter a valid email.";
                newEmail.Select(0, newEmail.Text.Length);
                newEmail.Focus();
            }
            if (newUsername.Text.Length == 0)
            {
                // No username was entered
                registerStatus.Text = "Enter a username.";
                newUsername.Focus();
            }

            // Return if the status text is not empty
            if (registerStatus.Text.Length > 0)
            {
                return;
            }

            // All done, the 3 fields have been validated
            // Do your registration processing here....
        }
    }
}