C# - Issues using Reflection to get Model in Order

I originally posted this question and got an answer.

https://www.experts-exchange.com/questions/29099706/C-Service-Export-Extended-Price-does-not-export-in-the-same-position.html#acceptAnswerByMember

I'm trying to modify my code to implement the solution but having issues.  I indicated in "CAPS" in code below where the error is occurring.
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Export.Models
{
    public class POModel
    {
        [Display(Order = 0)]
        public string name { get; set; }
        [Display(Order = 1)]
        public string en { get; set; }
        [Display(Order = 2)]
        public string state { get; set; }
        [Display(Order = 3)]
        public string purchaseOrderNumber { get; set; }
        [Display(Order = 4)]
        public string dateOrder { get; set; }
        [Display(Order = 5)]
        public string currency { get; set; }
        [Display(Order = 6)]
        public string requiredDate { get; set; }
        [Display(Order = 7)]
        public string promisedDate { get; set; }
        [Display(Order = 8)]
        public string shipDateNew { get; set; }
        [Display(Order = 9)]
        public string total { get; set; }
        [Display(Order = 10)]
        public string Name2 { get; set; }
        [Display(Order = 11)]
        public string unitPrice { get; set; }
        [Display(Order = 12)]
        public string rate { get; set; }
        [Display(Order = 13)]
        public string id_customer { get; set; }
        [Display(Order = 14)]
        public string Customer_Name { get; set; }
        [Display(Order = 15)]
        public string id_product { get; set; }
        [Display(Order = 16)]
        public string Product_Name { get; set; }
        [Display(Order = 17)]
        public string extendedPrice
        {
            get
            {
                double value = ((Convert.ToDouble(unitPrice) * Convert.ToDouble(total)) - ((Convert.ToDouble(unitPrice) * Convert.ToDouble(total) * (Convert.ToDouble(rate) / 100))));
                return value.ToString("###0.00");
            }
        }
    }
}

Open in new window

namespace Export.Classes
{
    public static class ExportPOData
    {
        public static void PerformPOExport()
        {
            List<Parameters> parameters = new List<Parameters>();
            parameters.Add(new Parameters(){
                parameterName = "@OrderDate",
                parameterValue = AppSettings.GetItemsRegionOrderDate()
            });

            SQLData<POModel> sqldata = new SQLData<POModel>();
            IEnumerable<POModel> poModel = sqldata.SelectSPROC(AppSettings.GetPOSPROC(), parameters);
            //List<POModel> poModel = sqldata.SelectSPROC(AppSettings.GetItemsRegionSPROC(), parameters);

            if (poModel.Count() > 0)
            {
                ExportExcelCVS<POModel> exportExcelCVS = new ExportExcelCVS<POModel>();
                exportExcelCVS.ExportData(poModel);
            }
        }
    }
}

Open in new window

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ExportItemsRegion.Classes;

namespace Export.Classes
{
    public class ExportExcelCVS<T> : IExportData<T>
    {
        string filename = string.Empty;

        //public void ExportData(IList<T> value)  ORIGINAL METHOD
        internal void ExportData(IEnumerable<T> value)
        {
            try
            {
                filename = DateTime.Now.ToString("yyyyMMdd") + AppSettings.GetExportLocationFileName();
                string filenameexport = AppSettings.GetExportLocation() + filename + AppSettings.GetExportLocationFileNameExt();
                string filenamefrom = AppSettings.GetExportProcessLocation() + filename + AppSettings.GetExportLocationFileNameExt();
                string filenameto = AppSettings.GetExportLocationArchive() + filename + AppSettings.GetExportLocationFileNameExt();
                string ext = "*" + AppSettings.GetExportLocationFileNameExt();
                string extPrice = string.Empty;

                FileService.DeleteFiles(AppSettings.GetExportLocation(), ext);

                using (StreamWriter sw = new StreamWriter(filenamefrom, false))
                {
                    Type type = typeof(T);
                    PropertyInfo[] properties = type.GetProperties();

                    Console.WriteLine("Test");

                    foreach (var property in type)  //ERROR HERE -> foreach statement cannot operate on variables of type 'System.Type' because 'System.Type' does not contain a public definition for 'GetEnumerator'	

                    {
                        Console.WriteLine(string.Join("|", (from prop in property.GetOrderedProperties() select property.GetValue(prop, null))));
                    }

                    //foreach (PropertyInfo property in type.GetProperties())
                    //{
                    //    Console.WriteLine(string.Join("|", (from prop in property.GetOrderedProperties() select property.GetValue(prop, null))));
                    //    //Console.WriteLine("{{ {string.Join(", ", (from prop in person.GetOrderedProperties() select "{property.Name}: {prop.GetValue(person, null)}"))} }}");
                    //}

                    //sw.WriteLine(result.ToString());
                }
                FileService.CopyFiles(filenamefrom, filenameto);
                FileService.CopyFiles(filenamefrom, filenameexport);
                FileService.DeleteFiles(AppSettings.GetExportProcessLocation(), ext);

                filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportResultFileName();
                ExportResult.WriteResult(AppSettings.GetItemsRegionResult(), filename);
            }
            catch (Exception ex)
            {
                filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportErrorFileName();
                ExportResult.WriteError(ex.ToString(), filename);
                Environment.Exit(1);
            }
        }
    }
}

