System.Diagnostics.Debug.Assert(bool, string, string, params object[])

Here are the examples of the csharp api System.Diagnostics.Debug.Assert(bool, string, string, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6765 Examples 7

19 View Source File : TrackingExpressionVisitor.cs
License : MIT License
Project Creator : 71

public Expression GenerateBody(Expression body, Expression vsmExpression)
        {
            Debug.replacedert(vsmExpression.Type.IsreplacedignableTo<VirtualStateMachine>());

            if (Variables.Count == 0)
                return body;

            Expression[] loadVariableExpressions = new Expression[Variables.Count];
            Expression[] saveVariableExpressions = new Expression[Variables.Count];

            Expression localsExpression = Expression.Field(vsmExpression, VirtualStateMachine.LocalsField);

            for (int i = 0; i < Variables.Count; i++)
            {
                ParameterExpression variable = Variables[i];

                loadVariableExpressions[i] = Expression.replacedign(
                    variable, Expression.Convert(
                        Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
                        variable.Type
                    )
                );

                saveVariableExpressions[i] = Expression.replacedign(
                    Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
                    Expression.Convert(variable, typeof(object))
                );
            }

            Expression init = loadVariableExpressions.Length == 0
                ? (Expression)Expression.Empty() : Expression.Block(typeof(void), loadVariableExpressions);
            Expression end = saveVariableExpressions.Length == 0
                ? (Expression)Expression.Empty() : Expression.Block(typeof(void), saveVariableExpressions);

            if (body.Type == typeof(void))
                return Expression.Block(Variables, init, body, end);

            ParameterExpression result = Expression.Variable(body.Type, "result");

            return Expression.Block(Variables.Prepend(result), init, Expression.replacedign(result, body), end, result);
        }

19 View Source File : ByteBuffer.cs
License : MIT License
Project Creator : a1q123456

private void TakeOutMemoryNoCheck(Span<byte> buffer)
        {
            lock (_sync)
            {
                var discardBuffers = new List<byte[]>();
                bool prevDiscarded = false;
                if (Length < buffer.Length && _maxiumBufferSize >= 0)
                {
                    throw new InvalidProgramException();
                }
                foreach (var b in _buffers)
                {
                    if (buffer.Length == 0)
                    {
                        break;
                    }
                    var start = 0;
                    var end = BufferSegmentSize;
                    var isFirst = b == _buffers.First() || prevDiscarded;
                    var isLast = b == _buffers.Last();
                    if (isFirst)
                    {
                        start = _bufferStart;
                    }
                    if (isLast)
                    {
                        end = _bufferEnd;
                    }
                    var length = end - start;
                    var needToCopy = Math.Min(buffer.Length, length);

                    b.replacedpan(start, needToCopy).CopyTo(buffer);

                    start += needToCopy;
                    if (isFirst)
                    {
                        _bufferStart += needToCopy;
                    }

                    if (end - start == 0)
                    {
                        if (isFirst)
                        {
                            _bufferStart = 0;
                        }
                        if (isLast)
                        {
                            _bufferEnd = 0;
                        }
                        discardBuffers.Add(b);
                        prevDiscarded = true;
                    }
                    else
                    {
                        prevDiscarded = false;
                    }

                    buffer = buffer.Slice(needToCopy);
                }
                //Console.WriteLine(Length);
                Debug.replacedert(buffer.Length == 0 || _maxiumBufferSize < 0);
                while (discardBuffers.Any())
                {
                    var b = discardBuffers.First();
                    _arrayPool.Return(b);
                    discardBuffers.Remove(b);
                    _buffers.Remove(b);
                }
                if (!_buffers.Any())
                {
                    AddNewBufferSegment();
                }
            }
            if (Length <= _maxiumBufferSize && _maxiumBufferSize >= 0)
            {
                _memoryUnderLimit?.Invoke();
            }
        }

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnInsert(LineNode node)
		{
			Debug.replacedert(node != null);
			Debug.replacedert(node.color == RED);
			Debug.replacedert(node.left == null || node.left.color == BLACK);
			Debug.replacedert(node.right == null || node.right.color == BLACK);

			LineNode parentNode = node.parent;
			if (parentNode == null) {
				// we inserted in the root -> the node must be black
				// since this is a root node, making the node black increments the number of black nodes
				// on all paths by one, so it is still the same for all paths.
				node.color = BLACK;
				return;
			}
			if (parentNode.color == BLACK) {
				// if the parent node where we inserted was black, our red node is placed correctly.
				// since we inserted a red node, the number of black nodes on each path is unchanged
				// -> the tree is still balanced
				return;
			}
			// parentNode is red, so there is a conflict here!

			// because the root is black, parentNode is not the root -> there is a grandparent node
			LineNode grandparentNode = parentNode.parent;
			LineNode uncleNode = Sibling(parentNode);
			if (uncleNode != null && uncleNode.color == RED) {
				parentNode.color = BLACK;
				uncleNode.color = BLACK;
				grandparentNode.color = RED;
				FixTreeOnInsert(grandparentNode);
				return;
			}
			// now we know: parent is red but uncle is black
			// First rotation:
			if (node == parentNode.right && parentNode == grandparentNode.left) {
				RotateLeft(parentNode);
				node = node.left;
			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
				RotateRight(parentNode);
				node = node.right;
			}
			// because node might have changed, rereplacedign variables:
			parentNode = node.parent;
			grandparentNode = parentNode.parent;

			// Now recolor a bit:
			parentNode.color = BLACK;
			grandparentNode.color = RED;
			// Second rotation:
			if (node == parentNode.left && parentNode == grandparentNode.left) {
				RotateRight(grandparentNode);
			} else {
				// because of the first rotation, this is guaranteed:
				Debug.replacedert(node == parentNode.right && parentNode == grandparentNode.right);
				RotateLeft(grandparentNode);
			}
		}

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnDelete(LineNode node, LineNode parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (parentNode == null)
				return;

			// warning: node may be null
			LineNode sibling = Sibling(node, parentNode);
			if (sibling.color == RED) {
				parentNode.color = RED;
				sibling.color = BLACK;
				if (node == parentNode.left) {
					RotateLeft(parentNode);
				} else {
					RotateRight(parentNode);
				}

				sibling = Sibling(node, parentNode); // update value of sibling after rotation
			}

			if (parentNode.color == BLACK
				&& sibling.color == BLACK
				&& GetColor(sibling.left) == BLACK
				&& GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				FixTreeOnDelete(parentNode, parentNode.parent);
				return;
			}

			if (parentNode.color == RED
				&& sibling.color == BLACK
				&& GetColor(sibling.left) == BLACK
				&& GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				parentNode.color = BLACK;
				return;
			}

			if (node == parentNode.left &&
				sibling.color == BLACK &&
				GetColor(sibling.left) == RED &&
				GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				sibling.left.color = BLACK;
				RotateRight(sibling);
			} else if (node == parentNode.right &&
					   sibling.color == BLACK &&
					   GetColor(sibling.right) == RED &&
					   GetColor(sibling.left) == BLACK) {
				sibling.color = RED;
				sibling.right.color = BLACK;
				RotateLeft(sibling);
			}
			sibling = Sibling(node, parentNode); // update value of sibling after rotation

			sibling.color = parentNode.color;
			parentNode.color = BLACK;
			if (node == parentNode.left) {
				if (sibling.right != null) {
					Debug.replacedert(sibling.right.color == RED);
					sibling.right.color = BLACK;
				}
				RotateLeft(parentNode);
			} else {
				if (sibling.left != null) {
					Debug.replacedert(sibling.left.color == RED);
					sibling.left.color = BLACK;
				}
				RotateRight(parentNode);
			}
		}

19 View Source File : DocumentLineTree.cs
License : MIT License
Project Creator : Abdesol

static LineNode Sibling(LineNode node, LineNode parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (node == parentNode.left)
				return parentNode.right;
			else
				return parentNode.left;
		}

19 View Source File : TextAnchorTree.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnInsert(TextAnchorNode node)
		{
			Debug.replacedert(node != null);
			Debug.replacedert(node.color == RED);
			Debug.replacedert(node.left == null || node.left.color == BLACK);
			Debug.replacedert(node.right == null || node.right.color == BLACK);

			TextAnchorNode parentNode = node.parent;
			if (parentNode == null) {
				// we inserted in the root -> the node must be black
				// since this is a root node, making the node black increments the number of black nodes
				// on all paths by one, so it is still the same for all paths.
				node.color = BLACK;
				return;
			}
			if (parentNode.color == BLACK) {
				// if the parent node where we inserted was black, our red node is placed correctly.
				// since we inserted a red node, the number of black nodes on each path is unchanged
				// -> the tree is still balanced
				return;
			}
			// parentNode is red, so there is a conflict here!

			// because the root is black, parentNode is not the root -> there is a grandparent node
			TextAnchorNode grandparentNode = parentNode.parent;
			TextAnchorNode uncleNode = Sibling(parentNode);
			if (uncleNode != null && uncleNode.color == RED) {
				parentNode.color = BLACK;
				uncleNode.color = BLACK;
				grandparentNode.color = RED;
				FixTreeOnInsert(grandparentNode);
				return;
			}
			// now we know: parent is red but uncle is black
			// First rotation:
			if (node == parentNode.right && parentNode == grandparentNode.left) {
				RotateLeft(parentNode);
				node = node.left;
			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
				RotateRight(parentNode);
				node = node.right;
			}
			// because node might have changed, rereplacedign variables:
			parentNode = node.parent;
			grandparentNode = parentNode.parent;

			// Now recolor a bit:
			parentNode.color = BLACK;
			grandparentNode.color = RED;
			// Second rotation:
			if (node == parentNode.left && parentNode == grandparentNode.left) {
				RotateRight(grandparentNode);
			} else {
				// because of the first rotation, this is guaranteed:
				Debug.replacedert(node == parentNode.right && parentNode == grandparentNode.right);
				RotateLeft(grandparentNode);
			}
		}

19 View Source File : TextAnchorTree.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnDelete(TextAnchorNode node, TextAnchorNode parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (parentNode == null)
				return;

			// warning: node may be null
			TextAnchorNode sibling = Sibling(node, parentNode);
			if (sibling.color == RED) {
				parentNode.color = RED;
				sibling.color = BLACK;
				if (node == parentNode.left) {
					RotateLeft(parentNode);
				} else {
					RotateRight(parentNode);
				}

				sibling = Sibling(node, parentNode); // update value of sibling after rotation
			}

			if (parentNode.color == BLACK
				&& sibling.color == BLACK
				&& GetColor(sibling.left) == BLACK
				&& GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				FixTreeOnDelete(parentNode, parentNode.parent);
				return;
			}

			if (parentNode.color == RED
				&& sibling.color == BLACK
				&& GetColor(sibling.left) == BLACK
				&& GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				parentNode.color = BLACK;
				return;
			}

			if (node == parentNode.left &&
				sibling.color == BLACK &&
				GetColor(sibling.left) == RED &&
				GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				sibling.left.color = BLACK;
				RotateRight(sibling);
			} else if (node == parentNode.right &&
					   sibling.color == BLACK &&
					   GetColor(sibling.right) == RED &&
					   GetColor(sibling.left) == BLACK) {
				sibling.color = RED;
				sibling.right.color = BLACK;
				RotateLeft(sibling);
			}
			sibling = Sibling(node, parentNode); // update value of sibling after rotation

			sibling.color = parentNode.color;
			parentNode.color = BLACK;
			if (node == parentNode.left) {
				if (sibling.right != null) {
					Debug.replacedert(sibling.right.color == RED);
					sibling.right.color = BLACK;
				}
				RotateLeft(parentNode);
			} else {
				if (sibling.left != null) {
					Debug.replacedert(sibling.left.color == RED);
					sibling.left.color = BLACK;
				}
				RotateRight(parentNode);
			}
		}

19 View Source File : TextAnchorTree.cs
License : MIT License
Project Creator : Abdesol

static TextAnchorNode Sibling(TextAnchorNode node, TextAnchorNode parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (node == parentNode.left)
				return parentNode.right;
			else
				return parentNode.left;
		}

19 View Source File : TextSegmentCollection.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnInsert(TextSegment node)
		{
			Debug.replacedert(node != null);
			Debug.replacedert(node.color == RED);
			Debug.replacedert(node.left == null || node.left.color == BLACK);
			Debug.replacedert(node.right == null || node.right.color == BLACK);

			TextSegment parentNode = node.parent;
			if (parentNode == null) {
				// we inserted in the root -> the node must be black
				// since this is a root node, making the node black increments the number of black nodes
				// on all paths by one, so it is still the same for all paths.
				node.color = BLACK;
				return;
			}
			if (parentNode.color == BLACK) {
				// if the parent node where we inserted was black, our red node is placed correctly.
				// since we inserted a red node, the number of black nodes on each path is unchanged
				// -> the tree is still balanced
				return;
			}
			// parentNode is red, so there is a conflict here!

			// because the root is black, parentNode is not the root -> there is a grandparent node
			TextSegment grandparentNode = parentNode.parent;
			TextSegment uncleNode = Sibling(parentNode);
			if (uncleNode != null && uncleNode.color == RED) {
				parentNode.color = BLACK;
				uncleNode.color = BLACK;
				grandparentNode.color = RED;
				FixTreeOnInsert(grandparentNode);
				return;
			}
			// now we know: parent is red but uncle is black
			// First rotation:
			if (node == parentNode.right && parentNode == grandparentNode.left) {
				RotateLeft(parentNode);
				node = node.left;
			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
				RotateRight(parentNode);
				node = node.right;
			}
			// because node might have changed, rereplacedign variables:
			parentNode = node.parent;
			grandparentNode = parentNode.parent;

			// Now recolor a bit:
			parentNode.color = BLACK;
			grandparentNode.color = RED;
			// Second rotation:
			if (node == parentNode.left && parentNode == grandparentNode.left) {
				RotateRight(grandparentNode);
			} else {
				// because of the first rotation, this is guaranteed:
				Debug.replacedert(node == parentNode.right && parentNode == grandparentNode.right);
				RotateLeft(grandparentNode);
			}
		}

19 View Source File : TextSegmentCollection.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnDelete(TextSegment node, TextSegment parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (parentNode == null)
				return;

			// warning: node may be null
			TextSegment sibling = Sibling(node, parentNode);
			if (sibling.color == RED) {
				parentNode.color = RED;
				sibling.color = BLACK;
				if (node == parentNode.left) {
					RotateLeft(parentNode);
				} else {
					RotateRight(parentNode);
				}

				sibling = Sibling(node, parentNode); // update value of sibling after rotation
			}

			if (parentNode.color == BLACK
				&& sibling.color == BLACK
				&& GetColor(sibling.left) == BLACK
				&& GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				FixTreeOnDelete(parentNode, parentNode.parent);
				return;
			}

			if (parentNode.color == RED
				&& sibling.color == BLACK
				&& GetColor(sibling.left) == BLACK
				&& GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				parentNode.color = BLACK;
				return;
			}

			if (node == parentNode.left &&
				sibling.color == BLACK &&
				GetColor(sibling.left) == RED &&
				GetColor(sibling.right) == BLACK) {
				sibling.color = RED;
				sibling.left.color = BLACK;
				RotateRight(sibling);
			} else if (node == parentNode.right &&
					   sibling.color == BLACK &&
					   GetColor(sibling.right) == RED &&
					   GetColor(sibling.left) == BLACK) {
				sibling.color = RED;
				sibling.right.color = BLACK;
				RotateLeft(sibling);
			}
			sibling = Sibling(node, parentNode); // update value of sibling after rotation

			sibling.color = parentNode.color;
			parentNode.color = BLACK;
			if (node == parentNode.left) {
				if (sibling.right != null) {
					Debug.replacedert(sibling.right.color == RED);
					sibling.right.color = BLACK;
				}
				RotateLeft(parentNode);
			} else {
				if (sibling.left != null) {
					Debug.replacedert(sibling.left.color == RED);
					sibling.left.color = BLACK;
				}
				RotateRight(parentNode);
			}
		}

19 View Source File : TextSegmentCollection.cs
License : MIT License
Project Creator : Abdesol

static TextSegment Sibling(TextSegment node, TextSegment parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (node == parentNode.left)
				return parentNode.right;
			else
				return parentNode.left;
		}

19 View Source File : HeightTree.cs
License : MIT License
Project Creator : Abdesol

static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (node == parentNode.left)
				return parentNode.right;
			else
				return parentNode.left;
		}

