Top 10 reads of July 2015

These are our Top 10 reads of July 2015.

  • How to match strings using wildcards in C# and VB.NET
  • IsSmallerThan generic extension method for C# and VB.NET
  • How to prevent your IOS app from going into sleeping mode using Objective-C
  • How to convert Color to Hex and Hex to Color using C# and VB.NET
  • How to read a embedded resource to String in C# and VB.NET
  • How to convert a Securestring to String using C# and VB.NET
  • How to change the encoding of a String using C# and VB.NET
  • How to get focusedrow cell value using Devexpress XtraGrid in C# and VB.NET
  • How to get the selected row index in Devexpress Xtragrid Control using C# and VB.NET
  • thanks to all visitors, bookmark us, share us, talk about us, Follow us!, Like us! let’s grow bigger! You can even participate in our Github Projects!

    How to XSL transform a XDocument in C# and VB.NET with custom namespaces

    This snippet will help you to xsl transform xml files with custom namespaces. A Basic snippet which does only work without custom namespaces can be found HERE. The snippet will return a path to a temporary file (transformed xml).

    Sample C#

    private static string TransformXDocument(string inputXml, string xslFile)
            {
                try
                {
                    var xslt = new XslCompiledTransform();
                    xslt.Load(xslFile);
                    string tempFile = string.Empty;
                    using (var sr = new StreamReader(inputXml, Encoding.Default))
                    {
                        var xDoc = XDocument.Load(xslFile);
                        if (xDoc.Root != null)
                        {
                            var result = xDoc.Root.Attributes().Where(a => a.IsNamespaceDeclaration).GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value)).ToDictionary(g => g.Key,g => g.First());
                            var nt = new NameTable();
                            var mgr = new XmlNamespaceManager(nt);
                            foreach (var ns in result.Where(ns => ns.Key != "xsl" && ns.Value != "http://www.w3.org/1999/XSL/Transform"))
                            {
                                mgr.AddNamespace(ns.Key, ns.Value.ToString());
                            }
                            var xpc = new XmlParserContext(nt, mgr, "", XmlSpace.Default);
                            var rds = new XmlReaderSettings {ConformanceLevel = ConformanceLevel.Document};
                            using (var rd = XmlReader.Create(sr, rds, xpc))
                            {
                                tempFile = Path.GetTempFileName();
                                using (var wr = new StreamWriter(tempFile))
                                {
                                    xslt.Transform(rd, new XsltArgumentList(), wr);
                                    wr.Flush();
                                    wr.Close();
                                }
                                rd.Close();
                            }
                        }
                    }
                    return tempFile;
    
                }
                catch (Exception ex)
                {
                    //handle the exception your way
                    return string.Empty;
                }
            }
    

    Sample VB.NET

    Private Shared Function TransformXDocument(inputXml As String, xslFile As String) As String
    	Try
    		Dim xslt = New XslCompiledTransform()
    		xslt.Load(xslFile)
    		Dim tempFile As String = String.Empty
    		Using sr = New StreamReader(inputXml, Encoding.Default)
    			Dim xDoc = XDocument.Load(xslFile)
    			If xDoc.Root IsNot Nothing Then
    				Dim result = xDoc.Root.Attributes().Where(Function(a) a.IsNamespaceDeclaration).GroupBy(Function(a) If(a.Name.[Namespace] = XNamespace.None, [String].Empty, a.Name.LocalName), Function(a) XNamespace.[Get](a.Value)).ToDictionary(Function(g) g.Key, Function(g) g.First())
    				Dim nt = New NameTable()
    				Dim mgr = New XmlNamespaceManager(nt)
    				For Each ns As var In result.Where(Function(ns) ns.Key <> "xsl" AndAlso ns.Value <> "http://www.w3.org/1999/XSL/Transform")
    					mgr.AddNamespace(ns.Key, ns.Value.ToString())
    				Next
    				Dim xpc = New XmlParserContext(nt, mgr, "", XmlSpace.[Default])
    				Dim rds = New XmlReaderSettings() With { _
    					Key .ConformanceLevel = ConformanceLevel.Document _
    				}
    				Using rd = XmlReader.Create(sr, rds, xpc)
    					tempFile = Path.GetTempFileName()
    					Using wr = New StreamWriter(tempFile)
    						xslt.Transform(rd, New XsltArgumentList(), wr)
    						wr.Flush()
    						wr.Close()
    					End Using
    					rd.Close()
    				End Using
    			End If
    		End Using
    
    		Return tempFile
    	Catch ex As Exception
    		'handle the exception your way
    		Return String.Empty
    	End Try
    End Function
    

    Simple Type Percent for XSD Files

    To use the simply type percent (xs:decimal), see the snippet below.

    <xs:simpleType name="percent">
      <xs:annotation>
        <xs:documentation>The percent type specifies a value from 0 to 100.</xs:documentation>
      </xs:annotation>
      <xs:restriction base="xs:decimal">
        <xs:minInclusive value="0"/>
        <xs:maxInclusive value="100"/>
      </xs:restriction>
    </xs:simpleType>
    

    How to trim a string using XSL 1.0

    Since XSL 1.0 dows not have inbuild Trimming functions for Strings, you need to define your own templates.
    You can use the Trim Templates shown in the codesnippet below.

    Sample XSL

    <xsl:variable name="whitespaceCharacters" select="'&#09;&#10;&#13; '" />
        
        <!-- Trim Right side of the String -->
        <xsl:template name="TrimRight">
            <xsl:param name="input" />
            <xsl:param name="trim" select="$whitespaceCharacters" />
            
            <xsl:variable name="length" select="string-length($input)" />
            <xsl:if test="string-length($input) &gt; 0">
                <xsl:choose>
                    <xsl:when test="contains($trim, substring($input, $length, 1))">
                        <xsl:call-template name="TrimRight">
                            <xsl:with-param name="input" select="substring($input, 1, $length - 1)" />
                            <xsl:with-param name="trim" select="$trim" />
                        </xsl:call-template>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="$input" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:if>
        </xsl:template>
        
        <!-- Trim Left side of the String -->
        <xsl:template name="TrimLeft">
            <xsl:param name="input" />
            <xsl:param name="trim" select="$whitespaceCharacters" />
            
            <xsl:if test="string-length($input) &gt; 0">
                <xsl:choose>
                    <xsl:when test="contains($trim, substring($input, 1, 1))">
                        <xsl:call-template name="TrimLeft">
                            <xsl:with-param name="input" select="substring($input, 2)" />
                            <xsl:with-param name="trim" select="$trim" />
                        </xsl:call-template>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="$input" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:if>
        </xsl:template>
        
        <!-- Trim both sides of the String -->
        <xsl:template name="Trim">
            <xsl:param name="input" />
            <xsl:param name="trim" select="$whitespaceCharacters" />
            <xsl:call-template name="TrimRight">
                <xsl:with-param name="input">
                    <xsl:call-template name="TrimLeft">
                        <xsl:with-param name="input" select="$input" />
                        <xsl:with-param name="trim" select="$trim" />
                    </xsl:call-template>
                </xsl:with-param>
                <xsl:with-param name="trim" select="$trim" />
            </xsl:call-template>
        </xsl:template>
    

    How to get element with the highest ID using XSL

    To get element with the highest ID using XSL you can use the following snippet.

    XML:

    <rootnode>
        <node>
            <id>3</id>
        </node>
        <node>
            <id>2</id>
        </node>
        <node>
            <id>1</id>
        </node>
    	<node>
            <id>5</id>
        </node>
        <node>
            <id>4</id>
        </node>
    </rootnode>
    

    XSL:

    <xsl:variable name="MaxNodeId"><xsl:value-of select="/rootnode/node[not(/rootnode/node/id > id)]/id"/></xsl:variable>
    

    How to check if String is Null or Empty in XSL

    To check if String is Null or Empty in XSL you can use the following snippet.

    Sample XSL

    <xsl:choose>
        <xsl:when test="fieldToTest != ''">
            <xsl:value-of select="Field1Value" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="Field2Value" />
        </xsl:otherwise>
    </xsl:choose>
    

    How to do String Replace in XSL 1.0

    To do String Replace in XSL 1.0 you can use the following snippet.

    <xsl:template name="StringReplace">
      <xsl:param name="input" />
      <xsl:param name="search" />
      <xsl:param name="replace" />
      <xsl:choose>
        <xsl:when test="contains($input, $search)">
          <xsl:value-of select="substring-before($input,$search)" />
          <xsl:value-of select="$replace" />
          <xsl:call-template name="StringReplace">
            <xsl:with-param name="input"
            select="substring-after($input,$search)" />
            <xsl:with-param name="search" select="$search" />
            <xsl:with-param name="replace" select="$replace" />
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$input" />
        </xsl:otherwise>
      </xsl:choose>
    </xsl:template>
    

    The Template can be invoked as:

    <xsl:variable name="newInput">
      <xsl:call-template name="StringReplace">
        <xsl:with-param name="input" select="$input" />
        <xsl:with-param name="search" select="string1" />
        <xsl:with-param name="replace" select="string2" />
      </xsl:call-template>
    </xsl:variable>