Open in new window

namespace Export.Classes
{
    public static class Extensions
    {
        public static IEnumerable<PropertyInfo> GetOrderedProperties<T>(this T source)
        {
            var x = (from prop in typeof(T).GetProperties()
                    let attributes = prop.GetCustomAttributes(typeof(DisplayAttribute)).ToArray()
                    where attributes.Count() != 0
                    orderby ((DisplayAttribute)attributes[0]).Order
                    select prop);
            return x;
        }
    }
}

Open in new window

LVL 2
CipherISAsked:
Who is Participating?
 
it_saigeDeveloperCommented:
If you want to test the output of your instances, this should be what you need to do (based on your original code):
public class ExportExcelCVS<T> : IExportData<T>
{
    string filename = string.Empty;

    public void ExportData(IList<T> value)  ORIGINAL METHOD
    {
        try
        {
            string currentDate = DateTime.Now.ToString("yyyyMMdd");
            filename = AppSettings.GetExportLocationFileName();
            string filenameexport = AppSettings.GetExportLocation() + filename + AppSettings.GetExportLocationFileNameExt();
            string filenamefrom = AppSettings.GetExportProcessLocation() + filename + AppSettings.GetExportLocationFileNameExt();
            string filenameto = AppSettings.GetExportLocationArchive() + currentDate + filename + AppSettings.GetExportLocationFileNameExt();
            string ext = "*" + AppSettings.GetExportLocationFileNameExt();
            string extPrice = string.Empty;  //ADDED 

            FileService.DeleteFiles(AppSettings.GetExportLocation(), ext);

            using (StreamWriter sw = new StreamWriter(filenamefrom, false))
            {
                sw.WriteLine(currentDate);

                Console.WriteLine("Test");

                foreach (T instance in value)
                {
                    Console.WriteLine(string.Join("|", (from prop in typeof(T).GetOrderedProperties() select prop.GetValue(instance, null))));
                    //StringBuilder result = new StringBuilder();

                    //foreach (PropertyInfo property in properties)
                    //{
                    //    string parsevalue = property.GetValue(instance, null).ToString();

                    //    if (parsevalue.Contains('\n'))
                    //        parsevalue = parsevalue.Replace('\n', ' ').Replace('\n', ' ');

                    //    if (parsevalue.Contains(';'))
                    //        parsevalue = parsevalue.Replace('\n', ' ').Replace(';', ':');

                    //    if (parsevalue.Contains(','))
                    //        parsevalue = parsevalue.Replace('\n', ' ').Replace(',', ' ');

                    //    if (property.Name == "extendedPrice")  //ADDED 
                    //        extPrice = parsevalue;  //ADDED 
                    //    else  //ADDED 
                    //        result.Append(parsevalue + AppSettings.GetSeparator());
                    //}

                    //result.Append(extPrice + AppSettings.GetSeparator());  //ADDED 
                    //sw.WriteLine(result.ToString());
                    //extPrice = string.Empty;  //ADDED 
                }
            }
            FileService.CopyFiles(filenamefrom, filenameto);
            FileService.CopyFiles(filenamefrom, filenameexport);
            FileService.DeleteFiles(AppSettings.GetExportProcessLocation(), ext);

            filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportResultFileName();
            ExportResult.WriteResult(AppSettings.GetItemsRegionResult(), filename);
        }
        catch (Exception ex)
        {
            filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportErrorFileName();
            ExportResult.WriteError(ex.ToString(), filename);
            //Environment.Exit(1);
        }
    }
}

Open in new window

-saige-
0
 
it_saigeDeveloperCommented:
When you are satisfied with the output, you can simply modify your original method like this:
public class ExportExcelCVS<T> : IExportData<T>
{
    string filename = string.Empty;

