using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Csla;
using Csla.Data;

namespace VEPROMS.CSLA.Library
{
	#region Enum stuff
	public enum CheckOutType : int
	{
		Procedure = 0, Document = 1, DocVersion = 2, Folder = 3, Session = 4
	}
	#endregion
	#region SessionInfoList stuff
	public partial class SessionInfoList
	{
		[Serializable()]
		public class CanCheckOutItemCriteria
		{
			private int _ObjectID;
			public int ObjectID
			{ get { return _ObjectID; } }
			private CheckOutType _ObjectType;
			public CheckOutType ObjectType
			{ get { return _ObjectType; } }
			public CanCheckOutItemCriteria(int objectID, CheckOutType objectType)
			{
				_ObjectID = objectID;
				_ObjectType = objectType;
			}
		}
		private void DataPortal_Fetch(CanCheckOutItemCriteria criteria)
		{
			this.RaiseListChangedEvents = false;
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfoList.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "vesp_SessionCanCheckOutItem";
						cm.Parameters.AddWithValue("@ObjectID", criteria.ObjectID);
						cm.Parameters.AddWithValue("@ObjectType", criteria.ObjectType);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							IsReadOnly = false;
							while (dr.Read()) this.Add(new SessionInfo(dr));
							IsReadOnly = true;
						}
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfoList.DataPortal_Fetch", ex);
				throw new DbCslaException("SessionInfoList.DataPortal_Fetch", ex);
			}
			this.RaiseListChangedEvents = true;
		}
	}
	#endregion
	#region SessionInfo stuff
	public partial class SessionInfo
	{
		private Int64 _LastContentChange;
		public Int64 LastContentChange
		{
			get { return _LastContentChange; }
			set { _LastContentChange = value; }
		}
		private byte[] _LastChanged = new byte[8];
		public byte[] LastChanged
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("LastChanged", true);
				return _LastChanged;
			}
			set { _LastChanged = value; }
		}
		public string LastChangedString
		{
			get { return ContentInfo.FormatByteArray(_LastChanged); }
		}
		public Int64 LastChangedInt64
		{
			get { return Convert.ToInt64(LastChangedString, 16); }
		}
		public static SessionInfo BeginSession(string machineName, int processID)
		{
			try
			{
				SessionInfo tmp = DataPortal.Fetch<SessionInfo>(new BeginSessionCriteria(Volian.Base.Library.VlnSettings.UserID, machineName, processID));
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up SessionInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on SessionInfo.BeginSession", ex);
			}
		}
		private Dictionary<int, Int64> _ChangedContents;
		public Dictionary<int, Int64> ChangedContents
		{
			get { return _ChangedContents; }
			set { _ChangedContents = value; }
		}
		private Dictionary<int, Int64> _ChangedItems;
		public Dictionary<int, Int64> ChangedItems
		{
			get { return _ChangedItems; }
			set { _ChangedItems = value; }
		}
		public List<int> PingSession()
		{
			List<int> myList = new List<int>();
			SessionPing.Execute(this.SessionID);
			ChangedContents = SessionChangedContents.Execute(this.LastContentChange);
			ChangedItems = SessionChangedItems.Execute(this.LastContentChange);
			OwnerInfoList oil = OwnerInfoList.GetBySessionID(this.SessionID);
			foreach (OwnerInfo oi in oil)
				myList.Add(oi.OwnerID);
			return myList;
		}
		public void EndSession()
		{
			SessionEnd.Execute(this.SessionID);
		}
		public bool CanCheckOutItem(int objectID, CheckOutType objectType, ref string message)
		{
			try
			{
				SessionInfoList sil = DataPortal.Fetch<SessionInfoList>(new SessionInfoList.CanCheckOutItemCriteria(objectID, objectType));
				if (sil.Count == 0)
					return true;
        if (objectType == CheckOutType.Session)
        {
          if (sil.Count == 1)
          {
            OwnerInfoList oil = OwnerInfoList.GetBySessionID(sil[0].SessionID);
            if (oil.Count == 0)
              return true;
            else
            {
              message = "Export Procedure Set and Import Procedure Set are not available because you have open procedures or documents";
              return false;
            }
          }
          else
          {
            message = "Export Procedure Set and Import Procedure Set are not available because there are other sessions open in the database";
            return false;
          }
        }
				bool rv = true;
				foreach (SessionInfo si in sil)
				{
					//if (si.SessionID != this.SessionID  && objectType == CheckOutType.Procedure)
					if (si.ProcessID != this.ProcessID && objectType == CheckOutType.Procedure)
					{
						message = string.Format("The procedure {0} is already checked out to {1}", ItemInfo.Get(objectID).MyProcedure.DisplayNumber, si.UserID);
						rv = rv && false;
					}
					//else if (si.SessionID != this.SessionID && objectType == CheckOutType.Document)
					else if (si.ProcessID != this.ProcessID && objectType == CheckOutType.Document)
					{
						message = string.Format("The document {0} is already checked out to {1}", DocumentInfo.Get(objectID).DocumentEntries[0].MyContent.Text, si.UserID);
						rv = rv && false;
					}
					else if (si.SessionID != this.SessionID && objectType == CheckOutType.DocVersion)
					//else if (si.ProcessID != this.ProcessID && objectType == CheckOutType.DocVersion)
					{
						// gets here if other session has working draft open & click on sam working draft.
						OwnerInfo oi = OwnerInfo.GetBySessionIDandVersionID(si.SessionID, objectID);
						if (oi == null)
							message = message + string.Format("The working draft is already checked out to {0}", si.UserID) + Environment.NewLine;
						else if(oi.OwnerType == 0)
							message = message + string.Format("The procedure {0} is already checked out to {1}", ItemInfo.Get(oi.OwnerItemID).MyProcedure.DisplayNumber, si.UserID) + Environment.NewLine;
						else if (oi.OwnerType == 1)
							message = message + string.Format("The document {0} is already checked out to {1}", DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text, si.UserID) + Environment.NewLine;
						else if (oi.OwnerType == 2)
							message = message + string.Format("The working draft is already checked out to {0}", si.UserID);
						rv = rv && false;
					}
					else if (si.SessionID != this.SessionID && objectType == CheckOutType.Folder)
					//else if (si.ProcessID != this.ProcessID && objectType == CheckOutType.Folder)
					{
						// gets here if other session has working draft open & click on folder above. Gets here
						// if other session has wd open and click on top folder - query returns empty.
						OwnerInfo oi = OwnerInfo.GetBySessionIDandFolderID(si.SessionID, objectID);
						if (oi != null)
						{
							if (oi.OwnerType == 0)
								message = message + string.Format("The procedure {0} is already checked out to {1}", ItemInfo.Get(oi.OwnerItemID).MyProcedure.DisplayNumber, si.UserID) + Environment.NewLine;
							else if (oi.OwnerType == 1)
								message = message + string.Format("The document {0} is already checked out to {1}", DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text, si.UserID) + Environment.NewLine;
							else if (oi.OwnerType == 2)
								message = message + string.Format("The working draft is already checked out to {0}", si.UserID);
							else if (oi.OwnerType == 3)
								message = message + string.Format("The folder is already checked out to {0}", si.UserID);
							rv = rv && false;
						}
					}
				}
				return rv;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on SessionInfo.Get", ex);
			}
		}
		public int CheckOutItem(int itemID, CheckOutType itemType)
		{
			int ownerID = SessionCheckOutItem.Execute(this.SessionID, itemID, itemType);
			return ownerID;
		}
		public void CheckInItem(int ownerID)
		{
			SessionCheckInItem.Execute(ownerID);
		}
		private void DataPortal_Fetch(BeginSessionCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfo.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "vesp_SessionBegin";
						cm.Parameters.AddWithValue("@UserID", criteria.UserID);
						cm.Parameters.AddWithValue("@MachineName", criteria.MachineName);
						cm.Parameters.AddWithValue("@ProcessID", criteria.ProcessID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
						}
					}
					// removing of item only needed for local data portal
					if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
						ApplicationContext.LocalContext.Remove("cn");
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("SessionInfo.DataPortal_Fetch", ex);
			}
		}
		//private void DataPortal_Fetch(CanCheckOutItemCriteria criteria)
		//{
		//  if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfo.DataPortal_Fetch", GetHashCode());
		//  try
		//  {
		//    using (SqlConnection cn = Database.VEPROMS_SqlConnection)
		//    {
		//      ApplicationContext.LocalContext["cn"] = cn;
		//      using (SqlCommand cm = cn.CreateCommand())
		//      {
		//        cm.CommandType = CommandType.StoredProcedure;
		//        cm.CommandText = "vesp_SessionCanCheckOutItem";
		//        cm.Parameters.AddWithValue("@ObjectID", criteria.ObjectID);
		//        cm.Parameters.AddWithValue("@ObjectType", criteria.ObjectType);
		//        using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
		//        {
		//          while(dr.Read())
								
		//          if (!dr.Read())
		//          {
		//            _ErrorMessage = "No Record Found";
		//            return;
		//          }
		//          ReadData(dr);
		//        }
		//      }
		//      // removing of item only needed for local data portal
		//      if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
		//        ApplicationContext.LocalContext.Remove("cn");
		//    }
		//  }
		//  catch (Exception ex)
		//  {
		//    if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfo.DataPortal_Fetch", ex);
		//    _ErrorMessage = ex.Message;
		//    throw new DbCslaException("SessionInfo.DataPortal_Fetch", ex);
		//  }
		//}
		[Serializable()]
		protected class BeginSessionCriteria
		{
			private string _UserID;
			public string UserID
			{ get { return _UserID; } }
			private string _MachineName;
			public string MachineName
			{ get { return _MachineName; } }
			private int _ProcessID;
			public int ProcessID
			{ get { return _ProcessID; } }
			public BeginSessionCriteria(string userID, string machineName, int processID)
			{
				_UserID = userID;
				_MachineName = machineName;
				_ProcessID = processID;
			}
		}
		//[Serializable()]
		//protected class CanCheckOutItemCriteria
		//{
		//  private int _ObjectID;
		//  public int ObjectID
		//  { get { return _ObjectID; } }
		//  private CheckOutType _ObjectType;
		//  public CheckOutType ObjectType
		//  { get { return _ObjectType; } }
		//  public CanCheckOutItemCriteria(int objectID, CheckOutType objectType)
		//  {
		//    _ObjectID = objectID;
		//    _ObjectType = objectType;
		//  }
		//}
	}
  public class TurnChangeManagerOff : CommandBase
  {
    private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    #region Factory Methods
    public static void Execute()
    {
      TurnChangeManagerOff cmd = new TurnChangeManagerOff();
      DataPortal.Execute<TurnChangeManagerOff>(cmd);
    }
    #endregion
    #region Server-Side code
    protected override void DataPortal_Execute()
    {
      try
      {
        using (SqlConnection cn = Database.VEPROMS_SqlConnection)
        {
          using (SqlCommand cmd = new SqlCommand("vesp_TurnChangeManagerOFF", cn))
          {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = 0;
            cmd.ExecuteNonQuery();
          }
        }
      }
      catch (Exception ex)
      {
        if (_MyLog.IsErrorEnabled) _MyLog.Error("TurnChangeManagerOff Error", ex);
        throw new ApplicationException("Failure on TurnChangeManagerOff", ex);
      }
    }
    #endregion
  }
  public class TurnChangeManagerOn : CommandBase
  {
    private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    #region Factory Methods
    public static void Execute()
    {
      TurnChangeManagerOn cmd = new TurnChangeManagerOn();
      DataPortal.Execute<TurnChangeManagerOn>(cmd);
    }
    #endregion
    #region Server-Side code
    protected override void DataPortal_Execute()
    {
      try
      {
        using (SqlConnection cn = Database.VEPROMS_SqlConnection)
        {
          using (SqlCommand cmd = new SqlCommand("vesp_TurnChangeManagerON", cn))
          {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = 0;
            cmd.ExecuteNonQuery();
          }
        }
      }
      catch (Exception ex)
      {
        if (_MyLog.IsErrorEnabled) _MyLog.Error("TurnChangeManagerOn Error", ex);
        throw new ApplicationException("Failure on TurnChangeManagerOn", ex);
      }
    }
    #endregion
  }
  public class ResetSecurity : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#region Factory Methods
		public static void Execute()
		{
			ResetSecurity cmd = new ResetSecurity();
			DataPortal.Execute<ResetSecurity>(cmd);
		}
		#endregion
		#region Server-Side code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_ResetSecurity", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.ExecuteNonQuery();
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("Reset Security Error", ex);
				throw new ApplicationException("Failure on Reset Security", ex);
			}
		}
		#endregion
	}
	public class SessionPing : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private int _SessionID;
		public int SessionID
		{
			get { return _SessionID; }
			set { _SessionID = value; }
		}
		#region Factory Methods
		public static void Execute(int sessionID)
		{
			try
			{
			SessionPing cmd = new SessionPing();
			cmd.SessionID = sessionID;
			DataPortal.Execute<SessionPing>(cmd);
		}
			catch (Exception ex)
			{
				_MyLog.Warn("Session Ping Failure", ex);
			}
		}
		#endregion
		#region Server-Side code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_SessionPing", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.Parameters.AddWithValue("@SessionID", SessionID);
						cmd.ExecuteNonQuery();
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("Session Ping Error", ex);
				throw new ApplicationException("Failure on Session Ping", ex);
			}
		}
		#endregion
	}
	public class SessionEnd : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private int _SessionID;
		public int SessionID
		{
			get { return _SessionID; }
			set { _SessionID = value; }
		}
		#region Factory Methods
		public static void Execute(int sessionID)
		{
			SessionEnd cmd = new SessionEnd();
			cmd.SessionID = sessionID;
			DataPortal.Execute<SessionEnd>(cmd);
		}
		#endregion
		#region Server-Side code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_SessionEnd", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.Parameters.AddWithValue("@SessionID", SessionID);
						cmd.ExecuteNonQuery();
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("Session End Error", ex);
				throw new ApplicationException("Failure on Session End", ex);
			}
		}
		#endregion
	}
	public class SessionCheckOutItem : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private int _SessionID;
		public int SessionID
		{
			get { return _SessionID; }
			set { _SessionID = value; }
		}
		private int _ItemID;
		public int ItemID
		{
			get { return _ItemID; }
			set { _ItemID = value; }
		}
		private int _ItemType;
		public int ItemType
		{
			get { return _ItemType; }
			set { _ItemType = value; }
		}
		private int _OwnerID;
		public int OwnerID
		{
			get { return _OwnerID; }
			set { _OwnerID = value; }
		}
		#region Factory Methods
		public static int Execute(int sessionID, int itemID, CheckOutType itemType)
		{
			SessionCheckOutItem cmd = new SessionCheckOutItem();
			cmd.SessionID = sessionID;
			cmd.ItemID = itemID;
			cmd.ItemType = (int)itemType;
			cmd = DataPortal.Execute<SessionCheckOutItem>(cmd);
			return cmd.OwnerID;
		}
		#endregion
		#region Server-Side code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_SessionCheckOutItem", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.Parameters.AddWithValue("@SessionID", SessionID);
						cmd.Parameters.AddWithValue("@ItemID", ItemID);
						cmd.Parameters.AddWithValue("@ItemType", ItemType);
						SqlParameter parm = cmd.Parameters.AddWithValue("@OwnerID", 0);
						parm.Direction = ParameterDirection.Output;
						cmd.ExecuteNonQuery();
						OwnerID = (int)cmd.Parameters["@OwnerID"].Value;
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("Session End Error", ex);
				throw new ApplicationException("Failure on Session End", ex);
			}
		}
		#endregion
	}
	public class SessionCheckInItem : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private int _OwnerID;
		public int OwnerID
		{
			get { return _OwnerID; }
			set { _OwnerID = value; }
		}
		private int _ItemID;
		#region Factory Methods
		public static void Execute(int ownerID)
		{
			SessionCheckInItem cmd = new SessionCheckInItem();
			cmd.OwnerID = ownerID;
			DataPortal.Execute<SessionCheckInItem>(cmd);
		}
		#endregion
		#region Server-Side code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_SessionCheckInItem", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.Parameters.AddWithValue("@OwnerID", OwnerID);
						cmd.ExecuteNonQuery();
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("Session End Error", ex);
				throw new ApplicationException("Failure on Session End", ex);
			}
		}
		#endregion
	}
	public class SessionChangedContents : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private Int64 _LastContentChange;
		public Int64 LastContentChange
		{
			get { return _LastContentChange; }
			set { _LastContentChange = value; }
		}
		private Dictionary<int,Int64> _ChangedContents;
		public Dictionary<int, Int64> ChangedContents
		{
			get { return _ChangedContents; }
			set { _ChangedContents = value; }
		}
		#region Factory Methods
		public static Dictionary<int, Int64> Execute(Int64 lastContentChanged)
		{
			SessionChangedContents cmd = new SessionChangedContents();
			cmd.LastContentChange = lastContentChanged;
			cmd = DataPortal.Execute<SessionChangedContents>(cmd);
			return cmd.ChangedContents;
		}
		#endregion
		#region Server-Side Code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_ListContentsAfterLastChanged2", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.Parameters.AddWithValue("@LastChanged", LastContentChange);
						cmd.Parameters.AddWithValue("@UserID", Volian.Base.Library.VlnSettings.UserID);
						SqlDataReader dr = cmd.ExecuteReader();
						ChangedContents = new Dictionary<int, Int64>();
						while (dr.Read())
							ChangedContents.Add(dr.GetInt32(0), (Int64)dr.GetSqlInt64(1));
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionChangedContents Error", ex);
				throw new ApplicationException("Failure on SessionChangedContents", ex);
			}
		}
		#endregion
	}
	public class SessionChangedItems : CommandBase
	{
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		private Int64 _LastContentChange;
		public Int64 LastContentChange
		{
			get { return _LastContentChange; }
			set { _LastContentChange = value; }
		}
		private Dictionary<int, Int64> _ChangedItems;
		public Dictionary<int, Int64> ChangedItems
		{
			get { return _ChangedItems; }
			set { _ChangedItems = value; }
		}
		#region Factory Methods
		public static Dictionary<int, Int64> Execute(Int64 lastContentChanged)
		{
			SessionChangedItems cmd = new SessionChangedItems();
			cmd.LastContentChange = lastContentChanged;
			cmd = DataPortal.Execute<SessionChangedItems>(cmd);
			return cmd.ChangedItems;
		}
		#endregion
		#region Server-Side Code
		protected override void DataPortal_Execute()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cmd = new SqlCommand("vesp_ListItemsAfterLastChanged", cn))
					{
						cmd.CommandType = CommandType.StoredProcedure;
						cmd.CommandTimeout = 0;
						cmd.Parameters.AddWithValue("@LastChanged", LastContentChange);
						cmd.Parameters.AddWithValue("@UserID", Volian.Base.Library.VlnSettings.UserID);
						SqlDataReader dr = cmd.ExecuteReader();
						ChangedItems = new Dictionary<int, Int64>();
						while (dr.Read())
							ChangedItems.Add(dr.GetInt32(0), (Int64)dr.GetSqlInt64(1));
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionChangedItems Error", ex);
				throw new ApplicationException("Failure on SessionChangedItems", ex);
			}
		}
		#endregion
	}
	#endregion
	#region OwnerInfo stuff
	public partial class OwnerInfoList
	{
		public static OwnerInfoList GetBySessionID(int sessionID)
		{
			OwnerInfoList tmp = DataPortal.Fetch<OwnerInfoList>(new GetBySessionIDCriteria(sessionID));
			return tmp;
		}
		[Serializable()]
		protected class GetBySessionIDCriteria
		{
			private int _SessionID;
			public int SessionID { get { return _SessionID; } }
			public GetBySessionIDCriteria(int sessionID)
			{
				_SessionID = sessionID;
			}
		}
		private void DataPortal_Fetch(GetBySessionIDCriteria criteria)
		{
			this.RaiseListChangedEvents = false;
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfoList.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "getOwnersBySessionID";
						cm.Parameters.AddWithValue("@SessionID", criteria.SessionID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							IsReadOnly = false;
							while (dr.Read()) this.Add(new OwnerInfo(dr));
							IsReadOnly = true;
						}
					}
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfoList.DataPortal_Fetch", ex);
				throw new DbCslaException("OwnerInfoList.DataPortal_Fetch", ex);
			}
			this.RaiseListChangedEvents = true;
		}
    public static OwnerInfoList GetByVersionID(int versionID)
    {
			try
			{
				OwnerInfoList tmp = DataPortal.Fetch<OwnerInfoList>(new GetByVersionIDCriteria(versionID));
				return tmp;
			}
			catch (Exception ex)
			{
				if (ex.Message.Contains("Could not find stored procedure")) 
					System.Windows.Forms.MessageBox.Show("Have your DBA run the latest version of PROMSFixes.SQL", "SQL code is not current", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
				return null;
			}
    }
    [Serializable()]
    protected class GetByVersionIDCriteria
    {
      private int _VersionID;
      public int VersionID { get { return _VersionID; } }
      public GetByVersionIDCriteria(int versionID)
      {
        _VersionID = versionID;
      }
    }
    private void DataPortal_Fetch(GetByVersionIDCriteria criteria)
    {
      this.RaiseListChangedEvents = false;
      if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfoList.DataPortal_Fetch", GetHashCode());
      try
      {
        using (SqlConnection cn = Database.VEPROMS_SqlConnection)
        {
          using (SqlCommand cm = cn.CreateCommand())
          {
            cm.CommandType = CommandType.StoredProcedure;
            cm.CommandText = "getOwnersByVersionID";
            cm.Parameters.AddWithValue("@VersionID", criteria.VersionID);
            using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
            {
              IsReadOnly = false;
              while (dr.Read()) this.Add(new OwnerInfo(dr));
              IsReadOnly = true;
            }
          }
        }
      }
      catch (Exception ex)
      {
        if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfoList.DataPortal_Fetch", ex);
        throw new DbCslaException("OwnerInfoList.DataPortal_Fetch", ex);
      }
      this.RaiseListChangedEvents = true;
    }
  }
	public partial class OwnerInfo
	{
		public static OwnerInfo GetBySessionIDandFolderID(int sessionID, int folderID)
		{
			try
			{
				OwnerInfo tmp = DataPortal.Fetch<OwnerInfo>(new GetBySessionIDandFolderIDCriteria(sessionID, folderID));
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up SessionInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on OwnerInfo.GetBySessionIDandFolderID", ex);
			}
		}
		[Serializable()]
		protected class GetBySessionIDandFolderIDCriteria
		{
			private int _SessionID;
			public int SessionID
			{ get { return _SessionID; } }
			private int _FolderID;
			public int FolderID
			{ get { return _FolderID; } }
			public GetBySessionIDandFolderIDCriteria(int sessionID, int folderID)
			{
				_SessionID = sessionID;
				_FolderID = folderID;
			}
		}
		private void DataPortal_Fetch(GetBySessionIDandFolderIDCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfo.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "getOwnerBySessionIDandFolderID";
						cm.Parameters.AddWithValue("@SessionID", criteria.SessionID);
						cm.Parameters.AddWithValue("@FolderID", criteria.FolderID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
						}
					}
					// removing of item only needed for local data portal
					if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
						ApplicationContext.LocalContext.Remove("cn");
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("OwnerInfo.DataPortal_Fetch", ex);
			}
		}
		public static OwnerInfo GetBySessionIDandVersionID(int sessionID, int versionID)
		{
			try
			{
				OwnerInfo tmp = DataPortal.Fetch<OwnerInfo>(new GetBySessionIDandVersionIDCriteria(sessionID, versionID));
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up SessionInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on OwnerInfo.GetBySessionIDandVersionID", ex);
			}
		}
		[Serializable()]
		protected class GetBySessionIDandVersionIDCriteria
		{
			private int _SessionID;
			public int SessionID
			{ get { return _SessionID; } }
			private int _VersionID;
			public int VersionID
			{ get { return _VersionID; } }
			public GetBySessionIDandVersionIDCriteria(int sessionID, int versionID)
			{
				_SessionID = sessionID;
				_VersionID = versionID;
			}
		}
		private void DataPortal_Fetch(GetBySessionIDandVersionIDCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfo.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "getOwnerBySessionIDandVersionID";
						cm.Parameters.AddWithValue("@SessionID", criteria.SessionID);
						cm.Parameters.AddWithValue("@VersionID", criteria.VersionID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
						}
					}
					// removing of item only needed for local data portal
					if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
						ApplicationContext.LocalContext.Remove("cn");
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("OwnerInfo.DataPortal_Fetch", ex);
			}
		}
		public static OwnerInfo GetByItemID(int itemID, CheckOutType itemType)
		{
			try
			{
				OwnerInfo tmp = DataPortal.Fetch<OwnerInfo>(new GetByItemIDCriteria(itemID, itemType));
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up SessionInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on OwnerInfo.GetByItemID", ex);
			}
		}
		[Serializable()]
		protected class GetByItemIDCriteria
		{
			private int _ItemID;
			public int ItemID
			{ get { return _ItemID; } }
			private CheckOutType _ItemType;
			public CheckOutType ItemType
			{	get { return _ItemType; }	}
			public GetByItemIDCriteria(int itemID, CheckOutType itemType)
			{
				_ItemID = itemID;
				_ItemType = itemType;
			}
		}
		private void DataPortal_Fetch(GetByItemIDCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfo.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "getOwnerByItemID";
						cm.Parameters.AddWithValue("@ItemID", criteria.ItemID);
						cm.Parameters.AddWithValue("@ItemType", (int)criteria.ItemType);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
						}
					}
					// removing of item only needed for local data portal
					if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
						ApplicationContext.LocalContext.Remove("cn");
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("OwnerInfo.DataPortal_Fetch", ex);
			}
		}
		public string SessionUserID
		{
			get
			{
				SessionInfo si = SessionInfo.Get(this.SessionID);
				return si.UserID;
			}
		}
	}
	#endregion
	#region UserInfo stuff
	public partial class UserInfo
	{
		public static bool CanEdit(UserInfo myUserInfo, DocVersionInfo myDVI)
		{
			return myUserInfo!=null && myDVI!=null && (myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsWriter(myDVI));
		}
		public static bool CanEditROs(UserInfo myUserInfo, DocVersionInfo myDVI)
		{
			return myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsROEditor(myDVI);
		}
		public static bool CanCreateFolders(UserInfo myUserInfo, DocVersionInfo myDVI)
		{
			return myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI);
		}
		public static bool CanCreateFolders(UserInfo myUserInfo, FolderInfo fi)
		{
			return myUserInfo != null && fi != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(fi);
		}
		public bool IsAdministrator()
		{
			if (this.UserMembershipCount == 0)
				return false;
			foreach (MembershipInfo mi in this.UserMemberships)
			{
				if (mi.EndDate == string.Empty)
				{
					foreach (AssignmentInfo ai in mi.MyGroup.GroupAssignments)
					{
						if (ai.FolderID == 1 && ai.MyRole.Name == "Administrator")
							return true;
					}
				}
			}
			return false;
		}
		public bool IsSetAdministrator(FolderInfo fi)
		{
			if (this.UserMembershipCount == 0)
				return false;
			foreach (MembershipInfo mi in this.UserMemberships)
			{
				if (mi.EndDate == string.Empty)
				{
					Dictionary<int, int> folders = new Dictionary<int, int>();
					//FolderInfo fi = FolderInfo.Get(dv.MyFolder.FolderID);
					while (fi.FolderID > 1)
					{
						folders.Add(fi.FolderID, fi.FolderID);
						fi = fi.MyParent;
					}
					folders.Add(1, 1);
					foreach (AssignmentInfo ai in mi.MyGroup.GroupAssignments)
					{
						if (folders.ContainsKey(ai.FolderID) && ai.MyRole.Name == "Set Administrator")
							return true;
					}
				}
			}
			return false;
		}
		public bool IsSetAdministrator(DocVersionInfo dv)
		{
			if (this.UserMembershipCount == 0)
				return false;
			foreach (MembershipInfo mi in this.UserMemberships)
			{
				if (mi.EndDate == string.Empty)
				{
					Dictionary<int, int> folders = new Dictionary<int, int>();
					FolderInfo fi = FolderInfo.Get(dv.MyFolder.FolderID);
					while (fi.FolderID > 1)
					{
						folders.Add(fi.FolderID, fi.FolderID);
						fi = fi.MyParent;
					}
					folders.Add(1, 1);
					foreach (AssignmentInfo ai in mi.MyGroup.GroupAssignments)
					{
						if (folders.ContainsKey(ai.FolderID) && ai.MyRole.Name == "Set Administrator")
							return true;
					}
				}
			}
			return false;
		}
		public bool IsWriter(DocVersionInfo dv)
		{
			if (this.UserMembershipCount == 0)
				return false;
			foreach (MembershipInfo mi in this.UserMemberships)
			{
				if (mi.EndDate == string.Empty)
				{
					Dictionary<int, int> folders = new Dictionary<int, int>();
					FolderInfo fi = FolderInfo.Get(dv.MyFolder.FolderID);
					while (fi.FolderID > 1)
					{
						folders.Add(fi.FolderID, fi.FolderID);
						fi = fi.MyParent;
					}
					folders.Add(1, 1);
					foreach (AssignmentInfo ai in mi.MyGroup.GroupAssignments)
					{
						if (folders.ContainsKey(ai.FolderID) && ai.MyRole.Name == "Writer")
							return true;
					}
				}
			}
			return false;
		}
		public bool IsReviewer(DocVersionInfo dv)
		{
			if (this.UserMembershipCount == 0)
				return false;
			foreach (MembershipInfo mi in this.UserMemberships)
			{
				if (mi.EndDate == string.Empty)
				{
					Dictionary<int, int> folders = new Dictionary<int, int>();
					FolderInfo fi = FolderInfo.Get(dv.MyFolder.FolderID);
					while (fi.FolderID > 1)
					{
						folders.Add(fi.FolderID, fi.FolderID);
						fi = fi.MyParent;
					}
					folders.Add(1, 1);
					foreach (AssignmentInfo ai in mi.MyGroup.GroupAssignments)
					{
						if (folders.ContainsKey(ai.FolderID) && ai.MyRole.Name == "Reviewer")
							return true;
					}
				}
			}
			return false;
		}
		public bool IsROEditor(DocVersionInfo dv)
		{
			if (this.UserMembershipCount == 0)
				return false;
			foreach (MembershipInfo mi in this.UserMemberships)
			{
				if (mi.EndDate == string.Empty)
				{
					Dictionary<int, int> folders = new Dictionary<int, int>();
					FolderInfo fi = FolderInfo.Get(dv.MyFolder.FolderID);
					while (fi.FolderID > 1)
					{
						folders.Add(fi.FolderID, fi.FolderID);
						fi = fi.MyParent;
					}
					folders.Add(1, 1);
					foreach (AssignmentInfo ai in mi.MyGroup.GroupAssignments)
					{
						if (folders.ContainsKey(ai.FolderID) && ai.MyRole.Name == "RO Editor")
							return true;
					}
				}
			}
			return false;
		}
		public static UserInfo GetByUserID(string userID)
		{
			try
			{
				UserInfo tmp = DataPortal.Fetch<UserInfo>(new GetByUserIDCriteria(userID));
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up SessionInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on UserInfo.GetByUserID", ex);
			}
		}
		[Serializable()]
		protected class GetByUserIDCriteria
		{
			private string _UserID;
			public string UserID
			{ get { return _UserID; } }
			public GetByUserIDCriteria(string userID)
			{
				_UserID = userID;
			}
		}
		private void DataPortal_Fetch(GetByUserIDCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserInfo.DataPortal_Fetch", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "getUserByUserID";
						cm.Parameters.AddWithValue("@UserID", criteria.UserID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
						}
					}
					// removing of item only needed for local data portal
					if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
						ApplicationContext.LocalContext.Remove("cn");
				}
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("UserInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("UserInfo.DataPortal_Fetch", ex);
			}
		}
	}
	#endregion
}
