Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Java

Ajaxion - Standalone AJAX - Part 2 of 2 - C# and Java Example

Rate me:
Please Sign up or sign in to vote.
4.97/5 (34 votes)
22 Jan 2013CPOL5 min read 55.1K   1.4K   42  
An article about how to keep AJAX simple as it is and get the most out of it.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;

using Ajaxion;
using Audit;


namespace AjaxionTest
{
	/// <summary>
	/// Summary description for AjaxCallbackWs.
	/// </summary>
	public class AjaxCallbackWs : System.Web.Services.WebService
	{
		#region Thread test

		public class ThreadingTest
		{
			private static Thread workThread = null;

			private static int maxLevel = 100;
			public static int MaxLevel
			{
				get
				{
					return maxLevel;
				}
			}

			private static int level = 0;
			public static int Level
			{
				get
				{
					return level;
				}
			}

			// Status
			public static bool IsWorkDone
			{
				get
				{
					return level == maxLevel - 1;
				}
			}

			private static bool isWorking = false;
			public static bool IsWorking
			{
				get
				{
					return isWorking;
				}
			}

			public static void SetLevel(int currentLevel)
			{
				level = currentLevel;
			}

			public static void StartThread()
			{
				if (workThread != null)
					workThread.Abort();
				workThread = new Thread( new ThreadStart(Work) );
				workThread.Start();
			}

			public static void StopThread()
			{
				if (workThread != null)
					workThread.Abort();
				workThread = null;
				isWorking = false;
			}

			public static void Work()
			{
				try
				{
					SetLevel(0);
					isWorking = true;

					ThreadWorker worker = new ThreadWorker(maxLevel);
					worker.Count();
				}
				catch (System.Threading.ThreadAbortException)
				{}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
					FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
				}
				finally
				{
					if (workThread != null)
						workThread.Abort();
					workThread = null;
					isWorking = false;
				}
			}

			public class ThreadWorker
			{
				private int maxIndex;

				private int level;
				public int Level
				{
					get
					{
						return level;
					}
				}

				public ThreadWorker(int maxLevel)
				{
					maxIndex = maxLevel;
				}
				public void Count()
				{
					for (int index = 0; index < maxIndex; ++index)
					{
						AjaxCallbackWs.ThreadingTest.SetLevel(index);
						Thread.Sleep(500);
					}
				}
			}
		}


		#endregion // Thread test

		public AjaxCallbackWs()
		{
			//CODEGEN: This call is required by the ASP.NET Web Services Designer
			InitializeComponent();

			FileLog.LogFile = @ConfigurationSettings.AppSettings["logFileName"];
		}


		#region Component Designer generated code
		
