Object property/fields cloner

Here is a class using reflection to transfer property or field values from an object to another, instead of copying values one by one like this:

b.Address = a.Address
b.Age = a.Age
b.Color = a.Color
b.Surname = a.Surname
b.Boss = a.Boss
[...]

Instead, this helper method will be used like this:
PropertyCopier.CopyPropertiesToTargetObject(a,b)

That's it. Object b now have same property values as a.



Imports System.Reflection

''' <summary>
''' Helper class using reflection to copy all fiels and/or properties
''' from a object A to object B
''' </summary>
''' <remarks></remarks>
Public Class PropertyCopier

''' flags to get all instance fields, even privates
Private Shared flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.[Public] Or BindingFlags.Instance

#Region " To copy object property values "

''' <summary>
''' Copy all property values from sourceObject to targetObject
''' Private and public properties values will be cloned from sourceObject to targetObject when property name exists on the two object
''' </summary>
''' <param name="sourceObject">Oject from which fields values will be copied</param>
''' <param name="targetObject">Object which will have copied property values</param>
''' <remarks>
''' By default, only properties having same value types are cloneed
''' </remarks>
Public Shared Sub CopyPropertiesToTargetObject(ByVal sourceObject As Object, ByVal targetObject As Object)
CopyPropertiesToTargetObject(sourceObject, targetObject, True)
End Sub

''' <summary>
''' Copy all property values from sourceObject to targetObject
''' Private and public properties values will be cloned from sourceObject to targetObject when property name exists on the two object
''' </summary>
''' <param name="sourceObject">Oject from which fields values will be copied</param>
''' <param name="targetObject">Object which will have copied property values</param>
''' <param name="sameValueTypesOnly">If true, only property having the same type of value (ex: String, CustomClassType, etc) will be cloned</param>
''' <remarks></remarks>
Public Shared Sub CopyPropertiesToTargetObject(ByVal sourceObject As Object, ByVal targetObject As Object, ByVal sameValueTypesOnly As Boolean)
'''' getting all properties from two objects
Dim sourceFields As FieldInfo() = sourceObject.[GetType]().GetFields(flags)
Dim targetFields As FieldInfo() = targetObject.[GetType]().GetFields(flags)

Dim tempValue As Object
For Each sourceField As FieldInfo In sourceFields
For Each targetField As FieldInfo In targetFields
If sourceField.Name = targetField.Name Then
'' Same property name => value to copy?
tempValue = sourceField.GetValue(sourceObject)
' If same value type between object, or not strict copy asked
If tempValue.GetType() Is targetField.GetValue(targetObject).GetType() Or Not sameValueTypesOnly Then
Try
targetField.SetValue(targetObject, tempValue)
Catch ex As Exception
If sameValueTypesOnly Then Throw
System.Diagnostics.Debug.WriteLine(ex.ToString())
End Try
End If
End If
Next
Next
End Sub
#End Region

#Region " To copy object fields values "
''' <summary>
''' Copy all fields values from sourceObject to targetObject
''' Private and public field values will be cloned from sourceObject to targetObject when fields name exists on the two object
''' </summary>
''' <param name="sourceObject">Oject from which fields values will be copied</param>
''' <param name="targetObject">Object which will have copied values</param>
''' <remarks>
''' By default, only fields having same value types are cloneed
''' </remarks>
Public Shared Sub CopyFieldsToTargetObject(ByVal sourceObject As Object, ByVal targetObject As Object)
CopyFieldsToTargetObject(sourceObject, targetObject, False)

End Sub
''' <summary>
''' Copy all fields values from sourceObject to targetObject
''' Private and public field values will be cloned from sourceObject to targetObject when fields name exists on the two object
''' </summary>
''' <param name="sourceObject">Oject from which fields values will be copied</param>
''' <param name="targetObject">Object which will have copied values</param>
''' <param name="sameValueTypesOnly">If true, only fields having the same type of value (ex: String, CustomClassType, etc) will be cloned</param>
''' <remarks></remarks>
Public Shared Sub CopyFieldsToTargetObject(ByVal sourceObject As Object, ByVal targetObject As Object, ByVal sameValueTypesOnly As Boolean)
'''' Getting fields from source & target objects
Dim sourceFields As PropertyInfo() = sourceObject.[GetType]().GetProperties(flags)
Dim targetFields As PropertyInfo() = targetObject.[GetType]().GetProperties(flags)
Dim tempValue As Object

