Merge pdf files using C#

Written by jf on October 3, 2008 – 8:00 pm -

Recently I had to create an assembly component using C# to merge multiple PDF files into one file. The specification was pretty straight forward:
1) Merge two of more PDF document into a single output PDF File.
2) Used on an ASP.NET Page

After a few minutes of GOOG, I came up to this “ITextSharp

iText# (iTextSharp) is a port of the iText open source java library written entirely in C# for the .NET platform. iText# is a library that allows you to generate PDF files on the fly. It is implemented as an assembly.

It must be noted that the assembly is coded and compiled using the .NET Framework 1.1. You might want to migrate to the version 2.0 or 3.5 of the .NET Framework.

With a some more research on PDF merging. I was able to create a class that will make use of the ITextSharp assembly and perform as the merge pdf operation as needed.

Here is the code:
Read more »

Subscribe to my RSS feed

Copy-Clone custom object in C#

Written by jf on August 5, 2008 – 6:00 am -

This post relates how to Copy/Clone custom object in C# (Deep and Shallow Clone).

In this example I will be having a base class that all my custom object will be inheriting from.

Updates: After quiet some research on the subject i recently found some interesting articles on this subject and wanted to share them on this post.

Object Cloning Using IL in C#

This subject is inspired on a session I followed on the TechDays 2008,
that addressed the fact that IL (Intermediate Language) can be used to clone objects, among other things, and that it’s not evil at all, and it can be pretty performant also.

You only have to see that you don’t overuse it tho, because otherwise the readability of your code is reduced, which is not a good thing for the maintenance.
And wrong usage of reflection (what IL is, or at least uses) can also result in poor performance.

Read more:
http://whizzodev.blogspot.com/2008/03/object-cloning-using-il-in-c.html

C# Class For Making a Deep Copy Clone of an Arbitrary Object

Here is a C# class that can create a deep copy clone of an arbitrary object. The thing that’s special about it is that it should work for any class that extends it, so that you don’t need to re-write a custom clone() function for every child class (as it seems the C# framework creators would like). This does a deep copy so be careful about members that recursively include one another.

Another way of doing this would be to use serialization . . . I just personally thought the reflection package would be more elegant.

Read more:
http://www.thomashapp.com/node/106

C# Object Clone Wars

Cloning C# objects is one of those things that appears easy but is actually quite complicated with many “gotchas.” This article describes the most common ways to clone a C# object.

Shallow vs. Deep Cloning

There are two types of object cloning: shallow and deep. A shallow clone copies the references but not the referenced objects. A deep clone copies the referenced objects as well.

hallow vs Deep Cloning

shallow vs Deep Cloning

Read more:
http://www.csharp411.com/c-object-clone-wars/

Clone C# Object using Serialization and De-serialization (Deep Clone)

In this example i’ll be using Serialization and De-Serialization to make a deep clone of the Person Class.

You must import the following namespaces to start with.


using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;

Read more »

Subscribe to my RSS feed

ASP.NET: HyperLink and Label without Id attribute

Written by jf on August 4, 2008 – 6:00 am -

Today, I’ll talk a bit about how ASP.NET handles HTML rendering of controls such as <asp:HyperLink> and <asp:Label>.  If you have developed using ASP.NET you must have noticed that when an <asp:Hyperlink> or <asp:Label> is rendered you will find something like that:

<html>

<a id="ctl00_ContentPlaceHolder1_rptShoppingCart_ctl00_lnkGotoCheckout" href="#" class="someCss">delete</a>

</html>

From an ASP.NET point of view, this is fine, since all object rendered should be identified uniquely on the client side. But many a time these are useless, since these hyperlinks are not used to trigger any server side events. Thus the id attributes just takes up a lot of space on your HTML and Page Size when you have many links like that. If you don’t want to have those, here is a solution I came up with, you can create custom server controls that inherits from the control that you want to remove the id attribute tag from.

Here is sample of the code that i used to remove the id attribute from the Hyperlink Control, without basically removing all the features provided by the Hyperlink control such as being able to handle Resource files for globalization.

[ToolboxData("<{0}:HyperLinkEx runat=server></{0}:HyperLinkEx>")]
public class HyperLinkEx: System.Web.UI.WebControls.HyperLink
{
private string rel;

/// <summary>
/// Gets or sets the rel.
/// </summary>
/// <value>The rel.</value>
public string Rel
{
get { return rel; }
set { rel = value; }
}

/// <summary>
/// Renders the control to the specified HTML writer.
/// </summary>
/// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"></see> object that receives the control content.</param>
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();

sb.Append("<a");

if (this.NavigateUrl.StartsWith("~"))
this.NavigateUrl = ResolveClientUrl(this.NavigateUrl);
sb.Append(" href=\"" + this.NavigateUrl + "\"");

if (!string.IsNullOrEmpty(rel)) sb.Append(" rel=\"" + rel + "\"");
if (!string.IsNullOrEmpty(this.CssClass)) sb.Append(" class=\"" + this.CssClass + "\"");
if (!string.IsNullOrEmpty(this.Target)) sb.Append(" target=\"" + this.Target + "\"");
if (this.Attributes["onclick"] != null) sb.Append(" onclick=\"" + this.Attributes["onclick"] + "\"");

sb.Append(">");

if (!string.IsNullOrEmpty(this.ImageUrl)) //Some image were found
{
if (this.ImageUrl.StartsWith("~"))
this.ImageUrl = ResolveClientUrl(this.ImageUrl);
sb.Append("<img src=\"" + this.ImageUrl + "\" alt=\"" + this.Text + "\" title=\"" + this.Text + "\" border=\"0\" />");
}
else
{
sb.Append(this.Text);
}

sb.Append("</a>");
writer.Write(sb.ToString());
}

}

