Transform XML Strings

This one is a quickie. It applies XML transformations where the source and destination are both strings.

string xml = txtXml.Text;
string xslString = txtTranstring.Text;
string transformedXml = string.Empty;

XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(new XmlTextReader(new StringReader(xslString)));
using (var stringWriter = new StringWriter())
{
    using (var xmlWriter = XmlWriter.Create(stringWriter))
        xsl.Transform(new XmlTextReader(new StringReader(xml)), xmlWriter);

    transformedXml = stringWriter.ToString();
}

txtResult.Text = transformedXml;

OrderBy Extension for Sorting by Multiple Column Names

I often use the OrderBy extension (https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx) to sort results using Linq method syntax. However as of late I have found it necessary to sort by multiple fields by using the field names. While it hasn’t been something critical I have been seeking a way to do this. Today I was able to make my own extension that can take the following types of parameters.

IEnumerable<Employees> sortedResult = employees.OrderBy("department, division asc, lastname desc");

If you try it out and find any issues let me know so I can update the code. While this works on IEnumerable (as it is what I was working with) I will work on an IQueriable version.

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyProject
{
    public static class Extensions
    {
        private enum OrderByType : Int16
        {
            Asc = 0,
            Desc = 1
        }

        public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> enumerable, string sortString)
        {
            if (string.IsNullOrWhiteSpace(sortString))
                throw new MissingMemberException("Sortstring missing or empty.");

            T obj = enumerable.FirstOrDefault();
            string[] orderBy, orderBys = sortString.Split(',');
            string fieldname = string.Empty;
            OrderByType direction;

            IOrderedEnumerable<T> result = null;
            for (int i = 0; i < orderBys.Length; i++)
            {
                if (string.IsNullOrWhiteSpace(orderBys[i]))
                    throw new MissingMemberException("Invalid sortstring.");

                orderBy = orderBys[i].Split(' ').Where(s => !string.IsNullOrWhiteSpace(s)).ToArray(); // 0 = fieldname, 1 = direction
                if (1 <= orderBy.Length) fieldname = orderBy[0];
                Enum.TryParse((2 == orderBy.Length ? orderBy[1] : string.Empty), true, out direction);

                var propertyInfo = obj.GetType().GetProperty(fieldname, System.Reflection.BindingFlags.IgnoreCase   |
                                                                        System.Reflection.BindingFlags.Public       |
                                                                        System.Reflection.BindingFlags.Instance);

                if (0 < i)
                {
                    if (direction.Equals(OrderByType.Asc))
                        result = result.ThenBy(f => propertyInfo.GetValue(f, null));
                    else if (direction.Equals(OrderByType.Desc))
                        result = result.ThenByDescending(f => propertyInfo.GetValue(f, null));
                }
                else if (0 == i)
                {
                    if (direction.Equals(OrderByType.Asc))
                        result = enumerable.OrderBy(f => propertyInfo.GetValue(f, null));
                    else if (direction.Equals(OrderByType.Desc))
                        result = enumerable.OrderByDescending(f => propertyInfo.GetValue(f, null));
                }
            }

            return result;
        }
    }
}

Executing an ISeries Stored Procedure from .NET with ODBC

Below is an example of how one might execute a stored procedure on the ISeries from a C# application. I understand that there are certainly other, much shorter ways to achieve this.

using (OdbcConnection DbConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MyISeres"].ConnectionString))
using (OdbcCommand DbCommand = new OdbcCommand())
{
    DbCommand.Connection = DbConnection;
    DbConnection.Open();
    DbCommand.CommandText = "call MYLIB.MYPROC(?, ?)";

    OdbcParameter p1= new OdbcParameter();
    p1.DbType = System.Data.DbType.String;
    p1.ParameterName = "MyParm1";
    p1.Size = 50;
    p1.Value = "some value";
    p1.Direction = System.Data.ParameterDirection.Input;
    DbCommand.Parameters.Add(p1);

    OdbcParameter p2= new OdbcParameter();
    p2.DbType = System.Data.DbType.String;
    p2.ParameterName = "MyParm2";
    p2.Size = 50;
    p2.Value = "some other value";
    p2.Direction = System.Data.ParameterDirection.Input;
    DbCommand.Parameters.Add(p2);

    using (OdbcDataReader DbReader = DbCommand.ExecuteReader())
    {
        GridView1.DataSource = DbReader;
        GridView1.DataBind();
    } 
}  

Remove JavaScript Tags From HTML

After a while of trying to create the perfect regular expression that would remove script tags from HTML I came across this super simple regular expression. It goes to show you, sometimes the simplest things work best.

s = Regex.Replace(s, "", "",RegexOptions.Singleline|RegexOptions.IgnoreCase);

Source: http://forums.asp.net/t/1323604.aspx/1

Looping Through a Directory And Its Files

A simple function to sift through all the files in a directory using .net

Private Function getEntries(ByVal dir As String)
Dim strEntry As String
Dim dirInfo As New DirectoryInfo(dir)
Dim strEntries As String() = Directory.GetFileSystemEntries(dirInfo.FullName)
     For Each strEntry In strEntries
          If (Directory.Exists(strEntry)) Then
               getEntries(strEntry)
          Else
               Response.Write(strEntry.ToString())
            End If
     Next
Return 0
End Function

Applying Simple Ajax Functionality On Visual Studio

Here are the simple steps to applying ajax functionality to an aspx page using the UpdatePanel control.

  1. Drag and drop a ScriptManager item from the Ajax Extensions section on the toolbox onto the form you wish to add Ajax to.
  2. Drag and drop an UpdatePanel from the Ajax Extensions section on the toolbox onto the form you wish to add Ajax to.
  3. Drag and drop your form controls to the inside of the UpdatePanel.

It’s as simple as that. Here is what the code should look like on the Default.aspx page.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
                <br />
                <asp:TextBox ID="txtMessage" runat="server"></asp:TextBox>
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

And here is what the code-behind page (Default.aspx.vb) should look like. Keep in mind this is a very simple example.

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Me.lblMessage.Text = Me.txtMessage.Text
    End Sub
End Class

Accessing the System.Configuration.ConfigurationManager

I’ve always found Visual Studio to be a great tool for .NET programming. However I ran into a problem while I was trying to access a connection string from the App.config file. As usual I would import the namespace System.Configuration to access the ConfigurationManager. However the ConfigurationManager was nowhere to be found. After a whole night of searching, changing my code, and thinking that maybe I forgot how to access the App.config file, I found the solution.

Apparently typing in Imports.System.Configuration is not enough for you to see the ConfigurationManager these days, you actually have to go to Project > Add Reference, go to the .NET tab, scroll down, click on System.Configuration, and then click OK.

File Funnel

File Funnel is a small application I made that copies files of a specific extension from one directory and its sub-directories to another. It gives you the option to either copy just the files or the directory structure as well.

*It is built on VB.NET and requires the Microsoft .NET Framework so an additional download might be necessary. The application will direct you to the Microsoft download site for that.

Source @ GIT: https://github.com/cquinterox/File-Funnel