вторник, 9 сентября 2014 г.

EF Migration

enable-migrations
add-migration InitialCreate

update-database
internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}
seed Method Example
namespace ContosoUniversity.Migrations
{
    using ContosoUniversity.Models;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
        {
            var students = new List<Student>
            {
                new Student { FirstMidName = "Carson",   LastName = "Alexander", 
                    EnrollmentDate = DateTime.Parse("2010-09-01") },
                new Student { FirstMidName = "Meredith", LastName = "Alonso",    
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Arturo",   LastName = "Anand",     
                    EnrollmentDate = DateTime.Parse("2013-09-01") },
                new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", 
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Yan",      LastName = "Li",        
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Peggy",    LastName = "Justice",   
                    EnrollmentDate = DateTime.Parse("2011-09-01") },
                new Student { FirstMidName = "Laura",    LastName = "Norman",    
                    EnrollmentDate = DateTime.Parse("2013-09-01") },
                new Student { FirstMidName = "Nino",     LastName = "Olivetto",  
                    EnrollmentDate = DateTime.Parse("2005-08-11") }
            };
            students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();

            var courses = new List<Course>
            {
                new Course {CourseID = 1050, Title = "Chemistry",      Credits = 3, },
                new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3, },
                new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3, },
                new Course {CourseID = 1045, Title = "Calculus",       Credits = 4, },
                new Course {CourseID = 3141, Title = "Trigonometry",   Credits = 4, },
                new Course {CourseID = 2021, Title = "Composition",    Credits = 3, },
                new Course {CourseID = 2042, Title = "Literature",     Credits = 4, }
            };
            courses.ForEach(s => context.Courses.AddOrUpdate(p => p.Title, s));
            context.SaveChanges();

            var enrollments = new List<Enrollment>
            {
                new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Alexander").ID, 
                    CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, 
                    Grade = Grade.A 
                },
                 new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID, 
                    Grade = Grade.C 
                 },                            
                 new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID, 
                    Grade = Grade.B
                 },
                 new Enrollment { 
                     StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID, 
                    Grade = Grade.B 
                 },
                 new Enrollment { 
                     StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID, 
                    Grade = Grade.B 
                 },
                 new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID = courses.Single(c => c.Title == "Composition" ).CourseID, 
                    Grade = Grade.B 
                 },
                 new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
                 },
                 new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade = Grade.B         
                 },
                new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
                    CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade = Grade.B         
                 },
                 new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Li").ID,
                    CourseID = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade = Grade.B         
                 },
                 new Enrollment { 
                    StudentID = students.Single(s => s.LastName == "Justice").ID,
                    CourseID = courses.Single(c => c.Title == "Literature").CourseID,
                    Grade = Grade.B         
                 }
            };

            foreach (Enrollment e in enrollments)
            {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                         s.Student.ID == e.StudentID &&
                         s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();
        }
    }
}
update-database

понедельник, 8 сентября 2014 г.

Строки подключения к локальным БД

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="Positions" connectionString="Server=.\SQLEXPRESS;Initial Catalog=Positions_12;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnet-PositionsMvc_01-20140818100456.mdf;Initial Catalog=aspnet-PositionsMvc_01-20140818100456;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings></appSettings>
  <system.web>

<add name="Positions" connectionString="Server=192.168.10.6;Initial Catalog=Positions_12;user=sa;password=qwerty" providerName="System.Data.SqlClient"/>

<add name="Positions" connectionString="Server=192.168.10.6;Initial Catalog=Positions_12;Integrated Security=True;" providerName="System.Data.SqlClient"/>

вторник, 2 сентября 2014 г.

Exception Handling in WebAPI

http://www.codeproject.com/Articles/733512/Exception-Handling-in-WebAPI

http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling

Форматтеры: Удаление xmlFormattera

public static class WebApiConfig
{
 public static void Register(System.Web.Http.HttpConfiguration config)
  {
     //Route Configuration
     config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}"
     );
            
     //Only JSON OUPUT
     var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault
     (t => t.MediaType == "application/xml");
     config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
  }
} 
Main with SelHost
class Program
    {
        public static void Main()
        {
            var config = new System.Web.Http.SelfHost.HttpSelfHostConfiguration("http://Localhost:8080");
            WebApiConfig.Register(config);
 
            using (var server = new System.Web.Http.SelfHost.HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            } 
        }
    }

FF.Positions

Конфигурация Вэб Клиентов

 //var tradeWebClient = new TradeWebClient(@"http://192.168.1.57/positionsMvc_01/", @"application/xml", @"api/apiTrades");
            var tradeWebClient = new TradeWebClient(@"http://192.168.10.6/positionsMvc_01/", @"application/xml", @"api/apiTrades");



Инициализация DB:

public class PositionsDbInit : DropCreateDatabaseIfModelChanges<PositionsContext>
    //public class PositionsDbInit : DropCreateDatabaseAlways<PositionsContext>
    {
        protected override void Seed(PositionsContext context)
        {
            Console.WriteLine("Seed");
            //context.PopulateTrades();
            //  context.PopulatePositions();      
        }
    }

            Database.SetInitializer<PositionsContext>(new PositionsDbInit());

Строки подключения:

<add name="Positions" connectionString="Server=192.168.10.6;Initial Catalog=Positions_12;user=sa;password=qwerty" providerName="System.Data.SqlClient"/>

<add name="Positions" connectionString="Server=192.168.10.6;Initial Catalog=Positions_12;Integrated Security=True;" providerName="System.Data.SqlClient"/>


<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnet-PositionsMvc_01-20140818100456.mdf;Initial Catalog=aspnet-PositionsMvc_01-20140818100456;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />