Refecltion - Dynamic class invocation - class

The following is the code where if else is used. If i need to dynamically create a class. how can i do it? is Reflection used ? If so : how can i implement the same using reflection?
public static Pizza getConcretePizza(String PType)
{
Pizza p=null;
if (PType.equals("Cheese"))
{
p=new CheesePizza();
//ResultIng = cp.FetchIng();
} else if (PType.equals("Pepperoni"))
{
p=new PepperoniPizza();
// ResultIng = pp.FetchIng();
}
else if (PType.equals("Clam"))
{
p = new CalmPizza();
//ResultIng = cap.FetchIng();
}
else if (PType.equals("Veggie"))
{
p= new VeggiePizza();
// ResultIng = vp.FetchIng();
}
return(p);
}

I tried getting the answer and finally found the solution.
(INSTEAD OF THE IF _ ELSE WE NEED TO REPLACE THE FOLLWOING CODE)
Class<?> clazz = Class.forName("PizzaTrail." + PType);
Object instance = clazz.newInstance();
p = (Pizza) instance;
return (p);
the above code will resolve the issue of writing the if else and reflection will help calling the class dynamically.

Related

How to convert Java constructor to Scala one with a stack as one member attribute?

public class BSTIterator {
private Stack<TreeNode> stk;
public BSTIterator(TreeNode root) {
stk = new Stack<>();
while (root != null) {
stk.push(root);
root = root.left;
}
}
/**
* #return whether we have a next smallest number
*/
public boolean hasNext() {
return !stk.isEmpty();
}
/**
* #return the next smallest number
*/
public int next() {
TreeNode curr = stk.pop();
int res = curr.val;
curr = curr.right;
while (curr != null) {
stk.push(curr);
curr = curr.left;
}
return res;
}
}
above is the java code snippet. how do i convert it to a scala class? I'm confused by the constructor part. how do i set up a constructor in this case?
var obj = new BSTIterator(root)
var param_1 = obj.next()
var param_2 = obj.hasNext()
The constructor parameters go on the class and can simply be used inside. You can also put statements directly in the body of the class and they become part of the constructor:
class BSTIterator(root: TreeNode) {
private val stk: Stack[TreeNode] = new Stack()
{
var root_ = root // you can't change parameters in Scala
while (root_ != null) {
stk.push(root_)
root_ = root_.left
}
}
...
}
The block is used so root_ doesn't become a field of the class. Also, you'd normally use Scala collections instead of Java Stack, but I'll leave that part to you.

Setting a hierarchy filter via script

In the top of the Hierarchy window of the Unity Editor there is a field for filtering the hierarchy:
My question is if you can set that filter from an editor script and how. I can barely find anything according to this on the web.
Thanks in advance.
UnityEditor.SceneModeUtility.SearchForType seems to be a step in the right direction.
The good news is, that you can see the implementation of that method in MonoDevelop..
Taking a closer look at it tells us the methods we'd need.
public static void SearchForType (Type type)
{
Object[] array = Resources.FindObjectsOfTypeAll (typeof(SceneHierarchyWindow));
SceneHierarchyWindow sceneHierarchyWindow = (array.Length <= 0) ? null : (array [0] as SceneHierarchyWindow);
if (sceneHierarchyWindow)
{
SceneModeUtility.s_HierarchyWindow = sceneHierarchyWindow;
if (type == null || type == typeof(GameObject))
{
SceneModeUtility.s_FocusType = null;
sceneHierarchyWindow.ClearSearchFilter ();
}
else
{
SceneModeUtility.s_FocusType = type;
if (sceneHierarchyWindow.searchMode == SearchableEditorWindow.SearchMode.Name)
{
sceneHierarchyWindow.searchMode = SearchableEditorWindow.SearchMode.All;
}
sceneHierarchyWindow.SetSearchFilter ("t:" + type.Name, sceneHierarchyWindow.searchMode, false);
sceneHierarchyWindow.hasSearchFilterFocus = true;
}
}
else
{
SceneModeUtility.s_FocusType = null;
}
}
And now the bad news, due to their protection level, you can neither access the hierarchy window directly, nor can you use the SetSearchFilter method.
Maybe you could write an editor script, similar to the hierarchy view, where you have full control, and can do whatever you want.
Thanks to d4RK I found out how to do it using Reflection:
public const int FILTERMODE_ALL = 0;
public const int FILTERMODE_NAME = 1;
public const int FILTERMODE_TYPE = 2;
public static void SetSearchFilter(string filter, int filterMode) {
SearchableEditorWindow[] windows = (SearchableEditorWindow[])Resources.FindObjectsOfTypeAll (typeof(SearchableEditorWindow));
foreach (SearchableEditorWindow window in windows) {
if(window.GetType().ToString() == "UnityEditor.SceneHierarchyWindow") {
hierarchy = window;
break;
}
}
if (hierarchy == null)
return;
MethodInfo setSearchType = typeof(SearchableEditorWindow).GetMethod("SetSearchFilter", BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = new object[]{filter, filterMode, false};
setSearchType.Invoke(hierarchy, parameters);
}
This may not be the most elegant way, but it works like a charm and can easily be extended to apply the same filter to the SceneView.
As of Unity 2018 there is an additional boolean parameter required for the SetSearchFilter method.
So change this line
object[] parameters = new object[]{filter, filterMode, false};
to
object[] parameters = new object[]{filter, filterMode, false, false};
This should resolve the TargetParameterCountException Ugo Hed mentioned.

Setting Field Within Class using Reflection

This should be easy but it's managed to confound me a few times. I'm trying to set a Value within a class using Reflection.
public class EngineeringValueClass<T> {
public T Value { get { } set { } }
}
Then in a calling class I have:
public class MyClass {
EngineeringValueClass<double> Value1;
EngineeringValueClass<double> Value2;
// Along with many others.
public void SetValueByName(object FieldName,object FieldValue) {
// Get the "Value" field of a generic EngineeringValueClass<double>
PropertyInfo MyValuePropRef =
typeof(EngineeringValueClass<double>).GetProperty("Value");
// Get the field within this class I want to set.
FieldInfo MyNameFieldRef = typeof(MyClass).GetField(FieldName.ToString());
MyValuePropRef.SetValue(MyNameFieldRef.GetValue,
FieldValue,
null);
}
}
My goal is to have
SetValueByName("Value1",2.3);
set Value1's "Value" using the set accessor. I presume my problem is that MyNameFieldRef.GetValue doesn't return an object reference but rather a "Value", but I'm not sure how to work around that. I don't want to pass "this" because that's not right either.
Okay, I finally figured this out:
public void SetValueByName(object FieldName, object FieldValue) {
Type t = typeof(MyClass);
FieldInfo PrimaryField = t.GetField(FieldName.ToString());
object ValueField = PrimaryField.GetValue(this);
// To get the type of Value
MethodInfo TypeValueField = ValueField.GetType().GetMethod("GetValueType");
Type ValueType = (Type) TypeValueField.Invoke(ValueField, null);
// I added a "GetValueType () { return typeof(T); } to EngineeringValueClass
if (ValueType == typeof(Int16))
{
((EngineeringValueClass<Int16>)ValueField).Value = Int16.Parse(FieldValue.ToString());
}...
}

Serializing Entity Framework problems

Like several other people, I'm having problems serializing Entity Framework objects, so that I can send the data over AJAX in a JSON format.
I've got the following server-side method, which I'm attempting to call using AJAX through jQuery
[WebMethod]
public static IEnumerable<Message> GetAllMessages(int officerId)
{
SIBSv2Entities db = new SIBSv2Entities();
return (from m in db.MessageRecipients
where m.OfficerId == officerId
select m.Message).AsEnumerable<Message>();
}
Calling this via AJAX results in this error:
A circular reference was detected while serializing an object of type \u0027System.Data.Metadata.Edm.AssociationType
Which is because of the way the Entity Framework creates circular references to keep all the objects related and accessible server side.
I came across the following code from (http://hellowebapps.com/2010-09-26/producing-json-from-entity-framework-4-0-generated-classes/) which claims to get around this problem by capping the maximum depth for references. I've added the code below, because I had to tweak it slightly to get it work (All angled brackets are missing from the code on the website)
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System;
public class EFObjectConverter : JavaScriptConverter
{
private int _currentDepth = 1;
private readonly int _maxDepth = 2;
private readonly List<int> _processedObjects = new List<int>();
private readonly Type[] _builtInTypes = new[]{
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)
};
public EFObjectConverter( int maxDepth = 2,
EFObjectConverter parent = null)
{
_maxDepth = maxDepth;
if (parent != null)
{
_currentDepth += parent._currentDepth;
}
}
public override object Deserialize( IDictionary<string,object> dictionary, Type type, JavaScriptSerializer serializer)
{
return null;
}
public override IDictionary<string,object> Serialize(object obj, JavaScriptSerializer serializer)
{
_processedObjects.Add(obj.GetHashCode());
Type type = obj.GetType();
var properties = from p in type.GetProperties()
where p.CanWrite &&
p.CanWrite &&
_builtInTypes.Contains(p.PropertyType)
select p;
var result = properties.ToDictionary(
property => property.Name,
property => (Object)(property.GetValue(obj, null)
== null
? ""
: property.GetValue(obj, null).ToString().Trim())
);
if (_maxDepth >= _currentDepth)
{
var complexProperties = from p in type.GetProperties()
where p.CanWrite &&
p.CanRead &&
!_builtInTypes.Contains(p.PropertyType) &&
!_processedObjects.Contains(p.GetValue(obj, null)
== null
? 0
: p.GetValue(obj, null).GetHashCode())
select p;
foreach (var property in complexProperties)
{
var js = new JavaScriptSerializer();
js.RegisterConverters(new List<JavaScriptConverter> { new EFObjectConverter(_maxDepth - _currentDepth, this) });
result.Add(property.Name, js.Serialize(property.GetValue(obj, null)));
}
}
return result;
}
public override IEnumerable<System.Type> SupportedTypes
{
get
{
return GetType().Assembly.GetTypes();
}
}
}
However even when using that code, in the following way:
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.RegisterConverters(new List<System.Web.Script.Serialization.JavaScriptConverter> { new EFObjectConverter(2) });
return js.Serialize(messages);
I'm still seeing the A circular reference was detected... exception being thrown!
I solved these issues with the following classes:
public class EFJavaScriptSerializer : JavaScriptSerializer
{
public EFJavaScriptSerializer()
{
RegisterConverters(new List<JavaScriptConverter>{new EFJavaScriptConverter()});
}
}
and
public class EFJavaScriptConverter : JavaScriptConverter
{
private int _currentDepth = 1;
private readonly int _maxDepth = 1;
private readonly List<object> _processedObjects = new List<object>();
private readonly Type[] _builtInTypes = new[]
{
typeof(int?),
typeof(double?),
typeof(bool?),
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(DateTime?),
typeof(Guid)
};
public EFJavaScriptConverter() : this(1, null) { }
public EFJavaScriptConverter(int maxDepth = 1, EFJavaScriptConverter parent = null)
{
_maxDepth = maxDepth;
if (parent != null)
{
_currentDepth += parent._currentDepth;
}
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
_processedObjects.Add(obj.GetHashCode());
var type = obj.GetType();
var properties = from p in type.GetProperties()
where p.CanRead && p.GetIndexParameters().Count() == 0 &&
_builtInTypes.Contains(p.PropertyType)
select p;
var result = properties.ToDictionary(
p => p.Name,
p => (Object)TryGetStringValue(p, obj));
if (_maxDepth >= _currentDepth)
{
var complexProperties = from p in type.GetProperties()
where p.CanRead &&
p.GetIndexParameters().Count() == 0 &&
!_builtInTypes.Contains(p.PropertyType) &&
p.Name != "RelationshipManager" &&
!AllreadyAdded(p, obj)
select p;
foreach (var property in complexProperties)
{
var complexValue = TryGetValue(property, obj);
if(complexValue != null)
{
var js = new EFJavaScriptConverter(_maxDepth - _currentDepth, this);
result.Add(property.Name, js.Serialize(complexValue, new EFJavaScriptSerializer()));
}
}
}
return result;
}
private bool AllreadyAdded(PropertyInfo p, object obj)
{
var val = TryGetValue(p, obj);
return _processedObjects.Contains(val == null ? 0 : val.GetHashCode());
}
private static object TryGetValue(PropertyInfo p, object obj)
{
var parameters = p.GetIndexParameters();
if (parameters.Length == 0)
{
return p.GetValue(obj, null);
}
else
{
//cant serialize these
return null;
}
}
private static object TryGetStringValue(PropertyInfo p, object obj)
{
if (p.GetIndexParameters().Length == 0)
{
var val = p.GetValue(obj, null);
return val;
}
else
{
return string.Empty;
}
}
public override IEnumerable<Type> SupportedTypes
{
get
{
var types = new List<Type>();
//ef types
types.AddRange(Assembly.GetAssembly(typeof(DbContext)).GetTypes());
//model types
types.AddRange(Assembly.GetAssembly(typeof(BaseViewModel)).GetTypes());
return types;
}
}
}
You can now safely make a call like new EFJavaScriptSerializer().Serialize(obj)
Update : since version Telerik v1.3+ you can now override the GridActionAttribute.CreateActionResult method and hence you can easily integrate this Serializer into specific controller methods by applying your custom [GridAction] attribute:
[Grid]
public ActionResult _GetOrders(int id)
{
return new GridModel(Service.GetOrders(id));
}
and
public class GridAttribute : GridActionAttribute, IActionFilter
{
/// <summary>
/// Determines the depth that the serializer will traverse
/// </summary>
public int SerializationDepth { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="GridActionAttribute"/> class.
/// </summary>
public GridAttribute()
: base()
{
ActionParameterName = "command";
SerializationDepth = 1;
}
protected override ActionResult CreateActionResult(object model)
{
return new EFJsonResult
{
Data = model,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxSerializationDepth = SerializationDepth
};
}
}
and finally..
public class EFJsonResult : JsonResult
{
const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
public EFJsonResult()
{
MaxJsonLength = 1024000000;
RecursionLimit = 10;
MaxSerializationDepth = 1;
}
public int MaxJsonLength { get; set; }
public int RecursionLimit { get; set; }
public int MaxSerializationDepth { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(JsonRequest_GetNotAllowed);
}
var response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var serializer = new JavaScriptSerializer
{
MaxJsonLength = MaxJsonLength,
RecursionLimit = RecursionLimit
};
serializer.RegisterConverters(new List<JavaScriptConverter> { new EFJsonConverter(MaxSerializationDepth) });
response.Write(serializer.Serialize(Data));
}
}
You can also detach the object from the context and it will remove the navigation properties so that it can be serialized. For my data repository classes that are used with Json i use something like this.
public DataModel.Page GetPage(Guid idPage, bool detach = false)
{
var results = from p in DataContext.Pages
where p.idPage == idPage
select p;
if (results.Count() == 0)
return null;
else
{
var result = results.First();
if (detach)
DataContext.Detach(result);
return result;
}
}
By default the returned object will have all of the complex/navigation properties, but by setting detach = true it will remove those properties and return the base object only. For a list of objects the implementation looks like this
public List<DataModel.Page> GetPageList(Guid idSite, bool detach = false)
{
var results = from p in DataContext.Pages
where p.idSite == idSite
select p;
if (results.Count() > 0)
{
if (detach)
{
List<DataModel.Page> retValue = new List<DataModel.Page>();
foreach (var result in results)
{
DataContext.Detach(result);
retValue.Add(result);
}
return retValue;
}
else
return results.ToList();
}
else
return new List<DataModel.Page>();
}
I have just successfully tested this code.
It may be that in your case your Message object is in a different assembly? The overriden Property SupportedTypes is returning everything ONLY in its own Assembly so when serialize is called the JavaScriptSerializer defaults to the standard JavaScriptConverter.
You should be able to verify this debugging.
Your error occured due to some "Reference" classes generated by EF for some entities with 1:1 relations and that the JavaScriptSerializer failed to serialize.
I've used a workaround by adding a new condition :
!p.Name.EndsWith("Reference")
The code to get the complex properties looks like this :
var complexProperties = from p in type.GetProperties()
where p.CanWrite &&
p.CanRead &&
!p.Name.EndsWith("Reference") &&
!_builtInTypes.Contains(p.PropertyType) &&
!_processedObjects.Contains(p.GetValue(obj, null)
== null
? 0
: p.GetValue(obj, null).GetHashCode())
select p;
Hope this help you.
I had a similar problem with pushing my view via Ajax to UI components.
I also found and tried to use that code sample you provided. Some problems I had with that code:
SupportedTypes wasn't grabbing the types I needed, so the converter wasn't being called
If the maximum depth is hit, the serialization would be truncated
It threw out any other converters I had on the existing serializer by creating its own new JavaScriptSerializer
Here are the fixes I implemented for those issues:
Reusing the same serializer
I simply reused the existing serializer that is passed into Serialize to solve this problem. This broke the depth hack though.
Truncating on already-visited, rather than on depth
Instead of truncating on depth, I created a HashSet<object> of already seen instances (with a custom IEqualityComparer that checked reference equality). I simply didn't recurse if I found an instance I'd already seen. This is the same detection mechanism built into the JavaScriptSerializer itself, so worked quite well.
The only problem with this solution is that the serialization output isn't very deterministic. The order of truncation is strongly dependent on the order that reflections finds the properties. You could solve this (with a perf hit) by sorting before recursing.
SupportedTypes needed the right types
My JavaScriptConverter couldn't live in the same assembly as my model. If you plan to reuse this converter code, you'll probably run into the same problem.
To solve this I had to pre-traverse the object tree, keeping a HashSet<Type> of already seen types (to avoid my own infinite recursion), and pass that to the JavaScriptConverter before registering it.
Looking back on my solution, I would now use code generation templates to create a list of the entity types. This would be much more foolproof (it uses simple iteration), and have much better perf since it would produce a list at compile time. I'd still pass this to the converter so it could be reused between models.
My final solution
I threw out that code and tried again :)
I simply wrote code to project onto new types ("ViewModel" types - in your case, it would be service contract types) before doing my serialization. The intention of my code was made more explicit, it allowed me to serialize just the data I wanted, and it didn't have the potential of slipping in queries on accident (e.g. serializing my whole DB).
My types were fairly simple, and I didn't need most of them for my view. I might look into AutoMapper to do some of this projection in the future.