'''' Searching match between objects property names
For Each sourceField As PropertyInfo In sourceFields
For Each targetField As PropertyInfo In targetFields
If sourceField.Name = targetField.Name Then
'' Same field name => value to copy?
tempValue = sourceField.GetValue(sourceObject, Nothing)

' If same value type between object, or not strict copy asked
If tempValue.GetType() Is targetField.GetValue(targetObject, Nothing).GetType() Or Not sameValueTypesOnly Then
Try
targetField.SetValue(targetObject, tempValue, Nothing)
Catch ex As Exception
If sameValueTypesOnly Then Throw
System.Diagnostics.Debug.WriteLine(ex.ToString())
End Try
End If

End If
Next
Next
End Sub

#End Region


End Class

SQL transaction & error handling template

Here is a small template to execute a SQL statement in a transaction scope, with a rollback if an error occured.


BEGIN TRAN
/*
( SQL CODE TO EXECUTE HERE)
*/
GO
IF (@@ERROR = 0)
BEGIN
COMMIT
PRINT 'EXECUTION COMPLETED WITH SUCCESS'
END
ELSE
BEGIN
ROLLBACK
PRINT 'ERROR HAS OCCURED'
END

Some tools

Here are somme useful tools I use:


Pure text (copy-paste in windows)
magic iso (virtual drive like)
win diff (file & folder comparer, comes with VS)
ndepend (profiler .net?)
web development helper

Expresso (regular expression ide)
Notepad ++
SQL Prompt (Intellisense in sql editors)
slick run
Gadwin System Print Screen (free & easy screen shot tool)

VS Plug-in:
Smart Paster (paste as comment, as stringbuilder, etc)
Resharper

Binding a Windows form to a TableAdapter through a Web Service

How can I use a TableAdapter object in a Windows Form aplication, when this TableAdapter object is returned from a Web Service? It's simple, but...

I wanted a simple thing:
1- define a TableAdapter in a Web Service project, to get a typed DataSet from the BD
2- return this TableAdater in a WebMethod
3- use the TableAdapter returned by the web service from a DataGridView in a Windows form application (referencing the web service, of course).

I tried many combinations before getting this worked, playing with objects and properties, and googling, and playing again... There is finally a recipe that works:

On the web service side:

  1. Create a TableAdapter (by dragging adatabase table from the werver explorer and settinga select method). This create a DataSet (name of the *.xsd file), a DataTable (name in the top of the box) and a TableAdapter (with a "TableAdapter" suffix after the DataTable name).
  2. Create a web method returning an instance of the new DataTable.
On the windows application side:
  1. In the Windows client project, add a Web Reference to the class of the web service (like the default name "Service1").
  2. Next, go on the design view of the web form. On the toolbox pane, some items are automatically added. There should be an item with the DataSet used in the web service; the name will be the "*.xsd" file name, not the DataTable or the TableAdapter name (default will be "DataSet1"). This should be in a section of the toolbox labeled with the web service namespace ("MyWebService components"). Drag this component on the web form. A DataSet object will be created.
  3. Drag a BindingSource on the web form
  4. In the properties of the new BindingSource object, set the datasource to the new DataSet objet. In the DataMember drop down list, you can now choose the name of the DataTable (similar to the TableAdapter name) within the DataSet.
  5. In the DataGridView control properties, set the DataSource to the new DataBindingSource object.
  6. All properties shoud now be ok.

To get the data populating the DataGridView on load, there is a line to write.In the Load() event of the form, add something like
Me.BindingSource1.DataSource = New [WebReferenceAliasName].[ServiceName]().[WebMethodName]()

It works fine this way.

Upcasting an object "for real"

This week, I had a problem with serialization in a web service. Theorically, any serializable object or object collection can be send or received by a web service. The problem occured when the web service's tried to send a object collection including objects of type A and objects of type B inherited from A. While it tried to serialize the collection (an array or a typed list) as a collection of type A, the runtime throwed this exception:

System.InvalidOperationException: The type [inheritedType] was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

Here is what happened (as I undersand): The SOAP protocol defines a strict serialisation format constructed with the declared type in the [WebMethod] functions, and this format is in the web service's contract. That's why the formatter refuses to serialise inherited types. For example, if type A have a Name and a Id attributes, the web service returning a A object defines theese two attributes it it's SOAP contract. But if the service tries to send a B object, inherited from A but having a added Employer attribute, the formatter will normally want to serialize it with this Employer attribute, whitch is not in the SOAP contract. That is why the exception is throwned.

Normally, upcasting objects is about upcasting reference, not instances. In other words, the program can use an object of type B as if it was an object of type A, but the .net runtime kows it is a object of type B. If you observe an upcasted or downcasted object with the compiler, you will see that the runtime can tell the original type.

Thas is why a object of type B can be upcasted to its parent class type A, then downcasted to type B and still preserve it's properties restricted to class B.

Now, how can I face my web service serialization problem without touching the serialisation process itself ? The serialization can be customized, but that's not what I wanted. I needed a process to handle this particular casting problem in a generic way. That's why I made a class to transform an object of type b in a new object of it's parent type and still preserve it's values. The class uses generic and reflection to convert an object B to a new object A having it's original field values. Note that by reflection, we can access objects private fields and set their values.

Here is the class:


/// <summary>
/// Helper class to Upcast an object to it's parent type in a definitive way.
/// To get an objet with a runtime type of the target parent type.
///
/// By reflection, it gets child instance fields values (event privates)
/// and assign them to a new instance of the given parent class.
/// </summary>
/// <typeparam name="ParentClass">Class to upcast object to</typeparam>
public class InstanceUpCaster<ParentType>
where ParentType : new()
{
/// parent class fields
FieldInfo[] fParents;

/// flags to get all instance fields, even privates
BindingFlags flags = BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Instance;

/// <summary>
/// Getting target class fields
/// </summary>
public InstanceUpCaster()
{
fParents = typeof(ParentType).GetFields(flags);
}

/// <summary>
/// Convert the object to a new object of the parent class.
/// Assign field values of the child instance to the new instance,
/// if theese fiels exists in the parent type.
/// (public and private fields can be set by reflection)
/// </summary>
/// <param name="instance">Object to upcast to ParentType</param>
/// <returns>New object with same values (where possible in this type)</returns>
public ParentType ToParentClassInstance(ParentType childTypeObject)
{
/// Object already of the wright type (not derived) ?
if (childTypeObject.GetType() == typeof(ParentType)) return childTypeObject;

// No -> new object to upcast to
ParentType newObject = new ParentType();

/// transfering child field values to new object
FieldInfo[] fChilds = childTypeObject.GetType().GetFields(flags);
object tempValue;
foreach (FieldInfo fParent in fParents)
{
foreach (FieldInfo fChild in fChilds)
{
if (fParent.Name == fChild.Name)
{
tempValue = fChild.GetValue(childTypeObject);
if (tempValue != null)
fParent.SetValue(newObject, tempValue);
}
}
}

return newObject;
}
}

Creating a HTTP POST from in C#

Here is a way to make a HTTP request to a web page with the POST method.
Use this method with parameters formatted like in GET method.

Example : result = PostPage("www.mypage.aspx", "id=2&name=Paul&amp;age=33");

public string PostPage(string url, string params)
{
byte[] dataToPost = new ASCIIEncoding().GetBytes(params);


HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";

//Request properties
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = dataToPost.Length;

//Writing data in stream
Stream myStream = myRequest.GetRequestStream();
myStream.Write(dataToPost, 0, dataToPost.Length);
myStream.Close();

//Getting response
WebResponse myResponse = myRequest.GetResponse();

//Reading it
Stream responseStream = myResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();


//closing all
streamReader.Close();
responseStream.Close();
myResponse.Close();
myStream.Close();

return result;
}

Simple HTTP request and response

For getting programmatically the HTML content of a web page:


using System.Net;

public string GetPage(string pageToGet)
{
HttpWebRequest request= (HttpWebRequest)HttpWebRequest.Create(pageToGet);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

return new streamReader(response.GetResponseStream()).ReadToEnd();

}