Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

this is a project i am working on it generates an html table out of a query result.

(the result DataTable of an sql command via SP)

this section of the project is the one that will generate the headers of the table according to the list of columns of each table selected(from the database list of tables)

what i am trying to review here is the section that's responsible for generating an Html Markup Programmatically ,

i would like to know what is your opinion and what will you do differently

if there is something missing out that is required please let me know so I will past it here too .

in aspx will move this to code behind after tests are completed

<%
   //instantiating class to Get A List<string> returned (of all db table-columns)
  // this code is  inplementing  GetClassFields class
  // you can see its code in section #2 below (helpers section)

    var TableColscls = GetClassFields.AsListStr(GetClassFields.SelectedClass.tables, tbls.TblTimeCPAReport);

%>

then using the list above for generated html table

<div style="width:90%; " dir="rtl">

<%=RenderHtmlTblHeaders(TableColscls)%>


</div>

.cs Code Behind

 // some usings 
 using Lsts = HTMLGenerator.dataSource.List;

 // this is what i call HTML TABLE GENERATOR 
 // or DB TO HTML Tables Adapter

public string RenderHtmlTblHeaders(List<string> SelectedListStr)
{

    List<string> OmittedCols = new List<string>();
    OmittedCols.Add(imprtCPAcols.tbName);
    OmittedCols.Add(imprtCPAcols.tbIdentCol);


    StringBuilder NwTRLoopSB = new StringBuilder();

    string curRowStyle= string.Empty,
           nwLine = Environment.NewLine + "\t\t\t",
           BaseTemplateTD = string.Empty;

    NwTRLoopSB.Append(
            string.Format(
                "<table id='tbl_Settings' cellspacing='0' border='1'><tr id='TR_headers'{0}>{1}",
                curRowStyle,
                nwLine
                )._Dhtml_DoubleQoutes()
        );

//a new approach i've discovered (in one of the posts on `SO` )
//to have a counter with foreach loops

    foreach (var Item in SelectedListStr.Select((Val, counter) => new { Value = Val, Index = counter }))
    {

            if(Lsts.ExcludeColumns(Item.Value, OmittedCols))
            {
                BaseTemplateTD = string.Format("<td>{0}</td>{1}", Item.Value, nwLine)._Dhtml_DoubleQoutes();
                NwTRLoopSB.Append(BaseTemplateTD);
            }    

    }///ENd TR cells generator Section

    NwTRLoopSB.Append("</tr></table>");
    return NwTRLoopSB.ToString();
}

and here is

.cs Helper namespaces And classes

the code blocks below are extracted by relevance to this project

as it(the whole file) serves all of my projcts as a bunch of helpers

1) Extensions this one is used to avoid the use of \" within a formatted text

                /// <summary>
                /// Replaces a single Quote with Double. used for html Attributes:
                /// </summary>
                public static string _Dhtml_DoubleQoutes(this string NewTRString)
                {
                    return NewTRString.Replace("'", "\"");
                }

2) class to list

    // using reflection to list / extract all fields of a given class

    public  class GetClassFields
    {
        public enum SelectedClass
        {
            tables, columns, ColHeaders
        }

        public List<string> AsListStr(SelectedClass tabls_Cols_StoerdProc, string TableName)
        {

            var tbls = new HTDB_Tables();
            HTDB_Cols Cols = new HTDB_Cols();
            var ColHeds = new Htdb_PresentedHebColHeaders();

            switch (tabls_Cols_StoerdProc)
            {
                case SelectedClass.tables:
                    return typeof(HTDB_Tables).GetFields()
                     .Select(f =>f.GetValue(tbls).ToString()).ToList<string>();


                case SelectedClass.columns:
                    return typeof(HTDB_Cols).GetNestedTypes()
                    .First(t => String.Compare(t.Name, TableName, true) == 0)
                    .GetFields()
                    .Select(f => f.GetValue(Cols).ToString())
                    .ToList<string>();
                case SelectedClass.ColHeaders:

                    return typeof(Htdb_PresentedHebColHeaders).GetNestedTypes()
                        .First(t => String.Compare(t.Name, TableName, true) == 0)
                        .GetFields()
                        .Select(f => f.GetValue(ColHeds).ToString())
                        .ToList<string>();

                  default:
                    return typeof(HTSPs.GetWorkerNameAndDataForTcReportCPABySnif_Fields).GetNestedTypes()
                    .First(t => String.Compare(t.Name, TableName, true) == 0)
                    .GetFields()
                    .Select(f => f.GetValue(null) as string)
                    .ToList();

            }
        }

    }

3) Html Generator (the short version, you could see my other post for a longer version)

another method to produce style- background-color as bgColor of the alternation of rows within the html generated table

public class HTMLGenerator
{
   //i guess i will add whats in cs code behind to this next section of helpers

            public class HTMFactory
            {

                //TablesAlternatingRow
                public static string DynamicStyle_Generator
                (
                    int RowCounter = -1,
                    Dictionary<string, string> StyleAttributeDict = null
                )
                {
                    string BaseStyle = "", propTerminator = "'", BgCol = "";

                    StringBuilder StylerSB = new StringBuilder();


                    BgCol = "";
                    bool bgclaltrnator;
                    if (RowCounter >= 0)
                    {
                        RowCounter++;
                        bgclaltrnator = (RowCounter % 2) == 0;
                        if (bgclaltrnator)
                            BgCol = "#70878F";
                        else BgCol = "#E6E6B8";
                    }
                    BaseStyle = string.Format("style='background-color:{0};", BgCol);


                    ///string.Format("{0}:{1};", StlProps.BgColor, val);
                    return string.Concat(BaseStyle, StyleAttributeDict, propTerminator);

                }
    }

   // when inside the loop this will supply the correct "data source"
   // that will be the content of the table cells
   // for now it is the "selector" of which column to omitt method that 
   // i have placed here...

    public class dataSource
    {
        public sealed class List
        {

            public static bool ExcludeColumns
                                       (
                                            string ListItem,
                                            List<string> OmittedColumns
                                       )
            {
                    bool Ret = false;

                        foreach (string col in OmittedColumns)
                        {
                            Ret = string.Compare(ListItem, col) ==0;
                            if (Ret)
                                return false;
                        }

                        return true;
            }


        }
    }
}
share|improve this question
    
Have you looked using the HTML Agility Pack. It may be overkill but it might also make some of the steps easier. –  Gene S Dec 17 '12 at 22:51
    
@GeneS I know HtmlAgilityPack... I am using it for parsing html documents , what else , I couldn't connect the idea ...(4am here) of usage with HtmlAgilityPack , as i don't really know more of it's features, but those I've already used for Parsing , so which part are you referring to and what features of HtmlAgilityPack would cover for it better ? , thanks for your time. –  LoneXcoder Dec 18 '12 at 2:48
    
You can also use it to create new Html documents. I'm not an expert with it so I am not sure if it would end up being too tedious to create new elements. But if not, it might be a nice way to create the document in an object-oriented fashion. –  Gene S Dec 18 '12 at 15:53
    
@GeneS thanks mate . i will look in to this aspect of the HtmlAgilityPack as i like to discover new implementation and see if it is more appropriate or easy to manipulate . did you ever try to pool some tricks of not having to hardcode your markup, also because it will be required as it will unnecessarily repeat itself –  LoneXcoder Dec 18 '12 at 16:06
    
No sorry, I have not had to do this. I suspect if you find the HtmlAgilityPack an acceptable solution you will have less hardcoded markup because you will be creating elements instead of strings. –  Gene S Dec 18 '12 at 17:31
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.