Can this extension method be improved?

I have the following extension method
public static class ListExtensions
{
public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch)
{
foreach (T t in collection)
{
Type k = t.GetType();
PropertyInfo pi = k.GetProperty("Name");
if (pi.GetValue(t, null).Equals(stringToSearch))
{
yield return t;
}
}
}
}
What it does is by using reflection, it finds the name property and then filteres the record from the collection based on the matching string.
This method is being called as
List<FactorClass> listFC = new List<FactorClass>();
listFC.Add(new FactorClass { Name = "BKP", FactorValue="Book to price",IsGlobal =false });
listFC.Add(new FactorClass { Name = "YLD", FactorValue = "Dividend yield", IsGlobal = false });
listFC.Add(new FactorClass { Name = "EPM", FactorValue = "emp", IsGlobal = false });
listFC.Add(new FactorClass { Name = "SE", FactorValue = "something else", IsGlobal = false });
List<FactorClass> listFC1 = listFC.Search("BKP").ToList();
It is working fine.
But a closer look into the extension method will reveal that
Type k = t.GetType();
PropertyInfo pi = k.GetProperty("Name");
is actually inside a foreach loop which is actually not needed. I think we can take it outside the loop.
But how?
PLease help. (C#3.0)
Using reflection in this way is ugly to me.
Are you sure you need a 100% generic "T" and can't use a base class or interface?
If I were you, I would consider using the .Where<T>(Func<T, Boolean>) LINQ method instead of writing your own Search function.
An example use is:
List<FactorClass> listFC1 = listFC.Where(fc => fc.Name == "BKP").ToList();
public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch)
{
Type k = typeof(T);
PropertyInfo pi = k.GetProperty("Name");
foreach (T t in collection)
{
if (pi.GetValue(t, null).Equals(stringToSearch))
{
yield return t;
}
}
}
There's a couple of things you could do -- first you could institute a constraint on the generic type to an interface that has a name property. If it can only take a FactorClass, then you don't really need a generic type -- you could make it an extension to an ICollection<FactorClass>. If you go the interface route (or with the non-generic version), you can simply reference the property and won't have a need for reflection. If, for some reason, this doesn't work you can do:
var k = typeof(T);
var pi = k.GetProperty("Name");
foreach (T t in collection)
{
if (pi.GetValue(t, null).Equals(stringToSearch))
{
yield return t;
}
}
using an interface it might look like
public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch) where T : INameable
{
foreach (T t in collection)
{
if (string.Equals( t.Name, stringToSearch))
{
yield return t;
}
}
}
EDIT: After seeing #Jeff's comment, this is really only useful if you're doing something more complex than simply checking the value against one of the properties. He's absolutely correct in that using Where is a better solution for that problem.
Just get the type of T
Type k = typeof(T);
PropertyInfo pi = k.GetProperty("Name");
foreach (T t in collection)
{
if (pi.GetValue(t, null).Equals(stringToSearch))
{
yield return t;
}
}