19 View Source File : HeightTree.cs
License : MIT License
Project Creator : Abdesol

void BeforeNodeRemove(HeightTreeNode removedNode)
		{
			Debug.replacedert(removedNode.left == null || removedNode.right == null);

			var collapsed = removedNode.collapsedSections;
			if (collapsed != null) {
				HeightTreeNode childNode = removedNode.left ?? removedNode.right;
				if (childNode != null) {
					foreach (CollapsedLineSection cs in collapsed)
						childNode.AddDirectlyCollapsed(cs);
				}
			}
			if (removedNode.parent != null)
				MergeCollapsedSectionsIfPossible(removedNode.parent);
		}

19 View Source File : HeightTree.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnInsert(HeightTreeNode node)
		{
			Debug.replacedert(node != null);
			Debug.replacedert(node.color == RED);
			Debug.replacedert(node.left == null || node.left.color == BLACK);
			Debug.replacedert(node.right == null || node.right.color == BLACK);

			HeightTreeNode parentNode = node.parent;
			if (parentNode == null) {
				// we inserted in the root -> the node must be black
				// since this is a root node, making the node black increments the number of black nodes
				// on all paths by one, so it is still the same for all paths.
				node.color = BLACK;
				return;
			}
			if (parentNode.color == BLACK) {
				// if the parent node where we inserted was black, our red node is placed correctly.
				// since we inserted a red node, the number of black nodes on each path is unchanged
				// -> the tree is still balanced
				return;
			}
			// parentNode is red, so there is a conflict here!

			// because the root is black, parentNode is not the root -> there is a grandparent node
			HeightTreeNode grandparentNode = parentNode.parent;
			HeightTreeNode uncleNode = Sibling(parentNode);
			if (uncleNode != null && uncleNode.color == RED) {
				parentNode.color = BLACK;
				uncleNode.color = BLACK;
				grandparentNode.color = RED;
				FixTreeOnInsert(grandparentNode);
				return;
			}
			// now we know: parent is red but uncle is black
			// First rotation:
			if (node == parentNode.right && parentNode == grandparentNode.left) {
				RotateLeft(parentNode);
				node = node.left;
			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
				RotateRight(parentNode);
				node = node.right;
			}
			// because node might have changed, rereplacedign variables:
			parentNode = node.parent;
			grandparentNode = parentNode.parent;

			// Now recolor a bit:
			parentNode.color = BLACK;
			grandparentNode.color = RED;
			// Second rotation:
			if (node == parentNode.left && parentNode == grandparentNode.left) {
				RotateRight(grandparentNode);
			} else {
				// because of the first rotation, this is guaranteed:
				Debug.replacedert(node == parentNode.right && parentNode == grandparentNode.right);
				RotateLeft(grandparentNode);
			}
		}

19 View Source File : HeightTree.cs
License : MIT License
Project Creator : Abdesol

void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
		{
			Debug.replacedert(node == null || node.parent == parentNode);
			if (parentNode == null)
				return;

			// warning: node may be null
			HeightTreeNode sibling = Sibling(node, parentNode);
			if (sibling.color == RED) {
				parentNode.color = RED;
				sibling.color = BLACK;
				if (node == parentNode.left) {
					RotateLeft(parentNode);
				} else {
					RotateRight(parentNode);
				}

				sibling = Sibling(node, parentNode); // update value of sibling after rotation
			}

			if (parentNode.color == BLACK
			    && sibling.color == BLACK
			    && GetColor(sibling.left) == BLACK
			    && GetColor(sibling.right) == BLACK)
			{
				sibling.color = RED;
				FixTreeOnDelete(parentNode, parentNode.parent);
				return;
			}

			if (parentNode.color == RED
			    && sibling.color == BLACK
			    && GetColor(sibling.left) == BLACK
			    && GetColor(sibling.right) == BLACK)
			{
				sibling.color = RED;
				parentNode.color = BLACK;
				return;
			}

			if (node == parentNode.left &&
			    sibling.color == BLACK &&
			    GetColor(sibling.left) == RED &&
			    GetColor(sibling.right) == BLACK)
			{
				sibling.color = RED;
				sibling.left.color = BLACK;
				RotateRight(sibling);
			}
			else if (node == parentNode.right &&
			         sibling.color == BLACK &&
			         GetColor(sibling.right) == RED &&
			         GetColor(sibling.left) == BLACK)
			{
				sibling.color = RED;
				sibling.right.color = BLACK;
				RotateLeft(sibling);
			}
			sibling = Sibling(node, parentNode); // update value of sibling after rotation

			sibling.color = parentNode.color;
			parentNode.color = BLACK;
			if (node == parentNode.left) {
				if (sibling.right != null) {
					Debug.replacedert(sibling.right.color == RED);
					sibling.right.color = BLACK;
				}
				RotateLeft(parentNode);
			} else {
				if (sibling.left != null) {
					Debug.replacedert(sibling.left.color == RED);
					sibling.left.color = BLACK;
				}
				RotateRight(parentNode);
			}
		}

19 View Source File : WindowExtensions.cs
License : MIT License
Project Creator : Accelerider

public static void ShowAndActivate(this Window window)
        {
            try
            {
                Debug.replacedert(window.Dispatcher.CheckAccess());

                window.Dispatcher.Invoke(() =>
                {
                    window.Show();
                    window.ActivateWindow();
                });
            }
            catch (Exception e)
            {
                Logger.Error($"An exception occured in the {window.Content.GetType()} dialog.", e);
            }
        }

19 View Source File : ChessLogic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public BasePiece AddPiece(ChessColor color, ChessPieceType type, uint x, uint y)
        {
            var to = new ChessPieceCoord((int)x, (int)y);
            Debug.replacedert(to.IsValid());

            BasePiece piece = null;
            switch (type)
            {
                case ChessPieceType.Pawn:
                    piece = new PawnPiece(color, to);
                    break;

                case ChessPieceType.Rook:
                    piece = new RookPiece(color, to);
                    break;

                case ChessPieceType.Knight:
                    piece = new KnightPiece(color, to);
                    break;

                case ChessPieceType.Bishop:
                    piece = new BishopPiece(color, to);
                    break;

                case ChessPieceType.Queen:
                    piece = new QueenPiece(color, to);
                    break;

                case ChessPieceType.King:
                    piece = new KingPiece(color, to);
                    break;

                default:
                    Debug.replacedert(false);
                    break;
            }

            return Board[x + y * Chess.BoardSize] = piece;
        }

19 View Source File : Trajectory.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool solve_ballistic_arc_lateral(Vector3 proj_pos, float lateral_speed, Vector3 target_pos, float max_height, out Vector3 fire_velocity, out float gravity)
        {
            // Handling these cases is up to your project's coding standards
            Debug.replacedert(proj_pos != target_pos && lateral_speed > 0 && max_height > proj_pos.Z, "fts.solve_ballistic_arc called with invalid data");

            fire_velocity = Vector3.Zero;
            gravity = float.NaN;

            if (proj_pos == target_pos || lateral_speed <= 0 || max_height <= proj_pos.Z)
                return false;

            Vector3 diff = target_pos - proj_pos;
            Vector3 diffXY = new Vector3(diff.X, diff.Y, 0f);
            float lateralDist = diffXY.Length();

            if (lateralDist == 0)
                return false;

            float time = lateralDist / lateral_speed;

            fire_velocity = Vector3.Normalize(diffXY) * lateral_speed;

            // System of equations. Hit max_height at t=.5*time. Hit target at t=time.
            //
            // peak = z0 + vertical_speed*halfTime + .5*gravity*halfTime^2
            // end = z0 + vertical_speed*time + .5*gravity*time^s
            // Wolfram Alpha: solve b = a + .5*v*t + .5*g*(.5*t)^2, c = a + vt + .5*g*t^2 for g, v
            float a = proj_pos.Z;       // initial
            float b = max_height;       // peak
            float c = target_pos.Z;     // final

            gravity = -4 * (a - 2 * b + c) / (time * time);
            fire_velocity.Z = -(3 * a - 4 * b + c) / time;

            return true;
        }

19 View Source File : Trajectory.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public static bool solve_ballistic_arc_lateral(Vector3 proj_pos, float lateral_speed, Vector3 target, Vector3 target_velocity, float gravity, out Vector3 fire_velocity, out float time, out Vector3 impact_point)
        {

            // Handling these cases is up to your project's coding standards
            Debug.replacedert(proj_pos != target && lateral_speed > 0, "fts.solve_ballistic_arc_lateral called with invalid data");

            // Initialize output variables
            fire_velocity = Vector3.Zero;
            time = 0.0f;
            impact_point = Vector3.Zero;

            // Ground plane terms
            Vector3 targetVelXY = new Vector3(target_velocity.X, target_velocity.Y, 0f);
            Vector3 diffXY = target - proj_pos;
            diffXY.Z = 0;

            // Derivation
            //   (1) Base formula: |P + V*t| = S*t
            //   (2) Subsreplacedute variables: |diffXY + targetVelXY*t| = S*t
            //   (3) Square both sides: Dot(diffXY,diffXY) + 2*Dot(diffXY, targetVelXY)*t + Dot(targetVelXY, targetVelXY)*t^2 = S^2 * t^2
            //   (4) Quadratic: (Dot(targetVelXY,targetVelXY) - S^2)t^2 + (2*Dot(diffXY, targetVelXY))*t + Dot(diffXY, diffXY) = 0
            float c0 = Vector3.Dot(targetVelXY, targetVelXY) - lateral_speed * lateral_speed;
            float c1 = 2f * Vector3.Dot(diffXY, targetVelXY);
            float c2 = Vector3.Dot(diffXY, diffXY);
            double t0, t1;
            int n = SolveQuadric(c0, c1, c2, out t0, out t1);

            // pick smallest, positive time
            bool valid0 = n > 0 && t0 > 0;
            bool valid1 = n > 1 && t1 > 0;

            float t;
            if (!valid0 && !valid1)
                return false;
            else if (valid0 && valid1)
                t = Math.Min((float)t0, (float)t1);
            else
                t = valid0 ? (float)t0 : (float)t1;

            // Calculate impact point
            impact_point = target + (target_velocity * t);

            // Calculate fire velocity along XZ plane
            Vector3 dir = impact_point - proj_pos;
            fire_velocity = new Vector3(dir.X, dir.Y, 0f).Normalize() * lateral_speed;

            // Solve system of equations. Hit max_height at t=.5*time. Hit target at t=time.
            //
            // peak = z0 + vertical_speed*halfTime + .5*gravity*halfTime^2
            // end = z0 + vertical_speed*time + .5*gravity*time^s
            // Wolfram Alpha: solve b = a + .5*v*t + .5*g*(.5*t)^2, c = a + vt + .5*g*t^2 for g, v
            float a = proj_pos.Z;       // initial
            //float b = Math.Max(proj_pos.Z, impact_point.Z) + max_height_offset;  // peak
            float c = impact_point.Z;   // final

            //gravity = -4 * (a - 2 * b + c) / (t * t);
            //fire_velocity.Z = -(3 * a - 4 * b + c) / t;

            var g = gravity;
            var b = (4 * a + 4 * c - g * t * t) / 8;

            fire_velocity.Z = (2 * a - 2 * c + g * t * t) / (t * 2) * -1;

            time = t;

            return true;
        }

19 View Source File : Trajectory.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public static bool SolveBallisticArc(Vector3 projectilePosition, float lateralSpeed, Vector3 targetPosition, out Vector3 velocityVector, out float time)
        {

            // Handling these cases is up to your project's coding standards
            Debug.replacedert(projectilePosition != targetPosition && lateralSpeed > 0, "fts.solve_ballistic_arc called with invalid data");

            velocityVector = Vector3.Zero;
            time = float.NaN;

            Vector3 diff = targetPosition - projectilePosition;
            Vector3 diffXY = new Vector3(diff.X, diff.Y, 0f);
            float lateralDist = diffXY.Length();

            if (lateralDist == 0)
                return false;

            time = lateralDist / lateralSpeed;

            velocityVector = diffXY.Normalize() * lateralSpeed;

            // System of equations. Hit max_height at t=.5*time. Hit target at t=time.
            //
            // peak = z0 + vertical_speed*halfTime + .5*gravity*halfTime^2
            // end = z0 + vertical_speed*time + .5*gravity*time^s
            // Wolfram Alpha: solve b = a + .5*v*t + .5*g*(.5*t)^2, c = a + vt + .5*g*t^2 for g, v
            float a = projectilePosition.Z; // initial
            float c = targetPosition.Z;     // final

            // Gravity value pulled from ACE property
            var g = PhysicsGlobals.Gravity;
            var b = (4 * a + 4 * c - g * time * time) / 8;

            velocityVector.Z = (2 * a - 2 * c + g * time * time) / (time * 2) * -1;

            return true;
        }

19 View Source File : Trajectory.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public static bool solve_ballistic_arc_lateral(Vector3 proj_pos, float lateral_speed, Vector3 target_pos, float max_height, out Vector3 fire_velocity, out float gravity)
        {

            // Handling these cases is up to your project's coding standards
            Debug.replacedert(proj_pos != target_pos && lateral_speed > 0 && max_height > proj_pos.Z, "fts.solve_ballistic_arc called with invalid data");

            fire_velocity = Vector3.Zero;
            gravity = float.NaN;

            Vector3 diff = target_pos - proj_pos;
            Vector3 diffXY = new Vector3(diff.X, diff.Y, 0f);
            float lateralDist = diffXY.Length();

            if (lateralDist == 0)
                return false;

            float time = lateralDist / lateral_speed;

            fire_velocity = diffXY.Normalize() * lateral_speed;

            // System of equations. Hit max_height at t=.5*time. Hit target at t=time.
            //
            // peak = z0 + vertical_speed*halfTime + .5*gravity*halfTime^2
            // end = z0 + vertical_speed*time + .5*gravity*time^s
            // Wolfram Alpha: solve b = a + .5*v*t + .5*g*(.5*t)^2, c = a + vt + .5*g*t^2 for g, v
            float a = proj_pos.Z;       // initial
            float b = max_height;       // peak
            float c = target_pos.Z;     // final

            gravity = -4 * (a - 2 * b + c) / (time * time);
            fire_velocity.Z = -(3 * a - 4 * b + c) / time;

            return true;
        }

19 View Source File : Trajectory.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public static int solve_ballistic_arc(Vector3 proj_pos, float proj_speed, Vector3 target, float gravity, out Vector3 s0, out Vector3 s1, out float t0, out float t1)
        {

            // Handling these cases is up to your project's coding standards
            Debug.replacedert(proj_pos != target && proj_speed > 0 && gravity > 0, "fts.solve_ballistic_arc called with invalid data");

            // C# requires out variables be set
            s0 = Vector3.Zero;
            s1 = Vector3.Zero;
            t0 = float.PositiveInfinity;
            t1 = float.PositiveInfinity;

            // Derivation
            //   (1) x = v*t*cos O
            //   (2) z = v*t*sin O - .5*g*t^2
            // 
            //   (3) t = x/(cos O*v)                                        [solve t from (1)]
            //   (4) z = v*x*sin O/(cos O * v) - .5*g*x^2/(cos^2 O*v^2)     [plug t into z=...]
            //   (5) z = x*tan O - g*x^2/(2*v^2*cos^2 O)                    [reduce; cos/sin = tan]
            //   (6) z = x*tan O - (g*x^2/(2*v^2))*(1+tan^2 O)              [reduce; 1+tan O = 1/cos^2 O]
            //   (7) 0 = ((-g*x^2)/(2*v^2))*tan^2 O + x*tan O - (g*x^2)/(2*v^2) - z    [re-arrange]
            //   Quadratic! a*p^2 + b*p + c where p = tan O
            //
            //   (8) let gxv = -g*x*x/(2*v*v)
            //   (9) p = (-x +- sqrt(x*x - 4gxv*(gxv - z)))/2*gxv           [quadratic formula]
            //   (10) p = (v^2 +- sqrt(v^4 - g(g*x^2 + 2*z*v^2)))/gx        [multiply top/bottom by -2*v*v/x; move 4*v^4/x^2 into root]
            //   (11) O = atan(p)

            Vector3 diff = target - proj_pos;
            Vector3 diffXY = new Vector3(diff.X, diff.Y, 0);
            float groundDist = diffXY.Length();

            float speed2 = proj_speed * proj_speed;
            float speed4 = proj_speed * proj_speed * proj_speed * proj_speed;
            float z = diff.Z;
            float x = groundDist;
            float gx = gravity * x;

            float root = speed4 - gravity * (gravity * x * x + 2 * z * speed2);

            // No solution
            if (root < 0)
                return 0;

            root = (float)Math.Sqrt(root);

            var lowAng = Math.Atan2(speed2 - root, gx);
            var highAng = Math.Atan2(speed2 + root, gx);
            int numSolutions = lowAng != highAng ? 2 : 1;

            Vector3 groundDir = diffXY.Normalize();
            s0 = groundDir * (float)Math.Cos(lowAng) * proj_speed + Vector3.UnitZ * (float)Math.Sin(lowAng) * proj_speed;
            if (numSolutions > 1)
                s1 = groundDir * (float)Math.Cos(highAng) * proj_speed + Vector3.UnitZ * (float)Math.Sin(highAng) * proj_speed;

            t0 = x / ((float)Math.Cos(lowAng) * proj_speed);
            t1 = x / ((float)Math.Cos(highAng) * proj_speed);

            return numSolutions;
        }

19 View Source File : WrappedException.cs
License : MIT License
Project Creator : actions

private Exception UnWrap(Exception innerException)
        {
            Exception exception = null;
            if (this.Type != null)  // m_type is typically null when this.Type getter is hit from here, so the LoadType method will get invoked here.
            {
                try
                {
                    Object[] args = null;

                    ConstructorInfo info = GetMatchingConstructor(new[] { typeof(WrappedException) });
                    if (info != null)
                    {
                        // a constructor overload on an exception that takes a WrappedException, is useful
                        // in cases where the other constructors manipulate the string that we preplaced in,
                        // which we do not want to happen when unwrapping an exception.
                        args = new object[] { this };
                    }
                    else
                    {
                        info = GetMatchingConstructor(new[] { typeof(String), typeof(Exception) });
                        if (info != null)
                        {
                            args = new object[] { Message, innerException };
                        }
                        else
                        {
                            //try just string
                            info = GetMatchingConstructor(new[] { typeof(String) });
                            if (info != null)
                            {
                                args = new object[] { Message };
                            }
                            else
                            {
                                //try default constructor
                                info = GetMatchingConstructor(new Type[0]);
                            }
                        }
                    }
                    if (info != null)
                    {
                        exception = info.Invoke(args) as Exception;
                        // only check exceptions that derive from VssExceptions, since we don't have control
                        // to make code changes to exceptions that we don't own.
                        Debug.replacedert(!(exception is VssException) || exception.Message == Message,
                            "The unwrapped exception message does not match the original exception message.",
                            "Type: {0}{1}Expected: {2}{1}Actual: {3}{1}{1}This can happen if the exception has a contructor that manipulates the input string.  You can work around this by creating a constructor that takes in a WrappedException which sets the message verbatim and optionally the inner exception.",
                            exception.GetType(),
                            Environment.NewLine,
                            Message,
                            exception.Message);
                    }
                }
                catch (Exception)
                { }
            }
            return exception;
        }

