text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;

using COM = SharedCache.WinServiceCommon;

namespace SharedCache.WinService
{
	/// <summary>
	/// All needed TCP logic upon Win32 start and stop;
	/// </summary>
	public class TcpServer : COM.Extenders.IInit
	{

		#region Cache Handling
		/// <summary>
		/// Provides a local variable of <see cref="SharedCache.WinServiceCommon.Cache"/> do not work directly with this
		/// instance, use the public property <see cref="LocalCache"/> which ensures the runtime
		/// </summary>
		private static SharedCache.WinServiceCommon.Cache _cache;
		/// <summary>
		/// Gets the local cache.
		/// </summary>
		/// <value>The local cache.</value>
		public static SharedCache.WinServiceCommon.Cache LocalCache
		{
			[System.Diagnostics.DebuggerStepThrough]
			get
			{
				EnsureHttpRuntime();
				return _cache;
			}
		}
		/// <summary>
		/// Provides a local variable of <see cref="SharedCache.WinServiceCommon.CacheCleanup"/> do not work directly with this
		/// instance, use the public property <see cref="CacheCleanup"/> which ensures the runtime
		/// </summary>
		private static SharedCache.WinServiceCommon.CacheCleanup _cacheCleanup;
		/// <summary>
		/// Gets the local cache.
		/// </summary>
		/// <value>The local cache.</value>
		public static SharedCache.WinServiceCommon.CacheCleanup CacheCleanup
		{
			[System.Diagnostics.DebuggerStepThrough]
			get
			{
				EnsureCleanupRuntime();
				return _cacheCleanup;
			}
		}

		/// <summary>
		/// Ensures the cleanup runtime.
		/// </summary>
		[System.Diagnostics.DebuggerStepThrough]
		private static void EnsureCleanupRuntime()
		{
			if (null == _cacheCleanup)
			{
				try
				{
					Monitor.Enter(typeof(Indexus));
					if (null == _cacheCleanup)
					{
						// Create an Cache Object which give us access.
						_cacheCleanup = new SharedCache.WinServiceCommon.CacheCleanup();
					}
				}
				finally
				{
					Monitor.Exit(typeof(Indexus));
				}
			}
		}

		/// <summary>
		/// Ensures the HTTP runtime.
		/// </summary>
		[System.Diagnostics.DebuggerStepThrough]
		private static void EnsureHttpRuntime()
		{
			if (null == _cache)
			{
				try
				{
					Monitor.Enter(typeof(Indexus));
					if (null == _cache)
					{
						// Create an Cache Object which give us access.
						_cache = new SharedCache.WinServiceCommon.Cache();
					}
				}
				finally
				{
					Monitor.Exit(typeof(Indexus));
				}
			}
		}
		#endregion Cache Handling

		#region Properties
		/// <summary>
		/// needed for lock(){} operations
		/// </summary>
		private static object bulkObject = new object();
		/// <summary>
		/// write Statistics
		/// </summary>
		static bool writeStats = false;
		/// <summary>
		/// reading IP Address from config file.
		/// </summary>
		private string cacheIpAdress = COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.ServiceCacheIpAddress;
		/// <summary>
		/// reading Tcp Port from config file.
		/// </summary>
		private int cacheIpPort = COM.Ports.ServerDefaultPortTcp();
		/// <summary>
		/// a value to set upper thread pool boundry
		/// </summary>
		private int maxThreadToSet = COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.TcpServerMaxThreadToSet;
		/// <summary>
		/// a value to set lower thread pool boundry
		/// </summary>
		private int minThreadToSet = COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.TcpServerMinThreadToSet;
		/// <summary>
		/// an Instance of <see cref="CacheExpire"/>
		/// </summary>
		private CacheExpire expire = null;
		/// <summary>
		/// The maximum size of the objects in the Cache in MB.
		/// </summary>
		private long cacheAmountOfObjects = -1;
		/// <summary>
		/// If the cache received the fillfactor it will start to throw away unused items from the cache suggested is a value between: 85% - 95%
		/// </summary>
		private long cacheAmountFillFactorInPercentage = 90;
		/// <summary>
		/// Delegate definition to handle received client data and proceed it.
		/// </summary>
		/// <param name="state">A <see cref="COM.Sockets.SharedCacheStateObject"/> object.</param>
		delegate void HandleClientMessageDelegate(COM.Sockets.SharedCacheStateObject state);
		/// <summary>
		/// Define maximum amount of sockets
		/// </summary>
		private int maxSockets;
		/// <summary>
		/// actual amount of sockets
		/// </summary>
		private int socketCount;
		/// <summary>
		/// Timer of type <see cref="Timer"/> to evaluate connected sockets
		/// </summary>
		private Timer lostTimer;
		/// <summary>
		/// Default amount of Threads
		/// </summary>
		private const int numberOfThreads = 1;
		/// <summary>
		/// Used for Timer to evaluate connected clients
		/// </summary>
		private const int timerTimeout = 300000;
		/// <summary>
		/// Used for Timer to evaluate connected clients
		/// </summary>
		private const int timeoutMinutes = 3;
		/// <summary>
		/// Define status if server is in shutdown mode
		/// </summary>
		private bool ShuttingDownServer = false;
		/// <summary>
		/// A <see cref="Hashtable"/> which contains connected clients
		/// </summary>
		private Hashtable conntectedHt = new Hashtable();
		/// <summary>
		/// A container for state objects
		/// </summary>
		private ArrayList conntectedSockets;
		private ManualResetEvent allDone = new ManualResetEvent(false);
		private Thread[] serverThread = new Thread[numberOfThreads];
		private AutoResetEvent[] threadEnd = new AutoResetEvent[numberOfThreads];
		/// <summary>
		/// Custom Thread pool <see cref="COM.Threading.SharedCacheThreadPool"/>
		/// </summary>
		private COM.Threading.SharedCacheThreadPool threadPool;
		/// <summary>
		/// <see cref="WaitCallback"/> after client connected.
		/// </summary>
		private WaitCallback AcceptConnection;
		#endregion Properties

		#region CTor
		/// <summary>
		/// Initializes a new instance of the <see cref="T:Tcp"/> class.
		/// </summary>
		public TcpServer()
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			#region validate first if provided configuration is a numeric value - ConfigCacheAmountOfObjects

			if (!string.IsNullOrEmpty(COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountOfObjects.ToString()) &&
					long.TryParse(
						COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountOfObjects.ToString(),
						out this.cacheAmountOfObjects) &&
						COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountOfObjects > 0
				)
			{
				// calculate the correct size for max cache size
				this.cacheAmountOfObjects =
					long.Parse(COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountOfObjects.ToString())
					* (1024 * 1024);
			}
			else
			{
				this.cacheAmountOfObjects = -1;
			}

			#endregion validate first if provided configuration is a numeric value - ConfigCacheAmountOfObjects

			#region validate first if provided configuration is a numeric value - ConfigCacheAmountFillFactorInPercentage
			if (!string.IsNullOrEmpty(
				COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountFillFactorInPercentage.ToString()) &&
				long.TryParse(
					COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountFillFactorInPercentage.ToString(),
					out this.cacheAmountFillFactorInPercentage)
				)
			{
				// this defines the purge factor for the dictonary
				this.cacheAmountFillFactorInPercentage = long.Parse(
					COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.CacheAmountFillFactorInPercentage.ToString());
			}
			else
			{
				this.cacheAmountFillFactorInPercentage = 90;
			}

			#endregion validate first if provided configuration is a numeric value - ConfigCacheAmountFillFactorInPercentage

			this.maxSockets = 30000;
			this.conntectedSockets = new ArrayList(this.maxSockets);

			#region Thread Pool Configuration
			int minThreadsInPool = 3;
			int maxThreadsInPool = 25;
			// validate min threads
			if (minThreadToSet > minThreadsInPool)
			{
				minThreadsInPool = minThreadToSet;
			}
			// validate max threads
			if (maxThreadToSet > maxThreadsInPool)
			{
				maxThreadsInPool = maxThreadToSet;
			}
			// recheck that min. amount is smaller then max. - set default values if this happend
			if (minThreadsInPool >= maxThreadsInPool)
			{
				minThreadsInPool = 3;
				maxThreadsInPool = 25;
			}
			#endregion Thread Pool Configuration

			try
			{
				// Init thread pool
				this.threadPool = new COM.Threading.SharedCacheThreadPool(minThreadsInPool, maxThreadsInPool, "TcpServer");
				COM.Handler.LogHandler.Info(string.Format("Configuration: Thread Pool initalized with min:{0} and max:{1} Threads", minThreadsInPool, maxThreadsInPool));
				Console.WriteLine("Configuration: Thread Pool initalized with min:{0} and max:{1} Threads", minThreadsInPool, maxThreadsInPool);
			}
			catch (Exception)
			{
				this.threadPool = null;
				COM.Handler.LogHandler.Error("Configuration Error: Thread Pool initalized with min: 3 and max: 25 Threads");
			}
			finally
			{
				if (this.threadPool == null)
				{
					minThreadsInPool = 3;
					maxThreadsInPool = 25;
					this.threadPool = new COM.Threading.SharedCacheThreadPool(minThreadsInPool, maxThreadsInPool, "TcpServer");
					COM.Handler.LogHandler.Error("Configuration Error: Thread Pool initalized with min: 3 and max: 25 Threads");
				}
			}

			this.threadPool.Priority = ThreadPriority.AboveNormal;
			this.threadPool.NewThreadTrigger = 1;
			this.threadPool.DynamicThreadDecay = 5000;
			this.threadPool.Start();
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="TcpServer"/> class.
		/// </summary>
		/// <param name="expire">The expire.</param>
		public TcpServer(CacheExpire expire)
			: this()
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			if (expire != null && expire.Expire != null && expire.Expire.Enable)
			{
				this.expire = expire;
			}
			else
			{
				this.expire = null;
				expire.Dispose();
				if (expire != null)
					expire = null;
			}
		}
		#endregion CTor