In this source code, i have overridden the render method of the control and outputted a cleaner HTML anchor with no Id attributes. I have also added support for ImageURL attribute of the hyperlink server control, thus maintaining the most of the asp:Hyperlink features.

I have also created a tiny library with some controls: <asp:HyperLink>, <asp:Label>, <asp:Image> which i think are the controls that need not have the id attribute in every scenario.

You can find it for download under GNU Public Licence here.

Subscribe to my RSS feed

Exception: Collection was modified; enumeration operation may not execute.

Written by jf on May 28, 2008 – 7:00 am -

It’s been a while that i didn’t get this Exception, while working, and yesterday, while I was performing some test on  a new module that I implemented i got this exception. I knew i did get it sometimes back last year, and managed to solve it. So here is one solution when you are dealing with this kind of issue:

IList<Product> productList = new List<Product>();
productList.Add(new Product("Some product 1");
productList.Add(new Product("Some product 2");
productList.Add(new Product("Some product 3");
productList.Add(new Product("Some product 4");

for(int i=(productList.Count -1); i >= 0; i--)
{
//Perform Edit, Update, Delete Operation using for .. i loop in reverse order
}

There is a list of other solutions that can be found on the following websites:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=372532&SiteID=1
http://forums.asp.net/p/1147145/1861164.aspx
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21585534.html

Subscribe to my RSS feed

Paging large result sets with SQL query

Written by jf on May 22, 2008 – 6:00 am -

I’ve been searching on the internet for several ways to perform paging on a large result set from an SQL Query, there are several solutions, that can be found some are custom and others are already provided with ASP.NET Controls. This is the solution i have been using for performing paging of large datasets for data that is being used on a current web 2.0 site.

Here is a common problem:
A website offering search capabilities for it’s users is having performance issues while getting the result from it’s database, they have more than 100K record, and users are able to perform criteria search or just a text search on it. Criteria search can take up a lot of time to process depending on how it has been implemented. Statistics have shown that the average result count is about 1000 record for text search and 500 for criteria search.

The Stored Procedure
Let’s take this SQL Query as a sample query to get result for a typical text search.

SELECT Id, ProductName, ProductDescription, ProductRating, ProductPrice
FROM tbl_Product
WHERE
ProductName LIKE '%' + @Query + '%'
OR
ProductDescription LIKE '%' + @Query + '%'

This stored procedure takes one parameter a query ( @Query ), that the website visitor types in to search for something. And the query search both the Product Name and Product Description Field. This may result in some huge result set for some key terms.

We need to optimize this query to be able to perform custom paging on the other side.

here is how the optimized code would be:

–Will calculate the number of records of this particular request
SELECT @RecordCount = COUNT(1)
FROM
tbl_Product
WHERE
ProductName LIKE ‘%’ + @Query + ‘%’
OR
ProductDescription LIKE ‘%’ + @Query + ‘%’

SELECT *
FROM
(SELECT ROW_NUMBER() OVER (ORDER BY Id ASC) AS Row, Id, ProductName, ProductDescription, ProductRating, ProductPrice
FROM
tbl_Product
WHERE
ProductName LIKE ‘%’ + @Query + ‘%’
OR
ProductDescription LIKE ‘%’ + @Query + ‘%’
) AS TmpTbl
WHERE Row BETWEEN @RowStart AND @RowEnd
ORDER BY ProductRating

I have added 2 input parameters which are the @RowStart and @RownEnd, and 1 output parameter which is @RecordCount. With these new parameters added you will be able to lauch a query based on the number of records you want to display on a particular page. If you want to display 10 records per page your input parameters will have the following values
@RowStart = 1
@RowEnd = 10
since the query is inclusive.

You can use your prefered data control to display the data, and to build up the Paging logic in ASP.NET

Subscribe to my RSS feed

Padding is invalid and cannot be removed.

Written by jf on January 18, 2008 – 4:32 pm -

Stop Google crawling WebResource.axd & ScriptResource.axd
As an ASP.NET developer i often get error message: “Padding is invalid and cannot be removed”. It’s a pretty annoying message that i have been trying to get rid of for days. It was caused by Google trying to index, crawl my WebResource.axd and session. But when the session expires you get this error message. Since Google caches the pages it visits the session on this page has already expired after it is crawled, when it tries to crawl the page again and request the WebResource.axd or ScriptResource.axd with an old key, an exception is raised.

Therefore to solve this problem the simple solution for that is to modify your robots.txt file in your root directory

and add the following at the end

Disallow: /ScriptResource.axd
Disallow:/WebResource.axd

With this no more issues regarding invalid padding.

If this does not solve your issue you can take a look at what other users propose here.

Some update on this issue, i found out while googling some days back:

On this post you can find out how to compress the webresource.axd and also somewhere in between prevent this error to occur.
http://mironabramson.com/blog/post/2007/10/New–Shiny–WebResourceaxd-compression-Module.aspx

Use the tool found at the website below to generate a machine key and a decryption key:
http://www.orcsweb.com/articles/aspnetmachinekey.aspx

Subscribe to my RSS feed

Retrieving anchor value from URL

Written by jf on January 16, 2008 – 2:08 pm -

Lately i have been trying to get a grasp of the anchor value from the URL using ASP.NET. From what i learned from the forum (This might be wrong since there is a way in PHP(http://www.php.net/manual/en/function.parse-url.php) to get the anchor value.)

Case study:

e.g http://www.somesamplebigsite.com/product.aspx?q=123&u=09#description
The url above send the user to a page product and then your browser interpret the anchor and scroll down way to the description anchor. But the question is why the heck would i want to get the anchor since it’s just an anchor ? There might be several reasons for that. Here is 2 of them:

  • You might not want to pass an extra parameter in your URL query string because of Referencing issues
  • You would like to perform an action when the page reaches the anchor: Example open an AJAX popup or load some information or Execute a JavaScript in the Description Section of the product.

There might be several other reasons, but these two give you and idea of what is to be achieved.

You can’t get access to the anchor value using server side ASP.NET, it will neither be seen in the Request.Url nor the Request.RawUrl. Therefore those who are trying in vain to get access to this information, don’t bother anymore. You can just use a simple javascript that will do that, and then if you want afterward to either make a new submit to the server or do it in AJAX.

var anchorValue;
var url = document.location;
var strippedUrl = url.toString().split(”#”);
if(strippedUrl.Length > 1)
anchorvalue = strippedUrl[1];

With these few lines of javascript you will be able to determine the value anchor that has been sent in your URL.

Subscribe to my RSS feed

Copy custom object in C#

Written by jf on August 9, 2007 – 8:27 am -

There are several ways to clone custom object in .NET.

  • Using reflection to get information about each field and properties in the custom class, create a new instance and assign the proper value.
  • Manually implementing the clone method and assign each field and method and then return a new object
  • Using serialization and deserialization.

I have tried the third method, that can be found here, it seems to be working fine for the time being, more test need to be done for performance overhead.

Subscribe to my RSS feed

Web Stress Tool

Written by jf on June 14, 2007 – 1:53 pm -

Today I have been trying to web stress my development website using ACT from Microsoft. I am using Visual Studio 2005 Professional, and while taking a look to find this precious tool that was readily available in the previous version VS.NET 2003. I couldn’t find it. (uh!!! did i forget to install it ???? ) checked out but nothing done, checked on the web and reach a forum post which said. Application Test Center is no more available on VS.NET 2005, you can buy a new licence of VS.NET Team tester to to be able to use some stress tool. Ok how nice :) marketing strategy…

Anyway, i have been wandering around the web to find a proper web stress/load tool to be able to test my web developments. results have been pretty deceiving… could not find a proper tool for testing ASP.NET Websites. After some time i came up on sourceforge. to find this tool : WEBLOAD (Open source performance testing) which is the open source version of the recognised Radview Webload.

I’ll be now trying this tool and then give some feedback soon after.

Subscribe to my RSS feed

BUG: Error message when you visit a Web page or interact with a Web application in Internet Explorer: “Operation aborted”

Written by jf on May 29, 2007 – 9:27 am -

Here is a bug that i came to recently while working with:

var d = document.createElement(”div”);
document.body.appendChild(d);

This bug is only on IE and it’s really annoying one. There is a fix provided by Microsoft, you can take a look at it here.

It is a pretty comprehensive and complete article but there is one thing missing in there. The state that the problem is caused

This problem occurs because a child container HTML element contains script code that tries to modify the parent container element of the child container. The script code tries to modify the parent container element by using either the innerHTML method or the appendChild method.

The solution is

To work around this problem, write script blocks that only modify closed containers or that only modify the script’s immediate container element. To do this, you can use a placeholder to close the target container, or you can move the script block into the container that you want to modify.

That’s a pretty good solution, but what if i don’t want to do that, or can’t handle a code that would generate something like that in the body, e.g When developing in ASP.NET using Master Pages. You must develop some specific module to have a handle in the master page body to be able to call your javascript in the body text itself.

Here is a quick fix that works pretty fine and easy to implement.

In your Page where you want to call the javascript create a DIV element in the body/content ( <div id=”ie_fix”></div> )
With this done you can now modify your javascript to be like that:

var d = document.createElement(”div”);

if(is_ie) //This is a browser check have to code here.
{
var ie_fix = document.getElementById(”ie_fix”);
ie_fix.appendChild(d)
}else
document.body.appendChild(d);

This is a quick fix that should help you waste/avoid unnecessary recoding. This has been Tested on IE 7 - Running on Windows Vista.

Subscribe to my RSS feed