public bool HandleResult( IResult result, IFormatInfo outputFormat, HttpRequestBase request, HttpResponseBase response )
        {
            response.AddHeader("Accept-Ranges", "bytes");

            Range range;
            if ( !TryGetRequestedRange( request, out range ) )
            {
                return false;
            }

            if (!ValidateIfRangeHeader(request, result))
            {
                return false;
            }

            var offset = range.Start ?? 0;
            var end = range.End.HasValue ? range.End.Value : result.ContentLength - 1;
            var length = end - offset + 1;

            response.AddHeader( "Content-Range", "bytes " + offset + "-" + end + "/" + result.ContentLength );
            response.StatusCode = 206;

            result.Serve( response, offset, length );
            return true;
        }
 public MainViewModel(IApriori apriori, IResult resultWindow)
 {
     _items = new ObservableSet<Item>();
     _transactions = new ObservableCollection<string>();
     this._apriori = apriori;
     this._resultWindow = resultWindow;
 }
Example #3
0
 public ResultExecutionTask(IResult result, ActionExecutionContext context)
 {
     Result = result;
     Context = context;
     CompletionEventArgs = new ResultCompletionEventArgs();
     ExecutionCompleteWaitHandle = new ManualResetEvent(false);
 }
Example #4
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                using (var key = Registry.CurrentUser.OpenSubKey(KeyPath, true))
                {
                    if (key == null)
                        return new NextResult();

                    var value = key.GetValue(ValueName).ToIntOrDefault(0);
                    if (value == 0)
                        return new NextResult();

                    key.SetValue(ValueName, 0);
                    Log.InfoFormat("Internet-connection proxy disabled");
                }

                return new NextResult();

            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #5
0
 void AuthCallBack(IResult result)
 {
     if (result.Error != null)
     {
         // display error popup
         popup.SetActive(true);
         newGame.enabled = true;
         loadGame.enabled = true;
         rulesButton.enabled = true;
     }
     else
     {
         if (FB.IsLoggedIn)
         {
             FB.API("/me?fields=first_name,last_name", HttpMethod.GET, DisplayUsername);
             FB.API("/me/friends?fields=first_name,last_name", HttpMethod.GET, DisplayFriends);
             //FB.API("me/picture?type=square&height=128&width=128", HttpMethod.GET, DisplayProfilePic);
             FB.GetAppLink(GetAppLink);
         }
         else
         {
             // display error popup
             popup.SetActive(true);
             newGame.enabled = true;
             loadGame.enabled = true;
             rulesButton.enabled = true;
         }
     }
 }
        public ContinueResultDecorator(IResult inner, Func<IEnumerable<IResult>> coroutine)
            : base(inner)
        {
            if (coroutine == null) throw new ArgumentNullException("coroutine");

            _coroutine = coroutine;
        }
        /// <summary>
        /// Called by the bootstrapper's constructor at runtime to start the framework.
        /// </summary>B
        protected virtual void StartRuntime()
        {
            EventAggregator.HandlerResultProcessing = (target, result) =>
            {
                var task = result as Task;
                if (task != null)
                {
                    result = new IResult[] { task.AsResult() };
                }

                var coroutine = result as IEnumerable<IResult>;
                if (coroutine != null)
                {
                    var viewAware = target as IViewAware;
                    var view = viewAware != null ? viewAware.GetView() : null;
                    var context = new CoroutineExecutionContext { Target = target, View = view };

                    Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
                }
            };

            AssemblySourceCache.Install();
            AssemblySource.Instance.AddRange(SelectAssemblies());

            Configure();

            IoC.GetInstance = GetInstance;
            IoC.GetAllInstances = GetAllInstances;
            IoC.BuildUp = BuildUp;
        }
Example #8
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                var request =
                    EndpointManager.GetContract<AbstractIdentityQueryContract>(EndPointFunctions.IdentityQuery);

                request.LoginId = SettingsManager.GetTemporarySettingString(UsernameKey);
                request.Credential1 = SettingsManager.GetTemporarySettingString(PassphraseKey);
                request.Credential2 = SettingsManager.GetTemporarySettingString(Credential2Key);
                request.Credential3 = SettingsManager.GetTemporarySettingString(Credential3Key);
                request.Credential4 = SettingsManager.GetTemporarySettingString(Credential4Key);
                request.Provider = CertificateProvider;
                request.Properties = _properties;
                request.GroupPaths = _groupPaths;

                var result = request.MakeRequest<IdentityQueryResult>();
                if (result == null)
                    return request.GetErrorResult();

                SettingsManager.SetTemporaryObject(UserPropertiesKey, result.Properties);
                SettingsManager.SetTemporaryObject(GroupPathsKey, result.Groups);

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
        private static bool ValidateLastModifyDate(string ifModifiedSinceHeader, IResult result)
        {
            if (string.IsNullOrEmpty(ifModifiedSinceHeader))
            {
                return true;
            }

            if (!result.LastModified.HasValue)
            {
                return false;
            }

            DateTime modifiedSince;
            if (string.IsNullOrEmpty(ifModifiedSinceHeader) || !DateTime.TryParse(ifModifiedSinceHeader, out modifiedSince))
            {
                return false;
            }

            if (modifiedSince <= result.LastModified.Value.Subtract(TimeSpan.FromSeconds(1)))
            {
                return false;
            }

            return true;
        }
Example #10
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(SettingKey))
                    throw new Exception("No settings key specified");

                var info = SettingsManager.GetTemporaryObject(SettingKey) as FileInfoWrapper;
                if (info == null)
                    throw new Exception("Data object is invalid");

                var result = info.VerifyFile(PathUtilities.DownloadFolder);
                if (!result.Result)
                {
                    Log.Warn(result.Reason);
                    return new CouldNotVerifyFile { Target = info.FileName, Issue = result.Reason };
                }

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #11
0
        private void ChildCompleted(IResult previous, Exception exception)
        {
            if(exception != null)
            {
                if (exception is CancelResult)
                    OnComplete(null);
                else OnComplete(exception);

                return;
            }

            if(previous != null)
                previous.Completed -= ChildCompleted;

            if(_enumerator.MoveNext())
            {
                try
                {
                    var next = _enumerator.Current;
                    next.Completed += ChildCompleted;
                    next.Execute(_message, _handlingNode);
                }
                catch(Exception ex)
                {
                    OnComplete(ex);
                    return;
                }
            }
            else OnComplete(null);
        }