    public void ExportData(IList<T> value)  ORIGINAL METHOD
    {
        try
        {
            string currentDate = DateTime.Now.ToString("yyyyMMdd");
            filename = AppSettings.GetExportLocationFileName();
            string filenameexport = AppSettings.GetExportLocation() + filename + AppSettings.GetExportLocationFileNameExt();
            string filenamefrom = AppSettings.GetExportProcessLocation() + filename + AppSettings.GetExportLocationFileNameExt();
            string filenameto = AppSettings.GetExportLocationArchive() + currentDate + filename + AppSettings.GetExportLocationFileNameExt();
            string ext = "*" + AppSettings.GetExportLocationFileNameExt();
            string extPrice = string.Empty;  //ADDED 

            FileService.DeleteFiles(AppSettings.GetExportLocation(), ext);

            using (StreamWriter sw = new StreamWriter(filenamefrom, false))
            {
                sw.WriteLine(currentDate);

                foreach (T instance in value)
                {
                    StringBuilder result = new StringBuilder();

                    foreach (PropertyInfo property in typeof(T).GetOrderedProperties())
                    {
                        string parsevalue = property.GetValue(instance, null).ToString();

                        if (parsevalue.Contains('\n'))
                            parsevalue = parsevalue.Replace('\n', ' ').Replace('\n', ' ');

                        if (parsevalue.Contains(';'))
                            parsevalue = parsevalue.Replace('\n', ' ').Replace(';', ':');

                        if (parsevalue.Contains(','))
                            parsevalue = parsevalue.Replace('\n', ' ').Replace(',', ' ');

                        if (property.Name == "extendedPrice")  //ADDED 
                            extPrice = parsevalue;  //ADDED 
                        else  //ADDED 
                            result.Append(parsevalue + AppSettings.GetSeparator());
                    }

                    result.Append(extPrice + AppSettings.GetSeparator());  //ADDED 
                    sw.WriteLine(result.ToString());
                    extPrice = string.Empty;  //ADDED 
                }
            }
            FileService.CopyFiles(filenamefrom, filenameto);
            FileService.CopyFiles(filenamefrom, filenameexport);
            FileService.DeleteFiles(AppSettings.GetExportProcessLocation(), ext);

            filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportResultFileName();
            ExportResult.WriteResult(AppSettings.GetItemsRegionResult(), filename);
        }
        catch (Exception ex)
        {
            filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportErrorFileName();
            ExportResult.WriteError(ex.ToString(), filename);
            //Environment.Exit(1);
        }
    }
}

Open in new window

0
 
CipherISAuthor Commented:
So, instance has a row but when it passes it to "GetOrderedProperties" nothing is returned.  I included a snapshot.  There is data I just removed it from the image.
ExportPO.jpg
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CipherISAuthor Commented:
Still Stuck.
0
 
it_saigeDeveloperCommented:
Do me a favor, print out the type returned from the instance; e.g. -
public class ExportExcelCVS<T> : IExportData<T>
{
    string filename = string.Empty;

    public void ExportData(IList<T> value)  ORIGINAL METHOD
    {
        try
        {
                foreach (T instance in value)
                {
                    Console.WriteLine("Instance is - ", {instance.GetType()});
                    Console.WriteLine(string.Join("|", (from prop in typeof(T).GetOrderedProperties() select prop.GetValue(instance, null))));
                }
        }
        catch (Exception ex)
        {
        }
    }
}

Open in new window

-saige-
0
 
CipherISAuthor Commented:
It didn't like the {}  So I replaced it with below

                        Console.WriteLine("Instance is - ", instance.GetType());


The result is "Instance is - "

Not seeing the type.
0
 
it_saigeDeveloperCommented:
My fault, had the brackets in the wrong spot:
public class ExportExcelCVS<T> : IExportData<T>
{
    string filename = string.Empty;

    public void ExportData(IList<T> value)  ORIGINAL METHOD
    {
        try
        {
                foreach (T instance in value)
                {
                    Console.WriteLine("Instance is - {0}", instance.GetType());
                    Console.WriteLine(string.Join("|", (from prop in typeof(T).GetOrderedProperties() select prop.GetValue(instance, null))));
                }
        }
        catch (Exception ex)
        {
        }
    }
}

Open in new window

-saige-
0
 
CipherISAuthor Commented:
Figured it out

Used below and I was able to get the model in order.
var xyz = instance.GetOrderedProperties();

Open in new window

Oiginal
foreach (T instance in value)
{
	Console.WriteLine(string.Join("|", (from prop in typeof(T).GetOrderedProperties() select prop.GetValue(instance, null))));
}

Open in new window

Fix.
foreach (T instance in value)
{
	Console.WriteLine(string.Join("|", (from prop in instance.GetOrderedProperties() select prop.GetValue(instance, null))));
}

Open in new window

0
All Courses

From novice to tech pro — start learning today.