19 View Source File : ExtendedViewLocalizer.cs
License : MIT License
Project Creator : adams85

public void Contextualize(ViewContext viewContext)
        {
            if (viewContext == null)
                throw new ArgumentNullException(nameof(viewContext));

            // Given a view path "/Views/Home/Index.cshtml" we want a baseName like "MyApplication.Views.Home.Index"
            var path = viewContext.ExecutingFilePath;

            if (string.IsNullOrEmpty(path))
            {
                path = viewContext.View.Path;
            }

            Debug.replacedert(!string.IsNullOrEmpty(path), "Couldn't determine a path for the view");
            
            var location =
                (viewContext.View is RazorView razorView ? replacedociatedreplacedemblyNameAttribute.GetCachedFor(razorView.RazorPage.GetType())?.replacedemblyName.Name : null) ??
                _applicationName;

            _localizer = _localizerFactory.Create(BuildBaseName(path, location), location);
        }

19 View Source File : ILASTTypeInference.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static ASTType? InferPush1(ILASTExpression expr)
        {
            switch(expr.ILCode)
            {
                case Code.Add:
                case Code.Add_Ovf:
                case Code.Add_Ovf_Un:
                case Code.Sub:
                case Code.Sub_Ovf:
                case Code.Sub_Ovf_Un:
                case Code.Mul:
                case Code.Mul_Ovf:
                case Code.Mul_Ovf_Un:
                case Code.Div:
                case Code.Div_Un:
                case Code.Rem:
                case Code.Rem_Un:
                    Debug.replacedert(expr.Arguments.Length == 2);
                    Debug.replacedert(expr.Arguments[0].Type != null && expr.Arguments[1].Type != null);
                    return TypeInference.InferBinaryOp(expr.Arguments[0].Type.Value, expr.Arguments[1].Type.Value);

                case Code.Xor:
                case Code.And:
                case Code.Or:
                    Debug.replacedert(expr.Arguments.Length == 2);
                    Debug.replacedert(expr.Arguments[0].Type != null && expr.Arguments[1].Type != null);
                    return TypeInference.InferIntegerOp(expr.Arguments[0].Type.Value, expr.Arguments[1].Type.Value);

                case Code.Not:
                    Debug.replacedert(expr.Arguments.Length == 1 && expr.Arguments[0].Type != null);
                    if(expr.Arguments[0].Type != ASTType.I4 &&
                       expr.Arguments[0].Type != ASTType.I8 &&
                       expr.Arguments[0].Type != ASTType.Ptr)
                        throw new ArgumentException("Invalid Not Operand Types.");
                    return expr.Arguments[0].Type;

                case Code.Neg:
                    Debug.replacedert(expr.Arguments.Length == 1 && expr.Arguments[0].Type != null);
                    if(expr.Arguments[0].Type != ASTType.I4 &&
                       expr.Arguments[0].Type != ASTType.I8 &&
                       expr.Arguments[0].Type != ASTType.R4 &&
                       expr.Arguments[0].Type != ASTType.R8 &&
                       expr.Arguments[0].Type != ASTType.Ptr)
                        throw new ArgumentException("Invalid Not Operand Types.");
                    return expr.Arguments[0].Type;

                case Code.Shr:
                case Code.Shl:
                case Code.Shr_Un:
                    Debug.replacedert(expr.Arguments.Length == 2);
                    Debug.replacedert(expr.Arguments[0].Type != null && expr.Arguments[1].Type != null);
                    return TypeInference.InferShiftOp(expr.Arguments[0].Type.Value, expr.Arguments[1].Type.Value);

                case Code.Mkrefany:
                    return ASTType.O;

                case Code.Ldarg:
                    return TypeInference.ToASTType(((Parameter) expr.Operand).Type);
                case Code.Ldloc:
                    return TypeInference.ToASTType(((Local) expr.Operand).Type);

                case Code.Unbox_Any:
                case Code.Ldelem:
                case Code.Ldobj:
                    return TypeInference.ToASTType(((ITypeDefOrRef) expr.Operand).ToTypeSig());

                case Code.Ldfld:
                case Code.Ldsfld:
                    return TypeInference.ToASTType(((IField) expr.Operand).FieldSig.Type);

                default:
                    throw new NotSupportedException(expr.ILCode.ToString());
            }
        }

19 View Source File : BranchHandlers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public void Translate(IRInstruction instr, ILTranslator tr)
        {
            tr.PushOperand(instr.Operand2);
            tr.PushOperand(instr.Operand1);

            var lastInstr = tr.Instructions[tr.Instructions.Count - 1];
            Debug.replacedert(lastInstr.OpCode == ILOpCode.PUSHI_DWORD && lastInstr.Operand is ILJumpTable);

            var switchInstr = new ILInstruction(ILOpCode.SWT)
            {
                Annotation = InstrAnnotation.JUMP
            };
            tr.Instructions.Add(switchInstr);

            var jmpTable = (ILJumpTable) lastInstr.Operand;
            jmpTable.Chunk.runtime = tr.Runtime;
            jmpTable.RelativeBase = switchInstr;
            tr.Runtime.AddChunk(jmpTable.Chunk);
        }

19 View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

IRRegister ReadRegister(Node node) {
			var type = ASTType.I4;
			TypeSig rawType = null;
			VMRegisters? reg = null;

			for (int i = 0; i < node.Count; i++) {
				var child = node[i];
				if (child.Id == (int)IRConstants.TYPE) {
					ReadType(child, ref type, ref rawType);
				}
				else if (child.Id == (int)IRConstants.REG) {
					var token = (Token)child;
					reg = (VMRegisters)Enum.Parse(typeof(VMRegisters), token.Image);
				}
			}
			Debug.replacedert(reg != null);
			return new IRRegister(reg.Value, type) {
				SourceVariable = rawType == null ? null : GetTypedVariable(type, rawType)
			};
		}

19 View Source File : BlockParser.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static List<BasicBlock<CILInstrList>> SplitBlocks(CilBody body, HashSet<Instruction> headers,
            HashSet<Instruction> entries)
        {
            var nextBlockId = 0;
            var currentBlockId = -1;
            Instruction currentBlockHdr = null;
            var blocks = new List<BasicBlock<CILInstrList>>();

            var instrList = new CILInstrList();
            for(var i = 0; i < body.Instructions.Count; i++)
            {
                var instr = body.Instructions[i];
                if(headers.Contains(instr))
                {
                    if(currentBlockHdr != null)
                    {
                        var footer = body.Instructions[i - 1];

                        Debug.replacedert(instrList.Count > 0);
                        blocks.Add(new BasicBlock<CILInstrList>(currentBlockId, instrList));
                        instrList = new CILInstrList();
                    }

                    currentBlockId = nextBlockId++;
                    currentBlockHdr = instr;
                }

                instrList.Add(instr);
            }
            if(blocks.Count == 0 || blocks[blocks.Count - 1].Id != currentBlockId)
            {
                var footer = body.Instructions[body.Instructions.Count - 1];

                Debug.replacedert(instrList.Count > 0);
                blocks.Add(new BasicBlock<CILInstrList>(currentBlockId, instrList));
            }
            return blocks;
        }

19 View Source File : ConstantTypePromotionTransform.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private void VisitInstr(IRInstrList instrs, IRInstruction instr, ref int index, IRTransformer tr)
        {
            switch(instr.OpCode)
            {
                case IROpCode.MOV:
                case IROpCode.NOR:
                case IROpCode.CMP:
                case IROpCode.ADD:
                case IROpCode.MUL:
                case IROpCode.DIV:
                case IROpCode.REM:
                case IROpCode.__OR:
                case IROpCode.__AND:
                case IROpCode.__XOR:
                case IROpCode.__GETF:
                    break;
                default:
                    return;
            }
            Debug.replacedert(instr.Operand1 != null && instr.Operand2 != null);
            if(instr.Operand1 is IRConstant) instr.Operand1 = PromoteConstant((IRConstant) instr.Operand1, instr.Operand2.Type);
            if(instr.Operand2 is IRConstant) instr.Operand2 = PromoteConstant((IRConstant) instr.Operand2, instr.Operand1.Type);
        }

