Ejemplo n.º 1
0
        /// <inheritdoc cref="Application.Excel.TextBox"/>
        internal void TextBox(
            int row, int column, ISessionObject sessionObject, RoleType roleType, RoleType relationType = null,
            RoleType displayRoleType              = null,
            string numberFormat                   = null,
            Func <object, dynamic> toDomain       = null,
            Func <ISessionObject, dynamic> toCell = null,
            Func <ICell, ISessionObject> factory  = null)
        {
            if (sessionObject != null || factory != null)
            {
                var cell = this.Worksheet[row, column];
                cell.NumberFormat = numberFormat;

                if (!this.ControlByCell.TryGetValue(cell, out var control))
                {
                    control = new TextBox(cell);
                    this.ControlByCell.TryAdd(cell, control);
                }

                var textBox = (TextBox)control;
                textBox.SessionObject   = sessionObject;
                textBox.RoleType        = roleType;
                textBox.RelationType    = relationType;
                textBox.DisplayRoleType = displayRoleType;
                textBox.ToDomain        = toDomain;
                textBox.ToCell          = toCell;
                textBox.Factory         = factory;

                this.ActiveControls.Add(control);
            }
        }
Ejemplo n.º 2
0
        internal ICell Select(int row, int column, Range options, ISessionObject sessionObject, RoleType roleType, RoleType relationType = null,
                              RoleType displayRoleType           = null,
                              Func <object, dynamic> getRelation = null,
                              string numberFormat     = null,
                              bool hideInCellDropDown = false)
        {
            ICell cell = null;

            if (sessionObject != null)
            {
                cell                    = this.Worksheet[row, column];
                cell.Options            = options ?? throw new ArgumentNullException(nameof(options));
                cell.NumberFormat       = numberFormat;
                cell.HideInCellDropdown = hideInCellDropDown;
                cell.IsRequired         = roleType.IsRequired;

                if (!this.ControlByCell.TryGetValue(cell, out var control))
                {
                    control = new ComboBox(cell);
                    this.ControlByCell.TryAdd(cell, control);
                }

                var comboBox = (ComboBox)control;

                comboBox.SessionObject   = sessionObject;
                comboBox.RoleType        = roleType;
                comboBox.RelationType    = relationType;
                comboBox.DisplayRoleType = displayRoleType;
                comboBox.ToDomain        = getRelation;

                this.ActiveControls.Add(control);
            }

            return(cell);
        }
