Error when add Handler - orchardcms

I developed new module, when I add below code for handler and want to create one content from my new contentType in dashboard and submit form, I get an error. When I remove Handler or comment that the error was fixed but none part of data saved in database.
I checked, migration run OK and table created successfully. here is my model, record and part codes. Thanks...
// MyModulePart.cs
using System;
using Orchard.ContentManagement;
namespace www.MyModule.com.Models {
public class MyModule : ContentPart<MyModuleRecord> {
public string Name { get { return Record.Name; } set { Record.Name = value; } }
public string ImdbRate { get { return Record.ImdbRate; } set { Record.ImdbRate = value; } }
}
}
// MyModulePartRecord.cs
using System;
using Orchard.ContentManagement.Records;
namespace www.MyModule.com.Models
{
public class MyModulePartRecord : ContentPartRecord
{
public virtual string Name { get; set; }
public virtual string ImdbRate { get; set; }
}
}
// Migration Code
SchemaBuilder.CreateTable("MyModulePartRecord", table => table
.ContentPartRecord()
.Column<string>("Name")
.Column<string>("ImdbRate"));
// Handler Code
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using www.MyModule.com.Models;
namespace www.MyModule.com.Handlers {
public class MyModuleHandler : ContentHandler
{
public MyModuleHandler(IRepository<MyModulePartRecord> MyModulePartRepository)
{
Filters.Add(StorageFilter.For(MyModulePartRepository));
}
}
}
Error:
null id in Orchard.ContentManagement.Records.ContentItemRecord entry
(don't flush the Session after an exception occurs)
please guide me.
Excuse me for my bad English.
Thanks...

Related

Error when adding Where or OrderBy clauses to Azure Mobile Apps request

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

adding initial rows into tables using Fluent migrator

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+"});

Orchard Custom Content Type isn't saving

I have created a custom content type called 'AccessFolder'. I can see it in the list of content types and can create a new one. When I create a new AccessFolder, I get my editor template that I created for it. After I enter the information and click save, I'm directed to a Not Found page however the indicator message tells me my AccessFolder was created successfully.
In the driver, I can see the model after it is bound using the updater.TryUpdateModel. The correct values are assigned to the model's properties.
It just never gets to the database.
AccessFolderPart:
public class AccessFolderPart : ContentPart<AccessFolderPartRecord>
{
public virtual string Name
{
get { return Record.Name; }
set { Record.Name = value; }
}
public virtual IEnumerable<RoleRecord> DownloadRoles
{
get { return Record.DownloadRoles.Select(x => x.RoleRecord); }
}
}
AccessFolderPartRecord
public class AccessFolderPartRecord : ContentPartRecord
{
public virtual string Name { get; set; }
public virtual List<ContentAccessFolderRoleRecord> DownloadRoles { get; set; }
}
Relevant Pieces of AccessFolderPartDriver
protected override DriverResult Editor(AccessFolderPart part, dynamic shapeHelper)
{
var viewModel = new AccessFolderViewModel(part, _roleService.GetRoles());
return ContentShape("Parts_AccessFolder_Edit", () =>
shapeHelper.EditorTemplate(TemplateName: templateName, Model: viewModel, Prefix: Prefix));
}
protected override DriverResult Editor(AccessFolderPart part, Orchard.ContentManagement.IUpdateModel updater, dynamic shapeHelper)
{
var viewModel = new AccessFolderViewModel { Part = part };
updater.TryUpdateModel(viewModel, Prefix, null, null);
if (part.ContentItem.Id != 0)
{
_roleService.UpdateRolesForAccessFolder(part.ContentItem, part.DownloadRoles);
}
return Editor(part, shapeHelper);
}
I've been stuck on this since Friday. I've created custom types before and never had any problems with it. I can't see what I've done wrong here.
Update - Added content Handler class
Here's the one line for the handler:
public class AccessFolderPartHandler : ContentHandler
{
public AccessFolderPartHandler(IRepository<AccessFolderPartRecord> repository)
{
Filters.Add(StorageFilter.For(repository));
}
}
I Think you are missing the proper mapping on your driver:
if (updater.TryUpdateModel(viewModel, Prefix, null, null))
{
part.Name= viewModel.Name;
if (part.ContentItem.Id != 0)
{
_roleService.UpdateRolesForAccessFolder(part.ContentItem, part.DownloadRoles);
}
}

Automapper ObservableCollection – refreshing is not working

I have small WPF application. There are 5 projects in solution.
I want separate DOMAIN classes with UI ENTITIES and I want to use AUTOMAPPER.
You can download whole solution here: TestWPFAutomapper.zip
Domain class(Domain.Source.cs) with UI Entity(Entities.Destination.cs) have same signature.
In Entities.Destination.cs I would like to put other logic.
namespace DOMAIN
{
public class Source
{
public int Id { get; set; }
public int Position { get; set; }
}
}
using System.ComponentModel;
namespace ENITITIES
{
public class Destination : INotifyPropertyChanged
{
private int _id;
private int _position;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
public int Position
{
get { return _position; }
set
{
_position = value;
OnPropertyChanged("Position");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
My data comes from DAL.DataContext using Entity Framework with CodeFirst. Here I´m using Source class.
using System.Data.Entity;
using DOMAIN;
namespace DAL
{
public class DataContext : DbContext
{
public DbSet<Source> Sources { get; set; }
}
}
Mapping is in BL.MyAppLogic.cs . In this class I have property Items which is ObservableCollection.
After puting another item into DB for Source class collection get refresh but for Destination is not refreshing.
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using AutoMapper;
using DAL;
using DOMAIN;
using ENITITIES;
namespace BL
{
public class MyAppLogic
{
private readonly DataContext _dataContext = new DataContext();
public ObservableCollection<Source> Items { get; set; }
//public ObservableCollection<Destination> Items { get; set; }
public MyAppLogic()
{
Database.SetInitializer(new MyInitializer());
Mapping();
_dataContext.Sources.Load();
Items = _dataContext.Sources.Local;
//Items = Mapper.Map<ObservableCollection<Source>, ObservableCollection<Destination>>(_dataContext.Sources.Local);
}
private void Mapping()
{
Mapper.CreateMap<Source, Destination>().ReverseMap();
// I tried also Mapper.CreateMap<ObservableCollection<Source>, ObservableCollection<Destination>>().ReverseMap();
}
public int GetLastItem()
{
return _dataContext.Database.SqlQuery<int>("select Position from Sources").ToList().LastOrDefault();
}
public void AddNewItem(Destination newItem)
{
_dataContext.Sources.Add(Mapper.Map<Destination, Source>(newItem));
_dataContext.SaveChanges();
}
}
}
My problem is not with mapping, that’s works good, but with refreshing collection after adding or removing items from db. If I use DOMAIN.Source class everything works, collection is refreshing. But when I’m using ENTITIES.Destination data comes from DB and also I can put som new data to DB but refresing ObservableCollection is not working.
Please try to comment lines(14 & 23) in BL.MyAppLogic.cs and uncomment(15 & 24) and you’ll see what I mean.
Thank you for any help.
I got it but I don´t know if is correct.
Local has CollectionChanged event
so in constructor I put these lines
public MyAppLogic()
{
Database.SetInitializer(new MyInitializer());
Mapping();
_dataContext.Sources.Load();
_dataContext.Sources.Local.CollectionChanged += SourcesCollectionChanged;
Items = Mapper.Map<ObservableCollection<Source>, ObservableCollection<Destination>>(_dataContext.Sources.Local);
}
and handler looks
private void SourcesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var source = sender as ObservableCollection<Source>;
Mapper.Map(source, Items);
}
Now is my collection automating refreshing when I put something to DB in my UI.
Looks like automapper don´t put reference into Items, but create new instance.

How to save data through Orchard module?

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

Resources