How can i make this script shorter and easier to use - short

Hi im currently making a weapon system for my top down mmo and after help from my last question ive managed to get it working but it requires alot of coding to add new weapons in id like your help on how i can shorten this process
using UnityEngine;
using System.Collections;
namespace States
{
public enum PlayerState{Forward,Backward,Left,Right}
public enum CurrentWeapon{Sword,Bow}
}
using UnityEngine;
using System.Collections;
using States;
[System.Serializable]
public class Weapons {// class for weapon variables
public GameObject WeaponFront;
public GameObject WeaponBack;
public GameObject WeaponLeft;
public GameObject WeaponRight;
public float Damage;
}
public class WeaponHandler : MonoBehaviour
{
public States.CurrentWeapon Weapon;
public Weapons Sword = new Weapons();//creating new weapons
public Weapons Bow = new Weapons();
Weapon weaponScript;
void Start()
{
weaponScript = GetComponent<Weapon> ();//accesing the attacking script
}
void Update()
{
if (Weapon == CurrentWeapon.Sword){//all of this code is requried to set up 1 weapon
Sword.WeaponFront.SetActive(true);//which is quite alot would ther be an easier way
Sword.WeaponBack.SetActive(true);
Sword.WeaponLeft.SetActive(true);
Sword.WeaponRight.SetActive(true);
weaponScript.Damage = Sword.Damage;
}
else{
Sword.WeaponFront.SetActive(false);
Sword.WeaponBack.SetActive(false);
Sword.WeaponLeft.SetActive(false);
Sword.WeaponRight.SetActive(false);
}
}
}

Related

Load page before content (data from database)

I am creating my first Blazor web application for self education purposes. There is a simple database with data. Dataset is currently rather small. However while clicking on page link it takes some 1-2 seconds to load. Just wondering that how long it would take if dataset would consist of larger amount of items. Is there a way to load page first and then populate the data?
public class EmployeesBase : ComponentBase:
[Inject]
protected IRepository Repository { get; set; }
protected List<BlazorCompanyManager.Data.Employee> employees;
protected override void OnInitialized()
{
this.employees = this.Repository.GetEmployees();
}
public interface IRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorCompanyManager.Data
{
public interface IRepository
{
public List<Employee> GetEmployees();
public Employee GetEmployee(Guid id);
public bool UpdateEmployee(Employee employee);
public void AddEmployee(Employee employee);
public void DeleteEmployee(Guid id);
}
}
public class Repository : IRepository:
protected readonly ApplicationDbContext dbContext;
public Repository(ApplicationDbContext db)
{
this.dbContext = db;
}
public List<Employee> GetEmployees()
{
return this.dbContext.EmployeeTable.ToList();
}
I have tried to make it work with OnInitializedAsync and other override methods, but got no success so far. Could anyone give some idea on how it can be done?
You''re running an async code block synchronously, thus blocking the UI thread.
this.dbContext.EmployeeTable.ToList()
should look like this:
public async ValueTask<List<Employee>> GetEmployeesAsync()
{
using var dbContext = this.DBContext.CreateDbContext();
var list = await dbContext
.EmployeeeTable
.ToListAsync()
?? new List<TRecord>();
return list;
}
To do this you also need to move to an IDbContextFactory in your Repository. You can no longer rely on a single DbContext.
protected virtual IDbContextFactory<MyDbContext> DBContext { get; set; } = null;
public xxxxxRepository(IConfiguration configuration, IDbContextFactory<MyDbContext> dbContext)
=> this.DBContext = dbContext;
Startup/Program
var dbContext = configuration.GetValue<string>("Configuration:DBContext");
services.AddDbContextFactory<MyDbContext>(options => options.UseSqlServer(dbContext), ServiceLifetime.Singleton);
You component initialization then looks like this.
protected async override void OnInitializedAsyc()
{
this.employees = await this.Repository.GetEmployeesAsync();
}
Data loading will be dependant on your data server, but the UI will be responsive. You may need to consider paging as the data set grows - you can only display so many rows at once so why fetch them all at once!

Design a class to be Unit testable

