Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Dynamic setting of properties from data stream

Dynamic setting of properties from data stream

Scheduled Pinned Locked Moved C#
csharpcomquestion
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    James R Twine
    wrote on last edited by
    #1

    So!  I finally am getting into more and more C#/.NET development, I am wondering if the following is possible using reflection and some other .NET-fu that I now nothing about (yet).    Here is what I am thinking... Presume I have several streams of CSV data that I want to convert into object form.  While it is possible to parse the CSV and manually assign properties for each value, I have to write specific code for each object and (expected) stream format that I want to process.    I am wondering if this code can be generic so that I can just pass in the CSV stream, an object, and a set of properties that are on that object, and the code can extract the values, and use reflection (or something) to get at the property by its name, and set the value.  Something like this:

    String sCSVString = "Value1,ValueABC,Value2,ValueXYZ";

    //
    // Object objMyObject has these string properties, Prop1, Prop2, Prop3, Prop4
    //
    // This Function Would Use The "params" Parameter Type/Handling...
    //
    AssignPropertiesFromCSV( sCSVString, objMyObject, "Prop1", "Prop2", null, "Prop4" );

    Where the result would be that objMyObject would have Prop1, Prop2 and Prop4 set to Value1, ValueABC and ValueXYZ respectively, skipping over the Prop3 property due to the null parameter passed in.    Is it possible to use reflection to dynamically examine objMyObject to find out if it has a Prop1 property, and then set it to a value?    My guess is that some ORM frameworks may work this way, but I have yet to delve into them and wanted to get a feel for it from the more C#-experienced devs here first.    While examples are not required, they are welcome.  I just want to know if this is worth looking into or not.    Thanks!    Peace!

    -=- James
    Please rate this message - let me know if I helped or not! * * * If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
    Remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
    See DeleteFXPFiles

    W N M 3 Replies Last reply
    0
    • J James R Twine

      So!  I finally am getting into more and more C#/.NET development, I am wondering if the following is possible using reflection and some other .NET-fu that I now nothing about (yet).    Here is what I am thinking... Presume I have several streams of CSV data that I want to convert into object form.  While it is possible to parse the CSV and manually assign properties for each value, I have to write specific code for each object and (expected) stream format that I want to process.    I am wondering if this code can be generic so that I can just pass in the CSV stream, an object, and a set of properties that are on that object, and the code can extract the values, and use reflection (or something) to get at the property by its name, and set the value.  Something like this:

      String sCSVString = "Value1,ValueABC,Value2,ValueXYZ";

      //
      // Object objMyObject has these string properties, Prop1, Prop2, Prop3, Prop4
      //
      // This Function Would Use The "params" Parameter Type/Handling...
      //
      AssignPropertiesFromCSV( sCSVString, objMyObject, "Prop1", "Prop2", null, "Prop4" );

      Where the result would be that objMyObject would have Prop1, Prop2 and Prop4 set to Value1, ValueABC and ValueXYZ respectively, skipping over the Prop3 property due to the null parameter passed in.    Is it possible to use reflection to dynamically examine objMyObject to find out if it has a Prop1 property, and then set it to a value?    My guess is that some ORM frameworks may work this way, but I have yet to delve into them and wanted to get a feel for it from the more C#-experienced devs here first.    While examples are not required, they are welcome.  I just want to know if this is worth looking into or not.    Thanks!    Peace!

      -=- James
      Please rate this message - let me know if I helped or not! * * * If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
      Remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
      See DeleteFXPFiles

      W Offline
      W Offline
      Wendelius
      wrote on last edited by
      #2

      If the object is created based on the info in the CSV-file, you could implement ISerializable interface, which allows you to control the serialization and deserialization. If you only want to set the values of an existing object based on CSV input, I would create a method on each class (based on an interface) which sets the properties for the class and understands the input paranmeter (CSV string). The input string would be easiest to handle using String.Split-method. In both cases you wouldn't need to use reflection. If you want to use reflection, you would have a method with two (csv+object) mandatory parameters and a third one as parameter array, for properties list. In this case you would examine the type of the object and then find each property's PropertyInfo given in a parameter using object type's GetProperty method. After that you can use the SetValue method for the PropertyInfo t set the value of the property (just check that the property is writable). Hope this helps, Mika

      The need to optimize rises from a bad design

      1 Reply Last reply
      0
      • J James R Twine

        So!  I finally am getting into more and more C#/.NET development, I am wondering if the following is possible using reflection and some other .NET-fu that I now nothing about (yet).    Here is what I am thinking... Presume I have several streams of CSV data that I want to convert into object form.  While it is possible to parse the CSV and manually assign properties for each value, I have to write specific code for each object and (expected) stream format that I want to process.    I am wondering if this code can be generic so that I can just pass in the CSV stream, an object, and a set of properties that are on that object, and the code can extract the values, and use reflection (or something) to get at the property by its name, and set the value.  Something like this:

        String sCSVString = "Value1,ValueABC,Value2,ValueXYZ";

        //
        // Object objMyObject has these string properties, Prop1, Prop2, Prop3, Prop4
        //
        // This Function Would Use The "params" Parameter Type/Handling...
        //
        AssignPropertiesFromCSV( sCSVString, objMyObject, "Prop1", "Prop2", null, "Prop4" );

        Where the result would be that objMyObject would have Prop1, Prop2 and Prop4 set to Value1, ValueABC and ValueXYZ respectively, skipping over the Prop3 property due to the null parameter passed in.    Is it possible to use reflection to dynamically examine objMyObject to find out if it has a Prop1 property, and then set it to a value?    My guess is that some ORM frameworks may work this way, but I have yet to delve into them and wanted to get a feel for it from the more C#-experienced devs here first.    While examples are not required, they are welcome.  I just want to know if this is worth looking into or not.    Thanks!    Peace!

        -=- James
        Please rate this message - let me know if I helped or not! * * * If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
        Remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
        See DeleteFXPFiles

        N Offline
        N Offline
        N a v a n e e t h
        wrote on last edited by
        #3

        Try this

        void AssignPropertiesFromCSV(string csv, object obj, params string[] propertyNames) {
        string[] csvValues = csv.Split(',');
        int index = 0;
        foreach (string propertyName in propertyNames) {
        if (!string.IsNullOrEmpty(propertyName))
        obj.GetType().GetProperty(propertyName).SetValue(obj, csvValues[index], null);
        index++;
        }
        }

        Navaneeth How to use google | Ask smart questions

        J 1 Reply Last reply
        0
        • J James R Twine

          So!  I finally am getting into more and more C#/.NET development, I am wondering if the following is possible using reflection and some other .NET-fu that I now nothing about (yet).    Here is what I am thinking... Presume I have several streams of CSV data that I want to convert into object form.  While it is possible to parse the CSV and manually assign properties for each value, I have to write specific code for each object and (expected) stream format that I want to process.    I am wondering if this code can be generic so that I can just pass in the CSV stream, an object, and a set of properties that are on that object, and the code can extract the values, and use reflection (or something) to get at the property by its name, and set the value.  Something like this:

          String sCSVString = "Value1,ValueABC,Value2,ValueXYZ";

          //
          // Object objMyObject has these string properties, Prop1, Prop2, Prop3, Prop4
          //
          // This Function Would Use The "params" Parameter Type/Handling...
          //
          AssignPropertiesFromCSV( sCSVString, objMyObject, "Prop1", "Prop2", null, "Prop4" );

          Where the result would be that objMyObject would have Prop1, Prop2 and Prop4 set to Value1, ValueABC and ValueXYZ respectively, skipping over the Prop3 property due to the null parameter passed in.    Is it possible to use reflection to dynamically examine objMyObject to find out if it has a Prop1 property, and then set it to a value?    My guess is that some ORM frameworks may work this way, but I have yet to delve into them and wanted to get a feel for it from the more C#-experienced devs here first.    While examples are not required, they are welcome.  I just want to know if this is worth looking into or not.    Thanks!    Peace!

          -=- James
          Please rate this message - let me know if I helped or not! * * * If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
          Remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
          See DeleteFXPFiles

          M Offline
          M Offline
          Mark Churchill
          wrote on last edited by
          #4

          Navaneeth has given you a solution. But... theres no benefit here to keeping these in properties. Assuming you have your Sale object taking a CSV row, just keep the row as an array when you split it:

          class BaseCSVThing
          {
          string[] data;

          BaseCSVThing(string Row) { data = SplitRowIntoArray(Row); }
          }

          class Customer : BaseCSVThing
          {
          string Name { get { return data[0]; } }
          }

          Or if you wanted to be less lazy, you could implement your own CSV serializer :P Or you could take Navaneeth's example, but throw in some attributes to indicate the column - so you have something like [CSV(Column = 3)] string Foo { get;set; }.

          Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
          Alpha release: Entanglar: Transparant multiplayer framework for .Net games.

          J 1 Reply Last reply
          0
          • N N a v a n e e t h

            Try this

            void AssignPropertiesFromCSV(string csv, object obj, params string[] propertyNames) {
            string[] csvValues = csv.Split(',');
            int index = 0;
            foreach (string propertyName in propertyNames) {
            if (!string.IsNullOrEmpty(propertyName))
            obj.GetType().GetProperty(propertyName).SetValue(obj, csvValues[index], null);
            index++;
            }
            }

            Navaneeth How to use google | Ask smart questions

            J Offline
            J Offline
            James R Twine
            wrote on last edited by
            #5

            I think that is exactly what I am looking to do.  Thanks a lot!  I will start playing with that now.    Peace!

            -=- James
            Please rate this message - let me know if I helped or not! * * * If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
            Remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
            See DeleteFXPFiles

            1 Reply Last reply
            0
            • M Mark Churchill

              Navaneeth has given you a solution. But... theres no benefit here to keeping these in properties. Assuming you have your Sale object taking a CSV row, just keep the row as an array when you split it:

              class BaseCSVThing
              {
              string[] data;

              BaseCSVThing(string Row) { data = SplitRowIntoArray(Row); }
              }

              class Customer : BaseCSVThing
              {
              string Name { get { return data[0]; } }
              }

              Or if you wanted to be less lazy, you could implement your own CSV serializer :P Or you could take Navaneeth's example, but throw in some attributes to indicate the column - so you have something like [CSV(Column = 3)] string Foo { get;set; }.

              Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
              Alpha release: Entanglar: Transparant multiplayer framework for .Net games.

              J Offline
              J Offline
              James R Twine
              wrote on last edited by
              #6

              Those are some good ideas as well.  Treating all of the internal data as Strings will be less efficient for me because I would have to keep converting them to their actual types (ints, Decimals, DateTime, etc.) over and over again.    I have not played around with Attributes yet, and that sounds interesting, but since I may have various CSV formats, where certain values may be in different locations, I am not sure if that would work.    But thanks anyway for the ideas -- great food for thought!    Peace!

              -=- James
              Please rate this message - let me know if I helped or not! * * * If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
              Remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
              See DeleteFXPFiles

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups