Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

//---always add to the root node---

TreeNode FeedTitleNode = new TreeNode() {

Text = title,

Tag = URL, //---stores the Feed URL---

ImageIndex = ICO_CLOSE,

SelectedImageIndex = ICO_OPEN

};

//---add the feed title---

TreeView1.Nodes[0].Nodes.Add(FeedTitleNode);

//---add individual elements (posts)---

for (int i = 0; i <= posts.Length - 2; i++) {

//---extract each post as "title:description"---

string[] str = posts[i].Split((char)3);

TreeNode PostNode = new TreeNode() {

Text = str[0], //---title---

Tag = str[1], //---description---

ImageIndex = ICO_POST,

SelectedImageIndex = ICO_POST

};

//---add the posts to the tree---

TreeView1.Nodes[0].Nodes[TreeView1.Nodes[0].Nodes.Count - 1].Nodes.Add(PostNode);

}

//---subscription is successful---

succeed = true;

//---highlight the new feed and expand its post---

TreeView1.SelectedNode = FeedTitleNode;

} else succeed = false;

} catch (Exception ex) {

MessageBox.Show(ex.Message);

//---subscription is not successful---

succeed = false;

} finally {

//---clears the panel and cursor---

Cursor.Current = Cursors.Default;

displayPanel.Visible = false;

//---update the UI---

Application.DoEvents();

}

return succeed;

}

Figure 1813 For each TreeView node representing a feed title such as Wrox - фото 331

Figure 18-13

For each TreeView node representing a feed title (such as Wrox: All New Titles), the Textproperty is set to the feed's title and its URL is stored in the Tagproperty of the node. For each node representing a posting (.NET Domain-Driven Design and so forth), the Textproperty is set to the posting's title and its description is stored in the Tag property.

Wiring All the Event Handlers

With the helper functions defined, let's wire up all the event handlers for the various controls. First, code the Form1_Loadevent handler as follows:

private void Form1_Load(object sender, EventArgs e) {

//---find out the app's path---

appPath = Path.GetDirectoryName(

System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

//---set the feed list to be stored in the app's folder---

feedsList = appPath + feedsList;

try {

//---create the root node---

TreeNode node = new TreeNode() {

ImageIndex = ICO_CLOSE,

SelectedImageIndex = ICO_OPEN,

Text = "Subscribed Feeds"

};

//---add the node to the tree---

TreeView1.Nodes.Add(node);

TreeView1.SelectedNode = node;

} catch (Exception ex) {

MessageBox.Show(ex.Message);

return;

}

try {

//---load all subscribed feeds---

if (File.Exists(feedsList)) {

TextReader textreader = File.OpenText(feedsList);

//---read URLs of all the subscribed feeds---

string[] feeds = textreader.ReadToEnd().Split('|');

textreader.Close();

//---add all the feeds to the tree---

for (int i = 0; i <= feeds.Length - 2; i++)

SubscribeFeed(feeds[i]);

} else {

//---pre-subscribe to a few feed(s)---

SubscribeFeed(

"http://www.wrox.com/WileyCDA/feed/RSS_WROX_ALLNEW.xml");

}

} catch (Exception ex) {

MessageBox.Show(ex.Message);

}

}

When the form is first loaded, you have to create a root node for the TreeViewcontrol and load all the existing feeds. All subscribed feeds are saved in a plain text file ( Feeds.txt), in the following format:

Feed URL|Feed URL|Feed URL|

An example is:

http://news.google.com/?output=rss|http://rss.cnn.com/rss/cnn_topstories.rss|

If there are no existing feeds (that is, if Feeds.txtdoes not exist), subscribe to at least one feed.

In the Clickevent handler of the Subscribe MenuItemcontrol, prompt the user to input a feed's URL, and then subscribe to the feed. If the subscription is successful, save the feed URL to file:

private void mnuSubscribe_Click(object sender, EventArgs e) {

if (!IsConnected()) {

MessageBox.Show("You are not connected to the Internet.");

return;

}

//---add a reference to Microsoft.VisualBasic.dll---

string URL = Microsoft.VisualBasic.Interaction.InputBox(

"Please enter the feed URL", "Feed URL", lastURLEntered, 0, 0);

if (URL != String.Empty) {

lastURLEntered = URL;

//---if feed is subscribed successfully---

if (SubscribeFeed(URL)) {

//---save in feed list---

TextWriter textwriter = File.AppendText(feedsList);

textwriter.Write(URL + "|");

textwriter.Close();

} else {

MessageBox.Show("Feed not subscribed. " +

"Please check that you have entered " +

"the correct URL and that you have " +

"Internet access.");

}

}

}

C# does not include the InputBox()function that is available in VB.NET to get user's input (see Figure 18-14). Hence, it is a good idea to add a reference to the Microsoft.VisualBasic.dlllibrary and use it as shown in the preceding code.

Figure 1814 Whenever a node in the TreeViewcontrol is selected you should - фото 332

Figure 18-14

Whenever a node in the TreeViewcontrol is selected, you should perform a check to see if it is a posting node and enable/disable the MenuItem controls appropriately (see Figure 18-15):

//---fired after a node in the TreeView control is selected---

private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e) {

//---if a feed node is selected---

if (e.Node.ImageIndex != ICO_POST && e.Node.Parent != null) {

mnuUnsubscribe.Enabled = true;

mnuRefreshFeed.Enabled = true;

} else {

//---if a post node is selected---

mnuUnsubscribe.Enabled = false;

mnuRefreshFeed.Enabled = false;

}

}

Figure 1815 When the user selects a post using the Select button on the - фото 333

Figure 18-15

When the user selects a post using the Select button on the navigation pad, Form2containing the WebBrowsercontrol is loaded and its content set accordingly (see Figure 18-16). This is handled by the KeyDownevent handler of the TreeView control:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x