Disabling Change Tracking in Entity Framework

This might come handy in case, you are having performance issue with Entity Framework and Change Tracking Option.

Short version :

using (SchoolEntities context = new SchoolEntities())
{
 context.Course.MergeOption = MergeOption.NoTracking;

 foreach (var course in context.Course)
 {
 // the courses we enumerate are detached state
 Console.WriteLine("{0} {1}", course.CourseID, course.Title);
 }
}
using (SchoolEntities context = new SchoolEntities())
{ 
 var query = new ObjectQuery<Course>(
 "SELECT VALUE c FROM SchoolEntities.Course AS c", 
 context, 
 MergeOption.NoTracking);

 foreach (var course in query)
 {
 // the courses we enumerate are detached state
 Console.WriteLine("{0} {1}", course.CourseID, course.Title);
 }
}

Thanks to Gil Fink’s for this post.

Read the whole article from : http://blogs.microsoft.co.il/blogs/gilf/archive/2009/02/20/disabling-change-tracking-in-entity-framework.aspx

 

Simple Resx Editor

I recently came to a nice Resx Editor alternative. It’s simple to use and the learning curve is very low. It’s perfect for your staff that you don’t want to train in Visual Studio to edit Resx file to text translation.

Take a look at it: http://simpleresxeditor.blogspot.com/2010/12/simple-resx-editor-0660-is-now.html

There is also a video tutorial available: http://www.youtube.com/watch?v=7hUdkqVXmWc&feature=player_embedded

It features:

* Highlight differences and coincidences (1)

* Highlight keys containing text

* Show/Hide keys

* Filter text-only rows

* Drag and drop support

* Multi-language UI

(1) With multiple resx files loaded

Merge pdf files using C#

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:
[csharp]using iTextSharp.text;
using iTextSharp.text.pdf;

public class MergeEx
{
#region Fields
private string sourcefolder;
private string destinationfile;
private IList fileList = new ArrayList();
#endregion

#region Public Methods
///
/// Add a new file, together with a given docname to the fileList and namelist collection
///
public void AddFile(string pathnname)
{
fileList.Add(pathnname);
}

///
/// Generate the merged PDF
///
public void Execute()
{
MergeDocs();
}
#endregion

#region Private Methods
///
/// Merges the Docs and renders the destinationFile
///
private void MergeDocs()
{

//Step 1: Create a Docuement-Object
Document document = new Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));

//Step 3: Open the document
document.Open();

PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;

int n = 0;
int rotation = 0;

//Loops for each file that has been listed
foreach (string filename in fileList)
{
//The current file path
string filePath = sourcefolder + filename;

// we create a reader for the document
PdfReader reader = new PdfReader(filePath);

//Gets the number of pages to process
n = reader.NumberOfPages;

int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();

//Insert to Destination on the first page
if (i == 1)
{
Chunk fileRef = new Chunk(” “);
fileRef.SetLocalDestination(filename);
document.Add(fileRef);
}

page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception e) { throw e; }
finally { document.Close(); }
}
#endregion

#region Properties
///
/// Gets or Sets the SourceFolder
///
public string SourceFolder
{
get { return sourcefolder; }
set {sourcefolder = value; }
}

///
/// Gets or Sets the DestinationFile
///
public string DestinationFile
{
get { return destinationfile; }
set { destinationfile = value; }
}
#endregion
}
[/csharp]
To use the MergeEx class:
1) Initialize the class
2) Set the SourceFolder and DestinationFile properties
3) Using the AddFile method, add the source file names that need to be merged (Filename only since the SourceFolder has already been set)
4) Call the Execute Method

If everything works fine you will find your Merged PDF Document at your stated destination file.

The code is pretty much self decribed. If there is any question, i can always be contacted via this post.

Copy-Clone custom object in C#

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.
[csharp]
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
[/csharp]

Let’s create a base class Person that all our other classes with inherit from. It will contain the following methods:

  • ToXMLString() : Returns an XML version of the current object
  • Deserialize(XmlDocument xml, Type type) : De-serialize the current XMLDocument cast it to the current type
  • Serialize(object o) : Serialize the current object and outputs an XMLDocument
  • Clone(): Runs a Serialization and De-serialization and returns a clone of the current Object

[csharp]
[Serializable()]
public abstract class Person
{
///

/// To XML string.
///

///
public string ToXMLString()
{
XmlSerializer serializer = new XmlSerializer(this.GetType());
MemoryStream dataStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(dataStream, Encoding.UTF8);
serializer.Serialize(dataStream, this);
return writer.ToString();
}

///

/// Deserializes an xml document back into an object
///

/// The xml data to deserialize /// The type of the object being deserialized /// A deserialized object
public static object Deserialize(XmlDocument xml, Type type)
{
XmlSerializer s = new XmlSerializer(type);
string xmlString = xml.OuterXml.ToString();
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
MemoryStream ms = new MemoryStream(buffer);
XmlReader reader = new XmlTextReader(ms);
Exception caught = null;

try
{
object o = s.Deserialize(reader);
return o;
}

catch (Exception e)
{
caught = e;
}
finally
{
reader.Close();

if (caught != null)
throw caught;
}
return null;
}

///

/// Serializes an object into an Xml Document
///

/// The object to serialize /// An Xml Document consisting of said object’s data
public static XmlDocument Serialize(object o)
{
XmlSerializer s = new XmlSerializer(o.GetType());

MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding());
writer.Formatting = Formatting.Indented;
writer.IndentChar = ‘ ‘;
writer.Indentation = 5;
Exception caught = null;

try
{
s.Serialize(writer, o);
XmlDocument xml = new XmlDocument();
string xmlString = ASCIIEncoding.UTF8.GetString(ms.ToArray());
xml.LoadXml(xmlString);
return xml;
}
catch (Exception e)
{
caught = e;
}
finally
{
writer.Close();
ms.Close();

if (caught != null)
throw caught;
}
return null;
}

///

/// Creates a new object that is a copy of the current instance.
///

///
/// A new object that is a copy of this instance.
///

public object Clone()
{
return Deserialize(Serialize(this), this.GetType());
}
}
[/csharp]

Here are sample classes that herits from the abstract base class and clone operation are performed upon them.

[csharp]

public class Clerk: Person
{
private string position;

///

/// Gets or sets the position.
///

/// The position.
public string Position
{
get { return position; }
set { position = value; }
}
}

public class Developer: Person
{
private string skill;

///

/// Gets or sets the skill.
///

/// The skill.
public string Skill
{
get { return skill; }
set { skill= value; }
}
}

[/csharp]

Using clone method.

[csharp]

public void UpdateSkills()
{
IList clerkList = new ArrayList();
IList newClerkList = new ArrayList();

foreach (Clerk clerk in clerkList)
{
newClerkList.Add((Clerk)clerk.Clone());
}
}

[/csharp]

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

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:

[csharp]

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”);

[/csharp]

[csharp]

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

[/csharp]

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

Padding is invalid and cannot be removed.

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

Copy custom object in C#

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.

Web Stress Tool

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.

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

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.