I am having issues with using dependency injection, I have many players which can be accessed via
{ route: 'player/:id', moduleId: 'player', name:'player' }
And inside my game class I can successfully create the player objects and list them in my game.html like this, and link them to the correct route.
<ul>
<li repeat.for="player of players">
<span>
${player.name}
</span>
<button click.trigger="removePlayer(player)">Remove</button>
<a route-href="route: player; params.bind: {id:player.id}">
player link
</a>
</li>
</ul>
But when I try to use DI on my player class where I inject a game object like below it wont work.
import {inject} from 'aurelia-framework';
//import {Draw} from './draw';
import {Game} from './game';
let id = 0;
function getId(){
return ++id;
}
#inject(Game)
export class Player {
constructor(name, game) {
this.name = name;
this.game = game;
//this.drawing = new Draw(this);
this.score = 0;
this.id = getId();
}
activate(params, routeConfig) {
console.log("test");
console.log(params);
}
created() {
console.log("created player");
}
}
I get the following error when I go to localhost:9000/#/player/1:
ERROR [app-router] Error: Error invoking Player. Check the inner error for details.
------------------------------------------------
Inner Error:
Message: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
Inner Error Stack:
I am new to aurelia, and not sure what is wrong here?
Related
Is it possible to use the first code to then add it to the Global file (second code)? I can't seem to get it to work. I want to display string user from the second code in the global.asax.
Thanks,
EB
void Session_Start(object sender, EventArgs e)
{
string username = HttpContext.Current.User.Identity.Name;
Session["Username"] = username;
}
Add This:
using (var context = new PrincipalContext(ContextType.Domain, "Domain.local"))
{
var user = UserPrincipal.FindByIdentity(context, username);
}
You can use User.Identity.Name both in Controller and Global.asax.cs.
This User comes from Base Controller Class which in inherited by your custom controller.
If you want to get names in your plain class files you can use these:
System.Security.Principal.WindowsIdentity.GetCurrent().Name
System.Web.HttpContext.Current.User.Identity.Name
In layout I am using this:
<a href="#" id="userRole">
<i class="fas fa-user" style="font-size:14px;"></i> #Business.FindPersonByMSID(User.Identity.Name.Substring(3))
</a>
You can use
#if(User.Identity.Name) in .cshtml anywhere.
Business.FindPersonByMSID is a static method in my Business class I am using to get the Full name of the person by his MSID or NTID .
You did not ask for below code but it will give you full view of what I am doing.
public static string FindPersonByMSID(string msid)
{
string displayName = "";
if (msid.Trim() != "")
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(cn={0}))", msid);
SearchResult allResults;
allResults = searcher.FindOne();
DirectoryEntry deMembershipUser = allResults.GetDirectoryEntry();
deMembershipUser.RefreshCache();
displayName = (string)deMembershipUser.Properties["displayname"].Value;
}
return displayName;
}
I'm trying (with partial success :( ) to retrieve full objects as observables from a collection of indexes of my firebase RTDB using angularfire2 basic methods such as list() and object() in an Ionic app.
When retrieving the list of keys for the courses a user has enrolled on I make a new query and get the full data as an observable using the object() method. I get several null in the view when loading the page for the first time but the observables are still alive, so if I make a small change in those objects in the console, the whole object is retrieved and shown in the view without any problem. Am I missing something?
Firebase RTDB root-level nodes
This is my page ts code
import { Component, ViewChild } from '#angular/core';
import { NavController, NavParams, List } from 'ionic-angular';
import { ProfileServiceProvider } from '../../providers/profile-service/profile-service';
import { MomentsFeedPage } from '../moments-feed/moments-feed';
import { CourseServiceProvider } from '../../providers/course-service/course-service';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
/**
* Generated class for the MomentsPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#Component({
selector: 'page-moments',
templateUrl: 'moments.html',
})
export class MomentsPage{
#ViewChild('enrolledList', { read: List }) enrolledList: List;
public enrolledLis: Observable <{}>;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public courseService: CourseServiceProvider,
public userProfile: ProfileServiceProvider,
public afDB: AngularFireDatabase
) {
if(this.userProfile.currentUser) {
console.log('constructor MomentsPage');
this.enrolledLis = this.afDB.list('/userEnrollments/'+this.userProfile.currentUser.uid).snapshotChanges()
.map( res => {
let enrolled = res;
let that = this;
return enrolled.map(key =>
that.courseService.getCourseDetail(key.key).snapshotChanges()
.map(snap =>
({ key: snap.key, ...snap.payload.val() } )
)
)
}
);
}
}
goToTopicsFeed(course: any) {
this.navCtrl.push(MomentsFeedPage, {
courseId: course.key, courseName: course.name, coursePic: course.coursePic
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad MomentsPage');
}
}
And this is the code for the view
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Moments</ion-title>
</ion-navbar>
</ion-header>
<ion-content no-padding fullscreen parallax-header>
<div class="header-image" style="background-image:url('./assets/imgs/lists/wishlist-1.jpg')">
<h1>Moments</h1>
</div>
<div class="main-content">
<ion-list #enrolledList>
<ion-item-sliding *ngFor="let course of enrolledLis | async" [attr.track]="(course|async)?.degree | courseTrackPipe ">
<button ion-item (click)="goToTopicsFeed(course)" >
<ion-thumbnail item-start>
<img [src]="(course|async)?.coursePic || './assets/imgs/Film-set-greyscale.jpg'" alt="Course profile pic">
</ion-thumbnail>
<h2>{{(course|async)?.name}}</h2>
<h3>{{(course|async)?.degree}}</h3>
<p>Topics info: #topics {{(course|async)?.topicsCount}} activity...</p>
</button>
</ion-item-sliding>
</ion-list>
</div>
</ion-content>
Here you can see the behaviour:
Partial processing of the observables (courses) during first call: css class in added so some rules are applied (border in blue or red)
The first object (course observable) was updated in the firebase console and updated without issues in the view
OK. I'll answer to myself: nothing wrong with the code, maybe I tested wrong. Anyway, there was something not so good in the code: returning async Observables may lead to some problems in the (click) action. Those can be solved using a *ngIf="course" block to make sure the object is got during runtime.
I am experimenting with the Microsoft Graph API and I set up a project with the QuickStarts on the Microsoft developers site.
I'm currently having problems when trying to list all email contacts associated with the logged account.
My problem seems to reside on how I'm requesting and passing the information to ViewBag as it throws a NullReference exceptions even with the proper front-end listing.
Here is the relevant code:
HomeController.cs
public async Task<ActionResult> GetMyContacts()
{
try
{
// Init GraphServiceClient
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
var contacts = await graphService.GetMyEmailContacts(graphClient);
ViewBag.Contacts = contacts;
return View("Graph");
}
catch (ServiceException se)
{
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message });
}
}
GraphService.cs
public async Task<IList<Contact>> GetMyEmailContacts(GraphServiceClient graphClient)
{
User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();
var contacts = me.Contacts;
return contacts;
}
Graph.cshtml
<div class="col-sm-12">
<pre name="user-contacts">#ViewBag.Contacts</pre>
</div>
<h2>TEST GET CONTACTS</h2>
<div class="col-sm-12">
<p>#Html.Raw(ViewBag.Contacts)</p>
</div>
What am I missing here?
In your view, you have to cast it back to the original type. ViewBag is a C# 4 dynamic type. Returned entities are also dynamic unless cast.
var contactList = ViewBag.Contacts as IEnumerable<Contact>;
If you want to display the whole list, it's as simple as this:
#foreach (var contact in contactList)
{
<li>#contact</li>
}
I'm trying to follow the MVC Music Store tutorial , but I got an error which I can't handle. I've created the action:
public ActionResult Browse(string category)
{
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
{
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.Single(c => c.Title == category);
return View(categoryModel);
}
}
Than I created and the respective View:
#model OnlineStoreMVC.Core.Models.Category
#{
ViewBag.Title = "Browse";
}
<h2>Browse Category: #Model.Title</h2>
<ul>
#foreach (var product in Model.Products)
{
<li>
#product.Title
</li>
}
</ul>
But when I try to open: http://localhost:51642/Store/Browse?cat=Action, I get error:
"Sequence contains no elements" regarding this line:
var categoryModel = db.Categories.Include("Products")
.Single(c => c.Title == category);
I've alredy tried to replace Single with SingleOrDefault, but then the error was
"Object reference not set to an instance of an object." regarding that line in the View: "<h2>Browse Category: #Model.Title</h2>"
The problem is that you're passing cat as key in you're url and it should be category. So you should call http://localhost:51642/Store/Browse?category=Action
About the the error "Object reference not set to an instance of the object" you have to change you Action method to:
public ActionResult Browse(string category)
{
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
{
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.SingleOrDefault(c => c.Title == category);
if (categoryModel == default(Category))
{
categoryModel = new Category();
categoryModel.Products = new List<Product>();
}
return View(categoryModel);
}
}
I am trying to add Category and Sub Categories to Organization(Currently logged in User). I can add category but failed to add subCategories to Organization. When I try, get following message:
No signature of method: com.vproc.market.Follower.addToSubCategories() is applicable for argument types: (com.vproc.market.SubCategory) values: [com.vproc.market.SubCategory : 4].
I try to add category and subcategories to Organization in follow method of Organization Controller which is below.
OrganizationController.groovy
def follow() {
Subscriber loggedinSubscriber = subscriberService.getLoggedinSubscriber()
Party organization = loggedinSubscriber?.customer?.party
def marketInstance = Category.get(params.abc)
def follower = new Follower()
follower.followedBy = organization
follower.category = marketInstance
def sub = params.list('subcategories')
sub.each { id ->
follower.addToSubCategories(SubCategory.get(id))
}
follower.save(failOnError: true);
flash.msg = "Okay. This market is now on your watchlist."
redirect (action: "profile")
}
In this method I get error in following line:
follower.addToSubCategories(SubCategory.get(id))
which is mentioned in title of question.
Organization.groovy
package com.vproc.member
import java.util.Date;
import com.vproc.market.SubCategory;
class Organization extends Party{
String orgName
Person contact
String orgSize
boolean isVendor = false
static hasMany = [follows: SubCategory]
static constraints = {
orgName blank: false
orgSize blank: false
}
}
Follower.groovy
package com.vproc.market
import com.vproc.member.Organization;
class Follower {
Category category
Organization followedBy
SubCategory subCategory
static constraints = {
}
}
Follower is domain where Category and subcategories are added to Organization and stored.
Category.groovy
package com.vproc.market
import com.vproc.enquiry.Enquiry;
class Category {
String name
String description
static constraints = {
}
static hasMany = [ subCategories: SubCategory ]
}
SubCategory.groovy
package com.vproc.market
import com.vproc.enquiry.Enquiry;
class SubCategory {
String name
static hasMany = [requirements: Enquiry]
static belongsTo = [ category: Category]
static constraints = {
requirements nullable:true
}
}
gsp file
<g:form controller="organization" params="[temp : marketInstance?.id]" action="follow" method="post">
<g:hiddenField name= "abc" value="${marketInstance?.id}" />
<g:hiddenField name="id" value="${subcategory?.id}" />
<div style="margin-left:200px">
<input type="button" class="button-inner" id="check1" value="Check All" />
<input type="hidden" id="isChkd" value="true" />
<g:each var="subcategory" in="${subCategroyInstanceList}">
<div>
<g:checkBox class="cb1-element" name="subcategories" value="${subcategory.id}"/>
<label for="subcategories"> ${subcategory.name}</label>
</div>
</g:each>
<button class="btn btn-inverse">Submit</button>
</div>
</g:form>
Summary: I want to add category and subcategories to Organization. I can successfully add category but failed to get subcategories to Organization.
Error occurs in following lines:
def sub = params.list('subcategories')
sub.each { id ->
follower.addToSubCategories(SubCategory.get(id))
}
No signature of method: com.vproc.market.Follower.addToSubCategories() is applicable for argument types:
Just a quick look at your domains, the Follower domain has direct association with SubCategory. You can simply assign subCategoty to that no need for follower.addToSubCategories(SubCategory.get(id))
Could be something like this:
follower.subCategory = SubCategory.get(id)
I am working on Grails currently and also found similar issue. I am using Grails 2.3.7 and I found this https://github.com/grails/grails-datastore-test-support/issues/1
Even from this link it mentioned it's a bug but I am still not really sure. So far I just do as following and it works for me:
if(follower.subCategories == null){
follower.subCategories = []
}
def sub = params.list('subcategories')
sub.each { id ->
follower.subCategories.add(SubCategory.get(id))
}
please let me know if you have better solution for this problem.. I am also keen to know it.