lundi 23 janvier 2017

How to create attribute to a function that will create a file before or without calling the function

I need to create attribute for functions that will create files according to a given name before the call to the function or even if there is no call to the function.
For example, if I have function with atribute [some("C:\\hello.txt")]:

[some("C:\\hello.txt")]
private void foo()
{
    // do something
}

When I will run the application it will create this file ("C:\hello.txt") before calling the function.

I tried with two techniques:
1. Creating the file in the constructor
2. Creating the file with reflection.

But none of them worked for me.

First try (with constructor):
I tried create the file in the constructor every time there is a new attribute.
In this method I tried to create the file before the enter to the Main function.
While it parsing the functions it will find the attributes and create the files.
Expected:
Two files should be created:
1. C:\hello.txt
2. C:\bye.txt

In reality => nothing happen.

[some("C:\\hello.txt")]
private void foo()
{
    // do something
}

[some("C:\\bye.txt")]
private void foo()
{
    // do something
}

public class someAttribute : Attribute
{
    public someAttribute(string fileToCreate)
    {
        // File.Create(fileToCreate);
        Console.WriteLine("Create file " + fileToCreate);
    }
}

static void Main(string[] args)
{
    // something
}

Second try (with reflection):
Expected:
One file should be created:
1. C:\hello.txt

In reality => "types" variables is empty and nothing is being created.

[some(fileToCreate = "C:\\hello.txt")]
private void foo()
{
    // do something
}

public class someAttribute : Attribute
{
    public string fileToCreate {get; set;}
}

static void Main(string[] args)
{

    var types = from t in Assembly.GetExecutingAssembly().GetTypes()
                where t.GetCustomAttributes<someAttribute>().Count() > 0
                select t;
    foreach(var t in types)  // types is null
    {
        string n = t.Name;
        foreach(var p in t.GetProperties()) 
        {
            // File.Create(fileToCreate)
            Console.WriteLine(p.fileToCreate);
        }
    }

}





Aucun commentaire:

Enregistrer un commentaire