Ejemplo n.º 3
0
 public RoleTypeBinding(ISessionObject @object, RoleType roleType, RoleType relationType = null, bool oneWayBinding = false)
 {
     this.Object        = @object;
     this.RoleType      = roleType;
     this.RelationType  = relationType;
     this.OneWayBinding = oneWayBinding;
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Adds a session into the dictionary
        /// </summary>
        /// <param name="Key">Session Key</param>
        /// <param name="Session">Session object</param>
        /// <param name="UpdateIfNotFound">Indicates whether session should be updated if the session was not found. If set to flase, this gives the caller a chance to query the network before trying again</param>
        /// <param name="LockedSessionInfo">Locked session information if session is locked</param>
        /// <returns>Result of Action</returns>
        public SessionActionResult Add(string Key, ISessionObject Session, bool UpdateIfNotFound, out SessionResponseInfo LockedSessionInfo)
        {
            //If an item with key already exists, return SessionActionResult.AlreadyExists
            //else add the item and return SessionActionResult.OK
            //Calls UpSert internally

            return(UpSert(Key, Session, true, UpdateIfNotFound, out LockedSessionInfo)); //Insert Item if it doesn't exist
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Updates a session (adds a new one if it was not found)
        /// </summary>
        /// <param name="Key">Session Key</param>
        /// <param name="Session">Session object</param>
        /// <param name="UpdateIfNotFound">Indicates whether session should be updated if the session was not found. If set to flase, this gives the caller a chance to query the network before trying again</param>
        /// <param name="LockedSessionInfo">Locked session information if session is locked</param>
        /// <returns>Result of Action</returns>
        public SessionActionResult Update(string Key, ISessionObject Session, bool UpdateIfNotFound, out SessionResponseInfo LockedSessionInfo)
        {
            //If the item is locked and the new items lockCookie does not match, return SessionActionResult.Locked
            //else add the item and return SessionActionResult.OK
            //Calls UpSert internally

            return(UpSert(Key, Session, false, UpdateIfNotFound, out LockedSessionInfo)); //Insert or Update item
        }
Ejemplo n.º 6
0
 public void OnChanged(object checkedValue, ISessionObject option)
 {
     if ((bool)checkedValue)
     {
         this.Object.Add(this.RoleType, option);
     }
     else
     {
         this.Object.Remove(this.RoleType, option);
     }
 }
Ejemplo n.º 7
0
        public static IntPtr GetHandle(this ISessionObject sessionObject)
        {
            INativeObject nativeObject = sessionObject as INativeObject;

            if (nativeObject != null)
            {
                return(nativeObject.Handle);
            }

            return(IntPtr.Zero);
        }
Ejemplo n.º 8
0
        public void Remove(RoleType roleType, ISessionObject value)
        {
            var roles = (ISessionObject[])this.Get(roleType);

            if (roles.Contains(value))
            {
                var newRoles = new List <ISessionObject>(roles);
                newRoles.Remove(value);
                roles = newRoles.ToArray();
            }

            this.Set(roleType, roles);
        }
Ejemplo n.º 9
0
 private void SetCellValue(ISessionObject obj, RoleType roleType)
 {
     if (roleType.ObjectType.ClrType == typeof(bool))
     {
         if (obj.Get(roleType) is bool boolvalue && boolvalue)
         {
             this.Cell.Value = Constants.YES;
         }
         else
         {
             this.Cell.Value = Constants.NO;
         }
     }
Ejemplo n.º 10
0
        public void TextBox(ISessionObject sessionObject, RoleType roleType)
        {
            var key = $"{sessionObject?.Id}:{roleType?.Id}";

            if (!this.Members.TryGetValue(key, out var control))
            {
                var textBox = new TextBox(this.Cell);

                textBox.SessionObject = sessionObject;
                textBox.RoleType      = roleType;

                this.Members.Add(key, textBox);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Copies all data from one Session object to this one
        /// </summary>
        /// <param name="ObjectToCopy">Session object to copy from</param>
        public void CopyFrom(ISessionObject ObjectToCopy)
        {
            //Do not copy inUse and isExporting properties (they are used internally)
            //inuse = ObjectToCopy.IsInUse ? -1 : 0;
            //isExporting = ObjectToCopy.IsExporting;

            data       = ObjectToCopy.Data;
            lockCookie = ObjectToCopy.LockCookie;
            lockDate   = ObjectToCopy.LockDate;
            updateDate = ObjectToCopy.UpdateDate;
            timeout    = ObjectToCopy.TimeOut;
            extraFlags = (sbyte)ObjectToCopy.ExtraFlags;
            locked     = ObjectToCopy.IsLocked;
        }
Ejemplo n.º 12
0
        public void Add(RoleType roleType, ISessionObject value)
        {
            var roles = (ISessionObject[])this.Get(roleType);

            if (!roles.Contains(value))
            {
                roles = new List <ISessionObject>(roles)
                {
                    value
                }.ToArray();
            }

            this.Set(roleType, roles);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets the session object.
        /// </summary>
        /// <returns></returns>
        public static ISessionObject GetSessionObject()
        {
            ISessionObject property = null;
            IObjectContext context;

            if (CoGetObjectContext(ref IID_IObjectContext, out context) == 0)
            {
                IGetContextProperties o = (IGetContextProperties)context;
                if (o != null)
                {
                    property = (ISessionObject)o.GetProperty("Session");
                    Marshal.ReleaseComObject(o);
                }
                Marshal.ReleaseComObject(context);
            }
            return(property);
        }
Ejemplo n.º 14
0
        public static ISessionObject GetSessionObject()
        {
            ISessionObject session = null;

            IObjectContext obj;

            if (0 == NativeMethods.CoGetObjectContext(ref IID_IObjectContext, out obj))
            {
                IGetContextProperties prop = (IGetContextProperties)obj;
                if (prop != null)
                {
                    session = (ISessionObject)prop.GetProperty("Session");
                    Marshal.ReleaseComObject(prop);
                }
                Marshal.ReleaseComObject(obj);
            }
            return(session);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Sets a readonly value in the cell. Changes are not handled.
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="sessionObject"></param>
        /// <param name="roleType"></param>
        /// <param name="relationType"></param>
        internal void Label(int row, int column, ISessionObject sessionObject, RoleType roleType, RoleType relationType = null, string numberFormat = null)
        {
            if (sessionObject != null)
            {
                var cell = this.Worksheet[row, column];
                cell.NumberFormat = numberFormat;

                if (!this.ControlByCell.TryGetValue(cell, out var control))
                {
                    control = new Label(cell);
                    this.ControlByCell.TryAdd(cell, control);
                }

                var label = (Label)control;
                label.SessionObject = sessionObject;
                label.RoleType      = roleType;
                label.RelationType  = relationType;

                this.ActiveControls.Add(control);
            }
        }
Ejemplo n.º 16
0
        public void Set(RoleType roleType, object value)
        {
            if (this.changedRoleByRoleType == null)
            {
                this.changedRoleByRoleType = new Dictionary <RoleType, object>();
            }

            if (value == null)
            {
                if (roleType.ObjectType.IsComposite && roleType.IsMany)
                {
                    value = new ISessionObject[0];
                }
            }

            if (roleType.ObjectType.IsComposite && roleType.IsMany)
            {
                value = new ArrayList((Array)value).ToArray(roleType.ObjectType.ClrType);
            }

            this.roleByRoleType[roleType]        = value;
            this.changedRoleByRoleType[roleType] = value;
        }
Ejemplo n.º 17
0
 static public void LogSessionExporting(string key, ISessionObject Session)
 {
     Debug.WriteLine("[" + GetFormattedTime(DateTime.Now) + "] " + string.Format("Export started for session key {0}, length: {1} bytes \n", key, Session.Data.Length), "SESSION_DICT");
 }
Ejemplo n.º 18
0
 public static void LogSessionExporting(string key, ISessionObject Session)
 {
     Debug.WriteLine( "[" + GetFormattedTime(DateTime.Now) + "] " + string.Format("Export started for session key {0}, length: {1} bytes \n", key, Session.Data.Length), "SESSION_DICT");
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Called by the SessionDictionary.Read method to complete processing the request, 
        /// if the requested session was found and read
        /// </summary>
        /// <param name="Session">The read session object</param>
        /// <param name="StateObject">The state object passed from the SessionDictionary.Read method</param>
        private void CompleteReadRequest(ISessionObject Session, object StateObject)
        {
            ServiceMessage msg = (ServiceMessage)StateObject;

            if (Session.IsLocked)
            {
                Reply(BuildResponse(typeof(LockedResponse), null, Session.CreateResponseInfo(), null));
                return;
            }
            else
            {

                Reply( BuildResponse(typeof(OKResponse), null, Session.CreateResponseInfo(), Session.Data));

                if (Session.ExtraFlags != -1) Session.ExtraFlags = -1; //Disable extraflags
            }
        }
Ejemplo n.º 20
0
 static public void LogUpdatedSession(string key, ISessionObject Session)
 {
     Debug.WriteLine("[" + GetFormattedTime(DateTime.Now) + "] " + string.Format("Updated session data for key {0} , length: {1} bytes \n", key, Session.Data.Length), "SESSION_DICT");
 }
Ejemplo n.º 21
0
        public object ToExcel(ISessionObject sessionObject, RoleType roleType)
        {
            var bl = (bool?)sessionObject.Get(roleType);

            return(bl == true ? "YES" : "NO");
        }
Ejemplo n.º 22
0
        public object IsSelected(ISessionObject option)
        {
            var model = (IEnumerable <ISessionObject>) this.Model;

            return(model.Contains(option));
        }
Ejemplo n.º 23
0
        public bool IsAttributeSet(ISessionObject session, string attributeName)
        {
            var strValue = GetAttributeValue(attributeName);

            return !string.IsNullOrEmpty(strValue) && strValue != ("#" + session.Session.SessionKey);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Called by the SessionDictionary.Read() method to complete processing the request, 
        /// if the requested session was found and read
        /// </summary>
        /// <param name="Session">The read session object</param>
        /// <param name="StateObject">The state object passed from the SessionDictionary.Read() method</param>
        private void CompleteResetTimeoutRequest(ISessionObject Session, object StateObject)
        {
            ServiceMessage msg = (ServiceMessage)StateObject;

            Session.ResetTimeout();
            Reply(BuildResponse(typeof(OKResponse), null, Session.CreateResponseInfo(), null));
        }
        public bool IsAttributeSet(ISessionObject session, string attributeName)
        {
            var strValue = GetAttributeValue(attributeName);

            return(!string.IsNullOrEmpty(strValue) && strValue != ("#" + session.Session.SessionKey));
        }
Ejemplo n.º 26
0
 public static void LogUpdatedSession(string key, ISessionObject Session)
 {
     Debug.WriteLine( "[" + GetFormattedTime(DateTime.Now) + "] " + string.Format("Updated session data for key {0} , length: {1} bytes \n", key, Session.Data.Length), "SESSION_DICT");
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Removes a session from the dictionary
        /// </summary>
        /// <param name="Key">Session Key</param>
        /// <param name="LockCookie">Lock Cookie</param>
        /// <param name="IsExpiring">Indicates that the item is being removed because it's expiring</param>
        /// <param name="ExpiryDate">The Item expiry date (for comparison)</param>
        /// <param name="LockedSessionInfo">Locked session information if session is locked</param>
        /// <returns>Result of Action</returns>
        private SessionActionResult Remove(string Key, uint LockCookie, bool IsExpiring, DateTime ExpiryDate, out SessionResponseInfo LockedSessionInfo)
        {
            if (Key == null)
            {
                throw new ArgumentNullException("Key");
            }
            LockedSessionInfo = null;

            bool tryAgain;

            Diags.ResetDeadLockCounter();

            do
            {
                tryAgain = false;
                AcquireReadLock();
                ISessionObject entry;
                try
                {
                    dict.TryGetValue(Key, out entry);
                }
                finally
                {
                    ReleaseReadLock();
                }

                if (entry == null)
                {
                    //Session not found
                    Diags.LogSessionNotFound(Key);
                    return(SessionActionResult.NotFound);
                }
                else
                {
                    //Session Found
                    if (entry.CompareExchangeIsInUse(true, false) == false)
                    {
                        try
                        {
                            //The InUse flag is set and so this code section has exclusive access to this session object
                            AcquireWriteLock();

                            try
                            {
                                //Check again to be sure, now that the write-lock has been obtained
                                ISessionObject oldEntry = entry;
                                if (!dict.TryGetValue(Key, out entry))
                                {
                                    //ooops -- another thread deleted the session from the dictionary while this thread
                                    //was either trying to do the compareExchange (or if buggy, while obtaining the write-lock)
                                    //so try again
                                    oldEntry.CompareExchangeIsInUse(false, true); //unlock the previously locked item
                                    tryAgain = true;
                                    continue;
                                }

                                if (IsExpiring)
                                {
                                    DateTime timeStamp;
                                    if (expiryList.TryGetTimeStamp(Key, out timeStamp))
                                    {
                                        if (timeStamp != ExpiryDate)
                                        {
                                            //The expiration date on this session was updated, so leave
                                            return(SessionActionResult.OK);
                                        }
                                    }
                                }

                                if (!IsExpiring && entry.IsLocked) //Locked items DO expire. if not expiring, LockCookie has to match session's
                                {
                                    if (!entry.UnLock(LockCookie))
                                    {
                                        //Lockcookie did not match
                                        LockedSessionInfo = (SessionResponseInfo)entry.CreateResponseInfo();
                                        Diags.LogSessionIsLocked(Key);
                                        return(SessionActionResult.Locked);
                                    }
                                }

                                if (dict.Remove(Key))
                                {
                                    expiryList.Remove(Key);
                                    if (IsExpiring)
                                    {
                                        Diags.LogSessionExpired(Key);
                                    }
                                    else
                                    {
                                        Diags.LogSessionDeleted(Key);
                                    }
                                }
                                else
                                {
                                    //This should never happen
                                    Diags.Fail("ASSERTION Failed -- Session dictionary was unable to remove key\r\n");
                                }
                            }
                            finally
                            {
                                ReleaseWriteLock();
                            }
                        }
                        finally
                        {
                            if (entry != null)
                            {
                                entry.CompareExchangeIsInUse(false, true);
                            }
                        }
                    }
                    else
                    {
                        //Is this entry being exported?
                        if (entry.IsExporting)
                        {
                            //This session is already been exported so leave
                            Diags.ResetDeadLockCounter();
                            return(SessionActionResult.Exporting);
                        }

                        //Another thread is using this session and will be done soon so try again

                        Thread.Sleep(1); //pause for 1 ms
                        tryAgain = true;
                    }

                    Diags.DetectDeadLock(Key, DeadLockIterationCount); //Signal a deadlock after 2000 iterations
                }
            } while (tryAgain);

            Diags.ResetDeadLockCounter(); //Signal deadlock was freed
            return(SessionActionResult.OK);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Called by the SessionDictionary.Read() method to complete processing the request,
        /// if the requested session was found and read
        /// </summary>
        /// <param name="Session">The read session object</param>
        /// <param name="StateObject">The state object passed from the SessionDictionary.Read() method</param>
        private void CompleteReleaseRequest(ISessionObject Session, object StateObject)
        {
            ServiceMessage msg = (ServiceMessage)StateObject;

            //check if LockCookies match
            if (Session.IsLocked)
            {
                if (!Session.UnLock(LockCookie.Value))
                {
                    //Reply with Locked response
                    Reply(BuildResponse(typeof(LockedResponse), null, Session.CreateResponseInfo(), null));
                    return;
                }
            }

            //Reply with OK response
            Reply(BuildResponse(typeof(OKResponse), null, Session.CreateResponseInfo(), null));

            if(Session.ExtraFlags != -1) Session.ExtraFlags = -1; //Disable extraflags
        }
Ejemplo n.º 29
0
        public static bool IsAttributeSet(this XmlElement xmlElement, ISessionObject session, string attributeName)
        {
            var strValue = xmlElement.GetAttributeValue(attributeName);

            return(!string.IsNullOrEmpty(strValue) && strValue != session.Session.SessionKey);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Called by the SessionDictionary.Read() method to complete processing the request, 
        /// if the requested session was found and read
        /// </summary>
        /// <param name="Session">The read session object</param>
        /// <param name="StateObject">The state object passed from the SessionDictionary.Read() method</param>
        private void CompleteExclusiveReadRequest(ISessionObject Session, object StateObject)
        {
            ServiceMessage msg = (ServiceMessage)StateObject;

            if (Session.IsLocked)
            {

                Reply(BuildResponse(typeof(LockedResponse), null, Session.CreateResponseInfo(), null));
                return;

            }
            else
            {

                if (socket.CheckConnection()) //This request locks up sessions so make sure connection is still valid before locking/responding
                {
                    Session.Lock();

                    //Increment LockCookie until it reaches the maximum LockCookie value;
                    Session.LockCookie++;
                    if (Session.LockCookie > MAX_LockCookieValue)
                    {
                        Session.LockCookie = 2; //Roll over
                    }

                    Reply(BuildResponse(typeof(OKResponse), null, Session.CreateResponseInfo(), Session.Data));

                    if (Session.ExtraFlags != -1) Session.ExtraFlags = -1; //Disable extraflags
                }
                else
                {
                    Diags.LogIgnoredMessage(this, "Connection was dropped");
                }
            }
        }
Ejemplo n.º 31
0
        public object ToExcel(ISessionObject sessionObject, RoleType roleType)
        {
            var dec = (decimal?)sessionObject.Get(roleType);

            return(dec / 1000);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Copies all data from one Session object to this one
        /// </summary>
        /// <param name="ObjectToCopy">Session object to copy from</param>
        public void CopyFrom(ISessionObject ObjectToCopy)
        {
            //Do not copy inUse and isExporting properties (they are used internally)
              //inuse = ObjectToCopy.IsInUse ? -1 : 0;
              //isExporting = ObjectToCopy.IsExporting;

              data = ObjectToCopy.Data;
              lockCookie = ObjectToCopy.LockCookie;
              lockDate = ObjectToCopy.LockDate;
              updateDate = ObjectToCopy.UpdateDate;
              timeout = ObjectToCopy.TimeOut;
              extraFlags = (sbyte)ObjectToCopy.ExtraFlags;
              locked = ObjectToCopy.IsLocked;
        }
Ejemplo n.º 33
0
 public string OptionName(ISessionObject option) => this.Name + "_" + option.Id.ToString().Replace("-", "_");
Ejemplo n.º 34
0
        /// <summary>
        /// Updates or inserts a session in the dictionary
        /// </summary>
        /// <param name="Key">Session Key</param>
        /// <param name="Session">Session object</param>
        /// <param name="InsertOnly">Indicates that session should only be inserted if it does not already exist</param>
        /// <param name="UpdateIfNotFound">Indicates whether session should be updated if the session was not found. If set to flase, this gives the caller a chance to query the network before trying again </param>
        /// <param name="LockedSessionInfo">Locked session information if session is locked</param>
        /// <returns>Result of Action</returns>
        private SessionActionResult UpSert(string Key, ISessionObject Session, bool InsertOnly, bool UpdateIfNotFound, out SessionResponseInfo LockedSessionInfo)
        {
            // Look for the session using a reader lock.
            // If session is not found, switch to a writer lock and insert item.
            // If session is found:
            // Perform an atomic compare exchange on the variable 'InUse'
            // If session is in Use, try Upsert again from the start.
            // If session is not in Use, Perform UpSert and reset InUse
            // Also update Sorted session list

            if (Key == null)
            {
                throw new ArgumentNullException("Key");
            }
            if (Session == null)
            {
                throw new ArgumentNullException("Session");
            }

            LockedSessionInfo = null;
            bool tryAgain;

            Diags.ResetDeadLockCounter();
            do
            {
                tryAgain = false;
                AcquireReadLock();
                ISessionObject entry;
                try
                {
                    dict.TryGetValue(Key, out entry);
                }
                finally
                {
                    ReleaseReadLock();
                }

                if (entry == null)
                {
                    if (!UpdateIfNotFound)
                    {
                        return(SessionActionResult.NotFound);
                    }

                    //Session not found -- insert brand new session object
                    AcquireWriteLock();
                    try
                    {
                        //Check again to be sure now that the write-lock has been obtained
                        dict.TryGetValue(Key, out entry);
                        if (entry != null)
                        {
                            //ooops -- another thread inserted a seesion with this key while this thread was trying to obtain the write-lock
                            //so try again
                            tryAgain = true;
                            continue;
                        }

                        Session.LockCookie = 1; //For some reason Lockcookie starts counting from 2 -- so set it to 1 now so that it increments to 2 when sought
                        dict[Key]          = Session;
                        expiryList.Add(DateTime.UtcNow.Add(new TimeSpan(0, Session.TimeOut, 0)), Key, Key);
                        Diags.LogNewSession(Key, Session);
                    }
                    finally
                    {
                        ReleaseWriteLock();
                    }
                }
                else
                {
                    //Session Found

                    if (InsertOnly)
                    {
                        Diags.LogSessionAlreadyExists(Key);
                        return(SessionActionResult.AlreadyExists); //Do not perform an update if InsertOnly is requested
                    }

                    //There is no need to acquire a write lock here since the dictionary is not been modified.
                    //Only the dictionary entry itself is been updated and such updates are guaranteed to be atomic
                    //if the atomic InUse property is set.

                    if (entry.CompareExchangeIsInUse(true, false) == false)
                    {
                        //the InUse flag is set, so this code section has exclusive access to this session object
                        try
                        {
                            if (entry.IsLocked)
                            {
                                if (!entry.UnLock(Session.LockCookie))
                                {
                                    //Lockcookie did not match
                                    LockedSessionInfo = (SessionResponseInfo)entry.CreateResponseInfo();
                                    Diags.LogSessionIsLocked(Key);
                                    return(SessionActionResult.Locked);
                                }
                            }

                            Session.LockCookie = entry.LockCookie;                                              //Overwrite the incoming session's lock-cookie with the internal one's so as not to let external input change the lockcookie
                            Session.ExtraFlags = -1;                                                            //disable extra flags since an update is being performed

                            entry.CopyFrom(Session);                                                            //Copy all information from Session to entry
                            expiryList.Add(DateTime.UtcNow.Add(new TimeSpan(0, Session.TimeOut, 0)), Key, Key); //reset expiry timeout
                            Diags.LogUpdatedSession(Key, Session);
                        }
                        finally
                        {
                            entry.CompareExchangeIsInUse(false, true);
                        }
                    }
                    else
                    {
                        //Is this entry being exported?
                        if (entry.IsExporting)
                        {
                            //This session is already been exported so leave
                            Diags.ResetDeadLockCounter();
                            return(SessionActionResult.Exporting);
                        }


                        //Another thread is using this session and will be done soon so try again

                        Thread.Sleep(1); //pause for 1 ms
                        tryAgain = true;
                    }
                }

                Diags.DetectDeadLock(Key, DeadLockIterationCount); //Signal a deadlock after 2000 iterations
            } while (tryAgain);

            Diags.ResetDeadLockCounter(); //Signal deadlock was freed

            return(SessionActionResult.OK);
        }
Ejemplo n.º 35
0
 public SessionGetter(ISessionReader sessionReader,ISessionObject sessionObject)
 {
     _sessionReader = sessionReader;
     _sessionObject = sessionObject;
 }
Ejemplo n.º 36
0
 public SessionGetter(ISessionReader sessionReader, ISessionObject sessionObject)
 {
     _sessionReader = sessionReader;
     _sessionObject = sessionObject;
 }
Ejemplo n.º 37
0
 public object ToExcel(ISessionObject sessionObject, RoleType roleType)
 {
     return(sessionObject.Get(roleType));
 }
Ejemplo n.º 38
0
        public static bool IsAttributeSet(this XmlElement xmlElement, ISessionObject session, string attributeName)
        {
            var strValue = xmlElement.GetAttributeValue(attributeName);

            return !string.IsNullOrEmpty(strValue) && strValue != session.Session.SessionKey;
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Called by the SessionDictionary.BeginExport method to complete processing the request, 
        /// if the requested session was found and read
        /// </summary>
        /// <param name="Session">The read session</param>
        /// <param name="StateObject">The state object passed from the SessionDictionary.BeginExport method</param>
        private void CompleteTransferRequest(ISessionObject Session, object StateObject)
        {
            ISessionResponseInfo response = Session.CreateResponseInfo();

            //Get the endpoint for the host to connect to
            string remoteHost;
            int? remotePort;
            ServerSettings.HostEndPoint.Parse(Host,out remoteHost,out remotePort);
            if(!remotePort.HasValue) remotePort = service.Settings.PeerPort;
            ServerSettings.HostEndPoint endPoint = new ServerSettings.HostEndPoint(remoteHost.Trim(),remotePort.Value);

            const int sentTransferExpiryTime = 2; // 2 seconds is sufficient for a broadcast to traverse half a reasonable network

            #region Callback Delegate declarations

            //SuccessAction
            Action<AsyncMessageTracker> successAction =
                delegate(AsyncMessageTracker asyncMsg)
                {
                    //Add this transfer to list of recently transferred sessions and have it expire in 15 seconds
                    service.SentTransfers.Add(DateTime.UtcNow + new TimeSpan(0, 0, sentTransferExpiryTime), Resource, null);

                    TransferSuccess(asyncMsg);
                    Diags.LogTransferSuccess(Resource);
                };

            //FailedAction
            Action<AsyncMessageTracker> failureAction =
                delegate(AsyncMessageTracker asyncMsg)
                {
                    TransferFailure(asyncMsg);
                    Diags.LogTransferFailed(Resource, string.Empty);

                };

            //AlreadyExistsAction
            Action<AsyncMessageTracker> alreadyExistsAction =
                delegate(AsyncMessageTracker asyncMsg)
                {
                    //Add this transfer to list of recently transferred sessions and have it expire in 15 seconds
                    service.SentTransfers.Add(DateTime.UtcNow + new TimeSpan(0, 0, sentTransferExpiryTime), Resource, null);

                    TransferSuccess(asyncMsg);
                    Diags.LogTransferFailed(Resource, "Resource already exists in remote peer -- deleted local copy");
                };

            //PeerShuttingDownAction
            Action<AsyncMessageTracker> peerShuttingDownAction =
                delegate(AsyncMessageTracker asyncMsg)
                {
                    TransferFailure(asyncMsg);
                    Diags.LogTransferFailed(Resource, "Peer is shutting down");
                };

            //TimeoutAction
            System.Threading.WaitCallback timeoutAction =
                delegate(object asyncMsg)
                {
                    //This anonymous method can be called directly from a background thread so make sure it's exception-safe
                    try
                    {
                        TransferFailure((AsyncMessageTracker)asyncMsg);
                        Diags.LogTransferFailed(Resource, "Timed out");
                    }
                    catch (Exception ex)
                    {
                        Diags.LogApplicationError( "TimeoutAction delegate error in CompleteTransferRequest", ex);
                    }
                };

            //FailedActionForExistingLink
            Action<AsyncMessageTracker> failureActionForExistingLink =
                delegate(AsyncMessageTracker asyncMsg)
                {
                    Diags.LogTransferFailed(Resource, "Existing link, trying again on new link");
                    //Try again by reconnecting
                    service.TransferSession(endPoint, Resource, response, Session.Data,
                        successAction, failureAction, alreadyExistsAction, peerShuttingDownAction, timeoutAction);

                };

            #endregion

            service.NewActiveExport(Resource); //create an entry in the exports list for this export

            //Look for standing link
            ServiceSocket linkSocket;
            if(service.TryGetLinkTo(endPoint, out linkSocket))
            {
                //There is a standing link to this peer so send transfer through it
                AsyncMessageTracker msg = new AsyncMessageTracker(AsyncMessageOperation.SetTransferOperation, Guid.NewGuid(), linkSocket);
                service.TransferSession(msg, Resource, response, Session.Data,
                    successAction, failureActionForExistingLink, alreadyExistsAction, peerShuttingDownAction, timeoutAction);
            }
            else
            {
                //Initiate a brand new connection
                service.TransferSession(endPoint, Resource, response, Session.Data,
                    successAction,failureAction,alreadyExistsAction,peerShuttingDownAction,timeoutAction);

            }
        }