Skip to content

Commit

Permalink
Added EditObjectView
Browse files Browse the repository at this point in the history
  • Loading branch information
tbm0115 committed Jul 25, 2024
1 parent 7da8245 commit 9b10a9b
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Consoul/Consoul.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<PackageTags>Console</PackageTags>
<Authors>tbm0115</Authors>
<Company />
<Version>1.6.5</Version>
<Version>1.6.6-prerelease.1</Version>
<PackageReleaseNotes>Added exception to logging.</PackageReleaseNotes>
<AssemblyVersion>1.6.5</AssemblyVersion>
<FileVersion>1.6.5</FileVersion>
Expand Down
80 changes: 80 additions & 0 deletions Consoul/Views/EditObjectView.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using System;
using System.Linq;
using System.Reflection;

namespace ConsoulLibrary.Views
{
/// <summary>
/// Creates a dynamic view to edit the properties of the given object.
/// </summary>
public class EditObjectView : DynamicView<object>
{
public EditObjectView(object entity, System.Reflection.BindingFlags bindingAttr = System.Reflection.BindingFlags.Public) : base()
{
Source = entity;

var entityType = entity.GetType();

var simpleTypes = new Type[]
{
typeof(bool),
typeof(byte),
typeof(sbyte),
typeof(char),
typeof(decimal),
typeof(double),
typeof(float),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(short),
typeof(ushort),
typeof(string),
typeof(DateTime),
typeof(Guid)
};

var properties = entityType.GetProperties(bindingAttr);
foreach ( var property in properties )
{
var propertyType = property.PropertyType;
if (simpleTypes.Contains(propertyType))
{
this.Options.Add(new DynamicOption<object>(
() => $"Edit {property.Name}: " + property.GetValue(Source)?.ToString() ?? "<N/A>",
() =>
{
var input = Consoul.Input("Enter new " + property.Name);
var newValue = Convert.ChangeType(input, propertyType);
property.SetValue(Source, newValue);
}
));
} else
{
this.Options.Add(new DynamicOption<object>(
() => $"Edit {property.Name}",
() =>
{
var recursiveView = new EditObjectView(property.GetValue(Source));
recursiveView.Run();
},
() => ConsoleColor.DarkYellow
));
}
}
}

/// <summary>
/// Creates a new instance of the <see cref="EditObjectView"/> for the provided <paramref name="entity"/>
/// </summary>
/// <param name="entity">Entity to create an <see cref="EditObjectView"/></param>
/// <param name="bindingAttr">Scope the properties that should be editable based on accessibility</param>
/// <returns>Dynamic view of the entity editor</returns>
public static EditObjectView CreateView(object entity, BindingFlags bindingAttr)
{
var view = new EditObjectView(entity, bindingAttr);
return view;
}
}
}

0 comments on commit 9b10a9b

Please sign in to comment.