public IStatus <EchoLocation> Update(ICoordinates coordinates)
        {
            var response = new Status <EchoLocation>();

            if (!this.IsValid)
            {
                response.AddError("Can only update valid Echo Locations");
            }

            foreach (var violation in CoordinatesRules.
                     GetCoordinatesRuleViolations(coordinates))
            {
                response.AddError(violation.Rule);
            }

            // if there wernt errors go ahead and update this location.
            if (response.IsSuccess())
            {
                Lattitude = coordinates.Lattitude;
                Longitude = coordinates.Longitude;
                TimeStamp = DateTimeOffset.UtcNow;
            }

            response.RespondWithObject(this);
            return(response);
        }
Beispiel #2
0
        static void TestStatus()
        {
            IStatus status = new Status();

            status.AddError(Error.From(AuthError.RegistrationError, "some technical jargon", "An unexpected error has occurred"));
            status.AddError(Error.From(AuthError.UserAlreadyExists, new [] { "*****@*****.**" }));
            status.AddError(Error.From(AuthError.InvalidCredentials));

            Console.WriteLine(status.ToString());
            Console.WriteLine();
            Console.WriteLine(status.ToUserFriendlyString());
        }
        private List <IValue> ArrayIndexAccess(ArrayClepsType expressionType, IList <ClepsParser.RightHandExpressionContext> arrayIndexExpression)
        {
            var indexValues = arrayIndexExpression.Select(i =>
            {
                var indexValueRet = Visit(i);
                IValue indexValue = indexValueRet as IValue;

                if (indexValue.ExpressionType != CompilerConstants.ClepsByteType)
                {
                    string errorMessage = String.Format("Array access {0} is not a byte type", i.GetText());
                    Status.AddError(new CompilerError(FileName, i.Start.Line, i.Start.Column, errorMessage));
                    //just use the first element access to avoid stalling
                    indexValue = CodeGenerator.CreateByte(0);
                }

                return(indexValue);
            }).ToList();

            if (indexValues.Count > expressionType.Dimensions.Length)
            {
                string errorMessage = String.Format("Accessing more dimensions than array has. Array has {0} dimensions, but accessing {1} dimensions", expressionType.Dimensions.Length, indexValues.Count);
                Status.AddError(new CompilerError(FileName, arrayIndexExpression[indexValues.Count - 1].Start.Line, arrayIndexExpression[indexValues.Count - 1].Start.Column, errorMessage));
                //truncate array access to allowed access to avoid stopping the compilation
                indexValues = indexValues.Take(expressionType.Dimensions.Length).ToList();
            }

            return(indexValues);
        }
        private void SenderStreams_CloneStreams(object sender, RoutedEventArgs e)
        {
            if (RestApi == null && ApiToken == null)
            {
                Status.AddError("Not logged in");
                return;
            }

            var cell = SenderStreams.CurrentCell.Item;

            if (cell.GetType() == typeof(Tuple <string, string>))
            {
                string streamID = (cell as Tuple <string, string>).Item2;

                Task.Run(() => SpeckleStreamManager.CloneStream(RestApi, ApiToken, streamID)).ContinueWith(res =>
                {
                    Application.Current.Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                        new Action(() =>
                    {
                        try
                        {
                            Status.AddMessage("Cloned to: " + res.Result);
                        }
                        catch { Status.AddError("Could not clone " + streamID); }
                    }
                                   ));
                });
            }
        }
        public override object VisitFunctionVariableDeclarationStatement([NotNull] ClepsParser.FunctionVariableDeclarationStatementContext context)
        {
            ClepsVariable variable = Visit(context.variableDeclaration()) as ClepsVariable;

            VariableManager variableManager = VariableManagers.Last();

            if (!variableManager.IsVariableNameAvailable(variable.VariableName))
            {
                string errorMessage = String.Format("Variable {0} is already defined", variable.VariableName);
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //Use a different variable name to avoid stopping the compilation
                string newVariableName = variableManager.GetAvailableVariableName(variable.VariableName);
                variable = new ClepsVariable(newVariableName, variable.VariableType, variable.IsConstant);
            }

            IValue value = null;

            if (context.rightHandExpression() != null)
            {
                value = Visit(context.rightHandExpression()) as IValue;
                if (variable.VariableType != value.ExpressionType)
                {
                    throw new NotImplementedException("Assignment for non identical types not supported yet");
                }
            }

            IValueRegister variableRegister = CurrMethodGenerator.CreateNewVariable(variable, value);

            variableManager.AddLocalVariable(variable, variableRegister);

            return(variable);
        }
        /// <summary>
        /// Login to a SpeckleServer
        /// </summary>
        private void Login(object sender, RoutedEventArgs e)
        {
            var signInWindow = new SpecklePopup.SignInWindow(true);

            var helper = new System.Windows.Interop.WindowInteropHelper(signInWindow)
            {
                Owner = new System.Windows.Interop.WindowInteropHelper(this).Handle
            };

            this.IsEnabled = false;

            signInWindow.ShowDialog();

            this.IsEnabled = true;

            if (signInWindow.AccountListBox.SelectedIndex != -1)
            {
                var account = signInWindow.accounts[signInWindow.AccountListBox.SelectedIndex];

                EmailAddress = account.Email;
                RestApi      = account.RestApi;
                ApiToken     = account.Token;
                (SenderTab.Content as Grid).IsEnabled   = FileOpened && LoggedIn;
                (ReceiverTab.Content as Grid).IsEnabled = FileOpened && LoggedIn;
                UpdateClientLists();

                Status.AddMessage("Logged in to account at: " + RestApi);
            }
            else
            {
                Status.AddError("Failed to log in");
            }
        }
        /// <summary>
        /// Receive all streams in the account.
        /// </summary>
        private void UpdateStreamList(object sender, RoutedEventArgs e)
        {
            if (RestApi == null && ApiToken == null)
            {
                Status.AddError("Not logged in");
                return;
            }

            Task.Run(() => SpeckleStreamManager.GetStreams(RestApi, ApiToken)).ContinueWith(res =>
            {
                Application.Current.Dispatcher.BeginInvoke(
                    DispatcherPriority.Background,
                    new Action(() =>
                {
                    List <Tuple <string, string> > streams = res.Result;
                    if (streams != null)
                    {
                        streams.Reverse();
                        StreamList.Items.Clear();
                        foreach (Tuple <string, string> t in streams)
                        {
                            StreamList.Items.Add(t);
                        }
                    }
                }
                               ));
            });
        }
Beispiel #8
0
        /// <summary>
        /// Return an echo from a pulse this radar emited.
        /// </summary>
        /// <param name="returnedEcho">The echo to return.</param>
        /// <returns></returns>
        public IStatus <CruiseRadar> ReturnEcho(RadarEcho returnedEcho)
        {
            var response = new Status <CruiseRadar>();

            try
            {
                if (_pulses.Contains(returnedEcho.OriginatingPulse))
                {
                    ContactOrClutter(returnedEcho);
                }
                else
                {
                    response.AddError
                        ("Echos can only be returned to the radars that " +
                        "emited the original pulse. ");
                }
            }
            catch (Exception ex)
            {
                response.AddException(ex);
            }

            response.RespondWithObject(this);
            return(response);
        }
Beispiel #9
0
        /// <summary>
        /// Removes a handkerchief from the hard no list if it was in it.
        /// </summary>
        /// <param name="handkerchief"></param>
        /// <returns></returns>
        public IStatus <Avatar> StopFlaggingHandkerchiefAsHardNo
            (Handkerchief handkerchief)
        {
            var response = new Status <Avatar>();

            try
            {
                if (hardNoHandkerchiefs.Contains(handkerchief))
                {
                    hardNoHandkerchiefs.Remove(handkerchief);
                    AddDomainEvent(new AvatarRemovedHardNoHandkerchiefDomainEvent
                                       (this, handkerchief));

                    CruiseRadar.ReEvaluateClutter();
                }
                else
                {
                    response.AddError
                        ("specified handkerchief not found in hard no list.");
                }
            }
            catch (Exception ex)
            {
                response.AddException(ex);
            }

            return(AvatarValidationStatus(response));
        }
