Im a classic programmer that is newbie at generics and this is an asp.net MVC5 sample application for learning purposes of integrating authorization (users/roles) using fluent migrator lib. I wantto add some sample datas into tables as they created (using migrator console tool).
getting compilation error: USERNAME does not exist in the current context
what should I add in to using section or any example of:
Insert.IntoTable method ?
(thanks)
namespace SampleApp.Migrations
{
[Migration(1)]
public class AuthMigrations:Migration
{
public override void Up()
{
Create.Table("users").
WithColumn("ID").AsInt32().Identity().PrimaryKey().
WithColumn("USERNAME").AsString(128).
WithColumn("EMAIL").AsCustom("VARCHAR(128)").
WithColumn("PASSWORD_HASH").AsString(128);
Create.Table("roles").
WithColumn("ID").AsInt32().Identity().PrimaryKey().
WithColumn("NAME").AsString(128);
Create.Table("role_users").
WithColumn("ID").AsInt32().Identity().PrimaryKey().
WithColumn("USER_ID").AsInt32().ForeignKey("users", "ID").OnDelete(Rule.Cascade).
WithColumn("ROLE_ID").AsInt32().ForeignKey("roles", "ID").OnDelete(Rule.Cascade);
//Error:The name 'USERNAME' does not exist in the current context
Insert.IntoTable("users").Row(new { USERNAME:"superadmin",EMAIL:"superadmin#mvcapp.com",PASSWORD_HASH:"dfgkmdglkdmfg34532+"});
Insert.IntoTable("users").Row(new { USERNAME:"admin",EMAIL:"admin#mvcapp.com",PASSWORD_HASH:"dfgkmdglkdmfg34532+"});
}
public override void Down()
{
Delete.Table("role_users");
Delete.Table("roles");
Delete.Table("users");
}
}
and
namespace SampleApp.Models
{
public class User
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string EMail { get; set; }
public virtual string passwordhash { get; set; }
}
public class UserMap : ClassMapping<User>
{
public UserMap()
{
Table("Users");
Id(x => x.Id, x => x.Generator(Generators.Identity));
Property(x => x.Username, x => x.NotNullable(true));
Property(x => x.EMail, x => x.NotNullable(true));
Property(x=>x.passwordhash,x=>
{
x.Column("PASSWORD_HASH");
x.NotNullable(true);
});
}
}
}
In C#, you must use an equals sign ("=") in the object initializer instead of a colon (":").
Insert.IntoTable("users").Row(new { USERNAME = "superadmin",EMAIL = "superadmin#mvcapp.com",PASSWORD_HASH = "dfgkmdglkdmfg34532+"});
Insert.IntoTable("users").Row(new { USERNAME = "admin",EMAIL = "admin#mvcapp.com",PASSWORD_HASH = "dfgkmdglkdmfg34532+"});
Related
I'm developing an Azure Mobile App service to interface to my Xamarin application.
I've created, connected and successfully populated an SQL Database, but when I try to add some filters to my request, for example an orderby() or where() clauses, it returns me a Bad Request error.
For example, this request: https://myapp.azurewebsites.net/tables/Race?$orderby=iRound%20desc,iYear%20desc&$top=1&ZUMO-API-VERSION=2.0.0 gives me {"message":"The query specified in the URI is not valid. Could not find a property named 'IYear' on type 'MyType'."}.
My configuration method is this:
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.AddTablesWithEntityFramework()
.ApplyTo(config);
config.MapHttpAttributeRoutes();
Database.SetInitializer(new CreateDatabaseIfNotExists<MainDataContext>());
app.UseWebApi(config);
and my DbContext is this:
public class MainDataContext : DbContext
{
private const string connectionStringName = "Name=MS_TableConnectionString";
public MainDataContext() : base(connectionStringName)
{
Database.Log = s => WriteLog(s);
}
public void WriteLog(string msg)
{
System.Diagnostics.Debug.WriteLine(msg);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}
public DbSet<Race> Race { get; set; }
public DbSet ...ecc...
}
Following this guide, I added a migration after creating my TableControllers. So the TableController for the example type shown above is pretty standard:
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public class RaceController : TableController<Race>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MainDataContext context = new MainDataContext();
DomainManager = new EntityDomainManager<Race>(context, Request);
}
// GET tables/Race
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<Race> GetAllRace()
{
return Query();
}
// GET tables/Race/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<Race> GetRace(string id)
{
return Lookup(id);
}
// PATCH tables/Race/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<Race> PatchRace(string id, Delta<Race> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/Race
public async Task<IHttpActionResult> PostRace(Race item)
{
Race current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/Race/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteRace(string id)
{
return DeleteAsync(id);
}
}
As you can see, I already tried to add the EnableQuery attribute to my TableController, as seen on Google. I also tried to add these filters to the HttpConfiguration object, without any success:
config.Filters.Add(new EnableQueryAttribute
{
PageSize = 10,
AllowedArithmeticOperators = AllowedArithmeticOperators.All,
AllowedFunctions = AllowedFunctions.All,
AllowedLogicalOperators = AllowedLogicalOperators.All,
AllowedQueryOptions = AllowedQueryOptions.All
});
config.AddODataQueryFilter(new EnableQueryAttribute
{
PageSize = 10,
AllowedArithmeticOperators = AllowedArithmeticOperators.All,
AllowedFunctions = AllowedFunctions.All,
AllowedLogicalOperators = AllowedLogicalOperators.All,
AllowedQueryOptions = AllowedQueryOptions.All
});
I don't know what to investigate more, as things seems to be changing too fast for a newbie like me who's first got into Azure.
EDIT
I forgot to say that asking for the complete table, so for example https://myapp.azurewebsites.net/tables/Race?ZUMO-API-VERSION=2.0.0, returns correctly the entire dataset. The problem occurs only when adding some clauses to the request.
EDIT 2
My model is like this:
public class Race : EntityData
{
public int iRaceId { get; set; }
public int iYear { get; set; }
public int iRound { get; set; }
ecc..
}
and the database table that was automatically created is this, including all the properties inherited from EntityData:
Database table schema
Digging into the source code, Azure Mobile Apps sets up camelCase encoding of all requests and responses. It then puts them back after transmission accordign to rules - so iRaceId becomes IRaceId on the server.
The easiest solution to this is to bypass the auto-naming and use a JsonProperty attribute on each property within your server-side DTO and client-side DTO so that they match and will get encoding/decoded according to your rules.
So:
public class Race : EntityData
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("raceId")]
public int iRaceId { get; set; }
[JsonProperty("year")]
public int iYear { get; set; }
[JsonProperty("round")]
public int iRound { get; set; }
etc..
}
I have a validator and I'm trying to use some session variables as part of the validation logic, however the base.Request is always coming back as NULL. I've added it in the lambda function as directed and also the documentation for Validation seems to be out of date as the tip in the Fluent validation for request dtos section mentions to use IRequiresHttpRequest, but the AbstractValidator class already implements IRequiresRequest.
This is my code:
public class UpdateContact : IReturn<UpdateContactResponse>
{
public Guid Id { get; set; }
public string Reference { get; set; }
public string Notes { get; set; }
public List<Accounts> Accounts { get; set; }
}
public class UpdateContactResponse : ResponseBase
{
public Guid ContactId { get; set; }
}
public class UpdateContactValidator : AbstractValidator<UpdateContact>
{
public UpdateContactValidator(IValidator<AccountDetail> accountDetailValidator)
{
RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
var session = base.Request.GetSession() as CustomAuthSession;
RuleFor(c => c.Reference).Must(x => !string.IsNullOrEmpty(x) && session.Region.GetCountry() == RegionCodes.AU);
});
RuleFor(R => R.Accounts).SetCollectionValidator(accountDetailValidator);
}
}
Is there something I'm missing?
Access to injected dependencies can only be done from within a RuleFor() lambda, delegates in a RuleSet() are executed on constructor initialization to setup the rules for that RuleSet.
So you need to change your access to base.Request to within RuleFor() lambda:
RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
RuleFor(c => c.Reference)
.Must(x => !string.IsNullOrEmpty(x) &&
(Request.GetSession() as CustomAuthSession).Region.GetCountry() == RegionCodes.AU);
});
I have the following classses
public pratial class Address
{
public Guid AddressID{ get; set; }
public AddressType AddressType{ get; set; }
}
public partial class AddressType
{
public string TypeName{ get; set; }
}
In my derived DBContext class I have overridden OnModelCreating
protected override OnModelCreating(DBModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>().HasKey( p => p.AddressID );
modelBuilder.Entity<Address>().Property ( p => p.AddressID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Address>().HasRequired( p => p.AddressType);
modelBuilder.Entity<AddrssType>().HasKey( p => p.TypeName );
...
}
This creates fine I fill out a record in the database where
My Tables in the database end up looking like this
Addresses Table
AddressID (PK, uniqueidentified, not null)
AddressType_TypeName(FK, nvarchar(32), not null)
AddressTypes Table
TypeName (PK, uniqueidentifies, not null)
Now I put some data in the tables
AddressTypes Record
TypeName I put in Business
in the Addresses Record
AddressType_TypeName I put in Business
When I run a unit test on this I expect to get back in for my record
List<Address> addresses = context.Addresses.ToList()
Assert.AreEqual(addresses[0].AddressType.TypeName, "Business");
But this fails telling me AddressType is null
How do I set up the relationship between Address and AddressType so that I get back the AddressType that I've hooked up?
To load related entities you must tell it Entity Framework, either by using eager loading:
using System.Data.Entity;
//...
var addresses = context.Addresses.Include(a => a.AddressType).ToList()
...or by lazy loading which is enabled by default if you mark your navigation properties as virtual:
public virtual AddressType AddressType { get; set; }
Eager loading loads the parent and related data together in a single database roundtrip. Lazy loading needs two roundtrips, the second happens under the convers when you access the navigation property in the line addresses[0].AddressType.TypeName.
Edit
Test project to show that lazy loading in this example works (EF 5.0, .NET 4.0, SQL Server Express 2008 R2 as database). I only put virtual in front of AddressType. The rest is identical to your model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
namespace EFLazyLoading
{
public partial class Address
{
public Guid AddressID{ get; set; }
public virtual AddressType AddressType{ get; set; }
}
public partial class AddressType
{
public string TypeName{ get; set; }
}
public class MyContext : DbContext
{
public DbSet<Address> Addresses { get; set; }
public DbSet<AddressType> AddressTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>().HasKey( p => p.AddressID );
modelBuilder.Entity<Address>().Property ( p => p.AddressID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Address>().HasRequired( p => p.AddressType);
modelBuilder.Entity<AddressType>().HasKey( p => p.TypeName );
}
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
using (var ctx = new MyContext())
{
var address = new Address
{
AddressType = new AddressType { TypeName = "Business" }
};
ctx.Addresses.Add(address);
ctx.SaveChanges();
}
using (var ctx = new MyContext())
{
List<Address> addresses = ctx.Addresses.ToList();
string typeName = addresses[0].AddressType.TypeName;
}
}
}
}
The result of typeName in the last line is as expected:
I am working with a database where the designers really seemed to enjoy capital letters and the underscore key. Since I have a simple ORM, my data models use these names as well. I need to build DTOs and I would prefer to give them standard names since we are exposing them through services.
The code below is now corrected! The test passes so use this as a reference if you need to use multiple naming conventions
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using AutoMapper;
using NUnit.Framework;
namespace AutomapperTest
{
public class DATAMODEL
{
public Guid ID { get; set; }
public string FIRST_NAME { get; set; }
public List<CHILD_DATAMODEL> CHILDREN { get; set; }
}
public class CHILD_DATAMODEL
{
public Guid ID { get; set; }
public int ORDER_ID { get; set; }
}
public class DataModelDto
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public List<ChildDataModelDto> Children { get; set; }
}
public class ChildDataModelDto
{
public Guid Id { get; set; }
public int OrderId { get; set; }
}
public class UpperUnderscoreNamingConvention : INamingConvention
{
private readonly Regex _splittingExpression = new Regex(#"[\p{Lu}0-9]+(?=_?)");
public Regex SplittingExpression { get { return _splittingExpression; } }
public string SeparatorCharacter { get { return "_"; } }
}
public class Profile1 : Profile
{
protected override void Configure()
{
SourceMemberNamingConvention = new UpperUnderscoreNamingConvention();
DestinationMemberNamingConvention = new PascalCaseNamingConvention();
CreateMap<DATAMODEL, DataModelDto>();
CreateMap<CHILD_DATAMODEL, ChildDataModelDto>();
}
}
[TestFixture]
public class Tests
{
[Test]
public void CanMap()
{
//tell automapper to use my convention
Mapper.Initialize(x => x.AddProfile<Profile1>());
//make a dummy source object
var src = new DATAMODEL();
src.ID = Guid.NewGuid();
src.FIRST_NAME = "foobar";
src.CHILDREN = new List<CHILD_DATAMODEL>
{
new CHILD_DATAMODEL()
{
ID = Guid.NewGuid(),
ORDER_ID = 999
}
};
//map to destination
var dest = Mapper.Map<DATAMODEL, DataModelDto>(src);
Assert.AreEqual(src.ID, dest.Id);
Assert.AreEqual(src.FIRST_NAME, dest.FirstName);
Assert.AreEqual(src.CHILDREN.Count, dest.Children.Count);
Assert.AreEqual(src.CHILDREN[0].ID, dest.Children[0].Id);
Assert.AreEqual(src.CHILDREN[0].ORDER_ID, dest.Children[0].OrderId);
}
}
}
Create your mappings in profiles, and define the INamingConvention parameters as appropriate.
I don't like the global/static, so I prefer using Initialize and define all of my mappings together. This also has the added benefit of allowing a call to AssertConfiguration... which means if I've borked my mapping I'll get the exception at launch instead of whenever my code gets around to using the problematic mapping.
Mapper.Initialize(configuration =>
{
configuration.CreateProfile("Profile1", CreateProfile1);
configuration.CreateProfile("Profile2", CreateProfile2);
});
Mapper.AssertConfigurationIsValid();
in the same class with that initialization method:
public void CreateProfile1(IProfileExpression profile)
{
// this.CreateMap (not Mapper.CreateMap) statements that do the "normal" thing here
// equivalent to Mapper.CreateMap( ... ).WithProfile("Profile1");
}
public void CreateProfile2(IProfileExpression profile)
{
profile.SourceMemberNamingConvention = new PascalCaseNamingConvention();
profile.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
// this.CreateMap (not Mapper.CreateMap) statements that need your special conventions here
// equivalent to Mapper.CreateMap( ... ).WithProfile("Profile2");
}
if you do it this way, and don't define the same mapping in both profiles, I don't think you need anything to "fill in the blank" from the original question, it should already be setup to do the right thing.
What about
public class DATAMODELProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<DATAMODEL, DATAMODEL>();
Mapper.CreateMap<DATAMODEL, SOMETHINGELSE>();
Mapper.CreateMap<DATAMODEL, DataModelDto>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.ID))
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.FIRST_NAME))
.ForMember(dest => dest.ChildDataModels, opt => opt.MapFrom(src => src.CHILD_DATAMODELS));
}
}
I'm new with orchard.
To learn orchard module development, I am following documentation to try to create a commerce module.
The module consists of product part and product type, which has product part.
When I try to save data in following method:
public ActionResult Create(FormCollection input)
{
var product = contentManager.New<ProductPart>("Product");
product.Description = input["Description"];
product.Sku = input["Sku"];
product.Price =Convert.ToDecimal(input["Price"]);
if (!ModelState.IsValid)
{
return View(product);
}
contentManager.Create(product);
return RedirectToAction("Index");
}
I am getting an error that specific cast is Invalid and part(ContentPart) is null.
public static T New<T>(this IContentManager manager, string contentType)
where T : class, IContent {
var contentItem = manager.New(contentType);
if (contentItem == null)
return null;
var part = contentItem.Get<T>();
if (part == null)
throw new InvalidCastException();
return part;
}
I used content type Product and I have ProductRecord class for storage data, as below:
public class ProductRecord:ContentPartRecord
{
// public virtual int Id { get; set; }
public virtual string Sku { get; set; }
public virtual string Description { get; set; }
public virtual decimal Price { get; set; }
}
public class ProductPart : ContentPart<ProductRecord>
{
/*
public int Id
{
get { return Record.Id; }
set{Record.Id = value;}
}
*/
[Required]
public string Sku
{
get { return Record.Sku; }
set { Record.Sku = value; }
}
[Required]
public string Description
{
get { return Record.Description; }
set{ Record.Description = value;}
}
[Required]
public decimal Price
{
get { return Record.Price; }
set { Record.Price = value; }
}
}
Can anybody tell me what my problem is?
I'm just guessing, but did you declare your record and your ContentType in migration.cs? If you didn't, the content management will be unable to create a content item with your type as it will not know the type in question.
Your migration.cs should look somehow like that:
public class Migrations : DataMigrationImpl
{
public int Create()
{
SchemaBuilder.CreateTable("ProductRecord",
table =>
{
table.ContentPartRecord()
.Column<string>("Sku")
.Column<string>("Description")
.column<decimal>("Price");
});
ContentDefinitionManager.AlterTypeDefinition("Product", cfg => cfg.WithPart("ProductPart"));
return 1;
}
}
On a side note, the naming convention in Orchard is to name the record for a part XXXPartRecord. I don't think your problem lies there though.
I have mentioned this in you other thread.. Orchard Content Type is null
you need
Migrations
public class Migrations : DataMigrationImpl {
public int Create() {
SchemaBuilder.CreateTable("ProductRecord",
table => table
.ContentPartRecord()
.COLUMNS NEED TO BE SPECIFIED
);
ContentDefinitionManager.AlterTypeDefinition("Forum",
cfg => cfg
.WithPart("ProductPart")
.WithPart("CommonPart")
);
Repository
public class ProductPartHandler : ContentHandler {
public ProductPartHandler(IRepository repository) {
Filters.Add(StorageFilter.For(repository));
}
Hope this helps
You could try generating a similar part using the command line utility by pszmyd and see whats different.
http://www.szmyd.com.pl/blog/generating-orchard-content-parts-via-command-line