Sunday, May 24, 2009

ContainsKey problem

Hi,
In case that u have generic Dictionary with non primitive key - ContainsKey function will return u a bad answer because this function compare objects by refrence an NOT by value!
so, if u have same key values in the Dictionary and in your test object u will get negative answer.
the solution is 2 override Equals and GetHashCode functions:


//@@@ I have Dictionary with Key_Event5 object as the key
Dictionary<Key_Event5, Event5_Employment> dictEmployment;
//@@@ 4 support ContainsKey function compare by value, i'll implement Key_Event5 on this way:
public class Key_Event5
{
public int iFormID { get; set; }
public int iEmploymentCode { get; set; }
public Key_Event5(int iFormID, int iEmploymentCode)
{
this.iFormID = iFormID;
this.iEmploymentCode = iEmploymentCode;
}

public override bool Equals(object obj)
{
Key_Event5 oKey_Event5 = obj as Key_Event5;
if (oKey_Event5 == null)
return false;
//@@@ Compare by iFormID and iEmploymentCode
return Equals(iFormID, oKey_Event5.iFormID)
&& Equals(iEmploymentCode, oKey_Event5.iEmploymentCode);

}
public override int GetHashCode()
{
return iFormID.GetHashCode() ^ iEmploymentCode.GetHashCode();
}

}
//@@@ And now this line will work
dictEmployment.ContainsKey(oKey_Event5)

Simple XPath Examples

Hi,
In this post i'll show some simple(but useful) XPath Examples
let's say that i have this xml file named 'Persons.xml':


<?xml version='1.0'?>

<Persons>

<Person Height="180">

<FullName>Yosi Havia</FullName>

<Age>18</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>


so, let's talk code lines:


//@@@ Select all the persons in 18 age
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[Age = '" + 18 + "']");


//@@@ Select all the persons with age greater than 17
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[Age > '" + 17 + "']");


//@@@ Select all the persons that contains Yosi in their names
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person/FullName[contains(.,'" + "Yosi" + "')]");


//@@@ Select all the persons with 180 height(attribute)
XmlNodeList oXmlNodeList =
XmlPersons.SelectNodes("/Persons/Person[@Height = '" + "180" + "']");

Saturday, May 9, 2009

How to merge 2 XmlDocuments

Hi,
In this post i'll show u how 2 merge 2 xml documents
let's say that i have 2 xml documents,

Persons.xml

<?xml version='1.0'?>

<Persons>

<Person Height="180">

<FullName>Yosi Havia</FullName>

<Age>18</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>



and Persons2.xml

<?xml version='1.0'?>

<Persons>

<Person Height="175">

<FullName>Yosi Havia</FullName>

<Age>15</Age>

</Person>

</Persons>



What i want 2 do in this example is 2 take the node with the full name 'Yosi Havia' from Persons2.xml file and replace the original node with the same full name in Persons.xml file.
this code lines make this assigment(with help of my last post Simple XPath Examples ):

XmlDocument XmlPersons1 = new XmlDocument();
XmlPersons1.Load(@"Persons.xml");

XmlDocument XmlPersons2 = new XmlDocument();
XmlPersons2.Load(@"Persons2.xml");

XmlNode oXmlNewData = XmlPersons2.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");
XmlNode targetNode = XmlPersons1.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");
//@@@ Add the node from XmlPersons2.xml to XmlPersons.xml
XmlNode sourceNode = XmlPersons1.ImportNode(oXmlNewData, true);
//@@@ Replace the original node
XmlPersons1.DocumentElement.ReplaceChild(sourceNode, targetNode);

and u can c the result here:

<?xml version="1.0"?>

<Persons>

<Person Height="175">

<FullName>Yosi Havia</FullName>

<Age>15</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>

Wednesday, May 6, 2009

Performence check in c# with Stopwatch

Hi,
System.Diagnostics has a very nice object called Stopwatch
i show here my very easy and simple example 4 making performence check:

