CS1646 Keyword, identifier, or string expected after verbatim specifier: # - asp.net-mvc-5

tables in my EntityFramework model are events, eventtypes, subevents, subeventtypes
using the MVC5 builders (right click on controllers, add, add controller) I created controllers and views for the last three tables without issue however when I create the controller and views for the events entity I produce the following errors
Keyword, identifier, or string expected after verbatim specifier: #
'EventType' is a type, which is not valid in the given context
the code that was generated in the event controller is
{
private Entities db = new Entities();
// GET: Events
public ActionResult Index()
{
var events = db.Events.Include(# => #.EventType); ERROR HERE
return View(events.ToList());
}
any help with this issue would be greatly appreciated
TIA

I experienced the same issue when using the "MVC Controller with views, using Entity Framework" template.
var #group = await _context.Groups
.Include(# => #.Company)
.FirstOrDefaultAsync(m => m.GroupId == id);
My workaround was simple to replace the # symbol with another character i.e. g
var #group = await _context.Groups
.Include(g => g.Company)
.FirstOrDefaultAsync(m => m.GroupId == id);

Related

Acumatica GetList error: Optimization cannot be performed.The following fields cause the error: Attributes.AttributeID

Developer's version of Acumatica 2020R1 is installed locally. Data for sample tenant MyTenant from training for I-300 were loaded, and WSDL connection established.
DefaultSoapClient is created fine.
However, attempts to export any data by using Getlist cause errors:
using (Default.DefaultSoapClient soapClient =
new Default.DefaultSoapClient())
{
//Sign in to Acumatica ERP
soapClient.Login
(
"Admin",
"*",
"MyTenant",
"Yogifon",
null
);
try
{
//Retrieving the list of customers with contacts
//InitialDataRetrieval.RetrieveListOfCustomers(soapClient);
//Retrieving the list of stock items modified within the past day
// RetrievalOfDelta.ExportStockItems(soapClient);
RetrievalOfDelta.ExportItemClass(soapClient);
}
public static void ExportItemClass(DefaultSoapClient soapClient)
{
Console.WriteLine("Retrieving the list of item classes...");
ItemClass ItemClassToBeFound = new ItemClass
{
ReturnBehavior = ReturnBehavior.All,
};
Entity[] ItemClasses = soapClient.GetList(ItemClassToBeFound);
string lcItemType = "", lcValuationMethod = "";
int lnCustomFieldsCount;
using (StreamWriter file = new StreamWriter("ItemClass.csv"))
{
//Write the values for each item
foreach (ItemClass loItemClass in ItemClasses)
{
file.WriteLine(loItemClass.Note);
}
}
The Acumatica instance was modified by adding a custom field to Stock Items using DAC, and by adding several Attributes to Customer and Stock Items.
Interesting enough, this code used to work until something broke it.
What is wrong here?
Thank you.
Alexander
In the request you have the following line: ReturnBehavior = ReturnBehavior.All
That means that you try to retrieve all linked/detail entities of the object. Unfortunately, some object are not optimized enough to not affect query performance in GetList scenarios.
So, you have to options:
Replace ReturnBehavior=All by explicitly specifying linked/detail entities that you want to retrieve and not include Attributes into the list.
Retrieve StockItem with attributes one by one using Get operation instead of GetList.
P.S. The problem with attributes will most likely be fixed in the next version of API endpoint.
Edit:
Code sample for Get:
public static void ExportItemClass(DefaultSoapClient soapClient)
{
Console.WriteLine("Retrieving the list of item classes...");
ItemClass ItemClassToBeFound = new ItemClass
{
ReturnBehavior = ReturnBehavior.Default //retrieve only default fields (without attributes and other linked/detailed entities)
};
Entity[] ItemClasses = soapClient.GetList(ItemClassToBeFound);
foreach(var entity in ItemClasses)
{
ItemClass itemClass= entity as ItemClass;
ItemClass.ReturnBehavior=ReturnBehavior.All;
// retrieve each ItemClass with all the details/linked entities individually
ItemClass retrievedItemCLass = soapClient.Get(itemClass);
}

What is the proper way to add a Field to a custom Part in code?

There are several similar questions that sort of deal with this issue like this one or this one offering a pretty hacky solution. None of the ones out there have a clear satisfactory answer, or an answer at all, or are asking quite the same thing to begin with.
Record
public class MyPartRecord : ContentPartRecord
{
public virtual Boolean Property1 { get; set; }
public virtual string Property2 { get; set; }
}
Part
public class MyPart : ContentPart<MyPartRecord>
{
public Boolean Property1
{
get { return Record.Property1; }
set { Record.Property1 = value; }
}
public string...
}
Migration (generated by codegen)
SchemaBuilder.CreateTable("MyPartRecord", table => table
.ContentPartRecord()
.Column("Property1", DbType.Boolean)
.Column("Property2", DbType.String)
);
ContentDefinitionManager.AlterPartDefinition("MyPart", part => part
.Attachable()
);
Editor template
#model Project.Module.Models.MyPart
<fieldset>
<legend>MyPart</legend>
<!-- Property1 -->
#Html.EditorFor(m => m.Property1)
#Html.LabelFor(m => m.Property1)
...
</fieldset>
This is all taken from the official documentation on writing Content Parts and works fine. However, I want my custom Part to also have a MediaLibraryPickerField. Adding one through a migration is easy enough:
ContentDefinitionManager.AlterPartDefinition("MyPart", part => part
.WithField("Image", field => field
.OfType("MediaLibraryPickerField")
.WithDisplayName("Image")
.WithSetting("MediaLibraryFieldSettings.Required", "False")
)
);
But there are several problems I bump into using this approach.
1) I can't render the field in my template, only use placement to have it show up somewhere above or below the rest of the template, so I can't group it with the properties that it belongs to.
2) Since it's attached to MyPart and not the ContentPart of the Type that MyPart gets attached to, admins can't adjust its settings through the GUI, only remove it (is this a bug or a feature that has yet to be implemented?).
3) I'm unsure how to access the MediaLibraryField in code, since ContentItem.MyPart returns a MyPart object now, so ContentItem.MyPart.Image.FirstMediaUrl no longer works.
How do I get around these issues? Am I missing something obvious here? Is there perhaps a way to add Media as a property to my model instead of using a Field and still have Orchard persist it? I would really like to avoid modifying my HTML and copying code from the official implementation to my custom views.
1) Use placement.info and alternates to customize where you want to render the field
2) You should be able to adjust the settings in Dashboard -> Content Definition -> YourContentType -> Parts -> under the MyPart settings.
You could also attach the field to the type instead (note: it isn't really attached to the type, but to the part with the same name as the type):
Migrations.cs:
ContentDefinitionManager.AlterPartDefinition("MyType", part => part
.WithField("Image", field => field
.OfType("MediaLibraryPickerField")
.WithDisplayName("Image")
.WithSetting("MediaLibraryFieldSettings.Required", "False")
)
);
ContentDefinitionManager.AlterTypeDefinition("MyType", type => type
.WithPart("MyType");
3) You can either use the dynamic notation, or search the field:
// cast to dynamic
var url = ((dynamic)ContentItem).MyPart.Image.FirstMediaUrl
// or search for the field
var field = ContentItem.MyPart.Fields.OfType<MediaLibraryPickerField>().Single(f => f.Name == "Image");
// or ContentItem.MyPart.Fields.Single(f => f.Name == "Image") as MediaLibraryPickerField;
var url = field.FirstMediaUrl;

Laravel 5 pagination Call to a member function render() on a non-object

I am trying to paginate some categories and this error popped up from nowhere and I don't know how to fix it :
Call to a member function render() on a non-object
This is my controller:
public function getFilmeByCateg()
{
$categorii = Categorii::all();
//$Movies = Movies::all();
$categorie = Request::segment(2);
$cat = Categorii::where('denumire', '=',$categorie)->first();
$cat2 = Categorii_filme::where('categorie_id', '=' ,$cat->categorie_id)->get();
$filme = array();
foreach($cat2 as $filmulet)
{
$film = Movies::where('movie_id','=',$filmulet->film_id)->paginate(12)->first();
$filme[] = $film;
}
return view('filme')->with('Movies',$filme)->with('categorii',$categorii);
}
And this is how I render the paginator in my layout:
{!!$Movies->render() !!}
This is in my routes:
Route::get('categorie/{categorie}','WelcomeController#getFilmeByCateg');
This is in my Movies.php:
class Movies extends Model {
protected $table = "movies";
}
Can someone tell me how can I manage to make this work ?
Since $filme is an array, you can access render() method whose object you wanted is $Movies which is array.
foreach($cat2 as $filmulet)
{
$film = Movies::where('movie_id','=',$filmulet->film_id)->paginate(12)->first();
$filme[] = $film;
}
Here $filme is an array.
return view('filme')->with('Movies',$filme)->with('categorii',$categorii);
Here you passed $filme as $Movie variable.
{!!$Movies->render() !!}
And here you wanted to access render() method of $filme which is not an object.
Change your controller to this:
public function getFilmeByCateg()
{
$categorii = Categorii::all();
//$Movies = Movies::all();
$categorie = Request::segment(2);
$cat = Categorii::where('denumire', '=',$categorie)->first();
$movie_ids = Categorii_filme::where('categorie_id', '=' ,$cat->categorie_id)->get()->lists('movie_id');
$filme = Movies::whereIn('movie_id','=',$movie_ids)->paginate(12);
return view('filme')->with('Movies',$filme)->with('categorii',$categorii);
}
OK First of all, you made it the wrong way.
Using an intermediate class for representing the pivot table is completely bad.
I'll make it work for you.
Your Category class
class Category extends \Model {
protected $table = 'categories';
public function movies()
{
return $this->belongsToMany('Your\Namespace\To\Movie');
}
}
Your Movie class
class Movie extends \Model {
protected $table = 'movies';
public function categories()
{
return $this->belongsToMany('Your\Namespace\To\Category');
}
}
Your route is still :
Route::get('categorie/{category_id}','WelcomeController#getFilmeByCateg');
So in your controller method you do the following :
public function getFilmeByCateg($category_id)
{
$category = Category::findOrFail($category_id);
return view('filme')->with('Movies',$category->movies()->paginate(12)->ge())->with('categorii',Category::all());
}
Now in your view $Movies->render() will work
If you wont paginate your data how would you render it ? Documents on the official laravel website states :
There are several ways to paginate items. The simplest is by using the paginate method on the query builder or an Eloquent model.
Paging database results
$users = DB::table('users')->paginate(15);
Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.
Creating A Paginator Manually
Sometimes you may wish to create a pagination instance manually,
passing it an array of items. You may do so by creating either an
Illuminate\Pagination\Paginator or
Illuminate\Pagination\LengthAwarePaginator instance, depending on your
needs.
Now in your case you should first
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
and then
$paginator = new Paginator($items, $count, $limit, $page, [
'path' => $this->request->url(),
'query' => $this->request->query(),
]);
Please supply parameters accordingly in the Paginator function above.
I know it is very late but it will help someone who get in to same issue. Instead of ->get() use ->paginate(10) in query.

Extract paging from IQueryable

I'm using a function to allow query composition from Web UI and I would to implement paging functionality which it will be available for dataBound controls such as ObjectDataSource, gridView, etc:
public class MyClass<TEntity> where TEntity : class
{
FakeEntities xxx = new FakeEntities();
public IEnumerable<TEntity> Get(Func<IQueryable<TEntity>, IQueryable<TEntity>> queryExpression)
{
var query = xxx.Set<TEntity>();
return queryExpression(query).ToList();
}
public int Count()
{
// What Can I return?
}
}
// **** USAGE ****
MyClass<User> u = new MyClass<User>();
var all = u.Get(p => p.Where(z => z.Account == "Smith").OrderBy(order => order.IdOther).Skip(1).Take(2));
The above query use Take and Skip function, so can I get real count of my entities? Obviously I must return Query Count without modifying filter expression.
I found this solution: Get count of an IQueryable<T>
However I get targetInvocationException with inner message {"This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code."}
I know my request could be freak-abnormal, because best practice should to impose to move "presentation needs" to some wrap class and that's is what I'll do. So I don't need anymore to get Count entities on my business logic class.
That's just UI concern only.
Thank you the same.

Security model and existing database

I have created a database with code first and DbContext.
However this sit separately to the security model database on a new MVC 4 site.
My question is how do i combine my existing database with the security model or should they be kept separate for a valid reason
For example is this the best solution
http://blog.spontaneouspublicity.com/including-asp-net-simple-membership-tables-as-part-of-your-entity-framework-model
This would recreate the security model and roles when i first ran the application.
Or is there an alternative way of doing this.
I love the new MVC and Simplemembership Provider for this reason. You can very easily combine your models with the asp.net account models.
When you use the default internet template it creates a context called UsersContext. To do something simple like add additional fields to a UserProfile object to track in the database you need to do 3 simple things.
Add the properties to the model (in the account models if you use the default template)
In the register action on the account controller, add the new fields IE:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
var db = new UsersContext();
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { FirstName = model.FirstName, LastName = model.LastName, Address = model.Address, Company = model.Company, Phone = model.Phone, Country = model.Country, City = model.City, State = model.State, Zip = model.Zip });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Dashboard");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Note the new keyword where I took values from the model passed and just matched them up to the model. (model binding may or may not work here but I haven't tested that yet)
3) Change the register View and model to pass all the info needed
I almost cried when this worked flawlessly the first time with no strange errors.
Good luck

Resources