Example #12
0
        public void SetUp()
        {
            var path = new[] { "path1, path2 " };

            this.ContentRepository.Stub(r => r.FindContent(path)).Return(null);
            this.result = this.RenderingService.GetPage(path, null, null, false);
        }
 public override IResult Execute(IResult previousResults)
 {
     try
     {
         var result = SecurityUtilities.QuerySecurityProviderHealth(SecurityUtilities.SecurityProviders.AntiVirus);
         switch (result)
         {
             case SecurityUtilities.SecurityProviderHealth.Good:
                 Log.Info("Windows reports that this computer's anti-virus software is in good health.");
                 return new NextResult();
             case SecurityUtilities.SecurityProviderHealth.NotMonitored:
                 Log.Warn("Windows reports that this computer's anti-virus software is not monitored.");
                 return new AntiVirusHealthNotMonitored();
             case SecurityUtilities.SecurityProviderHealth.Poor:
                 Log.Warn("Windows reports that this computer's anti-virus software is in poor health.");
                 return new AntiVirusHealthPoor();
             case SecurityUtilities.SecurityProviderHealth.Snooze:
                 Log.Warn("Windows reports that this computer's security center is not active.");
                 return new SecurityCenterNotActive();
              default:
                 throw new Exception(string.Format("Could not evaluate anti-virus health: Windows returned unexpected result ({0})",result));
         }
     }
     catch (Exception e)
     {
         return new ExceptionOccurred(e);
     }
 }
        public void SetUp()
        {
            var placeholder1 = new Placeholder("area 1");
            var placeholder2 = new Placeholder("area 2");
            var widgetSpecification = new WidgetSpecification("widget");
            widgetSpecification.Insert(0, placeholder1);
            widgetSpecification.Insert(1, placeholder2);

            var area = new Area("area 1");
            var widget = new Widget("widget", new[] { area });

            var buildContext = new BuildData(Enumerable.Empty<IContextItem>());

            var builder = new Builder(RenderingInstructions.BuildForPreview(), w => widgetSpecification, null);

            var instance = widget.Build(builder, new[] { 0 }, buildContext);

            var rendererFactory = MockRepository.GenerateStub<IRendererFactory>();
            this.viewHelper = MockRepository.GenerateStub<IViewHelper>();
            var multiRenderer = new MultiRenderer(rendererFactory);

            KolaConfigurationRegistry.RegisterRenderer(multiRenderer);

            this.result = instance.Render(multiRenderer);
        }
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                var startTime = DateTime.UtcNow;
                TimeSpan elapsed;
                do
                {
                    DialogsManager.WaitForDurationOrCancel(DateTime.UtcNow, new TimeSpan(0,0,0,Interval));
                    if (DialogsManager.CancelRequested)
                        break;

                    if (SecurityUtilities.SecurityProviderHealth.Good ==
                        SecurityUtilities.QuerySecurityProviderHealth(Provider))
                        break;

                    elapsed = DateTime.UtcNow.Subtract(startTime);
                } while (elapsed.Duration().TotalSeconds < Duration);

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #16
0
 public async Task<IResult> NegotiatedResult(IRequestContext context, IResult result)
 {
     foreach (var interceptor in _interceptors) {
         result = await interceptor.NegotiatedResult(context, result);
     }
     return result;
 }
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ObjectKey))
                    throw new Exception("Object key cannot be null");

                if (string.IsNullOrWhiteSpace(SettingsKey))
                    throw new Exception("Setting key cannot be null");

                if (string.IsNullOrWhiteSpace(BaseText))
                    BaseText = "{0}";

                var updateCollection = SettingsManager.GetTemporaryObject(ObjectKey) as UpdateCollection;
                if (updateCollection == null)
                    throw  new Exception("Update collection not present");

                SettingsManager.SetTemporarySettingString(SettingsKey, string.Format(BaseText, updateCollection.Count));

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(WindowTitle))
                    AdvancedMenuManager.WindowTitle = WindowTitle;

                if (!string.IsNullOrWhiteSpace(DefaultTitle))
                    AdvancedMenuManager.DefaultTitle = DefaultTitle;

                if (!string.IsNullOrWhiteSpace(DefaultDescription))
                    AdvancedMenuManager.DefaultDescription = DefaultDescription;

                if (_leftOffset.HasValue)
                    AdvancedMenuManager.InitialLeftOffset = _leftOffset.Value;

                if (_topOffset.HasValue)
                    AdvancedMenuManager.InitialTopOffset = _topOffset.Value;

                if (!string.IsNullOrWhiteSpace(HelpTopic))
                    AdvancedMenuManager.HelpTopic = HelpTopic;

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #19
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                var eventData = new LoggingEventData
                    {
                        Level = Event.GetAssociatedLevel(),
                        Message = Message,
                        TimeStamp = DateTime.Now
                    };

                if (eventData.Level == null)
                {
                    Log.Warn("Cannot upload log event; Level is null");
                    return new NextResult();
                }

                if (string.IsNullOrWhiteSpace(eventData.Message))
                    eventData.Message = "[no content]";

                var eventEntry = Asynchronous
                    ? new LoggingEvent(eventData)
                    : new BlockingLoggingEvent(eventData);

                Log.Logger.Log(eventEntry);

                return new NextResult();
            }
            catch (Exception e)
            {
                Log.WarnFormat("An exception occurred while attempting to record a log event: {0}", e.Message);
                return new NextResult();
            }
        }
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Archive))
                    throw new Exception("The archive parameter cannot be null or empty");

                if (string.IsNullOrWhiteSpace(Icon))
                    throw new Exception("The icon parameter cannot be null or empty");

                if (!File.Exists(Archive))
                    return new FileNotFound { Target = Archive };

                var trustedResult = CertificateUtilities.IsFileTrusted(Archive);
                if (!trustedResult.Result)
                    return new CouldNotImportContent { Issue = trustedResult.Reason };

                var bytes = CabArchiveUtilities.ExtractFile(Archive, Icon);
                if (bytes == null)
                    throw new Exception(string.Format("Could not extract {0} from archive", Icon));

                using (var stream = new MemoryStream(bytes))
                    AppearanceManager.ApplicationIcon = BitmapFrame.Create(stream);

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #21
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Value))
                    throw new Exception("Cannot truncate value; value is empty.");

                if (string.IsNullOrWhiteSpace(SettingKey))
                    throw  new Exception("Setting key cannot be empty");

                if (Length<=0)
                    throw new Exception("Length must be greater than zero");

                var newValue = Value;
                if (Length < Value.Length)
                    newValue = Value.Substring(0, Length);

                SettingsManager.SetTemporarySettingString(SettingKey, newValue);

                return new NextResult();

            }
            catch (Exception e)
            {
                Log.WarnFormat("An exception occurred while attempting to truncate a string: {0}", e.Message);
                return new NextResult();
            }
        }
Example #22
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                using (var controller = ServiceUtilities.GetServiceInstance("LanmanServer"))
                {
                    if (controller == null)
                    {
                        if (!ServiceUtilities.IsServiceInfoInRegistry("LanmanServer"))
                            return new ServiceInfoNotInRegistry { ServiceName = "LanmanServer"};

                        return new ServiceInstanceNotAvailable { ServiceName = "LanmanServer" };
                    }

                    var result = Enabled ? EnableService(controller) : DisableService(controller);
                    if (!result.Result)
                        throw  new Exception(result.Reason);

                    return new NextResult();
                }
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #23
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ChildDialog))
                    throw new Exception("Child dialog key cannot be null or empty");

                if (string.IsNullOrWhiteSpace(Banner))
                    throw new Exception("Banner key cannot be null or empty");

                var dialog = DialogsManager.GetExistingDialog(ParentDialog);
                if (dialog == null)
                    return new DialogInstanceNotFound { Dialog = ParentDialog };

                var childManager = DialogsManager.GetDialog<BorderedChildDialogModel>(ChildDialog);
                if (childManager == null)
                {
                    return new DialogInstanceNotFound { Dialog = ChildDialog };
                }

                return dialog.ShowChildBannerModal(childManager, Banner);
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #24
0
 //, Result C)
 protected void GreedySearchGlobalMinima(int parent, object q, IResult res)
 {
     var rs = this.SEQ.Unravel (parent);
     var children_count = rs.Count1;
     var closer_dist = double.MaxValue;
     var closer_objID = -1;
     for (int rank = 1; rank <= children_count; ++rank) {
         var objID = rs.Select1(rank);
         var dist = this.DB.Dist(q, this.DB[objID]);
         res.Push (objID, dist);
         if (dist < closer_dist) {
             closer_dist = dist;
             closer_objID = objID;
         }
         //if (C != null) C.Push (objID, dist);
     }
     if (closer_objID >= 0) {
         this.GreedySearchGlobalMinima (closer_objID, q, res); //, C);
     }
     //			for (int childID = 0; childID < children_count; ++childID) {
     //				var child_objID = C[childID];
     //				var child_dist = D[childID];
     //				var radius = res.CoveringRadius;
     //				//Console.WriteLine ("---- cov: {0}", this.COV[child_objID]);
     //				if (child_dist <= radius + this.GetCOV(child_objID) && child_dist <= closer_dist + radius + radius) {
     //					this.SearchKNNNode(child_objID, q, res);
     //                }
     //            }
 }
Example #25
0
    public void HandleResult(IResult result)
    {
        if (result == null)
        {
            print ( "Null Response\n");
            return;
        }

        // Some platforms return the empty string instead of null.
        if (!string.IsNullOrEmpty(result.Error))
        {
            print("Error Response:\n" + result.Error);
        }
        else if (result.Cancelled)
        {
            print("Cancelled Response:\n" + result.RawResult);
        }
        else if (!string.IsNullOrEmpty(result.RawResult))
        {
            print("Success Response:\n" + result.RawResult);
            getUserData();
        }
        else
        {
            print("Empty Response\n");
        }
    }
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                foreach (var setter in _setters)
                {
                    var key = setter.Key;
                    var value = setter.Value;

                    if (string.IsNullOrWhiteSpace(key))
                    {
                        Log.Warn("Cannot retrieve settings value to user settings; settings key not specified");
                        continue;
                    }

                    var settingsPropertyName = value;
                    if (string.IsNullOrWhiteSpace(settingsPropertyName))
                        settingsPropertyName = key;

                    var settingsValue = Properties.Settings.Default.GetKeyedProperty(settingsPropertyName);
                    SettingsManager.SetTemporarySettingString(key, settingsValue);
                }

                return new NextResult();
            }
            catch (Exception e)
            {
                Log.Warn(e);
                return new NextResult();
            }
        }
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Target))
                    throw new InvalidOperationException("The target path cannot be empty");

                if (!File.Exists(Target))
                    Target = Path.Combine(PathUtilities.DownloadFolder, Target);

                if (!File.Exists(Target))
                    return new FileNotFound { Target = Target };

                var result = CertificateUtilities.ImportUserCertificateFromFile(
                    Target,
                    SettingsManager.GetSecureTemporarySettingString(CredentialsKey));

                if (!result.Result)
                    return new CouldNotImportContent{Issue = result.Reason};

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContinueResultDecorator"/> class.
        /// </summary>
        /// <param name="result">The result to decorate.</param>
        /// <param name="coroutine">The coroutine to execute when <paramref name="result"/> was canceled.</param>
        public ContinueResultDecorator(IResult result, Func<IEnumerable<IResult>> coroutine)
            : base(result) {
            if (coroutine == null)
                throw new ArgumentNullException("coroutine");

            this.coroutine = coroutine;
        }