Stopwatch oStopwatch = new Stopwatch();
oStopwatch.Start();
//@@@ Start of code to make the performence check
Thread.Sleep(3000);
//@@@ End of code to make the performence check
oStopwatch.Stop();
TimeSpan oTimeSpan = oStopwatch.Elapsed;
Console.WriteLine(oTimeSpan.ToString());


the output of this code was:

00:00:02.9994520

Friday, April 24, 2009

Don't use XmlDocument use XmlTextReader instead

Hi,
I had an assignment to read a 200 MB xml file
i dont think that XmlDocument can help me here...
so i found the XmlTextReader object that made a great job
and from this moment i always use XmlTextReader to read
xml file content, so here is my example:

lets say that i want to read this Test.xml file:


<?xml version="1.0" encoding="utf-8" ?>

<RootNode>

<Child>

<Item Att="1">A</Item>

<Item Att="2">B</Item>

</Child>

<Child>

<Item Att="3">C</Item>

<Item Att="4">D</Item>

</Child>

</RootNode>



and this function read all the attributes and content
of the Item node in the xml:


public void ReadXml()
{
int iCodepage = 862;
string sAttribute, sNodeValue;
string sFilePath = @"Test.xml";
StreamReader oFileStream = null;
XmlTextReader reader = null;
//@@@ Check if the file exists
if (!File.Exists(sFilePath))
return;

//@@@ Get the file as XmlTextReader
oFileStream =
new StreamReader(sFilePath, Encoding.GetEncoding(iCodepage));
reader = new XmlTextReader(oFileStream);

//@@@ Loop through all the file
while (reader.Read())
{
//@@@ If we in Item node
if (reader.Name.Equals("Item") &&
(reader.NodeType == XmlNodeType.Element))
{
//@@@ Get the Attribute (Att) value
reader.MoveToAttribute("Att");
sAttribute = reader.Value;
Console.WriteLine(sAttribute);
//@@@ Get the node value
reader.MoveToElement();
sNodeValue = reader.ReadInnerXml();
Console.WriteLine(sNodeValue);
}
}
}

Tuesday, April 21, 2009

The perfect c# singleton

Hi,
after several tries i got the perfect thread safety c# singleton

public class DbProxy
{
private static DbProxy _oInstance = null;
private static readonly object padlock = new object();

// @@@ public "consructor"
public static DbProxy Instance
{
get
{
if (DbProxy._oInstance == null)
{
lock (padlock)
{
if (DbProxy._oInstance == null)
{
DbProxy newDB = new DbProxy();
System.Threading.Thread.MemoryBarrier();
DbProxy._oInstance = newDB;
}
}
}
return DbProxy._oInstance;
}
}
// @@@ private constructor
private DbProxy()
{

}
}


Monday, April 13, 2009

Output Cache by the book

Hi,
i found the best way to implement Output Cache
we have only 2 steps to make it:

step 1
------
define in the Web.config some different cache profiles that u need:

<system.web>

<caching>

<outputCacheSettings>

<outputCacheProfiles>

<add name="profile1" duration="100" varyByParam="param1" />

<add name="profile2" duration="100" varyByParam="None" />

</outputCacheProfiles>

</outputCacheSettings>

</caching>

</system.web>


step 2
------
define in your pages the profile that u want to use:

<%@ OutputCache CacheProfile="profile1" %>


now, if we want to check if it works
all we have to is to make aspx page, and to play with his links
and check if the DateTime changed or not
TEST.aspx

<%@ OutputCache CacheProfile="profile1" %>

<html xmlns="http://www.w3.org/1999/xhtml" >

<body>

<form id="form1" runat="server">

<%= DateTime.Now.ToString() %><br />

<a href="?param1=1">1</a><br />

<a href="?param1=2">2</a><br />

<a href="?param1=3">3</a><br />

</form>

</body>

</html>


Another small tip:
for disable the OutputCache(in the development environment for example) add location="None" in the appropriate profile in the web.config in this way:

<add name="profile1" duration="100" varyByParam="param1" location="None" />