C# Image Server Client (Using XML for the application protocol)

Our assignment in class this week was to create a network based client that would connect to the teachers Image Server and make requests via XML for information such as getting a category list, getting and image list, and ultimately, getting the image itself. There were a few different things that needed to be handled to make this work properly. Granted, this isn’t the best code in the word, since the summer semester is so short, but it does work. For it to run properly, you have to be connected to the VPN at UVU.Here is a link to the application protocol as defined in my class. Click here to get the document.

Here is my code for the main program form:

 1 using System; 2 using System.Collections.Generic;
 3 using System.Collections;
 4 using System.ComponentModel;
 5 using System.Data;
 6 using System.Drawing;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 
10 namespace ImageServer
11 {
12     public partial class FormMain : Form
13     {
14         ImageServerAPI isAPI;
16         public delegate void dStatusUpdate(string message);
16         public dStatusUpdate statusUpdate;
17         ArrayList cats;
18         ArrayList imgs;
19 
20         public FormMain()
21         {
22             InitializeComponent();
23         }
24 
25         private void FormMain_Load(object sender, EventArgs e)
26         {
27             comboServerIP.SelectedIndex = 0;
28             listImages.Items.Clear();
29             comboServerIP.Focus();
30             labelStatus.Text = "Started, awaiting orders...";
31             statusUpdate = new dStatusUpdate(displayMessage);
32             isAPI = new ImageServerAPI(this);
33         }
34 
35         private void buttonGetCategory_Click(object sender, EventArgs e)
36         {
37             comboCategory.Items.Clear();
38             cats = isAPI.getCategoriesList(comboServerIP.Text);
39             for (int i = 0; i < cats.Count; i++)
40             {
41                 comboCategory.Items.Add("(" + ((Category)(cats[i])).cId + ") " + ((Category)(cats[i])).cName);
42             }
43         }
44 
45         public void displayMessage(string message)
46         {
47             labelStatus.Text = message;
48             labelStatus.Refresh();
49         }
50 
51         private void buttonGetImage_Click(object sender, EventArgs e)
52         {
53             listImages.Items.Clear();
54             imgs = isAPI.getImagesList(comboServerIP.Text, ((Category)cats[comboCategory.SelectedIndex]).cId);
55             for (int i = 0; i < imgs.Count; i++)
56             {
57                 listImages.Items.Add("(" + ((Img)(imgs[i])).cId + ") " + ((Img)(imgs[i])).cName);
58             }
59             listImages.Refresh();
60         }
61 
62         public String getServer()
63         {
64             return comboServerIP.Text;
65         }
66 
67         public void addResponse(String str)
68         {
69             textXML.Text += str;
70             textXML.Refresh();
71         }
72 
73         public void setResponse(String str)
74         {
75             textXML.Text = str;
76             textXML.Refresh();
77         }
78 
79         private void listImages_MouseDoubleClick(object sender, MouseEventArgs e)
80         {
81             int id = listImages.SelectedIndices[0];
82             Bitmap img = isAPI.getImage(comboServerIP.Text, ((Img)imgs[id]).cId);
83             //Bitmap img = new Bitmap("G:SchoolCN3670labsImageServerImageClient1.bmp");
84             FormImage frmImage = new FormImage(img, ((Img)imgs[id]).cName);
85             frmImage.Show();
86         }
87     }
88 }

My code for the image form is as follows:

 1 using System; 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Windows.Forms;
 8 
 9 namespace ImageServer
10 {
11     public partial class FormImage : Form
12     {
13         Bitmap img;
14 
15         public FormImage(Bitmap img, String name)
16         {
17             InitializeComponent();
18             this.image.Image = img;
19             this.Text = name;
20         }
21 
22         public FormImage()
23         {
24             InitializeComponent();
25         }
26 
27         private void FormImage_Load(object sender, EventArgs e)
28         {
29             this.image.Refresh();
30         }
31     }
32 }

For the XML handling and sending:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Collections;
  4 using System.Text;
  5 using System.Net;
  6 using System.Net.Sockets;
  7 using System.Xml;
  8 using System.Drawing;
  9 using System.IO;
 10 
 11 namespace ImageServer
 12 {
 13     class ImageServerAPI
 14     {
 15         FormMain form;
 16         private Socket currentSocket;
 17         private IPAddress currentAddress;
 18         private static int PORT = 10000;
 19         private int state;
 20         private static int StateNewCategory = 1;
 21         private static int StateCategoryListRequest = 2;
 22         private static int StateCategoryListComplete = 3;
 23 
 24         private static int StateImageSession = 4;
 25         private static int StateImageListRequest = 5;
 26         private static int StateImageListComplete = 6;
 27 
 28         private static int StateGetSession = 7;
 29         private static int StateGetImage = 8;
 30         private static int StateGetComplete = 9;
 31 
 32         public ImageServerAPI(FormMain frm)
 33         {
 34             form = frm;
 35             state = StateNewCategory;
 36         }
 37 
 38         public int sendString(string send) {
 39             int counter = 0;
 40 
 41             Byte[] sendBytes = Encoding.ASCII.GetBytes(send);
 42             Byte[] nullByte = new Byte[] { 0 };
 43             int length = sendBytes.Length;
 44             int sendLength = send.Length;
 45             int sendIndex = 0;
 46             try
 47             {
 48                 if (currentSocket == null || !currentSocket.Connected)
 49                 {
 50                     return -1;
 51                 }
 52                 while (sendIndex < sendLength)
 53                 {
 54                     counter = currentSocket.Send(sendBytes, sendIndex, length, 0);
 55                     sendIndex += counter;
 56                 }
 57 
 58                 counter = currentSocket.Send(nullByte, 1, 0);
 59             }
 60             catch (SocketException se)
 61             {
 62                 return -1;
 63             }
 64             return sendIndex;
 65         }
 66 
 67         public String getResponse()
 68         {
 69             String recieve = "";
 70             try
 71             {
 72                 byte[] buffer = new byte[1];
 73                 int count = 0;
 74                 do
 75                 {
 76                     count += currentSocket.Receive(buffer, 1, SocketFlags.None);
 77                     recieve += Encoding.ASCII.GetString(buffer);
 78                 } while (buffer[0] != 0);
 79                 //Fixing this
 80 
 81             }
 82             catch (SocketException se)
 83             {
 84                 return "";
 85             }
 86             return recieve;
 87         }
 88 
 89         public ArrayList getCategoriesList(String server) {
 90             ArrayList lst = new ArrayList();
 91             form.displayMessage("Fetching Categories List");
 92             currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 93             IPHostEntry IPHost = Dns.GetHostEntry(server);
 94             IPEndPoint ipServer = new IPEndPoint(IPHost.AddressList[0].Address, PORT);
 95             currentSocket.Connect(ipServer);
 96 
 97             String sendString = "<ReqSession>dallin</ReqSession>";
 98             this.sendString(sendString);
 99             String res = this.getResponse();
100             form.setResponse(res);
101             sendString = "<CategoryListRequest />";
102             this.sendString(sendString);
103             res = this.getResponse();
104             form.setResponse(res);
105             //TODO: parse XML
106             XmlDocument xml = new XmlDocument();
107             xml.LoadXml(res);
108 
109             lst.AddRange(this.DomtoCategory(xml.DocumentElement, 0));
110 
111             sendString = "<Complete />";
112             this.sendString(sendString);
113             res = this.getResponse();
114             currentSocket.Disconnect(false);
115             currentSocket.Close();
116 
117             form.displayMessage("Categories List recieved");
118             return lst;
119         }
120 
121         private ArrayList DomtoImage(XmlNode parentNode, int level)
122         {
123             ArrayList list = new ArrayList();
124 
125             foreach (XmlNode domChild in parentNode.ChildNodes)
126             {
127                 String name = "";
128                 String id = "";
129                 String description = "";
130                 foreach (XmlAttribute domAtt in domChild.Attributes)
131                 {
132                     if (domAtt.Name == "name")
133                     {
134                         name = domAtt.Value;
135                     }
136                     if (domAtt.Name == "index")
137                     {
138                         id = domAtt.Value;
139                     }
140                 }
141                 list.Add(new Img(Int16.Parse(id), name, description));
142                 if (domChild.HasChildNodes)
143                 {
144                     list.AddRange(DomtoCategory(domChild, level + 1));
145                 }
146             }
147             return list;
148         }
149 
150 
151         // Recursively called routine that displays nodes in list box
152         private ArrayList DomtoCategory(XmlNode parentNode, int level)
153         {
154             ArrayList list = new ArrayList();
155 
156             foreach (XmlNode domChild in parentNode.ChildNodes)
157             {
158                 String name = "";
159                 String id = "";
160                 foreach (XmlAttribute domAtt in domChild.Attributes)
161                 {
162                     if (domAtt.Name == "name")
163                     {
164                         name = domAtt.Value;
165                     }
166                     if (domAtt.Name == "index")
167                     {
168                         id = domAtt.Value;
169                     }
170                 }
171                 list.Add(new Category(Int16.Parse(id), name));
172                 if (domChild.HasChildNodes)
173                 {
174                     list.AddRange(DomtoCategory(domChild, level + 1));
175                 }
176             }
177             return list;
178         }
179 
180         public ArrayList getImagesList(String server, int id)
181         {
182             ArrayList lst = new ArrayList();
183             form.displayMessage("Fetching Images List");
184             currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
185             IPHostEntry IPHost = Dns.GetHostEntry(server);
186             IPEndPoint ipServer = new IPEndPoint(IPHost.AddressList[0].Address, PORT);
187             currentSocket.Connect(ipServer);
188 
189             String sendString = "<ReqSession>dallin</ReqSession>";
190             this.sendString(sendString);
191             String res = this.getResponse();
192             form.setResponse(res);
193             sendString = "<ImageListRequest category="" + id + ""/>";
194             this.sendString(sendString);
195             res = this.getResponse();
196             form.setResponse(res);
197             XmlDocument xml = new XmlDocument();
198             xml.LoadXml(res);
199 
200             lst.AddRange(this.DomtoImage(xml.DocumentElement, 0));
201 
202             sendString = "<Complete />";
203             this.sendString(sendString);
204             res = this.getResponse();
205             currentSocket.Disconnect(false);
206             currentSocket.Close();
207             form.displayMessage("Images List recieved");
208             return lst;
209         }
210 
211         private Bitmap FieldToImage(Byte[] imageBytes)
212         {
213             Bitmap img;
214             MemoryStream ms;
215             ms = new MemoryStream(imageBytes);
216             img = new Bitmap(ms);
217             ms.Close();
218             return img;
219         }
220 
221         private Bitmap fetch(int length)
222         {
223             byte[] buffer = new byte[length];
224             try
225             {
226                 int count = 0;
227                 while (count < length)
228                 {
229                     count += currentSocket.Receive(buffer, count, (length - count), SocketFlags.None);
230                 }
231             }
232             catch (SocketException se)
233             {
234                 return new Bitmap("G:SchoolCN3670labsImageServerImageClient1.bmp");
235             }
236             return FieldToImage(buffer);
237         }
238         //This is to be added for part two.
239         public Bitmap getImage(String server, int id)
240         {
241             Bitmap img;
242             ArrayList lst = new ArrayList();
243             form.displayMessage("Fetching Image ::" + id);
244             currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
245             IPHostEntry IPHost = Dns.GetHostEntry(server);
246             IPEndPoint ipServer = new IPEndPoint(IPHost.AddressList[0].Address, PORT);
247             currentSocket.Connect(ipServer);
248 
249             String sendString = "<ReqSession>dallin</ReqSession>";
250             this.sendString(sendString);
251             String res = this.getResponse();
252             form.setResponse(res);
253             sendString = "<GetImage index="" + id + ""/>";
254             this.sendString(sendString);
255             res = this.getResponse();
256             form.setResponse(res);
257             XmlDocument xml = new XmlDocument();
258             xml.LoadXml(res);
259             int length = Int32.Parse(xml.DocumentElement.Attributes["length"].Value);
260 
261             img = fetch(length);
262 
263             sendString = "<Complete />";
264             this.sendString(sendString);
265             res = this.getResponse();
266             currentSocket.Disconnect(false);
267             currentSocket.Close();
268             form.displayMessage("Image ::" + id + " recieved ("+length+" byte(s) long)");
269             return img;
270         }
271     }
272 }

