15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

a Custom resource reader ❘ 599<br />

A resource reader has to implement the interface IResourceReader . This interface defi nes the methods<br />

Close() <strong>and</strong> GetEnumerator() to return an IDictionaryEnumerator that returns keys <strong>and</strong> values for the<br />

resources. In the implementation of GetEnumerator() , create a Hashtable where all keys <strong>and</strong> values for<br />

a specifi c language are stored. Next, you can use the SqlConnection class in the namespace System.Data<br />

.SqlClient to access the database in SQL Server. Connection.CreateComm<strong>and</strong>() creates a SqlComm<strong>and</strong>()<br />

object that you use to specify the SQL SELECT statement to access the data in the database. If the language is<br />

set to de , the SELECT statement is SELECT [key], [de] FROM Messages . Then you use a SqlDataReader<br />

object to read all values from the database <strong>and</strong> put them into a Hashtable . Finally, the enumerator of the<br />

Hashtable is returned.<br />

For more information about accessing data with ADO.<strong>NET</strong>, see Chapter 30, “ Core<br />

ADO.<strong>NET</strong>.”<br />

public System.Collections.IDictionaryEnumerator GetEnumerator()<br />

{<br />

Dictionary < string, string > dict = new Dictionary < string, string > ();<br />

SqlConnection connection = new SqlConnection(connectionString);<br />

SqlComm<strong>and</strong> comm<strong>and</strong> = connection.CreateComm<strong>and</strong>();<br />

if (String.IsNullOrEmpty(language))<br />

language = "Default";<br />

comm<strong>and</strong>.Comm<strong>and</strong>Text = "SELECT [key], [" + language + "] " +<br />

"FROM Messages";<br />

try<br />

{<br />

connection.Open();<br />

SqlDataReader reader = comm<strong>and</strong>.ExecuteReader();<br />

while (reader.Read())<br />

{<br />

if (reader.GetValue(1) != System.DBNull.Value)<br />

{<br />

dict.Add(reader.GetString(0).Trim(), reader.GetString(1));<br />

}<br />

}<br />

}<br />

reader.Close();<br />

}<br />

catch (SqlException ex)<br />

{<br />

if (ex.Number != 207) // ignore missing columns in the database<br />

throw; // rethrow all other exceptions<br />

}<br />

finally<br />

{<br />

connection.Close();<br />

}<br />

return dict.GetEnumerator();<br />

public void Close()<br />

{<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!