Example #29
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(SettingKey))
                    throw new Exception("Setting key not specified");

                var request =
                    EndpointManager.GetContract<AbstractLocationQueryContract>(EndPointFunctions.LocationQuery);
                request.IgnoreCertificateErrors = true;
                var result = request.MakeRequest<LocationQueryResult>();
                if (result == null)
                {
                    Log.WarnFormat("An issue occurred while querying server for location data: {0}",
                        request.GetErrorResult().GetDetails());
                    return null;
                }

                SettingsManager.SetTemporarySettingString(SettingKey, result.Location);

                return new NextResult();
            }
            catch (Exception e)
            {
                return new ExceptionOccurred(e);
            }
        }
Example #30
0
 public IEnumerable<Bitmap> IteratePartsKNN(IResult res, double dqp, float stddev, float mean, Sequence seq)
 {
     var sym = this.Discretize(dqp, stddev, mean);
     yield return seq.Unravel(sym);
     var left = sym - 1;
     var right = sym + 1;
     bool do_next = true;
     while (do_next) {
         do_next = false;
         var __left = this.Discretize(dqp - res.CoveringRadius, stddev, mean);
         if (0 <= left && __left <= left) {
             yield return seq.Unravel(left);
             --left;
             do_next = true;
         }
         var __right = this.Discretize(dqp + res.CoveringRadius, stddev, mean);
         if (right <= __right && right < seq.Sigma) {
             yield return seq.Unravel(right);
             ++right;
             do_next = true;
         }
         /*Console.WriteLine ("left: {0}, right: {1}, __left: {2}, __right: {3}",
                            left, right, __left, __right);*/
     }
 }
Example #31
0
        private Task OnCommandExecuted(Optional <CommandInfo> commandInfo, ICommandContext context, IResult result)
        {
            if (!result.IsSuccess)
            {
                _logger.LogError("Failed running command {CommandName} for reason {Reason} in guild {Guild} ({GuildId}) for user {User} ({UserId})",
                                 commandInfo.IsSpecified ? commandInfo.Value.Name : "Unknown",
                                 result.ErrorReason,
                                 context.Guild?.Name ?? "DM",
                                 context.Guild?.Id ?? context.User.Id,
                                 context.User.Username,
                                 context.User.Id);
            }

            return(Task.CompletedTask);
        }