		#region IInit Members
		/// <summary>
		/// Inits this instance.
		/// </summary>
		public void Init()
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			for (int i = 0; i < numberOfThreads; ++i)
			{
				this.threadEnd[i] = new AutoResetEvent(false);
			}

			ThreadStart serverListener = new ThreadStart(this.StartListening);
			serverThread[0] = new Thread(serverListener);
			serverThread[0].IsBackground = true;
			serverThread[0].Start();

			TimerCallback timerDelegate = new TimerCallback(this.CheckSockets);
			this.lostTimer = new Timer(timerDelegate, null, TcpServer.timerTimeout, TcpServer.timeoutMinutes);

			COM.Handler.LogHandler.Force("Listener Started" + COM.Enums.LogCategory.ServiceStart.ToString());
			Console.WriteLine("Listener Started");
		}
		/// <summary>
		/// Gets the name.
		/// </summary>
		/// <value>The name.</value>
		public string Name
		{
			get
			{
				return string.Format(@"Thread Id: {0}; Name: {0}; ", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name);
			}
		}
		/// <summary>
		/// Disposes this instance.
		/// </summary>
		public void Dispose()
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log
			// send shutdown over network if family mode is enabled.
			COM.Handler.LogHandler.Force(string.Format(@"Thread abort's Id: {0}; Name: {0}; ", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name));
			this.Stop();
		}

		/// <summary>
		/// Stops this instance.
		/// </summary>
		public void Stop()
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			int lcv;
			lostTimer.Dispose();
			lostTimer = null;

			for (lcv = 0; lcv < numberOfThreads; lcv++)
			{
				if (!serverThread[lcv].IsAlive)
					threadEnd[lcv].Set();	// Set event if thread is already dead
			}
			this.ShuttingDownServer = true;
			try
			{
				// Create a connection to the port to unblock the listener thread
				Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, this.cacheIpPort);
				sock.Connect(endPoint);
				//sock.Close();
				sock = null;
			}
			catch (Exception)
			{
				// do nothing ...
			}
			// Check thread end events and wait for up to 5 seconds.
			for (lcv = 0; lcv < numberOfThreads; lcv++)
				threadEnd[lcv].WaitOne(500, false);
		}

		#endregion

		#region Async TCP Connection Handling
		#region Private Methods
		private void StartListening()
		{
			IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, this.cacheIpPort);
			// fix for issue: http://sharedcache.codeplex.com/WorkItem/View.aspx?WorkItemId=9370
			using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
			{
				try
				{
					socket.Bind(endPoint);
					socket.Listen(this.maxSockets);

					string msg = string.Format(@"TCP - Listener started on: {0}:{1}", this.cacheIpAdress, this.cacheIpPort);
					COM.Handler.LogHandler.Force(msg);
					COM.Handler.LogHandler.Traffic(msg);
					Console.WriteLine(msg);

					AcceptConnection = new WaitCallback(AcceptConnection_Handler);

					while (!this.ShuttingDownServer)
					{
						this.allDone.Reset();
						// start async socket listener for connections
						// socket.BeginAccept(new AsyncCallback(this.AccecptCallback), socket);

						this.threadPool.PostRequest(this.AcceptConnection, new object[] { socket });

						//ThreadPool.QueueUserWorkItem(AcceptConnection, socket);
						// wait until the connection is established befor we continue
						this.allDone.WaitOne();
					}
				}
				catch (SocketException sEx)
				{
					#region Socket exception handling
					threadEnd[0].Set();

					COM.Handler.LogHandler.Fatal(string.Format("Could not bind enpoint {0}:{1} - Socket Excpetion No: {2}", endPoint.Address, endPoint.Port, sEx.ErrorCode));
					COM.Handler.LogHandler.Error(string.Format("Could not bind enpoint {0}:{1} - Socket Excpetion No: {2}", endPoint.Address, endPoint.Port, sEx.ErrorCode));
					Console.WriteLine("");
					Console.WriteLine(@"FATAL ERROR:");
					Console.WriteLine("");
					Console.WriteLine("Server cannot start to listen because it could not bind your requested enpoint {0}:{1} - Socket Excpetion No: {2}", endPoint.Address, endPoint.Port, sEx.ErrorCode);
					Console.WriteLine("use the command: 'netstat -a' to evaluate which application takes usage of port: {0}", endPoint.Port);
					#endregion Socket exception handling
				}
				catch (Exception ex)
				{
					#region Regular Exception Handling
					threadEnd[0].Set();
					COM.Handler.LogHandler.Fatal(string.Format("Could not bind enpoint {0}:{1} - Excpetion Message: {2}", endPoint.Address, endPoint.Port, ex.Message));
					COM.Handler.LogHandler.Error(string.Format("Could not bind enpoint {0}:{1} - Excpetion Message: {2}", endPoint.Address, endPoint.Port, ex.Message));
					Console.WriteLine("");
					Console.WriteLine(@"FATAL ERROR:");
					Console.WriteLine("");
					Console.WriteLine("Could not bind enpoint {0}:{1} - Excpetion Message: {2}", endPoint.Address, endPoint.Port, ex.Message);
					#endregion Regular Exception Handling
				}
			}
		}

		/// <summary>
		/// Accepts connection handler.
		/// </summary>
		/// <param name="s">The a new socket</param>
		private void AcceptConnection_Handler(object s)
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			Socket socket = s as Socket;
			// start async socket listener for connections
			socket.BeginAccept(new AsyncCallback(this.AccecptCallback), socket);
		}

		/// <summary>
		/// Accecpts the callback.
		/// </summary>
		/// <param name="ar">The ar.</param>
		private void AccecptCallback(IAsyncResult ar)
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log
			// signal main thread to continue
			this.allDone.Set();

			Socket clientListener = ar.AsyncState as Socket;

			if (clientListener != null)
			{
				Socket handler = clientListener.EndAccept(ar);

				// after accepted Client is available create a new state object.
				COM.Sockets.SharedCacheStateObject state = new COM.Sockets.SharedCacheStateObject();

				// assign the socket to the worker sockets
				state.WorkSocket = handler;

				// keep state alive
				state.AliveTimeStamp = DateTime.Now;

				try
				{
					// increment the amount of connected sockets
					Interlocked.Increment(ref this.socketCount);

					if (1 == COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
					{
#if DEBUG
						Console.WriteLine(@"Connected by client: {0}; current amount of connected clients: {1}", handler.RemoteEndPoint.ToString(), this.socketCount);
#endif
						COM.Handler.LogHandler.Info(string.Format(@"Connected by client: {0}; current amount of connected clients: {1}", handler.RemoteEndPoint.ToString(), this.socketCount));
					}
#if DEBUG
					if (writeStats)
					{
						Console.WriteLine(@"SocketCount: {0}", this.socketCount);
					}
#endif
					lock (this.conntectedSockets)
					{
						this.conntectedSockets.Add(state);
					}

					// ready to start with receiving data.
					handler.BeginReceive(state.Buffer, 0,
						COM.Sockets.SharedCacheStateObject.BufferSize, 0,
						new AsyncCallback(this.ReadCallback), state);

					// if the server has to much connected clients as configured the state will be removed.
					if (this.socketCount > this.maxSockets)
					{
						RemoveSocket(state);
						handler = null;
						state = null;
					}
				}
				catch (SocketException sEx)
				{
					Console.WriteLine("Socket Exception: {0} \n{1}", sEx.ErrorCode, sEx.Message);
					COM.Handler.LogHandler.Error(string.Format("Socket Exception: {0} \n{1}", sEx.ErrorCode, sEx.Message));
					RemoveSocket(state);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Exception: {0}", ex.Message);
					COM.Handler.LogHandler.Error(string.Format("Exception: {0}", ex.Message));
					RemoveSocket(state);
				}
			}
		}

		/// <summary>
		/// Reads the callback.
		/// </summary>
		/// <param name="ar">The ar.</param>
		private void ReadCallback(IAsyncResult ar)
		{
			#region Access Log
#if TRACE

			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			COM.Sockets.SharedCacheStateObject state = ar.AsyncState as COM.Sockets.SharedCacheStateObject;
			if (state != null)
			{
				Socket handler = state.WorkSocket;
				if (handler != null)
				{
					try
					{
						// read data from the client sockets
						int read = handler.EndReceive(ar);
						if (read > 0)
						{
							Monitor.Enter(state);
							// save 2.5 seconds while i copy data to local variables and i do not access the property
							byte[] localBuffer;
							localBuffer = state.Buffer;
							byte[] tmp = new byte[read];
							// copy all buffer data into DataBuffer which is list and contains all data until we get the whole message.
							Array.Copy(localBuffer, tmp, tmp.Length);

							// localList.AddRange(state.DataBuffer);
							// localList.AddRange(tmp);
							if (state.DataBigBuffer == null)
								state.DataBigBuffer = new byte[0];

							byte[] localBuffer1 = state.DataBigBuffer;

							byte[] tmp2 = new byte[tmp.Length + localBuffer1.Length];
							Array.Copy(localBuffer1, tmp2, localBuffer1.Length);
							Array.Copy(tmp, 0, tmp2, localBuffer1.Length, tmp.Length);

							state.DataBigBuffer = tmp2;
							Monitor.Exit(state);

							// check for header
							if (state.ReadHeader)
							{
								// message header are long values for this issue we need to add 8 bytes to length
								state.MessageLength = BitConverter.ToInt64(state.Buffer, 0) + 8;
								// upon next read the header will not be readed again.
								state.ReadHeader = false;
							}
							state.AlreadyRead += read;

							// check for received message length
							if (state.AlreadyRead == state.MessageLength)
							{
								// keep state alive with a new timestamp
								// state.AliveTimeStamp = DateTime.Now;

								// manipulate message - we need to remove the header before we can handle it
								byte[] r = new byte[state.DataBigBuffer.Length - 8];
								Array.Copy(state.DataBigBuffer, 8, r, 0, r.Length);
								state.DataBigBuffer = r;

								// HandleClientMessage(state);

								HandleClientMessageDelegate cb = new HandleClientMessageDelegate(this.HandleClientMessage);
								object[] args = { state };
								this.threadPool.PostRequest(cb, args);
							}
							else
							{
								// Thread.Sleep(1);
								// not all data received ... get more data
								handler.BeginReceive(state.Buffer, 0, COM.Sockets.SharedCacheStateObject.BufferSize, 0,
									new AsyncCallback(this.ReadCallback), state);
							}
						}
						else
						{
							this.RemoveSocket(state);
						}
					}
					catch (SocketException sEx)
					{
						#region
						//Console.WriteLine(
						//  @"Socket Error Code: {0}" + Environment.NewLine +
						//  "Exception Title: {1}" + Environment.NewLine +
						//  "Exception Stacktrace: ", sEx.ErrorCode, sEx.Message, sEx.StackTrace);
						switch (sEx.SocketErrorCode)
						{
							// 10054
							case SocketError.ConnectionReset:
								{
									Console.WriteLine(@"Client Disconnected: {0}; {1}", sEx.ErrorCode, state.WorkSocket.RemoteEndPoint.ToString());
									COM.Handler.LogHandler.Traffic(string.Format(@"Client Disconnected: {0}; {1}", sEx.ErrorCode, state.WorkSocket.RemoteEndPoint.ToString()));
									RemoveSocket(state);
									break;
								}
							default:
								{
									RemoveSocket(state);
									Console.WriteLine(@"Socket Exception {0} Code: {1}", sEx.SocketErrorCode, sEx.ErrorCode);
									break;
								}
						}
						#endregion
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.Message);
					}
				}
			}
		}

		/// <summary>
		/// Handles the client message.
		/// </summary>
		/// <param name="state">The state.</param>
		private void HandleClientMessage(COM.Sockets.SharedCacheStateObject state)
		{
			#region Access Log
#if TRACE

			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			if (state != null)
			{
				COM.IndexusMessage msg = null;

				try
				{
					System.IO.MemoryStream stream = new System.IO.MemoryStream(state.DataBigBuffer);
					stream.Seek(0, 0);
					msg = new COM.IndexusMessage(stream);
				}
				catch (Exception ex)
				{
					#region Error Handling
					COM.Handler.LogHandler.Fatal(string.Format("[{0}] Could not create IndexusMessage from received data", state.WorkSocket.RemoteEndPoint.ToString()), ex);
					COM.Handler.LogHandler.Error(string.Format("[{0}] Could not create IndexusMessage from received data", state.WorkSocket.RemoteEndPoint.ToString()), ex);
					COM.Handler.LogHandler.Traffic(string.Format("[{0}] Could not create IndexusMessage from received data", state.WorkSocket.RemoteEndPoint.ToString()));
					Console.WriteLine(string.Format("[{0}] Could not create IndexusMessage from received data", state.WorkSocket.RemoteEndPoint.ToString()));

					using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
					{
						resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
						resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
						resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
							new COM.CacheException("Could not convert MemoryStream to indeXusMessage", msg.Action, msg.Status, ex)
						);

						this.SendResponse(state, resultMsg);
					}
					return;
					#endregion Error Handling
				}

				if (msg != null)
				{
					// check status first [Request || Response]
					switch (msg.Status)
					{
						case COM.IndexusMessage.StatusValue.Request:
						case COM.IndexusMessage.StatusValue.ReplicationRequest:
							{
								try
								{
									#region Logging
#if DEBUG
									if (1 == COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
									{
										// Add request to log
										COM.Handler.LogHandler.Traffic(
											string.Format(COM.Constants.TRAFFICLOG,
												state.WorkSocket.RemoteEndPoint,
												System.Threading.Thread.CurrentThread.ManagedThreadId,
												msg.Id,
												msg.Action.ToString(),
												msg.Status.ToString(),
												state.DataBigBuffer.LongLength
												)
											);
									}
#else
								if (1 == COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
								{
									// Add request to log
									COM.Handler.LogHandler.Traffic(
										string.Format(COM.Constants.TRAFFICLOG,
											state.WorkSocket.RemoteEndPoint,
											System.Threading.Thread.CurrentThread.ManagedThreadId,
											msg.Id,
											msg.Action.ToString(),
											msg.Status.ToString(),
											state.DataBigBuffer.LongLength
											)
										);
								}
#endif
									#endregion
									#region request case
									COM.IndexusMessage replicationMessage = null;

									// if replication Request arrives as status value a different server node is the holder of this object
									if (ServiceLogic.NetworkDistribution.ReplicationEnabled && msg.Status != COM.IndexusMessage.StatusValue.ReplicationRequest)
									{
										// create a new object of received msg. to broadcast on servers.
										replicationMessage = new SharedCache.WinServiceCommon.IndexusMessage();
										replicationMessage.Action = msg.Action;
										replicationMessage.Status = COM.IndexusMessage.StatusValue.ReplicationRequest;
										replicationMessage.Key = msg.Key;
										replicationMessage.Payload = msg.Payload;
									}

									// switch over cache actions
									switch (msg.Action)
									{
										case SharedCache.WinServiceCommon.IndexusMessage.ActionValue.VersionNumberSharedCache:
											{
												#region VersionNumberSharedCache
												msg.Action = COM.IndexusMessage.ActionValue.Successful;
												msg.Payload = COM.Formatters.Serialization.BinarySerialize(
														new AssemblyInfo().Version
													);
												this.SendResponse(state, msg);
												break;
												#endregion VersionNumberSharedCache
											}
										case COM.IndexusMessage.ActionValue.VersionNumberClr:
											{
												#region VersionNumberClr
												msg.Action = COM.IndexusMessage.ActionValue.Successful;
												msg.Payload = COM.Formatters.Serialization.BinarySerialize(Environment.Version.ToString());
												this.SendResponse(state, msg);
												break;
												#endregion VersionNumberClr
											}
										case COM.IndexusMessage.ActionValue.Ping:
											{
												#region Ping
												msg.Action = COM.IndexusMessage.ActionValue.Successful;
												msg.Payload = null;
												this.SendResponse(state, msg);
												break;
												#endregion Ping
											}
										case COM.IndexusMessage.ActionValue.Add:
											{
												#region Add Case
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine(@"Adding new Item with Key: {0}", msg.Key);
													}
#endif
													LocalCache.Add(msg.Key, msg.Payload);
													// if the given msg expires is not MaxValue
													// it will be listed sub-process which clean
													// up in iterations the cache.
													// QuickFix
													if (msg.Expires != DateTime.MaxValue)
													{
														if (this.expire != null)
														{
															this.expire.Expire.DumpCacheItemAt(msg.Key, msg.Expires);
														}
													}

													// update cleanup list with new object
													CacheCleanup.Update(msg);

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Payload = null;
													msg.Status = COM.IndexusMessage.StatusValue.Response;

													// send object back throug the connection
													this.SendResponse(state, msg);

													#region rschuetz: MODIFIED: 21-07-2007: distribute object over wire to other installations
													// Question is if the client needs to wait until this happens,
													// or should the client first get an answer and just then it
													// will distribute it.
													if (ServiceLogic.NetworkDistribution.ReplicationEnabled && msg.Status != COM.IndexusMessage.StatusValue.ReplicationRequest)
													{
														ServiceLogic.NetworkDistribution.Replicate(replicationMessage);
													}
													#endregion
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												finally
												{
													// handle max size and purge issues
													if (this.cacheAmountOfObjects != -1 && this.cacheAmountOfObjects <= LocalCache.CalculatedCacheSize && !CacheCleanup.PurgeIsRunning)
													{
#if DEBUG
														if (writeStats)
														{
															Console.WriteLine(@"Current Size of Cache: {0} ; {1} ", LocalCache.CalculatedCacheSize, LocalCache.CalculatedCacheSize <= 0 ? 0 : LocalCache.CalculatedCacheSize / (1024 * 1024));
														}
#endif
														List<string> remove = CacheCleanup.Purge(LocalCache.CalculatedCacheSize);
														if (remove != null)
														{
															lock (bulkObject)
															{
																foreach (string s in remove)
																{
																	LocalCache.Remove(s);
																}
															}
														}
													}
												}
												break;
												#endregion Add Case
											}
										case COM.IndexusMessage.ActionValue.ExtendTtl:
											{
												#region Extend Time To Live
												// workitem: http://www.codeplex.com/SharedCache/WorkItem/View.aspx?WorkItemId=6129
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Search for Object with Key: {0}, Current Cache Size: {1}", msg.Key, LocalCache.Amount());
													}
#endif
													CacheCleanup.Update(msg);
													this.expire.Expire.DumpCacheItemAt(msg.Key, msg.Expires);

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = null;
													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												break;
												#endregion Extend Time To Live
											}
										case COM.IndexusMessage.ActionValue.Get:
											{
												#region Receive object from cache
												byte[] objectFromCache = new byte[1] { 0 };
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Search for Object with Key: {0}, Current Cache Size: {1}", msg.Key, LocalCache.Amount());
													}
#endif
													objectFromCache = LocalCache.Get(msg.Key);
													// send new object back to client within same socket which contains the cache object.
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Action = COM.IndexusMessage.ActionValue.Successful;

													msg.Payload = objectFromCache;
													// update cleanup list
													CacheCleanup.Update(msg);

													// bugfix: http://www.codeplex.com/WorkItem/View.aspx?ProjectName=SharedCache&WorkItemId=6167
													// return null if item is already expried
													if (this.expire.Expire.CheckExpired(msg.Key))
													{
														this.expire.Expire.Remove(msg.Key);
														LocalCache.Remove(msg.Key);
														CacheCleanup.Remove(msg.Key);

#if DEBUG
														if (writeStats)
														{
															Console.WriteLine("Cleared Object with Key: {0}, Current Cache Size: {1}", msg.Key, LocalCache.Amount());
														}
#endif
														if (1 == COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
														{
															COM.Handler.LogHandler.Info(string.Format("Item with Key:'{0}' has been removed and Server node {1} return NULL", msg.Key, Environment.MachineName));
														}

														msg.Payload = null;
													}
													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												break;
												#endregion
											}
										case COM.IndexusMessage.ActionValue.Remove:
											{
												#region Remove Case
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Remove Object with Key: {0}, current Cache amount: {1}", msg.Key, LocalCache.Amount());
													}
#endif
													// remove it from the cache.
													LocalCache.Remove(msg.Key);
													if (this.expire != null)
													{
														// remove it from the cache expiry job.
														this.expire.Expire.Remove(msg.Key);
													}
													// update cleanup list
													CacheCleanup.Remove(msg.Key);

													#region rschuetz: MODIFIED: 21-07-2007: distribute object over wire to other installations
													// Question is if the client needs to wait until this happens,
													// or should the client first get an answer and just then it
													// will distribute it.
													if (ServiceLogic.NetworkDistribution.ReplicationEnabled && msg.Status != COM.IndexusMessage.StatusValue.ReplicationRequest)
													{
														ServiceLogic.NetworkDistribution.Replicate(replicationMessage);
													}
													#endregion

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = null;
													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												break;
												#endregion Remove Case
											}
										case COM.IndexusMessage.ActionValue.RegexGet:
											{
												#region Receiving data based on regular expression pattern
												try
												{
													#region
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine(@"RegexGet Operation");
													}
#endif
													#endregion
													IDictionary<string, byte[]> result = new Dictionary<string, byte[]>();

													string regularExpressionPattern = Encoding.UTF8.GetString(msg.Payload);
													Regex regex = new Regex(regularExpressionPattern, RegexOptions.CultureInvariant);

													List<string> actualData = LocalCache.GetAllKeys();

													foreach (string n in actualData)
													{
														if (regex.IsMatch(n))
														{
															result.Add(n, LocalCache.Get(n));
														}
													}

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = COM.Formatters.Serialization.BinarySerialize(result);

													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													#region Exception Handling
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);
														this.SendResponse(state, resultMsg);
													}
													#endregion Exception Handling
												}
												break;
												#endregion Receiving data based on regular expression pattern
											}
										case COM.IndexusMessage.ActionValue.RegexRemove:
											{
												#region Regex Remove
												try
												{
													Regex regex = new Regex(Encoding.UTF8.GetString(msg.Payload), RegexOptions.CultureInvariant);

													#region local logging
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Regex Remove Keys which match pattern: {0}", regex.ToString());
													}
#endif
													#endregion local logging
													List<string> keysToRemove = new List<string>();
													List<string> actualData = LocalCache.GetAllKeys();
													foreach (string n in actualData)
													{
														if (regex.IsMatch(n))
															keysToRemove.Add(n);
													}

													foreach (string key in keysToRemove)
													{
														// remove it from the cache.
														LocalCache.Remove(key);
														if (this.expire != null)
														{
															// remove it from the cache expiry job.
															this.expire.Expire.Remove(key);
														}
														// update cleanup list
														CacheCleanup.Remove(key);
													}

													#region rschuetz: MODIFIED: 21-07-2007: distribute object over wire to other installations
													// Question is if the client needs to wait until this happens,
													// or should the client first get an answer and just then it
													// will distribute it.
													if (ServiceLogic.NetworkDistribution.ReplicationEnabled && msg.Status != COM.IndexusMessage.StatusValue.ReplicationRequest)
													{
														ServiceLogic.NetworkDistribution.Replicate(replicationMessage);
													}
													#endregion

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = null;
													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												break;
												#endregion Regex Remove
											}
										case COM.IndexusMessage.ActionValue.RemoveAll:
											{
												#region Clear all cache items!
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Clear all cache items!");
													}
#endif
													lock (bulkObject)
													{
														// remove all items from cache
														LocalCache.Clear();

														if (this.expire != null)
														{
															// remove all items from the cache expiry job.
															this.expire.Expire.Clear();
														}

														// remove all items from cleanup
														CacheCleanup.Clear();
													}

													//#region rschuetz: MODIFIED: 21-07-2007: distribute object over wire to other installations
													//// Question is if the client needs to wait until this happens,
													//// or should the client first get an answer and just then it
													//// will distribute it.
													//if (ServiceLogic.NetworkDistribution.ReplicationEnabled && msg.Status != COM.IndexusMessage.StatusValue.ReplicationRequest)
													//{
													//  ServiceLogic.NetworkDistribution.Replicate(replicationMessage);
													//}
													//#endregion

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = null;
													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}

												}
												break;
												#endregion
											}
										case COM.IndexusMessage.ActionValue.GetAllKeys:
											{
												#region Get All Keys
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Get All available Key's!");
													}
#endif
													List<string> keys = LocalCache.GetAllKeys();

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = COM.Formatters.Serialization.BinarySerialize(keys);

													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);
														this.SendResponse(state, resultMsg);
													}
												}
												break;
												#endregion
											}
										case COM.IndexusMessage.ActionValue.Statistic:
											{
												#region Statistic

												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("Message Action: {0}", msg.Action.ToString());
													}
#endif
													COM.IndexusStatistic stats;
													// previous clients are sending a stats object, newer clients are
													// sending nothing to reduce interaction on the wire.
													if (msg.Payload != null)
														stats = COM.Formatters.Serialization.BinaryDeSerialize<COM.IndexusStatistic>(msg.Payload);
													else
														stats = new COM.IndexusStatistic();

													// receive cache attributes and add them to cache object
													stats.ServiceAmountOfObjects = LocalCache.Amount();
													stats.ServiceTotalSize = LocalCache.Size();
													stats.ServiceUsageList = CacheCleanup.GetAccessStatList();

													// adding results to return message and set all needed attributes.
													msg.Payload = COM.Formatters.Serialization.BinarySerialize(stats);
													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;

													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);
														this.SendResponse(state, resultMsg);
													}
												}
												break;
												#endregion
											}
										case COM.IndexusMessage.ActionValue.GetAbsoluteTimeExpiration:
											{
												// As requested: http://www.codeplex.com/SharedCache/WorkItem/View.aspx?WorkItemId=6170
												#region Collecting absolut expiration DateTime for provided keys
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine(@"GetAbsoluteTimeExpiration Operation: {0}", msg.Key);
													}
