XSL/T Transform from String to String

The following example transforms the supplied xml string, using XSL/T and outputs to another string

using (StringReader rdr = new StringReader(selectedLine.AdditionalInformation))
{
    XPathDocument doc = new XPathDocument(rdr);

    using (StringWriter writer = new StringWriter())
    {

        transformer.Transform(doc, null, writer);
        titleLabel.Attributes.Add("onmouseover", string.Format(@"showDiv(""{0}"")", writer.ToString()));
    }
}


The XSL/T loaded into the transformer variable is as follows




    

        
<table class='panelTable'></table>
        
        
<tr><td colspan='2' class='TitlePanelHeader'></td></tr>
        
        
<tr><td></td><td></td></tr>
        


And a sample xml string is as follows:



	
	
	
	
	
	
	
	
	
	
	


The result from the transformation is as follows:

Body Rides
Additional answer code
Additional answer date
Answer code
TOS
Answer date
AuthorRichard Laymon
Delivery toCompany Name, Address Line 1, AddressLine 2
Expected delivery09/08/2009
Held orders
Ordered on20/07/2009
Print runs


The code to build up the xml within the object is below, note that the values are HtmlEncoded to ensure that there are no problems in the web page.

public string AdditionalInformation
{
    get
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(string.Format(CultureInfo.CurrentCulture, 
                                        @"", 
                                        HttpUtility.HtmlEncode(this.Title)));
        AddLabelValue(builder, "Account number", ParentPurchaseOrder.AccountNumber);
        AddLabelValue(builder, "Additional answer code", this.AdditionalAnswerCode);
        AddLabelValue(builder, "Additional answer date", 
            this.AdditionalAnswerDate.Year != 1 ? this.AdditionalAnswerDate.ToShortDateString() : "" );
        AddLabelValue(builder, "Answer code", this.AnswerCode);
        AddLabelValue(builder, "Answer date",
            this.AnswerDate.Year != 1 ? this.AnswerDate.ToShortDateString() : "");
        AddLabelValue(builder,"Author", this.Author);
        AddLabelValue(builder, "Delivery to",
            ParentPurchaseOrder.DeliveryName + ", " + ParentPurchaseOrder.Address1 + ", " +
                          ParentPurchaseOrder.Address2 + ", " +
                          ParentPurchaseOrder.Address3 + ", " +
                          ParentPurchaseOrder.Address4 + ", " +
                          ParentPurchaseOrder.Address5 + ", " +
                          ParentPurchaseOrder.Postcode);

        AddLabelValue(builder, "Expected delivery",
ParentPurchaseOrder.ExpectedDeliveryDate.ToShortDateString());
        AddLabelValue(builder, "Held orders", this.HeldOrders);
        AddLabelValue(builder, "Ordered on", ParentPurchaseOrder.OrderedOn.ToShortDateString());
        AddLabelValue(builder, "Print runs", this.PrintRuns);
                builder.Append("");

        return builder.ToString();

    }
}

private void AddLabelValue(StringBuilder builder, string label, string value)
{
      builder.Append(string.Format(CultureInfo.CurrentCulture,
                        @"",
                         label, HttpUtility.HtmlEncode(value)));
}

?? Operator (C# Reference)

This operator allows you to supply an alternative value if the value being supplied is null. It only works on nullable datatypes but with a bit of googling came accross this article.

public int CurrentPage
{
    get
    {
        return (int)(ViewState["_CurrentPage"] ?? 0);
    }
    set
    {
        this.ViewState["_CurrentPage"] = value;
    }
}

The offical Microsoft article

Creating Event Handler Signatures

In Visual Studio 2008 you’ve lost the abillity to click on the drop down in the code behind and see all the event signatures that are available but haven’t handled yet. To get the signature you are after without using the properites in the desinger you can type…


this.

As you hit the . all methods and events should appear, pick the event you after e.g. Load

Then add type += after the event name and press TAB TAB, the event is automatically generated. ASP.Net auto wires the events with the correct name and signature so you should be able to delete the line of code that binds the event.

Check out this article for more info.

SessionId – keeping it the same

If you don’t populate a value in the session of a page then the session Id will reset everytime the page is loaded.

protected void Page_PreInit(object sender, EventArgs e)
{
    //Need this line otherwise it resets the Session Id everytime!
    Session["keepme"] = "True";
}

Sort Collection

Here is a simple solution based on this article to implement a sort of a generic collection.

public ContentCollection Sort()
{
    List items = (List)Items;
    items.Sort();
    return this;
}

The Content class needs to implement IComparable

C# – IsNumeric

Use the TryParse method to determine if a value is numeric

int retNum;
if (Int32.TryParse(BookId, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum))
{
    //Is numeric
}

Singleton Class – Basic Example

Below is an example of a Singleton implementation C# class.

public sealed class StaticData
{
    private  StaticData() {}
    public static readonly StaticData Instance = new StaticData();
    string connectionString = "";
    public string ConnectionToUse
    {
        get
        {
            if (connectionString.Length == 0)
            {
                connectionString = System.Configuration.ConfigurationManager.AppSettings.Get("DBConnection").ToString();
            }
            return connectionString;
        }
    }
}

Output Parameters with returned value

When using output parameter values you need to check that the value is not DBNull before using it…

using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings.Get("DBConnection").ToString();
    conn.Open();
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@ChapterId", _ChapterId));
        cmd.Parameters.Add(new SqlParameter("@Sequence", _Sequence));
        cmd.CommandText = "Get_ContentPrevNext";
        SqlParameter parameterPreviousId = new SqlParameter("@PreviousId", System.Data.SqlDbType.Int)
        {
            Direction = System.Data.ParameterDirection.Output
        };
        cmd.Parameters.Add(parameterPreviousId);
        SqlParameter parameterNextId = new SqlParameter("@NextId", System.Data.SqlDbType.Int)
        {
            Direction = System.Data.ParameterDirection.Output
        };
        cmd.Parameters.Add(parameterNextId);
        cmd.ExecuteNonQuery();
        if (parameterPreviousId.Value != DBNull.Value)
        {
            _PreviousId = Convert.ToInt32(parameterPreviousId.Value);
        }
        if (parameterNextId.Value != DBNull.Value)
        {
            _NextId = Convert.ToInt32(parameterNextId.Value);
        }
    }
}

Image from Byte Array

To render an image to a picturebox using the data stored in a byte array use the following code

using (MemoryStream ms = new MemoryStream(ImageDetails.ThumbnailImage))
{
    ThumbnailImage.Image = Image.FromStream(ms);
}

Render Image using Generic Handler ASP.Net

The following code uses a property from an object that returns a byte array that contains an image.

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/jpg";
    if (context.Request.Params["Id"] != null)
    {
        Content selectedImage = new Content(Convert.ToInt32(context.Request.Params["Id"].ToString()));
        if (context.Request.Params["t"] == "D")
        {
            context.Response.OutputStream.Write(selectedImage.ImageDetails.FullImage, 0, selectedImage.ImageDetails.FullImage.Length);
        }
        else
        {
            context.Response.OutputStream.Write(selectedImage.ImageDetails.ThumbnailImage, 0, selectedImage.ImageDetails.ThumbnailImage.Length);
        }
    }
}

Previous Entries