Permalink
Browse files

Tweaks for AppHarbor

  • Loading branch information...
jchadwick committed Dec 23, 2011
1 parent 49e289e commit 42a3dcc9c319626707d838fd9f82963b5e687564
@@ -1,5 +1,6 @@
using System;
using System.Collections.ObjectModel;
+using System.Data.Entity;
using System.Linq;
namespace Ebuy.DataAccess
@@ -8,6 +9,11 @@ public partial class DataContext
{
public class DemoDataInitializer : Initializer
{
+ public DemoDataInitializer(IDatabaseInitializer<DataContext> initializer)
+ : base(initializer)
+ {
+ }
+
protected override void Seed(DataContext context)
{
base.Seed(context);
@@ -141,7 +147,6 @@ protected override void Seed(DataContext context)
var auction = new Auction()
{
- Bids = new Collection<Bid>(),
Categories = product.Categories.ToArray(),
Description = product.Description,
EndTime = startTime.AddDays(rand.Next(3, 14)),
@@ -155,28 +160,6 @@ protected override void Seed(DataContext context)
context.Auctions.Add(auction);
}
-
-
- foreach (var auction in context.Auctions.Local)
- {
- var nonOwners = users.Except(new[] { auction.Owner }).ToArray();
- var lastBid = new Bid(auction.Owner, auction, auction.StartingPrice);
-
- for (int x = 0; x < rand.Next(4, 20); x++)
- {
- var user = nonOwners[rand.Next(nonOwners.Length)];
- var amount = new Currency(String.Format("${0}", lastBid.Amount.Value + rand.Next(1, 20)));
-
- using (Clock.ModifiedTime(lastBid.Timestamp.AddMinutes(rand.Next(1, 1200))))
- {
- lastBid = new Bid(user, auction, amount);
- }
-
- context.Bids.Add(lastBid);
- }
-
- auction.WinningBidId = lastBid.Id;
- }
}
}
}
@@ -1,29 +1,43 @@
-using System.Data.Entity;
+using System;
+using System.Data.Entity;
using CustomExtensions.DataAnnotations;
namespace Ebuy.DataAccess
{
public partial class DataContext
{
- public class Initializer
-#if(DEBUG)
- : DropCreateDatabaseAlways<DataContext>
-#else
- : CreateDatabaseIfNotExists<DataContext>
-#endif
+ public class Initializer : IDatabaseInitializer<DataContext>
{
- protected override void Seed(DataContext context)
+ private readonly IDatabaseInitializer<DataContext> _initializer;
+
+ public Initializer(IDatabaseInitializer<DataContext> initializer)
+ {
+ _initializer = initializer;
+ }
+
+ public void InitializeDatabase(DataContext context)
+ {
+ _initializer.InitializeDatabase(context);
+
+ try
+ {
+ Seed(context);
+ context.SaveChanges();
+ }
+ catch (Exception)
+ {
+ }
+ }
+
+ protected virtual void Seed(DataContext context)
{
// Apply the custom UniqueAttribute to set unique constraints
// on columns with the attribute defined
new UniqueConstraintApplier().ApplyUniqueConstraints(context);
- base.Seed(context);
-
-
context.Users.Add(new User()
{
- DisplayName = "Uber Administrator",
+ DisplayName = "Administrator",
EmailAddress = "admin@ebuy.com",
FullName = "Administrator",
});
@@ -26,7 +26,7 @@ protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<Auction>()
.HasMany(x => x.Bids)
.WithOptional()
- .Map(x => x.MapKey("Auction_ID"));
+ .Map(x => x.MapKey("Auction_Id"));
*/
modelBuilder.Entity<Bid>()
@@ -43,7 +43,7 @@ protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<User>()
.HasMany(x => x.Bids)
.WithOptional()
- .Map(x => x.MapKey("User_ID"));
+ .Map(x => x.MapKey("User_Id"));
*/
}
}
View
@@ -16,7 +16,6 @@ public class Auction : Entity<Guid>
public virtual DateTime EndTime { get; set; }
public virtual Currency StartingPrice { get; set; }
- [ForeignKey("WinndingBid")]
protected internal Guid? WinningBidId { get; set; }
public virtual Bid WinningBid { get; private set; }
View
@@ -83,7 +83,7 @@ public override bool Equals(object obj)
public override string ToString()
{
var symbol = CurrencyCodesBySymbol.Single(x => x.Value == Code).Key;
- return string.Format("{0}{1}", symbol, Value);
+ return string.Format("{0}{1:N2}", symbol, Value);
}
public static Currency operator +(Currency x, double amount)
View
@@ -77,6 +77,11 @@ public override int GetHashCode()
}
}
+ public override string ToString()
+ {
+ return Key;
+ }
+
public static bool operator ==(Entity<TId> left, Entity<TId> right)
{
return Equals(left, right);
View
@@ -11,7 +11,7 @@ public class User : Entity<long>
{
public virtual ICollection<Auction> Selling { get; private set; }
- public virtual ICollection<Bid> Bids { get; private set; }
+// public virtual ICollection<Bid> Bids { get; private set; }
public virtual string DisplayName
{
@@ -34,7 +34,7 @@ public virtual string DisplayName
public User()
{
- Bids = new Collection<Bid>();
+// Bids = new Collection<Bid>();
Payments = new Collection<Payment>();
Reviews = new Collection<Review>();
WatchedAuctions = new Collection<Auction>();
@@ -62,8 +62,10 @@ public void Bid(Auction auction, Currency bidAmount)
public class Metadata
{
+/*
[InverseProperty("User")]
public object Bids;
+*/
[StringLength(50)]
public object DisplayName;
@@ -15,7 +15,7 @@ public static string Generate(string input)
{
Contract.Requires(!string.IsNullOrWhiteSpace(input));
- return HttpUtility.UrlEncode(input.Replace(" ", "").Replace("-", ""));
+ return HttpUtility.UrlEncode(input.Replace(" ", "_").Replace("-", "_"));
}
}
}
@@ -1,134 +0,0 @@
-using System.Data.Entity;
-using System.Data.Entity.Design;
-using System.Data.Entity.Infrastructure;
-using System.Data.Metadata.Edm;
-using System.Data.Objects;
-using System.Globalization;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Text;
-using System.Xml;
-
-namespace Devtalk
-{
- public class DontDropDbJustCreateTablesIfModelChanged<T> : IDatabaseInitializer<T> where T : DbContext
- {
- private EdmMetadata _edmMetaData;
-
- public void InitializeDatabase(T context)
- {
- ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
- string modelHash = GetModelHash(objectContext);
-
- if (CompatibleWithModel(modelHash, context, objectContext)) return;
-
- DeleteExistingTables(objectContext);
- CreateTables(objectContext);
-
- SaveModelHashToDatabase(context, modelHash, objectContext);
- }
-
- private void SaveModelHashToDatabase(T context, string modelHash, ObjectContext objectContext)
- {
- if (_edmMetaData != null) objectContext.Detach(_edmMetaData);
-
- _edmMetaData = new EdmMetadata();
- context.Set<EdmMetadata>().Add(_edmMetaData);
-
- _edmMetaData.ModelHash = modelHash;
- context.SaveChanges();
- }
-
- private void CreateTables(ObjectContext objectContext)
- {
- string dataBaseCreateScript = objectContext.CreateDatabaseScript();
- objectContext.ExecuteStoreCommand(dataBaseCreateScript);
- }
-
- private void DeleteExistingTables(ObjectContext objectContext)
- {
- objectContext.ExecuteStoreCommand(Dropallconstraintsscript);
- objectContext.ExecuteStoreCommand(Deletealltablesscript);
- }
-
- private string GetModelHash(ObjectContext context)
- {
- var csdlXmlString = GetCsdlXmlString(context).ToString();
- return ComputeSha256Hash(csdlXmlString);
- }
-
- private bool CompatibleWithModel(string modelHash, DbContext context, ObjectContext objectContext)
- {
- var isEdmMetaDataInStore = objectContext.ExecuteStoreQuery<int>(LookupEdmMetaDataTable).FirstOrDefault();
- if (isEdmMetaDataInStore == 1)
- {
- _edmMetaData = context.Set<EdmMetadata>().FirstOrDefault();
- if (_edmMetaData != null)
- {
- return modelHash == _edmMetaData.ModelHash;
- }
- }
- return false;
- }
-
- private string GetCsdlXmlString(ObjectContext context)
- {
- if (context != null)
- {
- var entityContainerList = context.MetadataWorkspace.GetItems<EntityContainer>(DataSpace.SSpace);
- if (entityContainerList != null)
- {
- EntityContainer entityContainer = entityContainerList.FirstOrDefault();
- var generator = new EntityModelSchemaGenerator(entityContainer);
- var stringBuilder = new StringBuilder();
- var xmlWRiter = XmlWriter.Create(stringBuilder);
- generator.GenerateMetadata();
- generator.WriteModelSchema(xmlWRiter);
- xmlWRiter.Flush();
- return stringBuilder.ToString();
- }
- }
- return string.Empty;
- }
-
- private static string ComputeSha256Hash(string input)
- {
- byte[] buffer = new SHA256Managed().ComputeHash(Encoding.ASCII.GetBytes(input));
- var builder = new StringBuilder(buffer.Length * 2);
- foreach (byte num in buffer)
- {
- builder.Append(num.ToString("X2", CultureInfo.InvariantCulture));
- }
- return builder.ToString();
- }
-
- private const string Dropallconstraintsscript =
- @"select
- 'ALTER TABLE ' + so.table_name + ' DROP CONSTRAINT ' + so.constraint_name
- from INFORMATION_SCHEMA.TABLE_CONSTRAINTS so";
-
- private const string Deletealltablesscript =
- @"declare @cmd varchar(4000)
- declare cmds cursor for
- Select
- 'drop table [' + Table_Name + ']'
- From
- INFORMATION_SCHEMA.TABLES
-
- open cmds
- while 1=1
- begin
- fetch cmds into @cmd
- if @@fetch_status != 0 break
- print @cmd
- exec(@cmd)
- end
- close cmds
- deallocate cmds";
-
- private const string LookupEdmMetaDataTable =
- @"Select COUNT(*)
- FROM INFORMATION_SCHEMA.TABLES T
- Where T.TABLE_NAME = 'EdmMetaData'";
- }
-}
@@ -32,9 +32,6 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
- <Reference Include="EntityFramework">
- <HintPath>..\packages\EntityFramework.4.2.0.0\lib\net40\EntityFramework.dll</HintPath>
- </Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
<HintPath>..\packages\MicrosoftWebInfrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
@@ -68,11 +65,8 @@
<Private>True</Private>
<HintPath>..\packages\AspNetWebPagesCore.2.0.10906.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath>
</Reference>
- <Reference Include="System.Xml.Linq" />
- <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
- <Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Controllers\ControllerAction.cs" />
@@ -36,10 +36,11 @@ public void ShouldPersistBids()
var savedAuction = context.Auctions.Find(auction.Id);
Assert.AreEqual(3, savedAuction.Bids.Count);
Assert.AreEqual((Currency)"$30", savedAuction.WinningBid.Amount);
-
+/*
var savedUser = context.Users.Find(user1.Id);
Assert.AreEqual(2, savedUser.Bids.Count);
Assert.IsTrue(savedUser.Bids.OrderBy(x => x.Amount.Value).Last().IsWinningBid);
+ */
});
}
}
@@ -10,7 +10,8 @@ public class RepositoryInitializer
[AssemblyInitialize]
public static void InitializeDatabase(TestContext context)
{
- Database.SetInitializer(new DataContext.DemoDataInitializer());
+ var initializer = new DataContext.DemoDataInitializer(new DropCreateDatabaseAlways<DataContext>());
+ Database.SetInitializer(initializer);
}
}
}
View
@@ -12,6 +12,10 @@
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
+ <dependentAssembly>
+ <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
+ <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
+ </dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Oops, something went wrong.

0 comments on commit 42a3dcc

Please sign in to comment.