I am going though the Apress ASP.NET MVC 3 book and trying to ensure I create Unit Tests for everything possible but after spending a good part of a day trying to work out why edit's wouldn't save (see this SO question) I wanted to create a unit test for this.
I have worked out that I need to create a unit test for the following class:
public class EFProductRepository : IProductRepository {
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products {
get { return context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
context.Products.Add(product);
}
context.SaveChanges();
}
public void DeleteProduct(Product product) {
context.Products.Remove(product);
context.SaveChanges();
}
}
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
I am using Ninject.MVC3 and Moq and have created several unit tests before (while working though the previously mentioned book) so am slowly getting my head around it. I have already (hopefully correctly) created a constructor method to enable me to pass in _context:
public class EFProductRepository : IProductRepository {
private EFDbContext _context;
// constructor
public EFProductRepository(EFDbContext context) {
_context = context;
}
public IQueryable<Product> Products {
get { return _context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
_context.Products.Add(product);
} else {
_context.Entry(product).State = EntityState.Modified;
}
_context.SaveChanges();
}
public void DeleteProduct(Product product) {
_context.Products.Remove(product);
_context.SaveChanges();
}
}
BUT this is where I start to have trouble... I believe I need to create an Interface for EFDbContext (see below) so I can replace it with a mock repo for the tests BUT it is built on the class DbContext:
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
from System.Data.Entity and I can't for the life of me work out how to create an interface for it... If I create the following interface I get errors due to lack of the method .SaveChanges() which is from the DbContext class and I can't build the interface using "DbContext" like the `EFDbContext is as it's a class not an interface...
using System;
using System.Data.Entity;
using SportsStore.Domain.Entities;
namespace SportsStore.Domain.Concrete {
interface IEFDbContext {
DbSet<Product> Products { get; set; }
}
}
The original Source can be got from the "Source Code/Downloads" on this page encase I have missed something in the above code fragments (or just ask and I will add it).
I have hit the limit of what I understand and no mater what I search for or read I can't seem to work out how I get past this. Please help!
The problem here is that you have not abstracted enough. The point of abstractions/interfaces is to define a contract that exposes behavior in a technology-agnostic way.
In other words, it is a good first step that you created an interface for the EFDbContext, but that interface is still tied to the concrete implementation - DbSet (DbSet).
The quick fix for this is to expose this property as IDbSet instead of DbSet. Ideally you expose something even more abstract like IQueryable (though this doesn't give you the Add() methods, etc.). The more abstract, the easier it is to mock.
Then, you're left with fulfilling the rest of the "contract" that you rely on - namely the SaveChanges() method.
Your updated code would look like this:
public class EFProductRepository : IProductRepository {
private IEFDbContext context;
public EFProductRepository(IEFDbContext context) {
this.context = context;
}
...
}
public interface IEFDbContext {
IDbSet<Product> Products { get; set; }
void SaveChanges();
}
BUT... the main question you have to ask is: what are you trying to test (conversely, what are you trying to mock out/avoid testing)? In other words: are you trying to validate how your application works when something is saved, or are you testing the actual saving.
If you're just testing how your application works and don't care about actually saving to the database, I'd consider mocking at a higher level - the IProductRepository. Then you're not hitting the database at all.
If you want to make sure that your objects actually get persisted to the database, then you should be hitting the DbContext and don't want to mock that part after all.
Personally, I consider both of those scenarios to be different - and equally important - and I write separate tests for each of them: one to test that my application does what it's supposed to do, and another to test that the database interaction works.
I guess your current code looks something like this (I put in the interface):
public class EFProductRepository : IProductRepository {
private IEFDbContext _context;
// constructor
public EFProductRepository(IEFDbContext context) {
_context = context;
}
public IQueryable<Product> Products {
get { return _context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
_context.Products.Add(product);
} else {
_context.Entry(product).State = EntityState.Modified;
}
**_context.SaveChanges();**
}
public void DeleteProduct(Product product) {
_context.Products.Remove(product);
**_context.SaveChanges();**
}
}
public class EFDbContext : DbContext, IEFDbContext {
public DbSet<Product> Products { get; set; }
}
public interface IEFDbContext {
DbSet<Product> Products { get; set; }
}
The problem is EFProductRepository now expects an object implementing the IEFDbContext interface, but this interface does not define the SaveChanges method used at the lines I put between the asteriskes so the compiler starts complaining.
Defining the SaveChanges method on the IEFDbContext interface solves your problem:
public interface IEFDbContext {
DbSet<Product> Products { get; set; }
void SaveChanges();
}

Simplest approach for applying the MVP pattern on a Desktop (WinForms) and Web (ASP.NET) solution

Having almost no architectural experience I'm trying to design a DRY KISS solution for the .NET 4 platform taking an MVP approach that will eventually be implemented as a Desktop (WinForms) and Web (ASP.NET or Silverlight) product. I did some MVC, MVVM work in the past but for some reason I'm having difficulties trying to wrap my head around this particular one so in an effort to get a grip of the pattern I've decided to start with the simplest sample and to ask you guys for some help.
So assuming a quite simple Model as follows (in practice it'd most definitely be a WCF call):
internal class Person
{
internal string FirstName { get; set; }
internal string LastName { get; set; }
internal DateTime Born { get; set; }
}
public class People
{
private readonly List<Person> _people = new List<Person>();
public List<Person> People { get { return _people; } }
}
I was wondering:
What would be the most generic way to implement its corresponding View/Presenter triad (and helpers) for say, a Console and a Forms UI?
Which of them should be declared as interfaces and which as abstract classes?
Are commands always the recommended way of communication between layers?
And finally: by any chance is there a well-docummented, testeable, light framework to achieve just that?
I've written a number of apps that require a GUI and a winforms UI, the approach I have typically taken to implementing MVP is to create a generic view interface (you can subclass this for more specific views) and a controllerbase class which is given a view. You can then create different view implementations which inherit from the IView (or more specific view) interface
interface IView
{
event EventHandler Shown;
event EventHandler Closed;
void ShowView(IView parentView);
void CloseView();
}
class ControllerBase<T> where T: IView
{
private T _view;
public ControllerBase(T view)
{
_view = view;
}
public T View
{
get { return _view; }
}
public void ShowView(IView owner)
{
_view.ShowView(owner);
}
public void ShowView()
{
ShowView(null);
}
public void CloseView()
{
_view.CloseView();
}
}
Heres an example of how it would work in a specific case
interface IPersonView: IView
{
event EventHandler OnChangeName;
string Name { get; set; }
}
class PersonController: ControllerBase<IPersonView>
{
public PersonController(string name,IPersonView view) : base(view)
{
View.Name = name;
View.OnChangeName += HandlerFunction;
}
private void HandlerFunction(object sender, EventArgs e)
{
//logic to deal with changing name here
}
}
To implement this view in winforms, just make sure your form inherits from IPersonView and implements all the required properties/events and you're good to go. To instantiate the view/controller you'd do something like the following
PersonForm form = new PersonForm();
PersonController controller = new PersonController("jim",form);
controller.ShowView();

Abstraction and information hiding

Abstraction means hiding 'implementation details'..... So the goal of abstraction is to achieve information hiding?? And what is hidden in Information hiding if not implementation details??
And how abstraction is a technique to information hiding?
The goal of abstraction is not to hide information in the sense of variable values, that would be encapsulation.
Abstraction's only goal is allow programmers to use an algorithm or concept without understanding it. Information hiding may be a by-product of this but it is not its goal.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* Example of Abstratcion: An application for mobile manufacturing company - Every phone must have to implement caller
* and sms feature but it depends on company to company (or model to model) if they want to include other features or not
* which are readily available , you just have to use it without knowing its implementation (like facebook in this example).
*/
namespace AbstractTest
{
public abstract class feature
{
public abstract void Caller();
public abstract void SMS();
public void facebook()
{
Console.WriteLine("You are using facebook");
}
}
public class Iphone : feature
{
public override void Caller()
{
Console.WriteLine("iPhone caller feature");
}
public override void SMS()
{
Console.WriteLine("iPhone sms feature");
}
public void otherFeature()
{
facebook();
}
}
public class Nokia : feature
{
public override void Caller()
{
Console.WriteLine("Nokia caller feature");
}
public override void SMS()
{
Console.WriteLine("Nokia sms feature");
}
}
class Program
{
static void Main(string[] args)
{
Iphone c1 = new Iphone();
c1.Caller();
c1.SMS();
c1.otherFeature();
Nokia n1 = new Nokia();
n1.Caller();
n1.SMS();
Console.ReadLine();
}
}
}

sharp architecture question

I am trying to get my head around the sharp architecture and follow the tutorial. I am using this code:
using Bla.Core;
using System.Collections.Generic;
using Bla.Core.DataInterfaces;
using System.Web.Mvc;
using SharpArch.Core;
using SharpArch.Web;
using Bla.Web;
namespace Bla.Web.Controllers
{
public class UsersController
{
public UsersController(IUserRepository userRepository)
{
Check.Require(userRepository != null,"userRepository may not be null");
this.userRepository = userRepository;
}
public ActionResult ListStaffMembersMatching(string filter) {
List<User> matchingUsers = userRepository.FindAllMatching(filter);
return View("ListUsersMatchingFilter", matchingUsers);
}
private readonly IUserRepository userRepository;
}
}
I get this error:
The name 'View' does not exist in the current context
I have used all the correct using statements and referenced the assemblies as far as I can see. The views live in Bla.Web in this architecture.
Can anyone see the problem?
Thanks.
Christian
You should inherit UsersController from System.Web.Mvc.Controller class. View() method is defined in Controller class.
public class UsersController : Controller
{
//...
}

Resources