Beispiel #10
0
        /// <summary>
        /// Stop the currenly active cruise, if there is one.
        /// </summary>
        /// <returns></returns>
        public IStatus <Avatar> StopActiveCruise()
        {
            var response = new Status <Avatar>();

            try
            {
                if (HasActiveCruise)
                {
                    LastCruise.StoppedAt = DateTimeOffset.UtcNow;

                    AddDomainEvent(new CruiseStoppedDomainEvent
                                       (LastCruise, this));
                }
                else
                {
                    response.AddError("No active cruise avalable to stop.");
                }
            }
            catch (Exception ex)
            {
                response.AddException(ex);
            }

            return(AvatarValidationStatus(response));
        }
        public override object VisitMemberDeclarationStatement([NotNull] ClepsParser.MemberDeclarationStatementContext context)
        {
            string memberName = context.FieldName.Name.Text;

            ClepsClassBuilder classBuilder = ClassManager.GetClassBuilder(FullyQualifiedClassName);

            if (classBuilder == null)
            {
                //This is probably because of some earlier error. Return gracefully
                return(false);
            }

            if (classBuilder.DoesClassContainMember(memberName))
            {
                string errorMessage = String.Format("Class {0} has multiple definitions of member {1}", FullyQualifiedClassName, memberName);
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //Don't process this member
                return(false);
            }

            bool      isStatic   = context.STATIC() != null;
            ClepsType memberType = Visit(context.typename()) as ClepsType;

            if (memberType.IsFunctionType)
            {
                CodeGenerator.CreateMethod(FullyQualifiedClassName, isStatic, memberType, memberName);
            }

            classBuilder.AddNewMember(isStatic, memberType, memberName);
            return(true);
        }
Beispiel #12
0
        /// <summary>
        /// Emits a radar pulse via a PulseEmittedDomainEvent
        /// </summary>
        /// <param name="location">The center point of the pulse</param>
        /// <remarks>
        /// Emitting a pulse triggers a PulseEmittedDomainEvent. Higher layers
        /// in Hankies handle the PulseEmittedDomainEvent and return a
        /// IRadarPulse to the radar object before saving to the database
        /// context.
        /// </remarks>
        public IStatus <PulseEmitedDomainEvent> EmitPulse(ICoordinates location)
        {
            var resultStatus = new Status <PulseEmitedDomainEvent>();
            var pulseEvent   = new PulseEmitedDomainEvent(location.Lattitude,
                                                          location.Longitude, Range, this);

            try
            {
                if (pulseEvent.IsValid)
                {
                    Owner.AddDomainEvent(pulseEvent);
                }
                else
                {
                    resultStatus.AddError("Invalid PulseEmitedDomainEvent, " +
                                          "could not add to domain events");
                }
            }
            catch (Exception ex)
            {
                resultStatus.AddException(ex);
            }

            resultStatus.RespondWithObject(pulseEvent);
            return(resultStatus);
        }
        public override object VisitNumericAssignments([NotNull] ClepsParser.NumericAssignmentsContext context)
        {
            IValue val;
            string numericValue = context.numeric().NumericValue.Text;
            string numericType  = context.numeric().NumericType?.Text;

            if (numericType == "b")
            {
                byte byteVal;
                if (!byte.TryParse(numericValue, out byteVal))
                {
                    string errorMessage = String.Format("Value {0} is outside the range of values allowed for a byte. Allowed range is 0 to 255", numericValue);
                    Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                    //Use a different value to avoid stopping the compilation
                    byteVal = 0;
                }

                val = CodeGenerator.CreateByte(byteVal);
            }
            else
            {
                throw new NotImplementedException("Other numeric types not supported yet");
            }

            return(val);
        }