Example #32
0
        private async Task HandleCommandResultAsync(Optional <CommandInfo> command, ICommandContext context, IResult result)
        {
            _commandScopes.TryRemove(context, out var commandScope);

            using (commandScope)
            {
                if (!result.IsSuccess)
                {
                    var error = $"{result.Error}: {result.ErrorReason}";

                    if (!string.Equals(result.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                    {
                        Log.LogWarning(error);
                    }
                    else
                    {
                        Log.LogError(error);
                    }

                    if (result.Error != CommandError.Exception)
                    {
                        await _commandErrorHandler.AssociateError(context.Message, error);
                    }
                    else
                    {
                        await context.Channel.SendMessageAsync("Error: " + error);
                    }
                }
            }
        }
Example #33
0
 /// <summary>
 ///   Adds behavior to the result which is executed when the <paramref name = "result" /> is cancelled
 /// </summary>
 /// <param name = "result"></param>
 /// <returns></returns>
 public static ICancelledHandler WhenCancelled(this IResult result)
 {
     return(new CancelledHandler(result));
 }
Example #34
0
 /// <summary>
 ///   Adds a rescue for all exceptions to the <paramref name = "result" />
 /// </summary>
 /// <param name = "result"></param>
 /// <returns></returns>
 public static IExceptionHandler <Exception> Rescue(this IResult result)
 {
     return(Rescue <Exception>(result));
 }
Example #35
0
 /// <summary>
 ///   Adds a rescue for <typeparamref name = "TException" /> to the <paramref name = "result" />
 /// </summary>
 /// <typeparam name = "TException"></typeparam>
 /// <param name = "result"></param>
 /// <returns></returns>
 public static IExceptionHandler <TException> Rescue <TException>(this IResult result)
     where TException : Exception
 {
     return(new RescueHandler <TException>(result));
 }
Example #36
0
 /// <summary>
 ///   Returns an <see cref = "IEnumerable{IResult}" /> with one item, the result
 /// </summary>
 /// <param name = "result"></param>
 /// <returns></returns>
 public static IEnumerable <IResult> AsCoroutine(this IResult result)
 {
     yield return(result);
 }
Example #37
0
 /// <summary>
 /// Logs a failed HELO operation
 /// </summary>
 /// <param name="result"></param>
 private static void LogFailedHelloOperation(IResult result)
 {
     Log.Info("Error when trying to execute HELO operation - {0} - {1}", result.Message, result.Exception);
 }
Example #38
0
        public IResult PerformCommand(IMobileObject performer, ICommand command)
        {
            IResult result = base.PerfomCommand(performer, command);

            if (result != null)
            {
                return(result);
            }

            if (command.Parameters.Count <= 0)
            {
                StringBuilder strBldr = new StringBuilder();
                foreach (Equipment.AvalableItemPosition position in Enum.GetValues(typeof(Equipment.AvalableItemPosition)))
                {
                    if (position != Equipment.AvalableItemPosition.NotWorn)
                    {
                        bool found = false;
                        foreach (IEquipment equipment in performer.EquipedEquipment)
                        {
                            if (equipment.ItemPosition == position)
                            {
                                strBldr.AppendLine(position.ToString() + " " + equipment.ShortDescription);
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            strBldr.AppendLine(position.ToString() + " <Nothing>");
                        }
                    }
                }
                return(new Result(strBldr.ToString().Trim(), true));
            }

            IParameter parm = command.Parameters[0];
            IItem      item = GlobalReference.GlobalValues.FindObjects.FindHeldItemsOnMob(performer, parm.ParameterValue, parm.ParameterNumber);

            if (item != null)
            {
                if (!(item is IEquipment equipment) ||
                    equipment.ItemPosition == Equipment.AvalableItemPosition.NotWorn)
                {
                    string message = string.Format("You can not equip the {0}.", item.SentenceDescription);
                    return(new Result(message, true));
                }

                IEquipment equipedItem = performer.EquipedEquipment.Where(i => i.ItemPosition == equipment.ItemPosition).FirstOrDefault();
                if (equipedItem != null)
                {
                    string message = string.Format("You already have {0} in the {1} position.", equipedItem.SentenceDescription, equipedItem.ItemPosition);
                    return(new Result(message, true));
                }
                else
                {
                    performer.Items.Remove(equipment);
                    performer.AddEquipment(equipment);
                    string message = string.Format("You equipped the {0}.", equipment.SentenceDescription);
                    return(new Result(message, false));
                }
            }
            else
            {
                string message = string.Format("You were unable to find {0}.", parm.ParameterValue);
                return(new Result(message, true));
            }
        }
Example #39
0
 /// <summary>
 /// Creates a new instance of <see cref="Passed"/>, if the <paramref name="condition"/> is true and <paramref name="result"/> is not already <see cref="Failed"/>.
 /// Otherwise a new instance of <see cref="Failed"/> is created.
 /// </summary>
 /// <param name="result">The source <see cref="IResult"/> object the returned object is based on.</param>
 /// <param name="condition">If true creates <see cref="Passed"/>, otherwise <see cref="Failed"/>.</param>
 /// <returns>A new instance of <see cref="IResult"/> with the requested modifications.</returns>
 public static IResult PassIf(this IResult result, bool condition) => condition?result.Pass() : result.Fail();
        public async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result)
        {
            // command is unspecified when there was a search failure (command not found); we don't care about these errors
            if (!command.IsSpecified)
            {
                return;
            }

            // the command was successful, we don't care about this result, unless we want to log that a command succeeded.
            if (result.IsSuccess)
            {
                return;
            }

            // the command failed, let's notify the user that something happened.
            await context.Channel.SendMessageAsync($"error: {result}");
        }
Example #41
0
 public TestableResultDecorator(IResult inner)
     : base(inner)
 {
 }
Example #42
0
 public static ISelect <None, IEnumerable <T> > Many <T>(this IResult <IFixture> @this, uint count)
 => @this.Then().Select(new Many <T>(count)).Accept().Get();
Example #43
0
 public ArrayStore(IResult <Array <T> > source) : this(source.Get)
 {
 }
Example #44
0
        public IResult PerformCommand(IMobileObject performer, ICommand command)
        {
            IResult result = base.PerfomCommand(performer, command);

            if (result != null)
            {
                return(result);
            }

            if (command.Parameters.Count <= 0)
            {
                return(new Result("What would you like to get?", true));
            }
            else if (command.Parameters.Count == 1)
            {
                IParameter parameter = command.Parameters[0];

                if (parameter.ParameterValue.ToUpper() == "ALL")
                {
                    for (int i = performer.Room.Items.Count - 1; i >= 0; i--)
                    {
                        IItem      roomItem       = performer.Room.Items[i];
                        ICommand   innerCommand   = new Command();
                        IParameter innerParameter = new Parameter(roomItem.KeyWords[0]);
                        innerCommand.Parameters.Add(innerParameter);
                        IResult innerResult = PerformCommand(performer, innerCommand);
                        GlobalReference.GlobalValues.Notify.Mob(performer, new TranslationMessage(innerResult.ResultMessage));
                    }
                    return(new Result("", false));
                }
                else
                {
                    IItem item = GlobalReference.GlobalValues.FindObjects.FindItemsInRoom(performer.Room, parameter.ParameterValue, parameter.ParameterNumber);

                    if (item != null)
                    {
                        if (!item.Attributes.Contains(ItemAttribute.NoGet))
                        {
                            if (item is ICorpse corpse)
                            {
                                if (corpse.Killer != null)  //allow you to pick up corpses that don't have a killer
                                {
                                    IPlayerCharacter playerCharacter = performer as IPlayerCharacter;

                                    if ((corpse.Killer != performer &&
                                         corpse.OriginalMob != performer) &&
                                        (playerCharacter != null &&
                                         corpse.Killer.SentenceDescription != performer.SentenceDescription &&
                                         corpse.OriginalMob.SentenceDescription != performer.SentenceDescription))
                                    {
                                        return(new Result($"Unable to pickup the corpse belonging to {corpse.Killer.KeyWords[0]}.", true));
                                    }
                                }
                            }

                            IRoom room = performer.Room;
                            GlobalReference.GlobalValues.Engine.Event.Get(performer, item);
                            room.RemoveItemFromRoom(item);
                            AddItemToPerformer(performer, item);

                            string message = string.Format("You pickup the {0}.", item.SentenceDescription);
                            return(new Result(message, false));
                        }
                        else
                        {
                            string message = string.Format("You were unable to get {0}.", item.SentenceDescription);
                            return(new Result(message, true));
                        }
                    }
                    else
                    {
                        string message = string.Format("You were unable to find {0}.", parameter.ParameterValue);
                        return(new Result(message, true));
                    }
                }
            }
            else
            {
                IParameter parameterContainer = command.Parameters[1];
                if (GlobalReference.GlobalValues.FindObjects.FindObjectOnPersonOrInRoom(performer, parameterContainer.ParameterValue, parameterContainer.ParameterNumber, true, true, false, false) is IContainer container)
                {
                    if (container is ICorpse corpse)
                    {
                        if (corpse.Killer != performer)
                        {
                            return(new Result($"Unable to get items from the corpse belonging to {corpse.Killer.KeyWords[0]}.", true));
                        }
                    }

                    IParameter parameterItem = command.Parameters[0];
                    if (parameterItem.ParameterValue.ToUpper() == "ALL")
                    {
                        for (int i = container.Items.Count - 1; i >= 0; i--)
                        {
                            IItem      containerItem  = container.Items[i];
                            ICommand   innerCommand   = new Command();
                            IParameter innerParameter = new Parameter(containerItem.KeyWords[0]);
                            innerCommand.Parameters.Add(innerParameter);
                            innerCommand.Parameters.Add(parameterContainer);
                            IResult innerResult = PerformCommand(performer, innerCommand);
                            GlobalReference.GlobalValues.Notify.Mob(performer, new TranslationMessage(innerResult.ResultMessage));
                        }
                        return(new Result("", false));
                    }
                    else
                    {
                        List <IItem> foundItems = container.Items.FindAll(i => i.KeyWords.Contains(parameterItem.ParameterValue)).ToList();
                        if (foundItems.Count > parameterItem.ParameterNumber)
                        {
                            IItem  item = foundItems[parameterItem.ParameterNumber];
                            string message;

                            if (!item.Attributes.Contains(ItemAttribute.NoGet))
                            {
                                GlobalReference.GlobalValues.Engine.Event.Get(performer, item, container);
                                container.Items.Remove(item);
                                AddItemToPerformer(performer, item);

                                if (item is IMoney)
                                {
                                    IMoney money       = item as IMoney;
                                    string moneyString = GlobalReference.GlobalValues.MoneyToCoins.FormatedAsCoins(money.Value);
                                    message = string.Format("You get the {0} from the {1}.", moneyString, parameterContainer.ParameterValue);
                                }
                                else
                                {
                                    message = string.Format("You get the {0} from the {1}.", parameterItem.ParameterValue, parameterContainer.ParameterValue);
                                }
                            }
                            else
                            {
                                message = string.Format("You were unable to get {0}.", item.SentenceDescription);
                            }

                            return(new Result(message, false));
                        }
                        else
                        {
                            string message = string.Format("Unable to find item {0} in container {1}.", parameterItem.ParameterValue, parameterContainer.ParameterValue);
                            return(new Result(message, true));
                        }
                    }
                }
                else
                {
                    string message = string.Format("Unable to find container {0}.", parameterContainer.ParameterValue);
                    return(new Result(message, true));
                }
            }
        }
Example #45
0
 /// <summary>
 /// Executes the <paramref name="result"/> on a seperate worker thread
 /// </summary>
 /// <param name="result"></param>
 /// <returns></returns>
 public static IResult OnWorkerThread(this IResult result)
 {
     return(new WorkerThreadResultDecorator(result));
 }
Example #46
0
 public static IResult <TValue> Run <TValue, TPreviousValue>(Func <TValue> func, IResult <TPreviousValue> previousResult)
 {
     try
     {
         return(new SuccessResult <TValue>(func(), previousResult));
     }
     catch (Exception ex)
     {
         return(new ErrorResult <TValue, Exception>(ex, previousResult: previousResult));
     }
 }
Example #47
0
        public static IError AddExceptionError <T>(this IResult <T> result, string key, Exception exception)
        {
            var message = $"{exception.Message}\n{exception.StackTrace}";

            return(result.AddError(ErrorType.Error, key, message));
        }
        public OwnApiHttpResponse Edit([FromBody] RopSysRoleEdit rop)
        {
            IResult result = AdminServiceFactory.SysRole.Edit(this.CurrentUserId, Enumeration.BelongSite.Admin, rop);

            return(new OwnApiHttpResponse(result));
        }
        public OwnApiHttpResponse InitAdd()
        {
            IResult result = AdminServiceFactory.SysRole.InitAdd(this.CurrentUserId, Enumeration.BelongSite.Admin);

            return(new OwnApiHttpResponse(result));
        }
Example #50
0
 public static TaskResult GetTaskResult(this IResult result)
 {
     return(s_taskResults[result.State]);
 }
        protected void Create(DM model)
        {
            IResult result = this.Presenter.Add(model);

            this.TakeIResult(result);
        }
        public OwnApiHttpResponse InitEdit([FromUri] string id)
        {
            IResult result = AdminServiceFactory.SysRole.InitEdit(this.CurrentUserId, Enumeration.BelongSite.Admin, id);

            return(new OwnApiHttpResponse(result));
        }
        protected void UnDelete(object model)
        {
            IResult result = this.Presenter.UnDelete(model);

            this.TakeIResult(result);
        }
        public OwnApiHttpResponse GetList([FromUri] RupSysRoleGetList rup)
        {
            IResult result = AdminServiceFactory.SysRole.GetList(this.CurrentUserId, Enumeration.BelongSite.Admin, rup);

            return(new OwnApiHttpResponse(result));
        }
Example #55
0
 public OuterDecorator(IResult result)
 {
     this.Result = result;
 }
        protected void GetById <TModel>(object id, ref TModel outModel)
        {
            IResult result = this.Presenter.GetById <TModel>(id);

            this.TakeIResult(result, ref outModel);
        }
Example #57
0
 public static IError AddValidationError <T>(this IResult <T> result, string key, string message) => result.AddError(ErrorType.ValidationError, key, message);
        protected void Edit(DM model)
        {
            IResult result = this.Presenter.Update(model);

            this.TakeIResult(result);
        }
Example #59
0
 public static bool HasValidationErrors <T>(this IResult <T> result)
 => result.HasErrors(ErrorType.ValidationError);
Example #60
0
 public InnerDecorator(IResult result)
 {
     this.Result = result;
 }