19 View Source File : EHTransform.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private void AddTryStart(IRTransformer tr)
        {
            var tryStartInstrs = new List<IRInstruction>();
            for(var i = 0; i < thisScopes.Length; i++)
            {
                var scope = thisScopes[i];
                if(scope.Type != ScopeType.Try)
                    continue;
                if(scope.GetBasicBlocks().First() != tr.Block)
                    continue;

                // Search for handler/filter
                IBasicBlock handler = null, filter = null;
                SearchForHandlers(tr.RootScope, scope.ExceptionHandler, ref handler, ref filter);
                Debug.replacedert(handler != null &&
                             (scope.ExceptionHandler.HandlerType != ExceptionHandlerType.Filter || filter != null));

                // Add instructions
                tryStartInstrs.Add(new IRInstruction(IROpCode.PUSH, new IRBlockTarget(handler)));

                IIROperand tryOperand = null;
                int ehType;
                if(scope.ExceptionHandler.HandlerType == ExceptionHandlerType.Catch)
                {
                    tryOperand = IRConstant.FromI4((int) tr.VM.Data.GetId(scope.ExceptionHandler.CatchType));
                    ehType = tr.VM.Runtime.RTFlags.EH_CATCH;
                }
                else if(scope.ExceptionHandler.HandlerType == ExceptionHandlerType.Filter)
                {
                    tryOperand = new IRBlockTarget(filter);
                    ehType = tr.VM.Runtime.RTFlags.EH_FILTER;
                }
                else if(scope.ExceptionHandler.HandlerType == ExceptionHandlerType.Fault)
                {
                    ehType = tr.VM.Runtime.RTFlags.EH_FAULT;
                }
                else if(scope.ExceptionHandler.HandlerType == ExceptionHandlerType.Finally)
                {
                    ehType = tr.VM.Runtime.RTFlags.EH_FINALLY;
                }
                else
                {
                    throw new InvalidProgramException();
                }

                tryStartInstrs.Add(new IRInstruction(IROpCode.TRY, IRConstant.FromI4(ehType), tryOperand)
                {
                    Annotation = new EHInfo(scope.ExceptionHandler)
                });
            }
            tr.Instructions.InsertRange(0, tryStartInstrs);
        }

19 View Source File : TranslationHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static void EmitCompareEq(IRTranslator tr, ASTType type, IIROperand a, IIROperand b)
        {
            if(type == ASTType.O || type == ASTType.ByRef ||
               type == ASTType.R4 || type == ASTType.R8)
            {
                tr.Instructions.Add(new IRInstruction(IROpCode.CMP, a, b));
            }
            else
            {
                // I4/I8/Ptr
                Debug.replacedert(type == ASTType.I4 || type == ASTType.I8 || type == ASTType.Ptr);
                tr.Instructions.Add(new IRInstruction(IROpCode.CMP, a, b));
            }
        }

19 View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected virtual bool CheckFieldMaps()
        {
            var row = Sheet.GetRow(0);
            ColumnFields = new Dictionary<int, string>();
            var emptyCnt = 0;
            MaxColumn = 0;
            for (var column = 0; column < short.MaxValue; column++)
            {
                MaxColumn = column;
                var cell = row.GetCell(column);
                if (cell == null)
                {
                    if (++emptyCnt > 3)
                    {
                        break;
                    }
                    continue;
                }
                if (cell.CellType != CellType.String)
                {
                    cell.SetCellType(CellType.String);
                }
                var field = cell.StringCellValue;
                if (string.IsNullOrWhiteSpace(field))
                {
                    if (++emptyCnt > 3)
                    {
                        break;
                    }
                    continue;
                }
                if (emptyCnt > 0)
                {
                    WriteCellState(row, column, "�ֶ�����Ϊ�հ�,����ֱ����ֹ", true);
                    return false;
                }
                emptyCnt = 0;
                ColumnFields.Add(cell.ColumnIndex, field.Trim());
            }
            MaxColumn += 1;
            foreach (var f in ColumnFields)
            {
                Debug.replacedert(Access.FieldDictionary.ContainsKey(f.Value));
            }
            return true;
        }

19 View Source File : MySqlTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string CreateLoadValueSql(string field, string condition)
        {
            Debug.replacedert(FieldDictionary.ContainsKey(field));
            return [email protected]"SELECT `{FieldDictionary[field]}` FROM {ContextReadTable}{ConreplacedionSqlCode(condition)};";
        }

19 View Source File : MySqlTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public string FieldConditionSQL(string field, string expression = "=")
        {
            Debug.replacedert(FieldDictionary.ContainsKey(field));
            return [email protected]"`{FieldDictionary[field]}` {expression} ?{field}";
        }

19 View Source File : SqlServerTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private string CreateLoadValueSql(string field, string condition)
        {
            Debug.replacedert(FieldDictionary.ContainsKey(field));
            return [email protected]"SELECT [{FieldMap[field]}] FROM {ContextReadTable}{ConreplacedionSqlCode(condition)};";
        }

19 View Source File : SqlServerTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public string FieldConditionSQL(string field, string expression = "=")
        {
            Debug.replacedert(FieldDictionary.ContainsKey(field));
            return [email protected]"[{FieldMap[field]}] {expression} @{field}";
        }

