Posts Tagged Source code

LINQ to XML: using let, yield return and SelectMany


Introduction

This blog post continues my series on LINQ. The preceding editions which cover some of my experiences with LINQ are list blow, or to the right.

This addition to the LINQ series probably qualifies in the “cruel and unusual” things which can be done with LINQ category. The techniques which are listed here are probably uses of LINQ which fall into the “corner cases” or “edge cases” of LINQ usage.

What is in the C# Source Code Below

There are a couple of things which this code shows:

  • The use of the LINQ let clause. This has proved to be a very convenient way of taking the “bulk” out of the LINQ to XML expressions, and is something which could be seen as an application of the “DRY principle”. I’ve always had the feeling that LINQ to XML was very good for creating XML documents, but was a bit on the verbose side when it came to interrogating XML. Judicious use of the let clause seems like a way to knock some of the verbosity out of the LINQ to XML.
  • There is another benefit of the judicious use of the let clause, and that is that you can imbed complex LINQ expression into LINQ statements in a convenient way. The following code segment shows let used for simple, and one complex (the InfoLines) expressions. The InfoLines is string concatenation from multiple lines.
    var question3 = (from Nodes in XDocument.Load(nodeFileName).Elements("InformationGraph").Elements("Node")
                     from ToElements in Nodes.Elements("Tos").Elements("Entity")
                     from FromElements in Nodes.Elements("Froms").Elements("Entity")
                     let InfoLines = (from InfoLines in Nodes.Elements("InformationContent").Elements("InformationConentLine")
                                      select InfoLines.Value)
                                      .DefaultIfEmpty("No information Content Recorded")
                                      .Aggregate((current, next) => current + ", " + next)
                     let ToElement = ToElements.Element("EntityName").Value
                     let ToObjType = ToElements.Element("EntityObjectType").Value
                     let ToSubSystem = ToElements.Element("SubSystem").Value
                     let FromElement = FromElements.Element("EntityName").Value
                     let FromObjType = FromElements.Element("EntityObjectType").Value
                     let FromSubSystem = FromElements.Element("SubSystem").Value
                     select MakeElements(FromElement, FromSubSystem, FromObjType, ToElement, ToSubSystem, ToObjType, InfoLines))
                    .SelectMany(A => A);
  • The above code sample also introduces another  interesting use of LINQ. This one is the MakeElements function (the code for which follows). This function demonstrates how to produce more than one output (XElement in this case) from a single input. The .SelectMany unwraps the sequence which the MakeElements function generates, into a single level sequence.
    private static IEnumerable<XElement> MakeElements(string FromEntity, string FromSubSystem, string FromObjType,
                                                      string ToEntity, string ToSubSystem, string ToObjectType,
                                                      string LinkTypeDescription)
    {
        string TargetQ = MakeNodeID(ToEntity);
        string SourceQ = MakeNodeID(FromEntity);
        string SourceSubSysQ = String.Empty;
        string TargetSybSysQ = String.Empty;
        yield return new XElement("Node",
            new XAttribute("ID", SourceQ),
            new XAttribute("Label", FromEntity),
            new XAttribute("Category", FromObjType));
        yield return new XElement("Node",
            new XAttribute("ID", TargetQ),
            new XAttribute("Label", ToEntity),
            new XAttribute("Category", ToObjectType));
    
        if (!String.IsNullOrEmpty(FromSubSystem))
        {
            SourceSubSysQ = MakeNodeID(FromEntity + "::" + FromSubSystem);
            yield return new XElement("Node",
                new XAttribute("ID", SourceSubSysQ),
                new XAttribute("Label", FromSubSystem),
                new XAttribute("Category", "SubSystem"));
            yield return new XElement("Link",
                new XAttribute("Source", SourceQ),
                new XAttribute("Target", SourceSubSysQ),
                new XAttribute("Label", "Sub System"));
            SourceQ = SourceSubSysQ;
        }
        if (!String.IsNullOrEmpty(ToSubSystem))
        {
            TargetSybSysQ = MakeNodeID(ToEntity + "::" + ToSubSystem);
            yield return new XElement("Node",
                new XAttribute("ID", TargetSybSysQ),
                new XAttribute("Label", ToSubSystem),
                new XAttribute("Category", "Subsystem"));
            yield return new XElement("Link",
                new XAttribute("Source", TargetQ),
                new XAttribute("Tagert", TargetSybSysQ),
                new XAttribute("Label", "Sub System"));
            TargetQ = TargetSybSysQ;
        }
        yield return new XElement("Link",
            new XAttribute("Source", SourceQ),
            new XAttribute("Target", TargetQ),
            new XAttribute("Label", LinkTypeDescription));
    }
    • The above function demonstrates another interesting “abuse” of the yield return statement. In this case, using the yield return to emit an XElement into the output sequence. This a approach seems to work very well. Also, please note: that the DGML elements which are being generated need to have the DGML namespace added to the XName (http://schemas.microsoft.com/vs/2009/dgml ) (that one came to light today as I was using the output from this function).
    • The following code segment is the MakeNodeID function. This is yet another demonstration of the powers of LINQ to do manipulations on a string object.
      private static String MakeNodeID(string NameString)
      {
          return new String(NameString.Where(A => !Char.IsPunctuation(A) && !Char.IsSeparator(A)).ToArray());
      }

    Conclusions

  • This above code samples are just fragments from the systems I’m building which generates DGML from an XML file. The XML contains information about the relationships between systems, internal and external entities in the organisation I work for. This approach seems to be panning out quite well. I’ll include some more of the “interesting” code from this development in subsequent blog posts. I have an interesting set of LINQ statements which pulls a big DGML graph apart into smaller graphs.

    , , , , , , , , , ,

    1 Comment

    Purchase the WordPress Edit CSS Option


    Introduction

    I’ve finally been pushed into purchasing the Custom CSS option on this site. There have been a couple of reasons why I’ve finally taken the plunge and done this. The primary reason for purchasing the Custom CSS Options was to simplify my blogging process.  I can be quite pedantic about fonts, and formatting, for the posts which I place up here. The HTML which Windows Liver Writer produces (I’m currently using the 2011 versions), and WordPress reacts to that HTML was less than satisfactory.  I would spend some time editing the HTML and imbedding the all of the font information I wanted onto every text carrying tag in the HTML.

    The Reasons

    The reasons I have decided to purchasing the Edit CSS Option have included:

    • I was turning blogging into an HTML editing and checking process. The process of creating a blog post was:
      • I would create a blog post in Windows Live Writer 2011,
      • Then  edit the HTML either in the Source pane of Windows Live Writer, or in Visual Studio,
      • Then post the blog post to WordPress,
      • Then go, “Stuff done it again, wanted to make it a draft and edit it up there!”
      • Then edit the post using the Web Interface on WordPress,
        • Correct any formatting problems. This can be a bit of work as WordPress can clobber some formatting in the HTML. So, it ends up being a cycle between the Source and HTML views in the WordPress editor,
        • Cycle between the Editor and the Preview,
        • Add in Tags,
        • Add in Categories,
        • Add in Possible Associated Links,
      • Then republish the post
      • Then check that it was OK
    • Posting Source code in a blog posts was even worse.
      • Checking the formatting at each step in the process.
        • Writing the bulk of the post and pasting the source code in using Windows Liver Writer,
        • Then to WordPress Web Interface, and check that things look OK. This involved swapping between:
          • the source view,
          • the HTML view,  and
          • the Page Preview
      • I was either:
        • Losing some of the formatting in each of multiple hops, or
        • Gaining formatting which would “stuff up” the presentation of the source code.
    • Getting the capability to fix the banner on my blog
      • When using IE9 the “Craig’s Eclectic Blog”, was displaying with a Black background, which was not aesthetically pleasing. Part of my initial CSS, was a quick bit of CSS which then forced the  “background-color=transparent;”, and that fixed that “gremlin”.
      • I should create a “please fix” with the WordPress “Happiness Engineers” this issue. I’m certain that I will not be the only person to find this “foible” of IE9 and the Fusion Theme.

    What Do I Expect To Get?

    So, what does the Edit CSS Option give (and this post will validate some of these assertions):

    • Control over the formatting of my blog posts, without having to edit the HTML along the way. I was adding in details of the font information in particular onto each of the text carrying HTML tags. Now, the customisation of CSS should (fingers crossed) take care of that.
    • Fix up the banner on the blog pages. I know this works as I’ve fixed that problem already. Although, I may change the font being used, the current Calibri does not look quite right.
    • Assert some better control over the posting of source code onto this blog. I’m not sure what I’ll be able to achieve here, but at least I have the “tool” to do this now.
      • I was using some of the source code plug-ins in Window Live Writer to format the source code, on Windows Live Spaces. Now, I’ll see if I can “convince” them to work with WordPress as the host.
    • Learn what CSS can do. I may need to get a book about this or, better still check my reference library; I may have enough CSS help in one of the volumes I already have.
    • Learn how to do things with CSS, using my blog as a “test bed”. This could prove to be a dangerous thing to do. The potential for fatally breaking things in this blog is something which I will have to assess, and work within.

    The Tools Dimension

    The developing, deployment, and maintenance of the CSS which supports my blog are new technical challenges for me. I’ve not needed, up till now, to know CSS. I have had a “nodding acquaintance” with CSS and an acknowledgement that it was part of the web that I could conveniently ignore.  Well those days are gone, and behind me now. Now I’ll be diving into CSS “head first”, and learning how to get my web pages to do the things which I want.

    This brings me to the topic of tools for creating, testing, and managing, of CSS. There are a multitude of tools for the development of CSS. I’ve “dipped” a toe in the water with a couple of them already, and will be exploring the possibilities of others. These tools include:

    • Internet Explorer Developer Tools (F12).
      • Pros and Cons:
        • This is a good way to trace how IE is interpreting the CSS/HTML combination.
        • It is useful for tracking down where in the HTML the text you want to style is.
        • It displays the class and ID’s which CSS selectors “grab hold of”.
    • Visual Studio
      • Pros and Cons:
        • It works reasonable well with CSS. There is good support for CSS properties and values.
        • Is disconnected from the blog posts (well I’ve not connected it up as yet – not sure you can)
    • Expression Web
      • Pros and Cons:
        • Never used it before, and am just installing it now. Not sure what I’ll find in the package.

    Conclusions

    Well, I’ve accomplished the things I started out wanting to do. The Custom CSS is not very long, but is now doing the things which I wanted. But, there is plenty more to come (I’m sure of that). I’ve the feeling that I’ve opened “Pandora’s box”, in that I will be tinkering with CSS to “beatify” my blog, and coding my Custom CSS to format more parts of HTML (things I’ve not used as yet: pictures, tables, code, links and on the list goes).

    Was it worth it. For me YES. But, I’ve plenty of experience developing software

    , , , , , , ,

    Leave a comment

    Using the ForEach Method


    Introduction

    I’ve found a new “toy” in the C# language this week, the Foreach extension method. It seems to me to be a very effective way of expressing some of those short “iterate over an x and do something to the members.

    I’ve always been a bit “frustrated” with C# when it comes to iterating over collections. The foreach syntax is fine, when you’re doing a loop which has some complex logic. But, for short sharp thing, has always seemed to be a few too many keystrokes for the results. Sure, there is the code snippet for foreach which cuts down the keystrokes, but you still have the minimum of 2 lines of code, or 4 if you us { and }. Also my “inbuilt style guide” baulks at putting multiple statements on one line.

    foreach (string part in TransactionTriggers) Debug.WriteLine(String.Format(" [{0}] ", part));
    

    Or

    foreach (string Name in AllNames.Distinct().OrderBy(A => A))
    {
        Debug.WriteLine(Name);
    }
    

    Oops, the above includes some of my abuses of LINQ. Doing a Distinct and then sorting the list, probably stretching the friendship with LINQ. But, what the heck it works 😉 !

    Using the Foreach Extension Method

    TokenList.ForEach(a => Debug.WriteLine(a));
    

    the above is a quick dump of the contents of a List>String< to the debug console.

    private List LookupType(DataElementsDataContext deDC, List InformationDataElements)
    {
        List<string> result = new List>string<();
        InformationDataElements.ForEach(A => result.Add(LookupType(deDC, A)));
        return result;
    }
    

    An example of method invocation and adding to a list. I’ve also used LINQ to achieve the same sort of result:

    var log1 = from line in ParsedLines
               select new LogMessage(line);
    

     

    StringBuilder result = new StringBuilder();
    bool First = true;
    InformationNameDetails.ForEach(A =>
        {
        if(First)
            First = false;
        else
            result.Append(" and ");
        result.Append(A);
    }
    );
    

    It is probably an abuse of the lambda expressions to include chunks of procedural logic. But, again it works for me, so what the heck!

    Conclusions

    There are more than one observatins which should be made at this point. The major ones are:

    • The use of the Foreach extension method certainly, seems to me, to be an effective way of “cleaning up” C# code, and removing some of the padding which is necessary for the foreach statement.
    • The Foreach extension method is something which could be over used. Well more to the point the complexity of the lambda expression could get greater than the language designers intended.
    • Moving to the method syntax for some foreach loops, opens the door to using the Parallel ForEach Method from the System.Threading.Tasks namespace. You’ve done most of the hard work in the writing of the lambda expression. What is left in the move to a parallel ForEach is a lot of work making sure that what you’re invoking can be done in a parallel manner safely.

    References:

    , , , , , , , , , , , ,

    2 Comments

    %d bloggers like this: