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. Sammi Ullah says:

    i like this website for download apk foled for my compjuter and android mobile

  2. guimaraes says:

    What i do not understood is in fact how you are now not really much more neatly-favored than you might be now.
    You are very intelligent. You recognize therefore significantly in the case of this topic, produced me in my view
    believe it from a lot of various angles. Its like men and
    women aren’t involved until it is something to accomplish with Woman gaga!
    Your individual stuffs nice. All the time maintain it up!

  3. Excellent, what a web site it is! This website presents valuable information to us,
    keep it up.

  4. Simply want to say your article is as astonishing.

    The clarity in your post is just spectacular
    and i could assume you’re an expert on this subject.
    Fine with your permission allow me to grab your feed to keep
    up to date with forthcoming post. Thanks a million and
    please keep up the enjoyable work.

Leave a Reply


Switch to our mobile site