19 View Source File : StackUseAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private void replacedyzeCodePath(Stack<StackValue> stack, CodePath path, ref int tempVarIndex)
        {
            HLInstruction instruction = path.GetFirstInstruction();
            while (instruction != null)
            {
                try
                {
                    if (instruction.BranchFunction != null)
                    {
                        if (!instruction.Instruction.HreplacedtackUsageInfo)
                        {
                            instruction.Instruction.StackIn = instruction.BranchFunction.ParameterCount;
                            instruction.Instruction.StackOut = instruction.BranchFunction.ReturnCount;
                            instruction.Instruction.StackLeftOver = 0;
                            instruction.Instruction.HreplacedtackUsageInfo = true;
                        }
                    }

                    if (instruction.UnconditionalBranch)
                    {
                        // One should not even occur
                        //Debug.replacedert(false);
                    }
                    else if (instruction.ExitFunction)
                    {
                        var value = new StackValueOperation(StackValueOperationType.Return);

                        if (path.ParentFunction.ReturnCount > 0)
                        {
                            for (int i = 0; i < path.ParentFunction.ReturnCount; i++)
                            {
                                value.Operands.Add(stack.Pop());
                            }
                        }

                        instruction.ProcessedStackValue = value;
                    }
                    else if (instruction.IsConditionalBranch || instruction.IsSwitchBranch)
                    {
                        instruction.ProcessedStackValue = stack.Pop();
                    }
                    else
                    {
                        bool processDefault = false;

                        StackValueOperation operationValue = null;
                        StackValue tempAnyValue;
                        StackValueOperation tempOpValue;
                        StackValueLiteral tempLiteralValue;
                        StackValuePointerBase tempPointerValue;

                        OpCode opCode = instruction.Instruction.OpCode;
                        switch (opCode)
                        {
                            case OpCode.AddVec:
                                VectorOperation(StackValueOperationType.Add, stack);
                                break;
                            case OpCode.SubVec:
                                VectorOperation(StackValueOperationType.Sub, stack);
                                break;
                            case OpCode.MulVec:
                                VectorOperation(StackValueOperationType.Mul, stack);
                                break;
                            case OpCode.DivVec:
                                VectorOperation(StackValueOperationType.Div, stack);
                                break;
                            case OpCode.NegVec:
                                VectorOperation(StackValueOperationType.Neg, stack);
                                break;
                            case OpCode.VecFromF:
                                VectorOperation(StackValueOperationType.FromF, stack);
                                break;
                            case OpCode.PushS:
                                stack.Push(new StackValueLiteral((short) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.Push:
                                stack.Push(new StackValueLiteral((int) (uint) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.PushF:
                                stack.Push(new StackValueLiteral((float) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.PushString:
                                stack.Push(new StackValueLiteral((string) instruction.Instruction.Operands[0]));
                                break;
                            case OpCode.Dup:
                                stack.Push(stack.Peek());
                                break;
                            case OpCode.Pop:
                                tempOpValue = stack.Peek() as StackValueOperation;
                                if (tempOpValue != null && tempOpValue.OperationType == StackValueOperationType.Call)
                                {
                                    operationValue = new StackValueOperation(StackValueOperationType.Pop);
                                    processDefault = true;
                                }
                                break;
                            case OpCode.CallNative:
                                operationValue = new StackValueOperation(instruction.Instruction.Operands[2].ToString());
                                processDefault = true;
                                break;
                            case OpCode.Call:
                                operationValue = new StackValueOperation(instruction.BranchFunction.Name);
                                processDefault = true;
                                break;
                            case OpCode.RefGet:
                                stack.Push(new StackValueDeref(stack.Pop()));
                                break;
                            case OpCode.RefSet:
                                instruction.ProcessedStackValue = new StackValuereplacedign(PopPointer(stack), stack.Pop());
                                break;
                            case OpCode.RefPeekSet:
                                tempAnyValue = stack.Pop(); // value!
                                instruction.ProcessedStackValue = new StackValuereplacedign(PeekPointer(stack), tempAnyValue);
                                break;
                            case OpCode.ArrayExplode:
                                // This is used to either preplaced a structure to a native/function call
                                // or to explode the variables onto the stack to do a "shallow-copy"

                                tempPointerValue = PopPointer(stack);
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var explodeCount = (int) tempLiteralValue.Value;
                                for (int i = 0; i < explodeCount; i++)
                                {
                                    stack.Push(new StackValueDeref(new StackValuePointerIndex(tempPointerValue, i)));
                                }

                                break;
                            case OpCode.ArrayImplode:
                                // The only case this is ever used is for a shallow copy!

                                tempPointerValue = PopPointer(stack);
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var tempStack = new Stack<StackValue>();
                                var implodeCount = (int) tempLiteralValue.Value;
                                for (int i = implodeCount - 1; i >= 0; i--)
                                {
                                    tempStack.Push(
                                        new StackValuereplacedign(new StackValuePointerIndex(tempPointerValue, i),
                                                             stack.Pop()));
                                }

                                var stackValueGroup = new ProcessedStackValueGroup();

                                stackValueGroup.Values.AddRange(tempStack.ToArray());
                                instruction.ProcessedStackValue = stackValueGroup;

                                break;
                            case OpCode.Var0:
                            case OpCode.Var1:
                            case OpCode.Var2:
                            case OpCode.Var3:
                            case OpCode.Var4:
                            case OpCode.Var5:
                            case OpCode.Var6:
                            case OpCode.Var7:
                                stack.Push(new StackValuePointerVar(StackValuePointerType.Stack,
                                                                    (opCode - OpCode.Var0)));
                                break;
                            case OpCode.Var:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerVar(StackValuePointerType.Stack,
                                                                    (int) tempLiteralValue.Value));
                                break;
                            case OpCode.LocalVar:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerVar(StackValuePointerType.Local,
                                                                    (int) tempLiteralValue.Value));
                                break;
                            case OpCode.GlobalVar:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerVar(StackValuePointerType.Global,
                                                                    (int) tempLiteralValue.Value));
                                break;
                            case OpCode.ArrayRef:
                                tempPointerValue = PopPointer(stack);
                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                tempAnyValue = stack.Pop();
                                Debug.replacedert(tempPointerValue != null);
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                stack.Push(new StackValuePointerArray(tempPointerValue, tempAnyValue,
                                                                      (int) tempLiteralValue.Value));
                                break;
                            case OpCode.NullObj:
                                stack.Push(new StackValuePointerVar(StackValuePointerType.Null));
                                break;
                            case OpCode.Add:
                                // Special case for pointer add
                                tempAnyValue = stack.Pop();
                                tempPointerValue = stack.Peek() as StackValuePointerBase;

                                if (tempPointerValue != null)
                                {
                                    stack.Pop(); // tempPointerValue

                                    tempLiteralValue = tempAnyValue as StackValueLiteral;
                                    Debug.replacedert(tempLiteralValue != null && (int) tempLiteralValue.Value%4 == 0);

                                    stack.Push(new StackValuePointerIndex(tempPointerValue,
                                                                          (int) tempLiteralValue.Value/4));
                                }
                                else
                                {
                                    stack.Push(tempAnyValue);
                                    operationValue = new StackValueOperation(opCode);
                                    processDefault = true;
                                }
                                break;
                            case OpCode.StrCat:
                            case OpCode.StrCatI:
                            case OpCode.StrCpy:
                            case OpCode.IntToStr:
                                operationValue = new StackValueStringOperation(opCode, (byte)instruction.Instruction.Operands[0]);
                                processDefault = true;
                                break;
                            case OpCode.StrVarCpy:
                                tempPointerValue = PopPointer(stack);

                                tempLiteralValue = stack.Pop() as StackValueLiteral;
                                
                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var targetSize = (uint)(int)tempLiteralValue.Value;

                                tempLiteralValue = stack.Pop() as StackValueLiteral;

                                Debug.replacedert(tempLiteralValue != null &&
                                             tempLiteralValue.ValueType == StackValueType.Integer);

                                var sourceSize = (uint)(int)tempLiteralValue.Value;

                                var popSize = sourceSize;

                                tempAnyValue = PopPointer(stack);

                                // Pop till the last one
                                for (var i = 1; i < popSize; i++)
                                {
                                    tempAnyValue = PopPointer(stack);
                                }

                                operationValue = new StackValueStringOperation(opCode, targetSize, sourceSize);
                                operationValue.Operands.Add(new StackValueRef(tempAnyValue)); // 0 = source
                                operationValue.Operands.Add(tempPointerValue); // 1 = target
                                
                                instruction.ProcessedStackValue = operationValue;

                                break;
                            case OpCode.RefProtect:
                                tempLiteralValue = stack.Pop() as StackValueLiteral;

                                Debug.replacedert(tempLiteralValue != null &&
                                     tempLiteralValue.ValueType == StackValueType.Integer);

                                var protectMode = (int)tempLiteralValue.Value;

                                Debug.replacedert(protectMode == 1 || protectMode == 2 || protectMode == 5 || protectMode == 6);

                                tempLiteralValue = stack.Pop() as StackValueLiteral;

                                Debug.replacedert(tempLiteralValue != null &&
                                     tempLiteralValue.ValueType == StackValueType.Integer);

                                var protectCount = (int)tempLiteralValue.Value;

                                //Debug.replacedert(protectCount == 1);

                                tempPointerValue = PopPointer(stack);

                                operationValue = new StackValueOperation(StackValueOperationType.RefProtect);
                                operationValue.Operands.Add(tempPointerValue);
                                operationValue.Operands.Add(tempLiteralValue);

                                if ((protectMode & 1) != 0)
                                {
                                    stack.Push(operationValue);
                                }
                                
                                break;
                            default:
                                if (instruction.Instruction is InstructionPush)
                                {
                                    // PushD special case
                                    stack.Push(new StackValueLiteral((int) instruction.Instruction.Operands[0]));
                                }
                                else
                                {
                                    operationValue = new StackValueOperation(opCode);
                                    processDefault = true;
                                }
                                break;
                        }

                        if (processDefault)
                        {
                            Debug.replacedert(instruction.Instruction.HreplacedtackUsageInfo);

                            var stackValues = new Stack<StackValue>();
                            for (int i = 0; i < instruction.Instruction.StackIn; i++)
                            {
                                StackValue stackItem = stack.Pop();
                                stackValues.Push(stackItem);
                            }

                            operationValue.Operands.AddRange(stackValues);

                            if (instruction.Instruction.StackLeftOver > 0)
                            {
                                for (int i = 0; i < instruction.Instruction.StackLeftOver; i++)
                                {
                                    stackValues.Push(stackValues.Pop());
                                }
                            }

                            if (instruction.Instruction.StackOut > 0)
                            {
                                if (instruction.Instruction.StackOut > 1)
                                {
                                    var multireplacedign = new StackValuereplacedignMulti(operationValue);
                                    for (int i = 0; i < instruction.Instruction.StackOut; i++)
                                    {
                                        tempPointerValue = new StackValuePointerVar(StackValuePointerType.Temporary,
                                                                                    tempVarIndex + i);
                                        multireplacedign.replacedignPointers.Add(tempPointerValue);
                                        stack.Push(new StackValueDeref(tempPointerValue));
                                    }
                                    tempVarIndex += instruction.Instruction.StackOut;
                                    instruction.ProcessedStackValue = multireplacedign;
                                }
                                else
                                {
                                    stack.Push(operationValue);
                                }
                            }
                            else
                            {
                                instruction.ProcessedStackValue = operationValue;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(
                        "Error while decompiling instruction : " + instruction.Instruction + "\n", e);
                }

                instruction = instruction.GetNextInstruction();
            }
        }

19 View Source File : HttpSourceResourceProviderTestHost.cs
License : MIT License
Project Creator : ai-traders

public override Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
        {
            Debug.replacedert(source.PackageSource.IsHttp, "HTTP source requested for a non-http source.");

            HttpSourceResource curResource = null;

            if (source.PackageSource.IsHttp)
            {
                curResource = _cache.GetOrAdd(
                    source.PackageSource, 
                    packageSource => new HttpSourceResource(HttpSourceTestHost.Create(source, _httpClient)));
            }

            return Task.FromResult(new Tuple<bool, INuGetResource>(curResource != null, curResource));
        }

19 View Source File : LocalStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private long WriteImageData(Snapshot sshot, Database db)
		{
			long position;
			try
			{
				var sessionDate = db.SelectSingle<DateTime>("SessionInfo", "CreateTime", new { SessionId = sshot.SessionId });
				string path = Path.Combine(DataPath, string.Format(@"{0:yyyy}\{0:MMdd}\{1}.rdt", sessionDate, sshot.SessionId));
				if (!Directory.Exists(Path.GetDirectoryName(path)))
					Directory.CreateDirectory(Path.GetDirectoryName(path));
				using (FileStream fs = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.Read))
				{
					position = fs.Position;
					if (sshot.ImageData != null && sshot.ImageData.Length > 0)
					{
						fs.Write(sshot.ImageData, 0, sshot.ImageData.Length);
					}
					Debug.replacedert(sshot.EventsData != null && sshot.EventsData.Length > 0 && sshot.EventsData.Length % 16 == 0);
					fs.Write(sshot.EventsData, 0, sshot.EventsData.Length);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return position;
		}

19 View Source File : StorageEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static void ScanAndStoreCacheFiles(object state)
		{
			foreach (SessionInfo si in _cache.EnumSessions())
			{
				try
				{
					IEnumerable<Snapshot> snapshtos = _cache.EnumSnapshots(si.SessionId);
					if (snapshtos.GetEnumerator().MoveNext())
						_storage.WriteSessionInfo(si);

					ImageCompressor compressor = new ImageCompressor();
					foreach (Snapshot sshot in snapshtos)
					{
						Debug.replacedert(sshot.ImageData != null && sshot.ImageData.Length > 0);
						try
						{
							if (IsRecordingApp(sshot.ProcessName))
							{
								compressor.CompressSnapshot(sshot, Global.Config.GrayScale);
								_storage.WriteSnapshot(sshot);
							}
							_cache.RemoveSnapshot(sshot.SessionId, sshot.SnapshotId);
						}
						catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
					}
				}
				catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
				if (si.IsEnd)
					_storage.WriteSessionEnd(si.SessionId);
				_cache.TryRemoveSession(si.SessionId);
			}
		}

19 View Source File : StorageEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static void _ScanAndStoreCacheFiles(object state)
		{
			foreach (SessionInfo si in _cache.EnumSessions())
			{
				try
				{
					IEnumerable<Snapshot> snapshtos = _cache.EnumSnapshots(si.SessionId);
					if (snapshtos.GetEnumerator().MoveNext())
						_storage.WriteSessionInfo(si);
					foreach (Snapshot sshot in snapshtos)
					{
						Debug.replacedert(sshot.ImageData != null && sshot.ImageData.Length > 0);
						try
						{
							if (IsRecordingApp(sshot.ProcessName))
								_storage.WriteSnapshot(sshot);
							_cache.RemoveSnapshot(sshot.SessionId, sshot.SnapshotId);
						}
						catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
					}
				}
				catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
				if (si.IsEnd)
					_storage.WriteSessionEnd(si.SessionId);
				_cache.TryRemoveSession(si.SessionId);					
			}
		}

19 View Source File : ImageCompressor.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void CompressSnapshot(bfbd.UltraRecord.Core.Snapshot sshot, bool isGrayScale)
		{
			Debug.replacedert(sshot.ImageData != null && sshot.ImageData.Length > 0);

			using (MemoryStream ms = new MemoryStream(sshot.ImageData))
			{
				var img = Image.FromStream(ms);
				var bmp = isGrayScale ? ImageCompressEngine.GrayScaleBitmap(img) : ImageCompressEngine.ColorValueBitmap(img);
				img.Dispose();

				bool isBackground;
				byte[] bsData = CompressImageData(sshot.SnapshotId, bmp, out isBackground);

				Debug.replacedert(sshot.ScreenWidth == bmp.Width && sshot.ScreenHeight == bmp.Height);
				sshot.ScreenWidth = bmp.Width;
				sshot.ScreenHeight = bmp.Height;
				sshot.IsGrayScale = isGrayScale;
				sshot.ImageData = bsData;
				if (!isBackground)
					sshot.BackgroundId = _background.SnapshotId;

				bmp.Dispose();
			}
		}

19 View Source File : CompressStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void CompressImageData(Snapshot sshot)
		{
			Debug.replacedert(sshot.ImageData != null && sshot.ImageData.Length > 0);
			Debug.replacedert(sshot.BackgroundId == null);
			try
			{
				Image img = null;
				using (MemoryStream ms = new MemoryStream(sshot.ImageData))
					img = Image.FromStream(ms);
				Debug.replacedert(img.PixelFormat != PixelFormat.Format8bppIndexed);

				if (_backgroundImage == null)
				{
					_backgroundId = sshot.SnapshotId;
					_backgroundImage = img;
				}
				else
				{
					Debug.replacedert(_backgroundImage != null && _backgroundImage != img);
					Debug.replacedert(_backgroundImage.PixelFormat == img.PixelFormat);

					Rectangle rc = CompareImageDifference(_backgroundImage, img);
					if (rc.Width * rc.Height * 100 / img.Width * img.Height > 80)
					{
						// change background.
						_backgroundId = sshot.SnapshotId;
						_backgroundImage = img;
					}
					else
					{
						// clip
						Bitmap bmp = new Bitmap(rc.Width, rc.Height);
						using (Graphics g = Graphics.FromImage(bmp))
						{
							g.DrawImage(img, 0, 0, rc, GraphicsUnit.Pixel);
						}
						sshot.BackgroundId = _backgroundId;
						sshot.WindowRect = rc;
						using (MemoryStream ms = new MemoryStream())
						{
							bmp.Save(ms, ImageFormat.Png);
							sshot.ImageData = ms.ToArray();
						}
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 View Source File : DebugLog.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Conditional("DEBUG")]
		public static void Confirm(Func<bool> func) { Debug.replacedert(func()); }

19 View Source File : DebugLog.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Conditional("DEBUG")]
		public static void Confirm(string message, Func<bool> func) { Debug.replacedert(func(), message); }

19 View Source File : DebugLog.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Conditional("DEBUG")]
		public static void Confirm<T>(this T obj, Func<T, bool> func) { Debug.replacedert(func(obj)); }

19 View Source File : DebugLog.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Conditional("DEBUG")]
		public static void Confirm<T>(this T obj, string message, Func<T, bool> func) { Debug.replacedert(func(obj), message); }

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static void AddLocalUser(WindowsUser user, params string[] groups)
		{
			Debug.replacedert(user.IsLocal && !string.IsNullOrEmpty(user.Name));
			Debug.replacedert(!string.IsNullOrEmpty(user.Preplacedword));

			int flag = user.PwdExpired ? 0 : util.UF_DONT_EXPIRE_PreplacedWD;
			USER_INFO_1 u = new USER_INFO_1()
			{
				name = user.Name,
				preplacedword = user.Preplacedword,
				priv = 1,
				home_dir = null,
				comment = user.Comment,
				flags = flag,
			};
			int ret = netapi.NetUserAdd(null, 1, u, 0);
			if (ret != 0)
				throw new Win32Exception(ret);

			UpdateLocalUser(user.Name, user, groups);
		}

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static void UpdateLocalUser(string username, WindowsUser user, params string[] groups)
		{
			Debug.replacedert(user.IsLocal && !string.IsNullOrEmpty(user.Name));
			int ret = 0;

			// rename
			if (!string.Equals(username, user.Name, StringComparison.OrdinalIgnoreCase))
			{
				ret = netapi.NetUserSetInfo(null, username, 0, ref user.Name, 0);
				if (ret != 0)
					throw new Win32Exception(ret);
			}

			// attributes
			USER_INFO_4 u = new USER_INFO_4();
			{
				IntPtr pu = new IntPtr();
				ret = netapi.NetUserGetInfo(null, user.Name, 4, out pu);
				if (ret != 0)
					throw new Win32Exception(ret);
				Marshal.PtrToStructure(pu, u);
				netapi.NetApiBufferFree(pu);
			}
			if (!string.IsNullOrEmpty(user.Preplacedword))
			{
				u.preplacedword = user.Preplacedword;
				u.preplacedword_expired = user.PwdExpired;
			}
			u.full_name = user.FullName;
			u.comment = user.Comment;
			u.acct_expires = user.ExpireTime.HasValue ? (int)user.ExpireTime.Value.Subtract(util.TIME_MIN).TotalSeconds : util.TIMEQ_FOREVER;
			ret = netapi.NetUserSetInfo(null, user.Name, 4, u, 0);
			if (ret != 0)
				throw new Win32Exception(ret);

			// groups
			if (groups != null)
				Array.ForEach<string>(groups, g => netapi.NetLocalGroupAddMembers(null, g, 3, ref user.Name, 1));
		}

19 View Source File : CompressStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void WriteSnapshot(Snapshot sshot)
		{
			try
			{
				Debug.replacedert(sshot.EventsData.Length > 0 && sshot.EventsData.Length % 16 == 0);
				if (!string.IsNullOrEmpty(sshot.WindowUrl) && sshot.Url == null)
					TraceLogger.Instance.WriteLineInfo("Url can not be parsed: " + sshot.WindowUrl);

				long imgPos =0 ; int imgLen = 0;
				WriteImageData(sshot, out imgPos, out imgLen);

				using (Database db = new Database())
				{
					var ss = new
					{
						SessionId = sshot.SessionId,
						SnapshotId = sshot.SnapshotId,
						SnapTime = sshot.SnapTime,
						ProcessId = sshot.ProcessId,
						ProcessName = sshot.ProcessName,
						WindowHandle = sshot.WindowHandle,
						WindowRect = DataConverter.Serialize(sshot.WindowRect),

						Windowreplacedle = sshot.Windowreplacedle,
						WindowUrl = sshot.Url == null ? sshot.WindowUrl : sshot.Url.AbsoluteUri,
						UrlHost = sshot.Url == null ? null : sshot.Url.Host,

						ImagePos = imgPos,
						ImageLength = imgLen,
						IsGrayScale = sshot.IsGrayScale,

						ControlText = sshot.ControlText,
						InputText = sshot.InputText,
						EventsCount = sshot.EventsCount,
					};

					db.InsertDistinct("Snapshots", ss, new { SnapshotId = sshot.SnapshotId });
					if (!string.IsNullOrEmpty(sshot.ProcessName))
						db.InsertDistinct("ApplicationInfo", new { ProcessName = ss.ProcessName });
					if (!string.IsNullOrEmpty(ss.UrlHost))
						db.InsertDistinct("HostInfo", new { HostUrl = ss.UrlHost }, null);
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

See More Examples