Archive for December, 2007

How to read strings from a resource (resx) file in C# ?

December 26, 2007

Following is a source code that demonstrates How to Read a resource string from a Resx file. Here it is assumed that the resource file i.e. Sample.resx contains resource strings.
public void ReadResourceStrings()
{
//This hashtable will cache all the resource strings।
Hashtable resourceStringsHashTable = new Hashtable();
//Complete path of the resource file.
string resourceFilePath = “Sample.resx”;
if (String.IsNullOrEmpty(resourceFilePath)
!File।Exists(resourceFilePath))
{throw (new Exception(“Resource file cannot be found!”));}
ResXResourceReader resourceFileReader = null;
try
{
resourceFileReader = new ResXResourceReader(resourceFilePath);
foreach (DictionaryEntry resourceString in resourceFileReader)
{
if (!resourceStringsHashTable.Contains(resourceString.Key.ToString()))
{
resourceStringsHashTable.Add(resourceString.Key.ToString()
, resourceString.Value);
}
}
}
finally
{
resourceFileReader.Close();
}
}

What is LINQ ?

December 19, 2007

LINQ is Language Integrated Query. LINQ is an integrated part of Orcas. LINQ has a great power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable interface. Microsoft basically divides LINQ into three areas and that are give below.

1. LINQ to Object {Queries performed against the in-memory data}
2. LINQ to ADO.Net
3. LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
4. LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
5. LINQ to Entities {Microsoft ORM solution}
6. LINQ to XML (formerly XLinq) { Queries performed against the XML source}

LINQ to XML (XLINQ): Sample


Sample.xml will contain the following:

<feed>
<entry>
<title>LINQ Sample</title>
<id>01-AAA-BBB</id>
<article>This is a sample XLinq source.</article>
</entry>
</feed>

C# code to query the xml:
//Load the xml into XDocument.
XDocument sample = XDocument.Load(“sample.xml”);
//Query the XML document.
XElement samplexElement = new XElement(“feed”,
from b in sample.Element(“feed”).Elements(“entry”)
select new XElement
(
“entry”,
b.Elements(“title”),
b.Elements(“id”),
b.Elements(“article”)
)
);
//Display the XML.
Console.WriteLine(samplexElement);