		//Required by the Web Services Designer 
		private IContainer components = null;
				
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if(disposing && components != null)
			{
				components.Dispose();
			}
			base.Dispose(disposing);		
		}
		
		#endregion

		[WebMethod]
		public void GetImageUrl()
		{
			try
			{
				AjaxionEventConsumer consumer = new AjaxionEventConsumer(this.Context, 700);
				consumer.ConsumeEvent("images/" + consumer.Parameters, "text/html");
			}
			catch (System.Threading.ThreadAbortException)
			{}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}
		}

		[WebMethod]
		public void GetImageBinary()
		{
			try
			{
				AjaxionEventConsumer consumer = new AjaxionEventConsumer(this.Context, 700);
				string imageFile = Server.MapPath("images\\" + consumer.Parameters);
				if (consumer.EventId.Equals("imageBina"))
				{
					string response = "ImageLoaderHandler.ashx?imageFile=" + imageFile;
					consumer.ConsumeEvent(response, "text/html");
				}
				else if (consumer.EventId.Equals("imageBina2"))
				{
					string response = "ImageLoaderHandler.ashx?imageFile=" + imageFile;
					string contentType = imageFile.ToLower().LastIndexOf(".gif") > 0 ? "image/gif" : "image/jpeg";
					consumer.ConsumeEvent(response, contentType);
				}
			}
			catch (System.Threading.ThreadAbortException)
			{}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}
		}

		[WebMethod]
		public void GetXmlHtml()
		{
			try
			{
				AjaxionEventConsumer consumer = new AjaxionEventConsumer(this.Context, 700);
			
				string response, contentType;
				if (consumer.Parameters.Equals(string.Empty))
				{
					response = "<b>Receive data here.</b>";
					contentType = "text/html";
				}
				else
				{
					response = BuildResponse(consumer.Parameters);
					contentType = "text/xml";
				}

				consumer.ConsumeEvent(response, contentType);
			}
			catch (System.Threading.ThreadAbortException)
			{}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}
		}

		[WebMethod]
		public void GetLevel()
		{
			try
			{
				AjaxionEventConsumer consumer = new AjaxionEventConsumer(this.Context, 500);
				int full = Convert.ToInt32(consumer.Parameters);

				string response;

				// Do something, check a thread
				if (!ThreadingTest.IsWorking && !ThreadingTest.IsWorkDone)
					ThreadingTest.StartThread();
				int level = ThreadingTest.Level;

				int count;
				if (level < ThreadingTest.MaxLevel && !ThreadingTest.IsWorkDone)
				{
					count = Convert.ToInt32(full * level / 100) + 1;
					response = new string('|', count);
				}
				else
					response = "DONE";

				consumer.ConsumeEvent(response, "text/xml");
			}
			catch (System.Threading.ThreadAbortException)
			{}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}
		}

		[WebMethod]
		public void ResetLevel()
		{
			try
			{
				// Do something, stop the thread
				ThreadingTest.StopThread();
				ThreadingTest.SetLevel(0);

				AjaxionEventConsumer consumer = new AjaxionEventConsumer(this.Context, 700);
				consumer.ConsumeEvent(string.Empty, "text/HTML");
			}
			catch (System.Threading.ThreadAbortException)
			{}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}
		}

		private string BuildResponse(string param)
		{
			string response = string.Empty;

			try
			{
				XmlDocument xmlDoc = new XmlDocument();
				xmlDoc.LoadXml(param);

				StringBuilder sb = new StringBuilder("<handler><TABLE id='injected' border='1' cellSpacing='1' cellPadding='1' align='center' bgColor='lightgrey'><TR>");

				foreach (XmlNode node in xmlDoc.FirstChild.ChildNodes)
					sb.AppendFormat("<TD>{0}</TD>", node.InnerText);
				sb.Append("</TR></TABLE></handler>");

				response = sb.ToString();
			}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}

			return response;
		}

		public static void GetImageBinary(HttpContext context)
		{
			try
			{
				string imageFile = context.Request.QueryString["imageFile"];

				Bitmap image = new Bitmap(imageFile);
				MemoryStream ms = new MemoryStream();

				if (imageFile.ToLower().LastIndexOf(".gif") > 0)
					image.Save(ms, ImageFormat.Gif);
				else if (imageFile.ToLower().LastIndexOf(".jp") > 0)
					image.Save(ms, ImageFormat.Jpeg);
				else if (imageFile.ToLower().LastIndexOf(".png") > 0)
					image.Save(ms, ImageFormat.Png);
				else if (imageFile.ToLower().LastIndexOf(".bmp") > 0)
					image.Save(ms, ImageFormat.Bmp);
				else // and so on
					throw new Exception("Unexpected image format...");

				byte[] imageBytes = ms.ToArray();

				context.Response.BinaryWrite(imageBytes);
			}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
			}
		}

		public static byte[] GetImageBytes(string fileName)
		{
			try
			{

				Bitmap image = new Bitmap(fileName);
				MemoryStream ms = new MemoryStream();

				if (fileName.ToLower().LastIndexOf(".gif") > 0)
					image.Save(ms, ImageFormat.Gif);
				else if (fileName.ToLower().LastIndexOf(".jp") > 0)
					image.Save(ms, ImageFormat.Jpeg);
				else if (fileName.ToLower().LastIndexOf(".png") > 0)
					image.Save(ms, ImageFormat.Png);
				else if (fileName.ToLower().LastIndexOf(".bmp") > 0)
					image.Save(ms, ImageFormat.Bmp);
				else // and so on
					throw new Exception("Unexpected image format...");

				byte[] imageBytes = ms.ToArray();

				return imageBytes;
			}
			catch (Exception ex)
			{
				FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
				return null;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
New Zealand New Zealand
Coder

Comments and Discussions