How can I get the PropertyInfo's of all the static properties, with FlattenHierachy in the new for-apps .Net profile?
I want this code, but for App-.Net:
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
return type.GetProperties(bindingFlags);
All these tests are passing on Win8 RTM/.Net Core 4.5.
namespace Automatonymous.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using System.Reflection;
class SuperTarget
{
public static string StaticProp { get; set; }
public string InstanceProp { get; set; }
}
class SubTarget
: SuperTarget
{
public string AnotherProp { get; private set; }
}
class PrivateStatics
: SuperTarget
{
static string CanWeGetPrivates { get; set; }
}
class StaticsNoGetter
: SuperTarget
{
public static string ZupMan { set; private get; }
}
[TestFixture]
public class when_getting_static_properties
{
[Test]
public void can_get_property_on_stand_alone_class()
{
var props = GetAllStaticProperties(typeof(SuperTarget));
Assert.That(props.Count(), Is.EqualTo(1));
Assert.That(props.First().Name, Is.EqualTo("StaticProp"));
}
[Test]
public void can_get_single_property_on_super_from_sub()
{
var props = GetAllStaticProperties(typeof(SubTarget));
Assert.That(props.Count(), Is.EqualTo(1));
Assert.That(props.First().Name, Is.EqualTo("StaticProp"));
}
[Test]
public void can_get_private_static_properties()
{
var props = GetAllStaticProperties(typeof(PrivateStatics));
Assert.That(props.Count(), Is.EqualTo(2));
var names = props.Select(x => x.Name);
CollectionAssert.Contains(names, "CanWeGetPrivates");
CollectionAssert.Contains(names, "StaticProp");
}
[Test]
public void can_get_even_with_private_getter()
{
var props = GetAllStaticProperties(typeof(StaticsNoGetter));
Assert.That(props.Count(), Is.EqualTo(2));
var names = props.Select(x => x.Name);
CollectionAssert.Contains(names, "ZupMan");
CollectionAssert.Contains(names, "StaticProp");
}
[Test]
public void can_get_with_no_hierarchy()
{
var props = GetAllStaticProperties(typeof(StaticsNoGetter), false);
Assert.That(props.Count(), Is.EqualTo(1));
Assert.That(props.First().Name, Is.EqualTo("ZupMan"));
}
static IEnumerable<PropertyInfo> GetAllStaticProperties(Type type,
bool flattenHierachy = true)
{
var info = type.GetTypeInfo();
if (info.BaseType != null && flattenHierachy)
foreach (var prop in GetAllStaticProperties(info.BaseType, true))
yield return prop;
var props = info.DeclaredMethods
.Where(x => x.IsSpecialName && x.Name.StartsWith("get_") && x.IsStatic)
.Select(x => info.GetDeclaredProperty(x.Name.Substring("get_".Length)));
foreach (var propertyInfo in props)
yield return propertyInfo;
}
}
}
Related
I'm trying to follow this tutorial on SQLite-net-pcl: https://github.com/jamesmontemagno/MyCoffeeApp
I have this model:
public class TipoUsuarioModel
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string TipoUsuario { get; set;}
public bool PermiteConsultar { get; set; }
public bool PermiteBuscar { get; set; }
public bool PermiteReducirCantidad { get; set;}
public bool PermiteAumentarCantidad { get; set; }
public bool PermiteAgregarArticulos { get; set; }
}
This is my interface:
public interface IUsuarios
{
Task AgregarUsuario(
string nombre,
string contrasenna,
string imagen,
int idtipoUsuario,
bool administrador,
string tipoUsuario);
Task<IEnumerable<UsuarioModel>> ObtieneUsuarios();
Task<UsuarioModel> ObtieneUsuarios(int id);
}
This is my service:
public class TipoUsuario: ITipoUsuario
{
SQLiteAsyncConnection db;
async Task Init()
{
if (db != null)
return;
// Get an absolute path to the database file
var databasePath = Path.Combine(FileSystem.AppDataDirectory, "PlayOnData.db");
db = new SQLiteAsyncConnection(databasePath);
await db.CreateTableAsync<TipoUsuarioModel>();
await AgregarTipoUsuario("Administrador", true, true, true, true, true);
}
public async Task AgregarTipoUsuario(
string tipoUsuario,
bool permiteConsultar,
bool permiteBuscar,
bool permiteReducirCantidad,
bool permiteAumentarCantidad,
bool permiteAgregarArticulos)
{
await Init();
var usuario = new TipoUsuarioModel
{
TipoUsuario = tipoUsuario,
PermiteConsultar = permiteConsultar,
PermiteBuscar = permiteBuscar,
PermiteReducirCantidad = permiteReducirCantidad,
PermiteAumentarCantidad = permiteAumentarCantidad,
PermiteAgregarArticulos = permiteAgregarArticulos
};
await db.InsertAsync(usuario);
}
public async Task<IEnumerable<TipoUsuarioModel>> ObtieneTipoUsuarios()
{
await Init();
var tipoUsuario = await db.Table<TipoUsuarioModel>().ToListAsync();
return tipoUsuario;
}
public async Task<TipoUsuarioModel> ObtieneTipoUsuarios(int id)
{
await Init();
var tipoUsuario = await db.Table<TipoUsuarioModel>()
.FirstOrDefaultAsync(c => c.Id == id);
return tipoUsuario;
}
}
Now, On my main page, I have this:
public partial class HomePage : ContentPage
{
ITipoUsuario tipoService;
public HomePage ()
{
InitializeComponent ();
}
protected override async void OnAppearing()
{
await tipoService.AgregarTipoUsuario("Administrador", true, true, true, true, true);
base.OnAppearing();
}
}
Every time I run the app and excuse the line to create data, it throws this error message:
System.NullReferenceException
What am I missing? Thanks in advance!
How can I access the current ApplicationUser (or UserManager) within an ActionFilter in Asp.Net Core 2.0?
I am trying to lock down the entire application until the user accepts the EULA (End User License Agreement), changes their password, and fills out required personal information.
public class ApplicationUser : IdentityUser
{
...
public DateTime? DateEULAAccepted { get; set; }
...
}
Here is the ActionFilter code:
public class ProfileRequiredActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = UserManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}
I am instantiating the ActionFilter in the Startup > ConfigureServices as follows:
...
services.AddMvc(options =>
{
options.Filters.Add(new ProfileRequiredActionFilter());
});
...
Try adding your filter in ConfigureServices() as follows:
services.AddMvc(options => {
options.Filters.Add<ProfileRequiredActionFilter>();
});
You can then inject your UserManager into the filter as follows:
public class ProfileRequiredActionFilter : IActionFilter
{
private UserManager<ApplicationUser> _userManager;
public ProfileRequiredActionFilter(UserManager<ApplicationUser> userManager)
{
_userManager = userManager
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = _userManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}
I've currently built a simple Signalr Hub which I'm pushing messages to from a Unity5 project. Given that SignalR2 client doesn't work with Unity5 I'm using websocketsharp in order to intercept the websocket frames. The messages are being pushed to the Hub successfully, but when I attempt to call a method on the client, I do not get the payload string, only the message identifier {"I": 0}
Looking through the SignalR documentation, it looks like this gets sent last, but I have no idea how I can get a hold it it. I'm sure its something simple, but for the life of me I can't figure it out.
UPDATE
Upon request, I've added the code for the project below...
SignalRClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using WebSocketSharp;
namespace Assets.Scripts
{
class SignalRClient
{
private WebSocket _ws;
private string _connectionToken;
private Dictionary<string, UnTypedActionContainer> _actionMap;
private readonly string _socketUrl = "http://localhost/";
private readonly string _socket = "ws://localhost/";
public SignalRClient()
{
_actionMap = new Dictionary<string, UnTypedActionContainer>();
var webRequest = (HttpWebRequest)WebRequest.Create(_socketUrl + "/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%22myHub%22%7D%5D&clientProtocol=1.3");
var response = (HttpWebResponse)webRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
var payload = sr.ReadToEnd();
UnityEngine.Debug.Log(payload);
_connectionToken = Uri.EscapeDataString(JsonConvert.DeserializeObject<NegotiateResponse>(payload).ConnectionToken);
//UnityEngine.Debug.Log(_connectionToken);
}
}
public void Open()
{
_ws = _ws == null
? new WebSocket(_socket + "signalr/connect?transport=webSockets&connectionToken=" + _connectionToken)
: new WebSocket(_socket + "signalr/reconnect?transport=webSockets&connectionToken=" + _connectionToken);
AttachAndConnect();
}
public void Close()
{
_ws.Close();
}
public void SendMessage(string name, string message)
{
//{"H":"chathub","M":"Send","A":["tester","hello"],"I":0}
var payload = new RollerBallWrapper()
{
H = "myhub",
M = "Send",
A = new[] { name, message },
I = 12
};
var wsPacket = JsonConvert.SerializeObject(payload);
_ws.Send(wsPacket);
}
private void AttachAndConnect()
{
_ws.OnClose += _ws_OnClose;
_ws.OnError += _ws_OnError;
_ws.OnMessage += _ws_OnMessage;
_ws.OnOpen += _ws_OnOpen;
_ws.Connect();
}
void _ws_OnOpen(object sender, EventArgs e)
{
UnityEngine.Debug.Log("Opened Connection");
}
//
// This seems to be retriving the last frame containing the Identifier
void _ws_OnMessage(object sender, MessageEventArgs e)
{
//UnityEngine.Debug.Log(e.Data); // Returns {"I":"0"} ????
}
void _ws_OnError(object sender, WebSocketSharp.ErrorEventArgs e)
{
UnityEngine.Debug.Log(e.Message);
}
void _ws_OnClose(object sender, CloseEventArgs e)
{
UnityEngine.Debug.Log(e.Reason + " Code: " + e.Code + " WasClean: " + e.WasClean);
}
public void On<T>(string method, Action<T> callback) where T : class
{
_actionMap.Add(method, new UnTypedActionContainer
{
Action = new Action<object>(x =>
{
callback(x as T);
}),
ActionType = typeof(T)
});
}
}
internal class UnTypedActionContainer
{
public Action<object> Action { get; set; }
public Type ActionType { get; set; }
}
class MessageWrapper
{
public string C { get; set; }
public RollerBallWrapper[] M { get; set; }
}
class RollerBallWrapper
{
public string H { get; set; }
public string M { get; set; }
public string[] A { get; set; }
public int I { get; set; }
}
}
MyHub.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
public class MyHub : Hub
{
public void Send(string name, string message)
{
var myConn = Context.ConnectionId;
Clients.All.broadcastMessage("John", "Hello");
}
}
The problem is the websocket connection. I had the following:
new WebSocket(_socket + "signalr/connect?transport=webSockets&connectionToken=" + _connectionToken)
Which was missing 2 critical querystring parameters: connectionData and tid in addition to the connectionToken and transport. I wrongly assumed that these weren't needed.
I hope this helps anyone who didn't read the documentation like me :)
I'm pretty new to unit testing and I'm having some problems with regards, to unit testing a generic repository in my application. I've implemented the unit of work pattern in my ASP.NET MVC application. My classes look like this:
public class UnitOfWork : IUnitOfWork
{
private bool disposed = false;
private IGenericRepository<Shop> _shopRespository;
public UnitOfWork(PosContext context)
{
this.Context = context;
}
public PosContext Context { get; private set; }
public IGenericRepository<Shop> ShopRepository
{
get
{
return this._shopRespository ?? (this._shopRespository = new GenericRepository<Shop>(this.Context));
}
}
public void SaveChanges()
{
this.Context.SaveChanges();
}
public void Dispose()
{
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
this.Context.Dispose();
}
this.disposed = true;
}
}
}
public class PosContext : DbContext, IPosContext
{
public DbSet<Shop> Shops { get; private set; }
}
public class GenericRepository<T> : IGenericRepository<T>
where T : class
{
private readonly PosContext context;
private readonly DbSet<T> dbSet;
public GenericRepository(PosContext context)
{
this.context = context;
this.dbSet = context.Set<T>();
}
public virtual IEnumerable<T> Get(
Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = "")
{
IQueryable<T> query = this.dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual T Find(object id)
{
return this.dbSet.Find(id);
}
public virtual void Add(T entity)
{
this.dbSet.Add(entity);
}
public virtual void Remove(object id)
{
T entityToDelete = this.dbSet.Find(id);
this.Remove(entityToDelete);
}
public virtual void Remove(T entityToDelete)
{
if (this.context.Entry(entityToDelete).State == EntityState.Detached)
{
this.dbSet.Attach(entityToDelete);
}
this.dbSet.Remove(entityToDelete);
}
public virtual void Update(T entityToUpdate)
{
this.dbSet.Attach(entityToUpdate);
this.context.Entry(entityToUpdate).State = EntityState.Modified;
}
I'm using NUnit and FakeItEasy to write my unit tests. In my set up function, I create a UnitIfWork object with a fake PosContext object. I then populate the context with a few Shop objects.
[SetUp]
public void SetUp()
{
this.unitOfWork = new UnitOfWork(A.Fake<PosContext>());
this.unitOfWork.ShopRepository.Add(new Shop() { Id = 1, Name = "Test name1" });
this.unitOfWork.ShopRepository.Add(new Shop() { Id = 2, Name = "Test name2" });
this.unitOfWork.ShopRepository.Add(new Shop() { Id = 3, Name = "Test name3" });
this.unitOfWork.ShopRepository.Add(new Shop() { Id = 4, Name = "Test name4" });
this.unitOfWork.ShopRepository.Add(new Shop() { Id = 5, Name = "Test name5" });
this.Controller = new ShopController(this.unitOfWork);
}
It works fine when I test the Find-method of the GenericRepository. The correct Shop object is returned and I can assert that it works fine:
[TestCase]
public void DetailsReturnsCorrectShop()
{
// Arrange
int testId = 1;
// Act
Shop shop = this.unitOfWork.ShopRepository.Find(testId);
ViewResult result = this.Controller.Details(testId) as ViewResult;
// Assert
Shop returnedShop = (Shop)result.Model;
Assert.AreEqual(testId, returnedShop.Id);
}
But when I want to test that the Get-method returns all shops from the repository, if I do not give any filter params, I get an empty list back. I can't figure out why?
[TestCase]
public void IndexReturnsListOfShops()
{
// Arrange
// Act
ViewResult result = this.Controller.Index() as ViewResult;
// Assert
List<Shop> returnedShops = (List<Shop>)result.Model;
Assert.AreEqual(5, returnedShops.Count);
}
The ShopController looks like this:
public class ShopController : Controller
{
private readonly IUnitOfWork unitOfWork;
public ShopController(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
// GET: /Shop/
public ActionResult Index()
{
return View(this.unitOfWork.ShopRepository.Get());
}
// GET: /Shop/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Shop shop = this.unitOfWork.ShopRepository.Find(id);
if (shop == null)
{
return HttpNotFound();
}
return View(shop);
}
}
Can you help me figure out why I get an empty list back from the Get-method?
IPlugin Calss Library
namespace IPlugin
{
public interface IPlugin
{
string Name { get; set; }
void Start();
void Stop();
}
[Export(typeof(IPlugin))]
public abstract class BasePlugin:IPlugin
{
private string _name;
public BasePlugin()
{
Name = "Base Plugin";
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public virtual void Start()
{
fnDowWork();
}
protected abstract void fnDowWork();
public virtual void Stop()
{
}
}
}
Test Plugin Class Library
namespace TestPlugin
{
public class TestPlugin:IPlugin.BasePlugin
{
public TestPlugin()
{
Name = "Test Plugin";
}
protected override void fnDowWork()
{
Console.WriteLine("Do Work !");
}
}
}
Console Application
class Program
{
static void Main(string[] args)
{
var app = new MyApp();
foreach (var p in app._Plugins)
{
p.Start();
}
}
}
public class MyApp
{
[ImportMany(typeof(IPlugin.IPlugin))]
public IEnumerable<IPlugin.IPlugin> _Plugins;
public string _PluginFolder { get; set; }
public string _StartupPath { get; set; }
public MyApp()
{
_StartupPath = Environment.CurrentDirectory;
var pluginFolderName = System.Configuration.ConfigurationManager.AppSettings["PluginFolder"];
_PluginFolder = System.IO.Path.Combine(_StartupPath, pluginFolderName);
InitializeMEF();
}
private void InitializeMEF()
{
var dirCatalog = new DirectoryCatalog(_PluginFolder, "*.dll");
CompositionContainer container = new CompositionContainer(dirCatalog);
container.ComposeParts(this);
}
}
the DirectoryCatalog find tow Assembly IPlugin.dll and TestPlugin.dll and after Compose parts
the myApp._Plugins is not null but its empty , i don't know where i am doing wrong!
You will need to use the InheritedExportAttribute instead of the ExportAttribute:
[InheritedExport(typeof(IPlugin))]
public abstract class BasePlugin:IPlugin
Note that this will only work for plugins that derive from BasePlugin. Other implementations of IPlugin will not be marked for export. To do this you will have to decorate the interface instead.