#endif
													IDictionary<string, DateTime> result = new Dictionary<string, DateTime>();
													List<string> requstedData = COM.Formatters.Serialization.BinaryDeSerialize<List<string>>(msg.Payload);
													if (requstedData != null)
													{
														foreach (string key in requstedData)
														{
															bool addItem = true;

															if (this.expire.Expire.CheckExpired(key))
															{
																result.Add(key, DateTime.MinValue);
															}
															else
															{
																result.Add(key, this.expire.Expire.GetExpireDateTime(key));
															}
														}

														msg.Action = COM.IndexusMessage.ActionValue.Successful;
														msg.Status = COM.IndexusMessage.StatusValue.Response;
														msg.Payload = COM.Formatters.Serialization.BinarySerialize(result);

														this.SendResponse(state, msg);
													}
													else
													{
														throw new Exception("Payload could not be deserialized into a list of strings!");
													}
												}
												catch (Exception ex)
												{
													#region Exception Handling
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);
														this.SendResponse(state, resultMsg);
													}
													#endregion Exception Handling
												}
												break;
												#endregion Collecting absolut expiration DateTime for provided keys
											}
										case COM.IndexusMessage.ActionValue.MultiGet:
											{
												#region Receiving a list of single items from the cache
												try
												{
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine(@"MultiGet Operation: {0}", msg.Key);
													}
#endif
													IDictionary<string, byte[]> result = new Dictionary<string, byte[]>();
													List<string> requstedData = COM.Formatters.Serialization.BinaryDeSerialize<List<string>>(msg.Payload);
													if (requstedData != null)
													{
														foreach (string key in requstedData)
														{
															bool addItem = true;
															// bugfix: http://www.codeplex.com/WorkItem/View.aspx?ProjectName=SharedCache&WorkItemId=6167
															// return null if item is already expried
															if (this.expire.Expire.CheckExpired(key))
															{
																this.expire.Expire.Remove(key);
																LocalCache.Remove(key);
																CacheCleanup.Remove(key);
#if DEBUG
																if (writeStats)
																{
																	Console.WriteLine("Cleared Object with Key: {0}, Current Cache Size: {1}", msg.Key, LocalCache.Amount());
																}
#endif
																if (1 == COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
																{
																	COM.Handler.LogHandler.Info(string.Format("Item with Key:'{0}' has been removed and Server node {1} return NULL", msg.Key, Environment.MachineName));
																}

																addItem = false;
															}

															if (addItem)
															{
																result.Add(key, LocalCache.Get(key));
															}
														}

														msg.Action = COM.IndexusMessage.ActionValue.Successful;
														msg.Status = COM.IndexusMessage.StatusValue.Response;
														msg.Payload = COM.Formatters.Serialization.BinarySerialize(result);

														this.SendResponse(state, msg);
													}
													else
													{
														throw new Exception("Payload could not be deserialized into a list of strings!");
													}
												}
												catch (Exception ex)
												{
													#region Exception Handling
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);
														this.SendResponse(state, resultMsg);
													}
													#endregion Exception Handling
												}
												break;
												#endregion Receiving a list of single items from the cache
											}
										case COM.IndexusMessage.ActionValue.MultiAdd:
											{
												#region Adding a bunch of data
												try
												{
													#region Stats
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine(@"Adding a bunch of data - MultiAdd");
													}
#endif
													#endregion Stats

													IDictionary<string, byte[]> data =
														COM.Formatters.Serialization.BinaryDeSerialize<IDictionary<string, byte[]>>(msg.Payload);

													foreach (KeyValuePair<string, byte[]> item in data)
													{
														LocalCache.Add(item.Key, item.Value);
														// if the given msg expires is not MaxValue
														// it will be listed sub-process which clean
														// up in iterations the cache.
														// QuickFix
														if (msg.Expires != DateTime.MaxValue)
														{
															if (this.expire != null)
															{
																this.expire.Expire.DumpCacheItemAt(item.Key, msg.Expires);
															}
														}

														using (COM.IndexusMessage multiMsg = new COM.IndexusMessage(
																			COM.Handler.Unique.NextUniqueId(), msg.Status, msg.Action, msg.ItemPriority,
																			msg.Hostname, msg.Expires, item.Key, item.Value
																		)
																	)
														{
															// update cleanup list with new object
															CacheCleanup.Update(multiMsg);
														}
													}

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Payload = null;
													msg.Status = COM.IndexusMessage.StatusValue.Response;

													// send object back throug the connection
													this.SendResponse(state, msg);

													#region rschuetz: MODIFIED: 21-07-2007: distribute object over wire to other installations
													// Question is if the client needs to wait until this happens,
													// or should the client first get an answer and just then it
													// will distribute it.
													if (ServiceLogic.NetworkDistribution.ReplicationEnabled && msg.Status != COM.IndexusMessage.StatusValue.ReplicationRequest)
													{
														ServiceLogic.NetworkDistribution.Replicate(replicationMessage);
													}
													#endregion
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												finally
												{
													// handle max size and purge issues
													if (this.cacheAmountOfObjects != -1 && this.cacheAmountOfObjects <= LocalCache.CalculatedCacheSize && !CacheCleanup.PurgeIsRunning)
													{
#if DEBUG
														if (writeStats)
														{
															Console.WriteLine(@"Current Size of Cache: {0} ; {1} ", LocalCache.CalculatedCacheSize, LocalCache.CalculatedCacheSize <= 0 ? 0 : LocalCache.CalculatedCacheSize / (1024 * 1024));
														}
#endif
														List<string> remove = CacheCleanup.Purge(LocalCache.CalculatedCacheSize);
														if (remove != null)
														{
															lock (bulkObject)
															{
																foreach (string s in remove)
																{
																	LocalCache.Remove(s);
																}
															}
														}
													}
												}
												break;
												#endregion Adding a bunch of data
											}
										case COM.IndexusMessage.ActionValue.MultiDelete:
											{
												#region Remove a bunch of data
												try
												{
													#region Stats
#if DEBUG
													if (writeStats)
													{
														Console.WriteLine("MultiDelete Object with Key: {0}, current Cache amount: {1}", msg.Key, LocalCache.Amount());
													}
#endif
													#endregion Stats

													List<string> requstedDataToDelete = COM.Formatters.Serialization.BinaryDeSerialize<List<string>>(msg.Payload);

													foreach (string key in requstedDataToDelete)
													{
														// remove it from the cache.
														LocalCache.Remove(key);
														if (this.expire != null)
														{
															// remove it from the cache expiry job.
															this.expire.Expire.Remove(key);
														}
														// update cleanup list
														CacheCleanup.Remove(key);
													}

													msg.Action = COM.IndexusMessage.ActionValue.Successful;
													msg.Status = COM.IndexusMessage.StatusValue.Response;
													msg.Payload = null;
													this.SendResponse(state, msg);
												}
												catch (Exception ex)
												{
													using (COM.IndexusMessage resultMsg = new COM.IndexusMessage())
													{
														resultMsg.Action = COM.IndexusMessage.ActionValue.Error;
														resultMsg.Status = COM.IndexusMessage.StatusValue.Response;
														resultMsg.Payload = COM.Formatters.Serialization.BinarySerialize(
															new COM.CacheException(msg.Action.ToString(), msg.Action, msg.Status, ex)
														);

														this.SendResponse(state, resultMsg);
													}
												}
												break;

												#endregion Remove a bunch of data
											}

									}
									break;
									#endregion request case
								}
								finally
								{
									// msg is not needed anymore and since its implmente IDisposable it can be disposed at this place
									if (msg != null)
									{
										msg.Dispose();
									}
								}

							}
						case COM.IndexusMessage.StatusValue.Response:
							{
								#region response case
#if DEBUG
								if (writeStats)
								{
									Console.WriteLine("Received Action: {0}", msg.Status.ToString());
								}
#endif
								// Server never should receive a Response from the client!
								msg.Action = COM.IndexusMessage.ActionValue.Error;
								string info = string.Format("[{0}]Error, the message should have the Status Request!", state.WorkSocket.RemoteEndPoint);
								Console.WriteLine(info);
								COM.Handler.LogHandler.Traffic(info);
								COM.Handler.LogHandler.Error(info);
								break;
								#endregion response case
							}
					}
				}
			}
			else
			{
				COM.Handler.LogHandler.Error("Cannot handle state because state is NULL");
				Console.WriteLine("Cannot handle state because state is NULL");
			}
		}

		/// <summary>
		/// Sends the response.
		/// </summary>
		/// <param name="state">The state.</param>
		/// <param name="response">The response.</param>
		private void SendResponse(COM.Sockets.SharedCacheStateObject state, COM.IndexusMessage response)
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			// adding the protocol header !!!! very important
			byte[] arr = COM.Handler.UtilByte.CreateMessageHeader(response.GetBytes());

			// manage first state object values before sending back data;
			state.DataBigBuffer = arr;
			state.MessageLength = arr.LongLength;

			// start async send
			this.Send(state);
		}

		/// <summary>
		/// Sends the specified state.
		/// </summary>
		/// <param name="state">The state.</param>
		private void Send(COM.Sockets.SharedCacheStateObject state)
		{
			#region Access Log
#if TRACE

			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			if (state != null)
			{
				if (state.WorkSocket != null)
				{
					Socket socket = state.WorkSocket;
					if (state.DataBigBuffer != null && state.DataBigBuffer.Length > 0)
					{
						// Thread.Sleep(1);

						// todo: count is not good to use since its a int and not long value!!!
						socket.BeginSend(state.DataBigBuffer, 0, state.DataBigBuffer.Length, 0,
							new AsyncCallback(this.SendCallback), state);
					}
					else
					{
						// handler is now ready to receive more data from client
						//TimeSpan sp = DateTime.Now.Subtract(state.AliveTimeStamp);
						//Console.WriteLine("Send:" + sp.TotalMilliseconds);

						state.ReadHeader = true;
						state.AliveTimeStamp = DateTime.Now;
						state.AlreadySent = 0;
						state.DataBigBuffer = null;// new byte[COM.Sockets.SharedCacheStateObject.BufferSize * 2];
						state.MessageLength = 0;
						state.AlreadyRead = 0;

						socket.BeginReceive(state.Buffer, 0, COM.Sockets.SharedCacheStateObject.BufferSize, 0,
							new AsyncCallback(this.ReadCallback), state);
					}
				}
				else
				{
					Console.WriteLine(@"State worker socket is NULL");
					COM.Handler.LogHandler.Error(@"State worker socket is NULL");
				}
			}
			else
			{
				Console.WriteLine("Cannot handle state because state is NULL");
				COM.Handler.LogHandler.Error("Cannot handle state because state is NULL");
			}
		}

		/// <summary>
		/// Sends the callback.
		/// </summary>
		/// <param name="ar">The ar.</param>
		private void SendCallback(IAsyncResult ar)
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			COM.Sockets.SharedCacheStateObject state = ar.AsyncState as COM.Sockets.SharedCacheStateObject;
			if (state != null)
			{
				Socket handler = state.WorkSocket;
				if (handler != null)
				{
					try
					{

						int sent = handler.EndSend(ar);
						// Console.WriteLine(@"Sent: {0}", sent);
						state.AlreadySent += (long)sent;
						if (state.AlreadySent < state.MessageLength)
						{
							// send the next bunch of data until
							handler.BeginSend(state.DataBigBuffer, (int)state.AlreadySent,
								state.DataBigBuffer.Length, 0, new AsyncCallback(this.SendCallback), state);
						}
						else
						{
							//TimeSpan sp = DateTime.Now.Subtract(state.AliveTimeStamp);
							//Console.WriteLine("SendCallback:" + sp.TotalMilliseconds);
							// handler is now ready to receive more data from client
							state.ReadHeader = true;
							state.AliveTimeStamp = DateTime.Now;
							state.AlreadySent = 0;
							state.DataBigBuffer = null; // new byte[COM.Sockets.SharedCacheStateObject.BufferSize * 2];
							state.MessageLength = 0;
							state.AlreadyRead = 0;

							handler.BeginReceive(state.Buffer, 0, COM.Sockets.SharedCacheStateObject.BufferSize, 0,
								new AsyncCallback(this.ReadCallback), state);
						}
					}
					catch (SocketException sEx)
					{
						COM.Handler.LogHandler.Force(string.Format("[{0}] Socket ErrorCode:{1}\n SocketErrorCode:{2}\nMessage: {3}", state.WorkSocket.RemoteEndPoint.ToString(), sEx.ErrorCode, sEx.SocketErrorCode.ToString(), sEx.Message));
					}
					catch (Exception ex)
					{
						COM.Handler.LogHandler.Error(ex);
						Console.WriteLine("Exception: {0}", ex.Message);
					}
				}
				else
				{
					COM.Handler.LogHandler.Force(@"Socket is NULL and cannot send data to client back!!!");
				}
			}
			else
			{
				COM.Handler.LogHandler.Force(@"State is NULL!!!");
				Console.WriteLine(@"State is NULL!!!");
			}
		}

		/// <summary>
		/// Checks connected sockets.
		/// </summary>
		/// <param name="eventState">State of the event.</param>
		private void CheckSockets(object eventState)
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			this.lostTimer.Change(Timeout.Infinite, Timeout.Infinite);
			try
			{
				ArrayList arr = new ArrayList(this.conntectedSockets);

				foreach (COM.Sockets.SharedCacheStateObject state in arr)
				{
					if (state.WorkSocket == null)
					{
						// remove invalid state object
						try
						{
							lock (this.conntectedSockets)
							{
								if (this.conntectedSockets.Contains(state))
								{
									this.conntectedSockets.Remove(state);
									Interlocked.Decrement(ref socketCount);
								}
							}
						}
						catch (Exception ex)
						{
							COM.Handler.LogHandler.Error(@"Problem to cleanup", ex);
						}
					}
					else
					{
						if (DateTime.Now.AddTicks(-state.AliveTimeStamp.Ticks).Minute > timeoutMinutes)
						{
							this.RemoveSocket(state);
						}
					}
				}
			}
			catch (Exception ex)
			{
				COM.Handler.LogHandler.Error(@"Problem to cleanup", ex);
			}
			finally
			{
				lostTimer.Change(TcpServer.timerTimeout, TcpServer.timerTimeout);
			}
		}

		/// <summary>
		/// Removes socket
		/// </summary>
		/// <param name="state">The state.</param>
		private void RemoveSocket(COM.Sockets.SharedCacheStateObject state)
		{
			#region Access Log
#if TRACE
			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			Socket sock = state.WorkSocket;
			try
			{
				lock (this.conntectedSockets)
				{
					if (this.conntectedSockets.Contains(state))
					{
						this.conntectedSockets.Remove(state);
						Interlocked.Decrement(ref this.socketCount);
					}
				}

#if DEBUG
				Console.WriteLine("Connection Count {0}", this.socketCount);
#endif

			}
			catch (Exception ex)
			{
#if DEBUG
				Console.WriteLine("Excpetion: " + ex);
#endif
				if (1 == COM.Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.LoggingEnable)
				{
					COM.Handler.LogHandler.Error("Exception in RemoveSocket", ex);
				}
			}

			try
			{
				lock (this.conntectedHt)
				{
					if (sock != null && (this.conntectedHt.ContainsKey(sock)))
					{
						object socketTemp = this.conntectedHt[sock];
						if (this.conntectedHt.ContainsKey(socketTemp))
						{
							if (this.conntectedHt.ContainsKey(this.conntectedHt[socketTemp]))
							{
								this.conntectedHt.Remove(sock);
								if (sock.Equals(this.conntectedHt[socketTemp]))
								{
									this.conntectedHt.Remove(socketTemp);
								}
								else
								{
									object value, key = socketTemp;
									while (true)
									{
										value = this.conntectedHt[key];
										if (sock.Equals(value))
										{
											this.conntectedHt[key] = socketTemp;
											break;
										}
										else if (this.conntectedHt.ContainsKey(value))
										{
											key = value;
										}
										else
										{
											// chain is broken.
											break;
										}
									}
								}
							}
							else
							{
								COM.Handler.LogHandler.Info("Socket is not in connected Hash table");
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("Excpetion: " + ex);
			}

			try
			{
				if (sock != null)
				{
					sock.Shutdown(SocketShutdown.Both);
					// sock.Close();
					if (sock != null)
						sock = null;
					// shutdown the state
					state = null;
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("Excpetion: " + ex);
			}
		}
		#endregion Private Methods
		#endregion Async TCP Connection Handling

		#region Override Methods
		/// <summary>
		/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
		/// </returns>
		public override string ToString()
		{
			#region Access Log
#if TRACE

			{
				COM.Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
			}
#endif
			#endregion Access Log

			StringBuilder sb = new StringBuilder();

			#region Override ToString() default with reflection
			Type t = this.GetType();
			PropertyInfo[] pis = t.GetProperties();
			for (int i = 0; i < pis.Length; i++)
			{
				try
				{
					PropertyInfo pi = (PropertyInfo)pis.GetValue(i);
					COM.Handler.LogHandler.Info(
					string.Format(
					"{0}: {1}",
					pi.Name,
					pi.GetValue(this, new object[] { })
					)
					);
					sb.AppendFormat("{0}: {1}" + Environment.NewLine, pi.Name, pi.GetValue(this, new object[] { }));
				}
				catch (Exception ex)
				{
					COM.Handler.LogHandler.Error("Could not log property. Ex. Message: " + ex.Message);
				}
			}
			#endregion Override ToString() default with reflection

			return sb.ToString();
		}

		#endregion Override Methods
	}
}

redpajama_set_name: RedPajamaGithub


text:
Q: ` __webpack_require__(...) is not a function` when using babel 6 Everything seems to build fine: http://d.pr/i/1aZxR
with the following configs.
However, when I run the code I get the following error this (via webpack-dev-server):
Uncaught TypeError: __webpack_require__(...) is not a function(anonymous function) @ login.js:4__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ bootstrap.js:2363__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50(anonymous function) @ app.38790ff45722f55eb700.js:29__webpack_require__ @ bootstrap 38790ff45722f55eb700?6a08:50webpackJsonpCallback @ bootstrap 38790ff45722f55eb700?6a08:21(anonymous function) @ app.38790ff45722f55eb700.js:1
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.7/$injector/nomod?p0=app
    at http://localhost:3000/vendor.js:193:13
    at http://localhost:3000/vendor.js:2111:18
    at ensure (http://localhost:3000/vendor.js:2035:39)
    at module (http://localhost:3000/vendor.js:2109:15)
    at http://localhost:3000/vendor.js:4515:23
    at forEach (http://localhost:3000/vendor.js:461:21)
    at loadModules (http://localhost:3000/vendor.js:4499:6)
    at createInjector (http://localhost:3000/vendor.js:4424:12)
    at doBootstrap (http://localhost:3000/vendor.js:1782:21)
    at bootstrap (http://localhost:3000/vendor.js:1803:13)
http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=app&p1=Error%3A%20%…%20at%20bootstrap%20(http%3A%2F%2Flocalhost%3A3000%2Fvendor.js%3A1803%3A13)(anonymous function) @ angular.js:68(anonymous function) @ angular.js:4413forEach @ angular.js:336loadModules @ angular.js:4374createInjector @ angular.js:4299doBootstrap @ angular.js:1657bootstrap @ angular.js:1678angularInit @ angular.js:1572(anonymous function) @ angular.js:28899fire @ jquery.js:3099self.fireWith @ jquery.js:3211jQuery.extend.ready @ jquery.js:3417completed @ jquery.js:3433

I think babel is interfering with __webpack_require__ in some way but I'm not sure. I did try using different transforms/plugins but I wasn't able to find a solution.
.babelrc:
{
  "plugins":[
    "transform-runtime",
    "transform-node-env-inline"
  ],
  "presets":[
    "stage-0",
    "es2015"
  ]
}

here's my webpack.config.js:
var Clean = require('clean-webpack-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
var path = require('path');
var StatsPlugin = require('stats-webpack-plugin');
var webpack = require('webpack');

//CONSTANTS

var NODE_ENV = process.env.NODE_ENV;
var IS_DEV = NODE_ENV === 'development';
var babelFile = fs.readFileSync('./.babelrc', 'utf8');
var BABELRC = JSON.parse(babelFile);
var cleanFonts = function(){
  return new Clean(['dist/tmp/*.{ttf,eot,svg,woff}']);
}
var cleanImages = function(){
  return new Clean(['dist/tmp/*.{png,jpg}']);
}
var cleanJs = function(){
  return new Clean(['dist/*.{js,map}']);
}
var plugins = [
  new webpack.NoErrorsPlugin(),
  cleanJs(),
  // new StatsPlugin('stats.json', {chunkModules: true}),
  new webpack.ProvidePlugin({$: "jquery",jQuery: "jquery","window.jQuery": "jquery" }),
  new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
  new HtmlWebpackPlugin({
    template: 'client/app/vendors/assets/index-tmpl.html',
    filename: 'index.html'
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'vendor.js',
    chunks:['customer','personalOrganization','app']
  })
  // new ngAnnotatePlugin({add: true})
  // new ExtractTextPlugin("style.[hash].css", {
  //    disable: false,
  //    allChunks: true
  // }),

  //new webpack.optimize.CommonsChunkPlugin({minChunks: 2, children: true, async: true}),
  // new CompressionPlugin({asset: "{file}.gz", algorithm: "gzip", regExp: /\.js$|\.html$/, threshold: 10240, minRatio: 0.8 })
];
var dev_plugins = [
]
var prod_plugins = [
  cleanFonts(),
  cleanImages(),
  new webpack.optimize.UglifyJsPlugin({
    minimize: true,
    sourceMap: false,
    compress: { warnings: false },
    mangle: false
  }),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.AggressiveMergingPlugin()
];
if(NODE_ENV !== 'development'){
  plugins = plugins.concat(prod_plugins);
}
else{
  plugins = plugins.concat(dev_plugins);
}
babelLoaderOpts = {
  cacheDirectory: true
};
Object.assign(babelLoaderOpts, BABELRC);
module.exports = {
  cache: IS_DEV,
  // watch: IS_DEV,
  devtool: 'source-map',
  entry: {
    "app": "./client/app/app.js",
    "devserver": 'webpack-dev-server/client?http://localhost:3000'
  },
  output: {
      path: __dirname + "/dist",
      filename: '[name].[hash].js'
  },
  module: {
        noParse: [
          /moment.js/
        ],
        loaders: [
            { test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
            {
              test: /\.js$/,
              exclude: /(node_modules|bower_components|vendors)/,
              loader: 'babel',
              query: babelLoaderOpts
            },
            { test: /\.html$/, loader: 'raw' },
            { test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded"+"&includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")},
            { test: /\.css$/,  loader: 'style!css' },
            { test: /\.(png|jpeg|jpg|gif)$/, loader: 'url-loader?limit=30000&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff(\?\S*)?$/,  loader : 'url?prefix=font/&limit=10000&mimetype=application/font-woff&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.woff2/, loader: 'url?prefix=font/&limit=100000&mimetype=application/font-woff2&name=tmp/[name].[ext]&no_emit_env=development' },
            { test: /\.ttf/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.eot/,   loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            { test: /\.svg/,loader : 'file?prefix=font/&name=tmp/[name].[ext]&no_emit_env=development'},
            //{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true&&includePaths[]='+ path.resolve(__dirname, './node_modules/compass-mixins/lib')) },
            //{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
      ]
  },
  devServer: {
    contentBase: './client/app'
  },
  resolve: {
      modulesDirectories: ['vendors','node_modules', 'bower_components'],
      extensions: ['', '.js', '.json']
  },
  plugins: plugins
};

A: I had the same error. When dealing with es6 modules, you should use require(...).default
For instance:
const angular = require('angular');
const ngModule = angular.module('app', []);
require('./directives').default(ngModule);
// or
var kgdir = require('./directives').default;
kgdir(ngModule);

However, babel-plugin-add-module-exports should also work.
You can check out this page: github webpack issues 1685

A: I had a similar issue after updating to Babel 6 in my webpack-dev-server entry file. As mentioned by @Serhey in the comments, I resolved my issue by switching from require to import, i.e., require('./devTools)(store); to import devTools from './devTools'; devTools(store);

A: I believe the proposed solutions to switch from require to import are not correct. Imports need to happen at the top of the file and therefor you can't have your production build omit the devtools. You want a conditional require.
I think babel-plugin-add-module-exports solves the problem. Have a look at this react-redux-starter-kit to see how it's used in a project.

A: I had the same issue. The solution was to switch from require statements, such as
let fs = require("fs");

to imports via
import * as fs from 'fs';

You can also expose all Node modules via the externals array in your webpack config. Since they are provided through the Webpack externals, one does not have to require them but use them with imports.
module.exports = {
   "externals": {
      "electron": "require('electron')",
      "child_process": "require('child_process')",
      "fs": "require('fs')",
      "path": "require('path')",
      ...
   }
}

You can read more about this problem in my article.

A: I'd like to add another reason why this error might pop up:
I did the following:
import mapActions from 'vuex'

instead of:
import { mapActions } from 'vuex'

The former was importing the entire vuex export, which is an object. Adding object destructuring fixed the problem.

A: My case is just the reverse of the answer given by @William above.
Including {} in
 import mapActions from 'vuex'
 helped me.
As:
import { mapActions } from 'vuex'

A: I solved a similar issue by adding a missing loader into my webpack.config. No idea why this solves the issue, but you may want to see if you're missing a loader as well.
(Just to be clear - I originally found out that problem was with a loader when I downgraded the library causing the issue to an earlier version. Webpack error messages said that a json loader was missing, so I added the following to my config, and then was able to go back to the newest version:
module:{
loaders : [
  {
      test: /\.json$/,
      loader: "json-loader"
    }
]
}

)

A: I had this issue with my webpack because i was building my project for both web and node and I was using isomorphic-unfetch in both the entry.
I fixed it by replacing isomorphic-unfetch with the appropriate fetch: unfetch for web & node-fetch for nodejs
webpack.config.js
module.exports = [
  {
    entry: ['unfetch', 'regenerator-runtime/runtime', './lib/app.js'],
    ...
  },
  {
    entry: ['node-fetch', 'regenerator-runtime/runtime', './lib/app.js'],
    target: 'node',
    ...
  },
];

redpajama_set_name: RedPajamaStackExchange


text:
Finals not automatic for U.S., Canadian women
by Jon Lane
Prior to Canada's preliminary game against the United States last week at the 2014 Sochi Olympics, goalie Charline Labonte referred to the greatly anticipated match between two of international women's hockey hottest rivals as "our Stanley Cup." The intensity of Canada's 3-2 win against the U.S. was equivalent to a gold medal game or a Game 7 of the Stanley Cup Final, and whetted appetites for a golden rematch from the 2010 Vancouver Olympics.
It's widely expected that the Canadian and American women will meet again with everything on the line, so it's been easy to overlook their respective semfinal opponents, Switzerland and Sweden. Feb. 17, 2006 at the Torino Games is a reminder that anything can happen to detour those best-laid plans. It's a night Sweden cherishes to this day and one the Americans find impossible to forget even if they tried.
Sweden's 3-2 shootout win put it and not the U.S. into the final against Canada, a shocking upset considering the Americans had outscored the Swedes 68-12 in the previous nine games between the two over a 16-year span.
"I remember that too," U.S. head coach Katey Stone told reporters. "That's in the past. It's time to make the future."
Come Monday, there will be laser-like focus on the present from the U.S. and Canada in the semifinals that begin with the U.S. facing Sweden (7:30 a.m. ET, NBCSN). If there is any doubt the Swedes take great pleasure in playing the spoiler's role, look no further than when they stunned archrival Finland 4-2 in the quarterfinals on Saturday behind Emma Eliasson's power-play goal with 4:15 left in regulation. Sweden goalie Valentina Wallner outplayed her counterpart, Noora Raty, and her teammates barely gave the Finns time to breathe.
"They play a great game through the neutral zone," Stone told USAHockey.com. "They handle the puck well, are patient and their goaltender plays well behind them, so we have to be ready."
Despite their penchant for upsets, the odds are against the Swedes on Monday. In two international games since Torino, the United States earned 9-1 wins each time. But, after seeing what Sweden did to Finland, the Americans know another date with Canada is far from 100 percent guaranteed.
"You play so many games and anyone can beat anyone," U.S. captain Meghan Duggan said. "You think back to 2006 and Sweden beat the U.S. You think back earlier in the year and Finland beat us [at the Four Nations Cup]."
Canada continued its unbeaten run through the Sochi Games against the U.S. on Feb. 12 behind two Meghan Agosta-Marciano goals that stretched the Canadians' Olympics winning streak to 18 games. Canada will face a Switzerland team Monday (12 p.m. ET, MSNBC) that grinded out a 2-0 win against Russia to move into the semifinals.
It was Switzerland's first victory following a tough run in Group A, which included a 5-0 loss to Canada in the opener. Swiss goalie Florence Schelling made 41 saves against Russia and a whopping 64 the first time against Canada.
"It seems strange to say we only lost 5-0, but we were pleased that we showed some of our game as well," Swiss forward Stefanie Marty said. "This won't be a game where we are happy to just to turn up -- we want to score on Canada, we want to give our best. We know what Canada can do, but we play better as an underdog."

redpajama_set_name: RedPajamaCommonCrawl


Hi, it's Sandy, and I'm here with Leo, my brother and Alene's other boy, waiting for the coroner. Her Blogger page was still open so I thought I'd use it to let friends know what happened, probably on Monday night, and why we're here. After that, well I don't know Alene's password, so when I sign off on this it will be, so to speak, the last post for Alene. After that, no way of getting back into the blog again.
We found her, well, the Emergency boys actually found her, about two hours ago. Alarm goes off, neighbours report it, neighbours report it again, door gets kicked in, and there she is, stretched out on the floor, quite dead, with her head in the oven. She must have been a bit glum when she did it. It's an all electric house.
Paint is ruined from the smoke ($4000) and the house smells like Sunday roast. New stove ($1000)? Nah, buyers don't really need to know what's been cooking and we all don't hear the timer every now and again. Alene's proved that the oven works a treat, though. And for the replacement door, maybe a leadlight kookaburra, or some Federation-faux gum leaves and boomerangs ($800-$2500). Presentation, that's what moves a house at top dollar ($750K to $900K). Sorry seagrass, Bali puppets, Krishna and the cow maidens on the wall, it's time to go! Polished wood and sconces, that's the shot. Take out the Rheem and put in a woodchip donkey heater. Burns renewables, and your Seddon sorts like that, and it will cut the number of baths, too, because the water takes so long to heat. They will like that as well. No Dams! Wild Rivers Say No Salinity etc!. Yes indeed, maybe it will make a million with any luck.
LOOK, it's Leo here now, and I've taken the keyboard away from my brother because he makes this all sound flippant. It's not. It's horrible finding Mum like this. And she was a vegetarian too. But Sandy is like that and means no disrespect. It's the way we were brought up, as she explained in one of her last contributions to the SMH. You may have seen it.
As a "first wave" feminist and single mother, I raised my boys in a way that transgressed the gender norms and stereotypes that dominated the sixties. No toy guns or access to violence-themed superhero figures, limited "play exposure" to recreational aids that encouraged unthinking acceptance of the proposition that only the "hard" sciences and macho occupations -- firemen, cowboy, policemen etc -- were fit goals. Instead, the emphasis was on nurturing, empathetic and consensus-driven goals. At the beach, for example, we didn't make sand castles and then destroy them. Instead, we would have fun laying out sand gardens and making them bloom with "flowers" made out of icy pole sticks and rubbish we collected. This also helped introduce them to environmental principles.
Well that was decades ago and, even if I say so myself, the sandpit policy has worked. When each was an adolescent, both were felt free to be entirely open about their sexuality. There was no anguish about coming out of the closet for either Sandy or Leo because they were never in the closet to begin with.
Today the eldest is a happy, well adjusted figure in the art world and the youngest, who has just adopted a Congolese orphan with his partner, has made me a grandma.
We can change the world, us mothers. One person, one attitude, one generation at a time.
She was a beautiful person, Alene, always there with a smile and never a harsh word. Opinionated, but then aren't we all? And who is to decide if one idea is more sensible than any other? Don't discriminiate. Do not judge, that was her creed. We'll play "Imagine" at the funeral. It is a beautiful hymn and she always said it gave her such pride in believing in not believing in so many different things. No wonder the kiddies still love it in their music classes.
As far as we can tell, it was Media Watch and Jonathan Holmes that set the thermostat, so to speak. She was calling both Sandy and myself all day, saying we should come over, watch the show and try a new snack, something fishy with tahini and lemon that she was whipping up. There was going to be something very big, something Holmes was going to do for her, some injustice he was going to expose. Who knows what it was this time? Mum was always crusading for something.
Anyway, it was all such a mix-up! I thought Sandy was going over here and he thought I was going, so neither of us went over and Alene was here all alone. I can't tell you how often that happened. We were a pair of slack sausages when it came time to see a little of Mum. And now she has gone. Forever. But I think she was happy until right at the end, whenever whatever it was on Media Watch tipped her over the edge.
She could change like that, did it all the time in fact. I remember when we were kids how she agreed with Gough about keeping out those "slit-eyed Balts". And then, when Howard was in, she howled about the desert concentration camps and would have gone to Woomera and torn down the wire if only she could have left the house. Same with Timor and the carbon tax and the US alliance and how she loved Kevin one day and adored Julia the next. Always changing, always evolving in what Mum used to say was "the appropriate way". Just like Julia, actually, when you think about it.
What did it for Mum neither Sandy nor I can really know, despite page after page of the notes she made about what was on the ABC that night. Can anyone make heads or tails out of it? I don't think the first line is sexual or has anything to do with the warts (who knew!!!), but I really can't be sure.
ABC building up to Media Watch climax for me in grand style as Four Corners covers Japanese nuclear catastrophe. Fighting words from Friends of Earth, Nautilus Institute, Australian Conservation Foundation, and maybe the Seahorse Society too, or was that another item about Helen Caldicott's brother? I get confused. Not a pro-nuker or a denier on the show though. How good! Keep swinging, Aunty. We have a carbon tax to pass.
Finally, it's on! Media Watch – and there's Jonathan H. Had earthquake in NZ and they're still screwed, apparently. What losers, putting sheep dip ads or whatever on our national broadcaster.
My item must be next.
Climate change..climate change … climate..change … Jonathan just won't shut up. Yes, the climate modelers ARE heroes, Jonathan, we know that. But PLEEEZE go get a room after the show. My item next, surely?
And here is where the notes go very, very strange.
Now its Q&A and the ABC is pulling out all the stops. Nothing but Greens and Youth Climate Kids in the audience. Beautifully, beautifully stacked. ABC at its best.
Hear those cheers? Every syllable from Christine gets applause. And Pyne? Bring on that libidinous dog. More cheers for wind and tidal. That will scare the protesty old men who hate our planet! This tax is going to be so popular we're going to gain many, many seats. Big girls like Julia need two, just for herself. Ad campaign to obliterate Libs. Millions well spent.
Won't be here to see it, I'm afraid.
ABC stacked against me. I AM NOT CHRISTOPHER PYNE!!!! Please listen, please.
TEARS. Ink runs like life force down the page.
Every show tonight a wonderful, example of appropriate, responsible journalism, but not a word about the Drum's injustice to me. Or how the editor broke his word and destroyed an article that would have turned NSW voters against the Liberals, as we agreed. Not a word.
If even Jonathan is against me, what's the point?
That is where it ends. Where Mum ended too.
Oh well, that's it. House goes on the market and we better get the fixes done before the carbon tax starts to figure in the tradies bills'. Frankly it would have been much more considerate if Mum had done this last year.
Vale, Alene. I'm sure you're in a better place.
PS: In your next life, try a rope. That can be recycled, unlike electricity. Not to mention all that carbon that went towards your demise.
RIP, Alena, you beautiful soul.
I hope that the oven wasn't damaged.
Thus ends the most awesome piss-take in Australia's history, I tip my hat to you.
Sandy and Leo, I feel your pain you dear sweet children. Oh! How I also feel the pain.
take solace in that I'm sure Mother Composta will live on in the memories of all of her adoring carbon tax loving readers, just as we remember Mark Latham even today (albeit he tends to be a bit more lively).
I will think of Alene especially this Saturday evening and will burn an extra dozen candles in her honour.
Alene, I salute you. Ashes to ashes.
Absolutely tragic yet somehow heart warming. One question though. Was Alene fully or half-baked? What I mean is, could she rise again, warts and all? So to speak. I shall put out my best Navajo Dream Catcher for her. No, really. Colonel Neville.
Ps. Could this be an inside job? They always are.
'Real' or a sock puppet (I suspect more of the former than the latter), you've evidently been hurt by recent events and I empathise.
Your identity is irrelevant: you write well, you have useful stuff to say and you offer some fresh perspectives – just express yourself.
For what it's worth, I reckon you're at your best writing about what's going on in the world – rather than obsessing about hooking up with elite lefties, whose carbon footprints all too often betray them.
Be yourself. Be true to yourself. Win.
Sandy, Leo, I think a beautiful tribute to your mother would be a GREEN FUNERAL. Your loving, indiscriminate life-giver would have known about Labor MLA Carryn Sullivan and her crusade.
Like your peaceful, Gaia-worshipping mum, I'm not one to tell anyone else what to do, but in keeping with caring for the environment above all else, I'm telling you: DO NOT allow the traditional funeral/cremation industry to release toxins and carcinogens into our environment by allowing them access to our Alene.


Everyone needs to treat themselves to something a little bit luxurious every now and then, but it needn't always cost a bomb. There are clever ways to bring opulence closer to earth at a more reasonable price. Here are a few of our favourite hacks to help live out your extravagant side without breaking the bank!
Luckily you can get a lot of high quality inspired pieces that capture the same sense of style without the huge price tag. Places like John Lewis or Vertigo Interiors are a good place to start which looking for a price point product.
Napa Valley, California, has a beautiful vista of vineyards and is simple to get to on your private jet. Without the jet it will cost you around £500 and take about 16 hours from London airports. Once safely landed you can luxuriate in the warm Californian air by hopping on a balloon tour with Platypus followed by some delicious wines of the region for £325.
If you'd rather keep your feet firmly planted on the ground then you could take a trip over to a boutique wine shop and take a taste tour through the wines of South Africa, Italy or Spain. London's Humble Grape is selling tickets for such tastings at £45. English based wine shops are a bit easier to get to than Napa and if you want to take a bottle home it will travel a lot easier without baggage control.
Having a personalised registration plate is part and parcel of owning a high end car but can come with a hefty price tag. Own a Ferrari? Love Formula One? The F1 plate sold at £440,000 in 2008 if you're interested in going down a similar route.
You may prefer to keep a more low key look when cruising in your Corsa. For the subtler (and budget-constrained) folks looking for a plate that amuses them, personal registration specialist Click4Reg say "you can get a personalised plate with your initials in for as little as £200". . You never know, it may turn out as a big investment if a boy band with the same initials as your plate become megastars!
It would be lovely to attend Paris Fashion Week and sit on the FROW in order to buy our Spring/Summer wardrobes. It's more likely for most though that we may invest in one statement item from the big names like Chanel, for example one of their super fun shearling tote bags that will cost you just £4,985.
Go vintage, darlings. It may not be as cheap as it once was, with the overwhelming vintage trend that has swept our nation, but if you're willing to rummage you can find a classic Chanel bag for half the price of a brand spanking new one. If you can't stand the physical rummaging of vintage shops try your luck online at places like ASOS Marketplace.
If you have an unlimited budget when it comes to travel, things like booking in Advance, using hotel comparison sites or looking for deals are probably not something you need to think about and can just go straight to a luxury holiday provider for your trip, but to be honest we love finding deals for our family adventures.
If you are travelling as a family self catering is usually the best option and sites like Airbnb have some amazing and super stylish properties for less than that of a hotel. If you do want the luxury of a nice hotel using hotel comparison sites like Trivago are always useful to find the best deal as there can be huge differences in rates from providers. You can also look at cash-back sites before booking as you may even get some money back on your reservations. When it comes to transport always book in advance for the best rates and see if they offer any travel cards such a Two Together from National Rail which offers 33% off for a couple travelling together.
We have managed to find some great rates on high end hotels by comparing prices.
Great tips and I love that outfit you put together, you look amazing!
Good tips! I'm also a big fan of Eames. Love a bit of mid century interiors style. eBay is my friend when it comes to this!


Metro Police are looking for a man who robbed a convenience store near Lake Mead Boulevard and Torrey Pines Drive back in May.
According to police, the man walked into the store at around 3:20 a.m. May 21 and selected a beverage from one of the coolers. When he came to the counter, he threw the bottles of liquor at the clerk, jumped onto the counter and started hitting the clerk in the face.
The man then grabbed a plastic garbage bag from one of the garbage cans and filled it with cigarettes. He jumped back over the counter and left the store.
The man police are looking for is described as a white man between 26 and 27 years old. He is 5 foot 8 with a medium build. He has brown, short hair and is described as clean cut.
He was wearing a black hooded jacket with a checker pattern design, a black T-shirt, khaki cargo pants and black shoes with white bottoms. He was also wearing a black Chicago Bulls baseball cap.
Anyone with information about the robbery is asked to call Metro's Robbery Section at (702) 828-3591 or to remain anonymous, call Crime Stoppers at (702) 385-5555.