And the classes that handle the information from the database (used for list objects) Img.cs:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace ImageServer
 6 {
 7     class Img
 8     {
 9         public int cId;
10         public String cName;
11         public String cDescription;
12         //public Bitmap cImage;
13 
14         public Img(int id, String name, String description/*, Bitmap img*/)
15         {
16             cId = id;
17             cName = name;
18             cDescription = description;
19             //cImage = img;
20         }
21     }
22 }

Now the Category.cs file:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace ImageServer
 6 {
 7 
 8     class Category
 9     {
10         public int cId;
11         public String cName;
12 
13         public Category(int id, String name)
14         {
15             cId = id;
16             cName = name;
17         }
18 
19         string ToString()
20         {
21             return "(" + cId + ")" + cName;
22         }
23     }
24 }

104 Responses to “C# Image Server Client (Using XML for the application protocol)”

  1. jual kroto says:

    I was excited to discover this site. I need to to thank you for ones time
    due to this wonderful read!! I definitely enjoyed every
    bit of it and I have you saved to fav to see new things in your blog.

  2. Link exchange is nothing else except it is just placing the other person’s blog link on your page at proper place and other
    person will also do same in favor of you.

  3. web page says:

    Howdy I am so delighted I found your web site, I really found you by error, while I was researching on Bing for something else, Regardless I am here now
    and would just like to say kudos for a marvelous post and a all round thrilling blog (I also love the theme/design), I don’t have time to browse it all at the moment but I
    have saved it and also included your RSS feeds, so when I have time I will
    be back to read a great deal more, Please do keep up the awesome work.

  4. Blondell says:

    Plañir sin causa aparente, sudoración en las manos, cefalea y/ estómago, torcer arrancar el cabello,
    morderse las uñas, perturbación del sueño pesadillas.

  5. I drop a comment each time I appreciate a article on a blog or I
    have something to contribute to the conversation.
    It’s caused by the sincerness displayed in the post I looked at.

    And on this article C# Image Server Client (Using XML for the application protocol)

  6. Leonardo says:

    Right now it appears like Movable Type is the best blogging platform out there right now.
    (from what I’ve read) Is that what you are using on your blog?

  7. Milton says:

    De religión para la gente, cuando esta está llena de yerros y contradicciones durante la vida.

  8. Marylin says:

    I am regular reader, how are you everybody? This article posted
    at this web page is truly good.

  9. It’s genuinely very difficult in this busy life to listen news on TV, thus I
    simply use world wide web for that reason, and get the newest news.

  10. It is always preferable that you choose someone with experience in human hair extensions.
    Invisalign is another one that can be used for both adults and
    children. To be successful, a nail technician should maintain a good balance of marketing and
    nail care in order to remain ahead of competitors.

  11. They stop at nothing to get the latest look and express their ideas
    through nail design ideas. A typical manicure for a man includes all
    the pampering the ladies receive, minus the nail painting and acrylic tips.
    Doctors and nurses wash hands before and after every patient contact.

  12. hair becomes says:

    WOW just what I was searching for. Came
    here by searching for frizzy hair

  13. Videos porno XXX con la mejor calidad HD, dispuestos para el móvil, tanto para descargar como para ver en línea.

  14. Hilario says:

    This is especially useful if the person you’re inquiring about has a less than common name.
    The website navigation should cater to both the users and the search engine
    bots. A money making attitude plus a money making opportunity almost always
    result in a money making reality.

  15. underwear says:

    Customer satisfaction is paramount to success in a business this also particularly
    can be a business where customer care is of prime importance.
    The purpose of theeditor of the lingerie is to present the top lingerie to their customers.
    However there can be a minute difference between baby doll lingeries and
    baby doll dresses.

  16. I’m really loving the theme/design of your web site.

    Do you ever run into any web browser compatibility problems?
    A couple of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Chrome.

    Do you have any suggestions to help fix this issue?

  17. Utilising the Platinum that is made free, Wood and acquire and Food
    you will not be unable to essentially uncover anything within Battle of Kings no cost.

  18. As first trailers go, the critique for Ant-Man is short (although that was to be anticipated).

  19. I do believe all the ideas you’ve introduced on your post. They’re really convincing and will definitely work.

    Nonetheless, the posts are too brief for newbies.

    May just you please lengthen them a little from subsequent time?
    Thanks for the post.

  20. Hello it’s me, I am also visiting this web page daily, this website is
    actually nice and the users are truly sharing pleasant thoughts.

  21. Apart from these, Windows and Blackberry are also available in
    the market. The i – Phone 6 would have a bigger screen than
    the i – Phone 5S. With so much smartphone usage, the marketing and advertising industry cannot lean solely on Internet advertising for their digital messaging.

  22. I think this is among the most vital info for me.
    And i am glad reading your article. But should remark on some general things,
    The web site style is wonderful, the articles is really great
    : D. Good job, cheers

  23. No matter what sort of deals you carry out online use a
    virtual data room minimize risks in transactions;
    any kind of deal whether of private equity type or complex corporate transactions
    are protected and more secure. Guests had to make reservations and pay a fee to dine there, skipping one of
    their regular restaurants. Ranging to three, the methods are:
    Boot Camps, trainer conducted sessions and online training.

  24. The whats up application has registered an increase in popularity lately, being
    used by the vast majority of smart phone or tablet owners who want to be able to efficiently
    communicate with their friends and family without paying.
    1 app in Apple’s App Store in dozens of countries”, “and it has been downloaded
    more than 100 million times on Google Play. Double-click the ‘Symbol’ key to insert smileys into a message when using Blackberry Messenger.

  25. It’s similar because the game’s story deals with
    criminals and it’s an open world game. Of course, I have also played plenty of twisted games too and some
    of them are surprisingly fun, humorous, and sometimes even popular, and in this article, I will talk about at least 5 of them.
    Along, for 1986 within Vice Location, a good fantastic community patterned following Las vegas,
    your scenario will be the Mafia Hitman Tommy Vercetti, who was
    simply just published right from dejecting prison.

  26. Youur stryle iss very unique compared too other perople I’ve read stuff from.
    Many thanks for posting when you have the opportunity, Guess I will just bookmark this blog.

  27. I am regular visitor, how are you everybody? This article posted at this web site
    is in fact nice.

  28. I do not know if it’s just me or if everybody else encountering problems with your website.
    It seems like some of the text in your posts are running off the screen.
    Can someone else please comment and let me know if this is happening to them too?
    This could be a issue with my web browser because I’ve had this happen before.
    Thanks

  29. If you could successfully make use of the Internet, you will certainly find it really simple to
    find the most effective pop up gazebo ebay uk solutions Seguin.

  30. I pay a quick visit each day some blogs and sites to read articles
    or reviews, except this website presents quality based writing.

  31. Bonita says:

    I’ll right aweay clutch your rss feed as I can’t find your e-mail subscription hyperlink
    or e-newsletter service. Do you’ve any? Kimdly allow me recognise so that I
    could subscribe. Thanks.

  32. Data from various research firms show that, there are more than 200 million Android activations until now.
    In a regular casino, there is a table with many players
    hovering on the sides. As most predicted Google Play became a big name instantly and the site hosts
    big name apps put out by Electronic Arts, Facebook, and Foursquare.

  33. The tape or string should run parallel across
    the head, just above the ears. ‘ A vehicle overtakes a bicycle and does not allow the bicycle enough space to safely pass and caused the cyclist to fall off
    the bike. Helmets are obliged for less than 18 years individuals.

  34. Thanks in support of sharing such a nice thought, article is good, thats why i have read it entirely

  35. Right now it looks like Movable Type is the top blogging platform out there right
    now. (from what I’ve read) Is that what you’re using on your blog?

  36. Then again, a ruthless drug dealer turning young kids on to
    drugs during school recess, needs to be kept away from the vulnerable members of society for good.
    Take some dumb kid who never hurt anyone else, but succumbed to peer pressure.
    There is a new ordinance on the books that requires the criminal background
    question to be removed from job applications.

  37. He is wanting to generate people see the truth behind these programs, as well as
    set them on top of the right track to make money online.
    Sexy lingerie no longer ends with the infamous derriere.
    t help but feel overwhelmed whenever you step into the lingerie department.

  38. obviously like your web-site however you have to test the spelling
    on quite a few of your posts. Many of them are rife with
    spelling problems and I in finding it very troublesome to tell the reality nevertheless I’ll certainly come
    back again.

  39. Hi, I do think this is a great web site. I stumbledupon it ;) I
    may return once again since i have book-marked it. Money
    and freedom is the best wway to change, may you be rich and continue to elp others.

  40. Simone says:

    Helpful information. Fortunate me I found your
    website accidentally, and I’m surprised why this accident did not came about in advance!

    I bookmarked it.

  41. m88 says:

    When I initially left a comment I appear to have clicked on the -Notify
    me when new comments are added- checkbox and from now on whenever a comment is added
    I get 4 emails with the exact same comment.
    Perhaps there is a way you are able to remove me from that service?
    Thank you!

  42. I am genuinely grateful to the owner of this web page who has shared this great piece
    of writing at at this time.

  43. link vao m88 says:

    What i do not understood is in truth how you’re no longer really much more neatly-favored than you might be now. You are so intelligent. You understand therefore considerably in terms of this topic, made me in my view believe it from a lot of various angles. Its like women and men are not interested unless it is something to accomplish with Girl gaga! Your own stuffs excellent. Always deal with it up!

  44. Why viewers still use to read news papers when in this
    technological world everything is available on net?

  45. Excellent post. I waѕ checking continuously thіѕ
    blog and ӏ am impressed! Extremely ᥙseful іnformation specially tҺе last ⲣart
    :) Ӏ care fօr ѕuch information much.

    I ԝaѕ looking fоr tҺіѕ ρarticular іnformation fоr ɑ long time.
    Thank yⲟu and ƅеѕt of luck.

  46. Garrett wrote Gwen a heartfelt and detailed letter where he listed everything that
    was special about Gwen and unlike Garrett’s ex.
    Interracial dating and marriage conjure up many emotions for some.

    and promise of the “sizzle” conflicts with the reality of the “steak,”
    one or both of.

  47. 2k16 vc says:

    You’ve gotten amazing info in this case

  48. nba 2k16 vc says:

    Very good Site, Stick to the wonderful work. Thanks for your time!.

  49. AO Sextreff says:

    What’s up mates, its impressive paragraph about teachingand completely explained, keep it
    up all the time.

  50. Merely want to state I am thrilled that i stumbled upon your internet page!.

Leave a Reply


Switch to our mobile site