Beispiel #14
0
 private Status <Avatar> IsCorrectSender(Status <Avatar> response, Avatar sender)
 {
     if (Avatar != sender)
     {
         response.AddError
             ("Only the owning avatar may modify its cruise.");
     }
     return(response);
 }
Beispiel #15
0
 /// <summary>
 /// Adds an error to a Status if Is Blindfold rule is violated.
 /// </summary>
 /// <param name="response"></param>
 /// <returns></returns>
 private Status <Avatar> IsBlindfolded(Status <Avatar> response)
 {
     if (!Blindfolded)
     {
         response.AddError
             ("Cannot don or doff blindfold for an avatar if you are " +
             "not wearing a Blindfold.");
     }
     return(response);
 }
Beispiel #16
0
 private Status <Avatar> IsHooded(Status <Avatar> response)
 {
     if (!Hooded)
     {
         response.AddError
             ("Cannot don or doff hood for an avatar if you are " +
             "not wearing a hood.");
     }
     return(response);
 }
        /// <summary>
        /// Clear all receivers.
        /// </summary>
        private void ClearReceiver(object sender, RoutedEventArgs e)
        {
            GSA.ReceiverInfo.Clear();
            if (!GSA.SetSpeckleClients(EmailAddress, RestApi))
            {
                Status.AddError("Error in communicating GSA - please check if the GSA file has been closed down");
                return;
            }

            UpdateClientLists();
        }
Beispiel #18
0
        public IStatus <IPattern> UpdateUri(Uri newUri)
        {
            Location = newUri;
            var updateStatus = new Status <IPattern>(true);

            if (!IsValid)
            {
                updateStatus.AddError("Updated uri had rule violations");
            }

            updateStatus.RespondWithObject(this);
            return(updateStatus);
        }
Beispiel #19
0
        public IStatus <IPattern> UpdateColor(NamedColor newColor)
        {
            Color = newColor;
            var updatePattern = new Status <IPattern>(true);

            if (!IsValid)
            {
                updatePattern.AddError("Updated color had rule violations");
            }

            updatePattern.RespondWithObject(this);
            return(updatePattern);
        }
Beispiel #20
0
 private IStatus <Avatar> AvatarValidationStatus(Status <Avatar> response)
 {
     // Add any validation errors.
     if (!IsValid)
     {
         foreach (var violation in GetRuleViolations())
         {
             response.AddError(violation.Rule);
         }
     }
     response.RespondWithObject(this);
     return(response);
 }
 public sealed override object VisitFunctionStatement([NotNull] ClepsParser.FunctionStatementContext context)
 {
     if (CurrentBlockStatus.Last().ReturnStatementReached)
     {
         string errorMessage = String.Format("Statement is dead code", FullyQualifiedClassName);
         Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
         return(false);
     }
     else
     {
         VisitFunctionStatement_Ex(context);
         return(true);
     }
 }
        public IStatus <IDomainEntity> AddDomainEvent(IDomainEvent eventItem)
        {
            var addEventStatus = new Status <IDomainEntity>(true);

            if (_domainEvents == null)
            {
                _domainEvents = new List <IDomainEvent>();
            }

            if (eventItem == null)
            {
                addEventStatus.AddError("Domain event can't be null.");
            }

            if (_domainEvents.Contains(eventItem))
            {
                addEventStatus.AddError("Can't contain duplicate events.");
            }

            _domainEvents.Add(eventItem);

            addEventStatus.RespondWithObject(this);
            return(addEventStatus);
        }
        public IStatus <EchoLocation> Refresh()
        {
            var response = new Status <EchoLocation>();

            if (!this.IsValid)
            {
                response.AddError("Can only refresh valid Echo Locations");
            }

            TimeStamp = DateTimeOffset.UtcNow;

            response.RespondWithObject(this);

            return(response);
        }
        public override object VisitClassDeclarationStatements_Ex([NotNull] ClepsParser.ClassDeclarationStatementsContext context)
        {
            //if this qualified name already exists, there is an error
            if (ClassManager.IsClassBuilderAvailable(FullyQualifiedClassName))
            {
                string errorMessage = String.Format("Class {0} has multiple definitions", FullyQualifiedClassName);
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //Don't process this class
                return(false);
            }

            ClassManager.AddNewClassDeclaration(FullyQualifiedClassName);
            CodeGenerator.CreateClass(FullyQualifiedClassName);
            return(true);
        }
        private void ReceiverStreams_RemoveStream(object sender, RoutedEventArgs e)
        {
            var streamID = ReceiverStreams.CurrentCell.Item;

            if (streamID.GetType() == typeof(string))
            {
                GSA.ReceiverInfo.Remove(GSA.ReceiverInfo.First(x => x.Item1 == (string)streamID));
                if (!GSA.SetSpeckleClients(EmailAddress, RestApi))
                {
                    Status.AddError("Error in communicating GSA - please check if the GSA file has been closed down");
                    return;
                }
                UpdateClientLists();
            }
        }
        public override object VisitValueAtOnExpression([NotNull] ClepsParser.ValueAtOnExpressionContext context)
        {
            IValue target = Visit(context.addressOfOrValueAtTargetExpression()) as IValue;

            if (!(target.ExpressionType is PointerClepsType))
            {
                string errorMessage = String.Format("Cannot derefernce object of type {0}.", target.ExpressionType.GetClepsTypeString());
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //Just return something to avoid stalling compilation
                return(target);
            }

            IValue ret = CodeGenerator.GetDereferencedValueFromPtr(target);

            return(ret);
        }
        /// <summary>
        /// Add a new receiver.
        /// </summary>
        private void AddReceiver(object sender, RoutedEventArgs e)
        {
            if (ReceiverTextbox.Text != "")
            {
                var streamId = ReceiverTextbox.Text.Trim();
                GSA.ReceiverInfo.Add(new Tuple <string, string>(streamId, null));
                if (!GSA.SetSpeckleClients(EmailAddress, RestApi))
                {
                    Status.AddError("Error in communicating GSA - please check if the GSA file has been closed down");
                    return;
                }
                UpdateClientLists();

                ReceiverTextbox.Clear();
            }
        }
Beispiel #28
0
        public override object VisitThisAssignment([NotNull] ClepsParser.ThisAssignmentContext context)
        {
            if (CurrMemberIsStatic)
            {
                string errorMessage = "Cannot use the this keyword in a static member";
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                //just return something to avoid stalling
                return(CodeGenerator.CreateByte(0));
            }

            BasicClepsType currentClassType = new BasicClepsType(FullyQualifiedClassName);
            IValue         thisValue        = CodeGenerator.GetThisInstanceValue(currentClassType);
            IValue         thisPtr          = CodeGenerator.GetPtrToValue(thisValue);

            return(thisPtr);
        }
        /// <summary>
        /// Add receivers from clipboard.
        /// </summary>
        private void PasteClipboardReceiver(object sender, RoutedEventArgs e)
        {
            string[] paste = Clipboard.GetText(TextDataFormat.Text).Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string p in paste)
            {
                var streamId = p.Trim();
                GSA.ReceiverInfo.Add(new Tuple <string, string>(streamId, null));
            }
            if (!GSA.SetSpeckleClients(EmailAddress, RestApi))
            {
                Status.AddError("Error in communicating GSA - please check if the GSA file has been closed down");
                return;
            }
            UpdateClientLists();
        }
        private IValueRegister GetVariableRegisterOrNullWithError([NotNull] ClepsParser.VariableAssignmentContext context)
        {
            string         variableName    = Visit(context.variable()) as string;
            var            variableManager = VariableManagers.Last();
            IValueRegister register;

            if (!variableManager.IsVariableAvailable(variableName))
            {
                string errorMessage = String.Format("Variable {0} does not exist", variableName);
                Status.AddError(new CompilerError(FileName, context.Start.Line, context.Start.Column, errorMessage));
                register = null;
            }
            else
            {
                register = variableManager.GetVariableRegister(variableName);
            }

            return(register);
        }