Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » Ajax » General » Downloads
 
Add your own
alternative version

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

, 22 Jan 2013 CPOL
An article about how to keep AJAX simple as it is and get the most out of it.
ajaxiontest1.0_java_src.zip
AjaxionTest
ajaxionTest.jpr
ajaxionTest.jpr.bak
AjaxionTest.jws
classes
ajaxionTest.cdi
pw
ajaxion
AjaxionEventConsumer.class
log
FileLog.class
servlet
ajaxionTest.class
servlet.cdi
public_html
css
images
processing.gif
ready.jpg
js
WEB-INF
pw.ajaxion
classes
pw
ajaxion
AjaxionEventConsumer.class
AjaxionEventHandler.class
pw.ajaxion.cdi
pw.ajaxion.jpr
src
pw
ajaxion
pw.log
classes
audit.log
pw
log
FileLog.class
pw.log.cdi
test
pw
log
FileLogTest.class
pw.log.jpr
src
pw
log
test
pw
log
src
servlet
ajaxiontest1.0_net1.1_src.zip
Ajaxion
Ajaxion.csproj.user
Ajaxion.ico
js
AjaxionTest.csproj.webinfo
Audit
Audit.csproj.user
Audit.ico
css
Global.asax
images
AjaxFlavour1.gif
AjaxFlavour2.gif
AjaxFlavour3.jpg
App.ico
HappyAccountant.jpg
processing.gif
ready.JPG
js
ajaxiontest1.0_net2.0_src.zip
Ajaxion.csproj.user
Ajaxion.ico
App_Code
Audit.csproj.user
Audit.ico
Global.asax
AjaxFlavour1.gif
AjaxFlavour2.gif
AjaxFlavour3.jpg
App.ico
HappyAccountant.jpg
processing.gif
ready.JPG
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)

Share

About the Author

radumi
Software Developer
New Zealand New Zealand
Coder

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150326.1 | Last Updated 22 Jan 2013
Article Copyright 2008 by radumi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid