Exemplo n.º 1
0
        public MutateRequest SerializeToProto()
        {
            var result = new MutateRequest
            {
                Region   = GetRegionSpecifier(),
                Mutation = new MutationProto
                {
                    Row        = ByteString.CopyFrom(Key),
                    MutateType = MutationType,
                    Durability = Durability
                }
            };

            if (Timestamp != null)
            {
                result.Mutation.Timestamp = Timestamp.Value.ToUnixU13();
            }

            if (Values?.Any() != true)
            {
                return(result);
            }

            var columns = Values
                          .Select(t =>
            {
                var clo = new MutationProto.Types.ColumnValue
                {
                    Family = ByteString.CopyFromUtf8(t.Key),
                };
                if (t.Value?.Any() != true)
                {
                    return(clo);
                }
                var quals = t.Value.Select(tt =>
                {
                    var quail = new MutationProto.Types.ColumnValue.Types.QualifierValue
                    {
                        Qualifier = ByteString.CopyFromUtf8(tt.Key),
                        Value     = ByteString.CopyFrom(tt.Value)
                    };
                    if (MutationType == MutationProto.Types.MutationType.Delete)
                    {
                        quail.DeleteType = MutationProto.Types.DeleteType.DeleteMultipleVersions;
                    }

                    return(quail);
                })
                            .ToArray();
                clo.QualifierValue.AddRange(quals);

                return(clo);
            }).ToArray();

            result.Mutation.ColumnValue.AddRange(columns);
            return(result);
        }
Exemplo n.º 2
0
 public SherpanyValuesPageViewModel(IDummyApiService apiService, ICachingService <List <SherpanyValueModel> > cachingService)
 {
     _apiService           = apiService;
     _cachingService       = cachingService;
     GetValuesCommand      = new RelayCommand(GetValues, () => !ValuesRetrievalInProgress);
     CreateNewValueCommand = new RelayCommand(CreateNewValue, () => Values?.Any() == true);
     AddValueCommand       = new RelayCommand(AddNewValue);
     DeleteValueCommand    = new RelayCommand(DeleteValue);
     ResetValuesCommand    = new RelayCommand(ResetValues, () => !ValuesRetrievalInProgress);
 }
Exemplo n.º 3
0
        private bool HasClaim(ClaimsPrincipal user)
        {
            if (user != null)
            {
                return(Values?.Any(v => user.HasClaim(Claim, v.Trim()))
                       ?? user.HasClaim(ClaimIsOfRequiredType));
            }

            return(false);
        }
Exemplo n.º 4
0
 public bool ContainsIngredient(string ingredient) => Values.Any(v => v.Contains(ingredient));
Exemplo n.º 5
0
        /// <summary>
        /// Calculate
        /// </summary>
        /// <returns></returns>
        public virtual IDictionary <string, IEnumerable <ScoreData> > Calculate()
        {
            if (Values.Any() == false)
            {
                return(new Dictionary <string, IEnumerable <ScoreData> >());
            }

            var balanceMax         = 0.0;
            var balanceDrawdown    = 0.0;
            var balanceDrawdownMax = 0.0;
            var count         = Values.Count();
            var longs         = new DirectionData();
            var shorts        = new DirectionData();
            var inputBalance  = Values.ElementAtOrDefault(0);
            var outputBalance = Values.ElementAtOrDefault(count - 1);

            for (var i = 0; i < count; i++)
            {
                var current  = Values.ElementAtOrDefault(i);
                var previous = Values.ElementAtOrDefault(i - 1);

                if (current != null && previous != null)
                {
                    var item     = current.Value - previous.Value;
                    var itemGain = Math.Abs(Math.Max(item, 0.0));
                    var itemLoss = Math.Abs(Math.Min(item, 0.0));

                    balanceDrawdownMax = Math.Max(balanceMax - current.Min, balanceDrawdownMax);
                    balanceDrawdown    = Math.Max(balanceMax - current.Value, balanceDrawdown);
                    balanceMax         = Math.Max(balanceMax, current.Value);

                    switch (current.Direction)
                    {
                    case 1:

                        longs.Gains       += itemGain;
                        longs.Losses      += itemLoss;
                        longs.GainsMax     = Math.Max(itemGain, longs.GainsMax);
                        longs.LossesMax    = Math.Max(itemLoss, longs.LossesMax);
                        longs.GainsCount  += item > 0.0 ? 1 : 0;
                        longs.LossesCount += item < 0.0 ? 1 : 0;
                        longs.Commissions += current.Commission;
                        break;

                    case -1:

                        shorts.Gains       += itemGain;
                        shorts.Losses      += itemLoss;
                        shorts.GainsMax     = Math.Max(itemGain, shorts.GainsMax);
                        shorts.LossesMax    = Math.Max(itemLoss, shorts.LossesMax);
                        shorts.GainsCount  += item > 0.0 ? 1 : 0;
                        shorts.LossesCount += item < 0.0 ? 1 : 0;
                        shorts.Commissions += current.Commission;
                        break;
                    }
                }
            }

            var stats = new List <ScoreData>();

            stats.Add(new ScoreData {
                Group = "Balance", Name = "Initial balance $", Value = inputBalance.Value
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Final balance $", Value = outputBalance.Value
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Commissions $", Value = longs.Commissions + shorts.Commissions
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Drawdown $", Value = -balanceDrawdown
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Drawdown %", Value = -Validate(() => balanceDrawdown * 100.0 / balanceMax)
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Equity drawdown $", Value = -balanceDrawdownMax
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Equity drawdown %", Value = -Validate(() => balanceDrawdownMax * 100.0 / balanceMax)
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Change $", Value = new Change {
                    Values = Values
                }.Calculate(0)
            });
            stats.Add(new ScoreData {
                Group = "Balance", Name = "Change %", Value = new Change {
                    Values = Values
                }.Calculate(1)
            });

            var gains         = longs.Gains + shorts.Gains;
            var losses        = longs.Losses + shorts.Losses;
            var gainsMax      = Math.Max(longs.GainsMax, shorts.GainsMax);
            var lossesMax     = Math.Max(longs.LossesMax, shorts.LossesMax);
            var gainsCount    = longs.GainsCount + shorts.GainsCount;
            var lossesCount   = longs.LossesCount + shorts.LossesCount;
            var gainsAverage  = Validate(() => gains / gainsCount);
            var lossesAverage = Validate(() => losses / lossesCount);
            var dealsCount    = gainsCount + lossesCount;

            stats.Add(new ScoreData {
                Group = "Wins", Name = "Total gain $", Value = gains
            });
            stats.Add(new ScoreData {
                Group = "Wins", Name = "Max single gain $", Value = gainsMax
            });
            stats.Add(new ScoreData {
                Group = "Wins", Name = "Average gain $", Value = gainsAverage
            });
            stats.Add(new ScoreData {
                Group = "Wins", Name = "Number of wins", Value = gainsCount
            });
            stats.Add(new ScoreData {
                Group = "Wins", Name = "Percentage of wins %", Value = Validate(() => gainsCount * 100.0 / dealsCount)
            });

            stats.Add(new ScoreData {
                Group = "Losses", Name = "Total loss $", Value = -losses
            });
            stats.Add(new ScoreData {
                Group = "Losses", Name = "Max single loss $", Value = -lossesMax
            });
            stats.Add(new ScoreData {
                Group = "Losses", Name = "Average loss $", Value = -lossesAverage
            });
            stats.Add(new ScoreData {
                Group = "Losses", Name = "Number of losses", Value = lossesCount
            });
            stats.Add(new ScoreData {
                Group = "Losses", Name = "Percentage of losses %", Value = Validate(() => lossesCount * 100.0 / dealsCount)
            });

            stats.Add(new ScoreData {
                Group = "Longs", Name = "Total gain $", Value = longs.Gains
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Total loss $", Value = -longs.Losses
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Max gain $", Value = longs.GainsMax
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Max loss $", Value = -longs.LossesMax
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Average gain $", Value = Validate(() => longs.Gains / longs.GainsCount)
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Average loss $", Value = -Validate(() => longs.Losses / longs.LossesCount)
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Number of longs", Value = longs.GainsCount + longs.LossesCount
            });
            stats.Add(new ScoreData {
                Group = "Longs", Name = "Percentage of longs %", Value = Validate(() => (longs.GainsCount + longs.LossesCount) * 100.0 / dealsCount)
            });

            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Total gain $", Value = shorts.Gains
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Total loss $", Value = -shorts.Losses
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Max gain $", Value = shorts.GainsMax
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Max loss $", Value = -shorts.LossesMax
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Average gain $", Value = Validate(() => shorts.Gains / shorts.GainsCount)
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Average loss $", Value = -Validate(() => shorts.Losses / shorts.LossesCount)
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Number of shorts", Value = shorts.GainsCount + shorts.LossesCount
            });
            stats.Add(new ScoreData {
                Group = "Shorts", Name = "Percentage of shorts %", Value = Validate(() => (shorts.GainsCount + shorts.LossesCount) * 100.0 / dealsCount)
            });

            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Profit Factor", Value = Validate(() => gains / losses)
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Mean", Value = Validate(() => (gains - losses) / dealsCount)
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "CAGR", Value = new CAGR {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Sharpe Ratio", Value = new SharpeRatio {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "MAE", Value = new MAE {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "MFE", Value = new MFE {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "MAR", Value = new MAR {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "AHPR", Value = new AHPR {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "GHPR", Value = new GHPR {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Z-Score", Value = new StandardScore {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "E-Ratio", Value = new EdgeRatio {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Martin Ratio", Value = new MartinRatio {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Sortino Ratio", Value = new SortinoRatio {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Sterling Ratio", Value = new SterlingRatio {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "Kestner Ratio", Value = new KestnerRatio {
                    Values = Values
                }.Calculate()
            });
            stats.Add(new ScoreData {
                Group = "Ratios", Name = "LR Correlation", Value = new RegressionCorrelation {
                    Values = Values
                }.Calculate()
            });

            StatsByFrames = new FrameMetrics {
                Values = Values
            }.Calculate();
            StatsBySeries = new SeriesMetrics {
                Values = Values
            }.Calculate();

            return(stats.GroupBy(o => o.Group).ToDictionary(o => o.Key, o => o.AsEnumerable()));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Determines of the Matrix is completely empty.
 /// May be as slow as O(rowCount * colCount)
 /// </summary>
 /// <returns>true if the matrix contains all missing values; otherwise, false.</returns>
 virtual public bool IsMissingAll()
 {
     return(!Values.Any());
 }
Exemplo n.º 7
0
 /// <summary>
 /// True when <see cref="Values"/> is not empty.
 /// </summary>
 /// <returns></returns>
 public bool HasValue()
 {
     return(Values.Any());
 }
 /// <summary>
 /// Compares two lists to see if they contain at least one value that is the same.
 /// </summary>
 /// <param name="values">Values for a profile</param>
 /// <param name="value">The value being sought</param>
 /// <returns></returns>
 private static bool Contains(Values values, string value)
 {
     return values == null || value == null ? false : values.Any(i => value.Equals(i.Name));
 }
Exemplo n.º 9
0
        public ListItem()
        {
            MappingHandler = (FromJson input) =>
            {
                // The AddValidateUpdateItemUsingPath call returns the id of the added list item
                if (input.FieldName == "AddValidateUpdateItemUsingPath")
                {
                    if (input.JsonElement.TryGetProperty("results", out JsonElement resultsProperty))
                    {
                        foreach (var field in resultsProperty.EnumerateArray())
                        {
                            var fieldName  = field.GetProperty("FieldName").GetString();
                            var fieldValue = field.GetProperty("FieldValue").GetString();

                            if (fieldName == "Id")
                            {
                                if (int.TryParse(fieldValue, out int id))
                                {
                                    Id = id;

                                    // Flag the parent collection as requested, most requests return a "full" json structure and then the standard json parsing
                                    // is used, which sets the collection as requested. Since in this case we get back a special structure we use custom
                                    // parsing and hence we need to flag the collection as requested ourselves
                                    (Parent as ListItemCollection).Requested = true;

                                    // populate the uri and type metadata fields to enable actions upon
                                    // this item without having to read it again from the server
                                    var parentList = Parent.Parent as List;
                                    AddMetadata(PnPConstants.MetaDataRestId, $"{id}");
                                    MetadataSetup();

                                    // Ensure the values are committed to the model when an item is being added
                                    Values.Commit();

                                    // We're currently only interested in the Id property
                                    continue;
                                }
                            }
                        }
                    }
                }
                else
                {
                    //Handle the mapping from json to the domain model for the cases which are not generically handled
                    input.Log.LogDebug(PnPCoreResources.Log_Debug_JsonCannotMapField, input.FieldName);
                }

                return(null);
            };

            PostMappingHandler = (string json) =>
            {
                // Extra processing of returned json
            };
            AddApiCallHandler = async(keyValuePairs) =>
            {
                var parentList = Parent.Parent as List;
                // sample parent list uri: https://bertonline.sharepoint.com/sites/modern/_api/Web/Lists(guid'b2d52a36-52f1-48a4-b499-629063c6a38c')
                var parentListUri = parentList.GetMetadata(PnPConstants.MetaDataUri);

                // sample parent list entity type name: DemolistList (skip last 4 chars)
                // Sample parent library type name: MyDocs
                var parentListTitle = !string.IsNullOrEmpty(parentList.GetMetadata(PnPConstants.MetaDataRestEntityTypeName)) ? parentList.GetMetadata(PnPConstants.MetaDataRestEntityTypeName) : null;

                // If this list we're adding items to was not fetched from the server than throw an error
                string serverRelativeUrl = null;
                if (string.IsNullOrEmpty(parentListTitle) || string.IsNullOrEmpty(parentListUri) || !parentList.IsPropertyAvailable(p => p.TemplateType))
                {
                    // Fall back to loading the rootfolder propery if we can't determine the list name
                    await parentList.EnsurePropertiesAsync(p => p.RootFolder).ConfigureAwait(false);

                    serverRelativeUrl = parentList.RootFolder.ServerRelativeUrl;
                }
                else
                {
                    serverRelativeUrl = ListMetaDataMapper.RestEntityTypeNameToUrl(PnPContext.Uri, parentListTitle, parentList.TemplateType);
                }

                // drop the everything in front of _api as the batching logic will add that automatically
                var baseApiCall = parentListUri.Substring(parentListUri.IndexOf("_api"));

                // Define the JSON body of the update request based on the actual changes
                dynamic body = new ExpandoObject();

                var decodedUrlFolderPath = serverRelativeUrl;
                if (keyValuePairs.ContainsKey(FolderPath))
                {
                    if (keyValuePairs[FolderPath] != null)
                    {
                        var folderPath = keyValuePairs[FolderPath].ToString();
                        if (!string.IsNullOrEmpty(folderPath))
                        {
                            if (folderPath.ToLower().StartsWith(serverRelativeUrl))
                            {
                                decodedUrlFolderPath = folderPath;
                            }
                            else
                            {
                                decodedUrlFolderPath = $"{serverRelativeUrl}/{folderPath.TrimStart('/')}";
                            }
                        }
                    }
                }

                var underlyingObjectType = (int)FileSystemObjectType.File;

                if (keyValuePairs.ContainsKey(UnderlyingObjectType))
                {
                    if (keyValuePairs[UnderlyingObjectType] != null)
                    {
                        underlyingObjectType = (int)((FileSystemObjectType)keyValuePairs[UnderlyingObjectType]);
                    }
                }

                body.listItemCreateInfo = new
                {
                    FolderPath = new
                    {
                        DecodedUrl = decodedUrlFolderPath
                    },
                    UnderlyingObjectType = underlyingObjectType
                };

                body.bNewDocumentUpdate = false;

                if (Values.Any())
                {
                    // Verify the needed locale settings are loaded
                    await EnsureRegionalSettingsAsync(PnPContext).ConfigureAwait(false);
                }

                // Add fields to the payload
                dynamic itemValues = new List <dynamic>();
                foreach (var item in Values)
                {
                    dynamic field = new ExpandoObject();
                    field.FieldName = item.Key;

                    BuildValidateUpdateItemPayload(PnPContext, item, field);

                    itemValues.Add(field);
                }
                body.formValues = itemValues;

                // Serialize object to json
                var bodyContent = JsonSerializer.Serialize(body, typeof(ExpandoObject), new JsonSerializerOptions {
                    WriteIndented = true
                });

                // Return created api call
                return(new ApiCall($"{baseApiCall}/AddValidateUpdateItemUsingPath", ApiType.SPORest, bodyContent));
            };
        }
Exemplo n.º 10
0
 public bool HasValue() => Values.Any();
Exemplo n.º 11
0
        public static IProperties <TKey, Object> ZSetAdd <TKey>(this IProperties <TKey, Object> IProperties, TKey Key, Object FirstValue, params Object[] Values)

            where TKey : IEquatable <TKey>, IComparable <TKey>, IComparable

        {
            #region Initial checks

            if (IProperties == null)
            {
                throw new ArgumentNullException();
            }

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

            if (FirstValue == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            Dictionary <Object, UInt64> _ZSet = null;
            Object _CountedValue = null;
            UInt64 _Counter;

            if (IProperties.TryGetProperty(Key, out _CountedValue))
            {
                _ZSet = _CountedValue as Dictionary <Object, UInt64>;

                if (_ZSet == null)
                {
                    throw new Exception("The value is not a counted set!");
                }

                else
                {
                    if (_ZSet.TryGetValue(FirstValue, out _Counter))
                    {
                        _ZSet[FirstValue] = _Counter + 1;
                    }
                    else
                    {
                        _ZSet.Add(FirstValue, 1);
                    }

                    if (Values != null && Values.Any())
                    {
                        Values.ForEach(value => {
                            if (_ZSet.TryGetValue(value, out _Counter))
                            {
                                _ZSet[value] = _Counter + 1;
                            }
                            else
                            {
                                _ZSet.Add(value, 1);
                            }
                        });
                    }

                    return(IProperties);
                }
            }

            _ZSet = new Dictionary <Object, UInt64>();
            _ZSet.Add(FirstValue, 1);

            if (Values != null && Values.Any())
            {
                Values.ForEach(value =>
                {
                    if (_ZSet.TryGetValue(value, out _Counter))
                    {
                        _ZSet[value] = _Counter + 1;
                    }
                    else
                    {
                        _ZSet.Add(value, 1);
                    }
                });
            }

            IProperties.Set(Key, _ZSet);

            return(IProperties);
        }
Exemplo n.º 12
0
        public static IProperties <TKey, Object> SetAdd <TKey>(this IProperties <TKey, Object> IProperties, TKey Key, Object FirstValue, params Object[] Values)

            where TKey : IEquatable <TKey>, IComparable <TKey>, IComparable
        {
            #region Initial checks

            if (IProperties == null)
            {
                throw new ArgumentNullException();
            }

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

            if (FirstValue == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            HashedSet <Object> _Set   = null;
            Object             _Value = null;

            if (IProperties.TryGetProperty(Key, out _Value))
            {
                _Set = _Value as HashedSet <Object>;

                if (_Set == null)
                {
                    throw new Exception("The value is not a set!");
                }

                else
                {
                    _Set.Add(FirstValue);

                    if (Values != null && Values.Any())
                    {
                        Values.ForEach(value => _Set.Add(value));
                    }

                    return(IProperties);
                }
            }

            _Set = new HashedSet <Object>()
            {
                FirstValue
            };

            if (Values != null && Values.Any())
            {
                Values.ForEach(value => _Set.Add(value));
            }

            IProperties.Set(Key, _Set);

            return(IProperties);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Determines whether all the elements inside this <see cref="HoconValue"/>
 /// are a string.
 /// </summary>
 /// <returns>
 ///   <c>true</c>if all elements inside this <see cref="HoconValue"/> are a string; otherwise <c>false</c>.
 /// </returns>
 public bool IsString()
 {
     return(Values.Any() && Values.All(v => v.IsString()));
 }
Exemplo n.º 14
0
        public static IProperties <TKey, Object> ListAdd <TKey>(this IProperties <TKey, Object> IProperties, TKey Key, Object FirstValue, params Object[] Values)

            where TKey : IEquatable <TKey>, IComparable <TKey>, IComparable

        {
            #region Initial checks

            if (IProperties == null)
            {
                throw new ArgumentNullException();
            }

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

            if (FirstValue == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            List <Object> _List  = null;
            Object        _Value = null;

            if (IProperties.TryGetProperty(Key, out _Value))
            {
                _List = _Value as List <Object>;

                if (_List == null)
                {
                    throw new Exception("The value is not a list!");
                }

                else
                {
                    _List.Add(FirstValue);

                    if (Values != null && Values.Any())
                    {
                        _List.AddRange(Values);
                    }

                    return(IProperties);
                }
            }

            _List = new List <Object>()
            {
                FirstValue
            };

            if (Values != null && Values.Any())
            {
                _List.AddRange(Values);
            }

            IProperties.Set(Key, _List);

            return(IProperties);
        }
Exemplo n.º 15
0
 public bool IsPrivate()
 {
     return(Values.Any(mode => mode is ModePrivate));
 }
Exemplo n.º 16
0
 public bool IsSecret()
 {
     return(Values.Any(mode => mode is ModeSecret));
 }
Exemplo n.º 17
0
        /// <summary>
        /// Performs a single HTTP health check
        /// </summary>
        /// <param name="webRequest">The request parameters for the health check</param>
        /// <returns>A task that can be awaited for completion of the check</returns>
        private async Task ExecuteWebRequest(WebAreWeUpRequest webRequest)
        {
            Stopwatch  SW = new Stopwatch();
            HttpClient Client;
            bool       IgnoreSslErrors = (webRequest.Protocol == Models.Protocol.HTTPS && ((HttpsAreWeUpRequest)webRequest).IgnoreSSLErrors);
            bool       StopRedirects   = webRequest.PreventAutoRedirect;

            if (IgnoreSslErrors && StopRedirects)
            {
                Client = _IgnoreSslErrorAndNoRedirectClient;
            }
            else if (IgnoreSslErrors)
            {
                Client = _IgnoreSslErrorClient;
            }
            else if (StopRedirects)
            {
                Client = _NoRedirectClient;
            }
            else
            {
                Client = _NormalClient;
            }

            bool   Success = false;
            string Message = String.Empty;

            // Initialize these here so we can dispose them later
            HttpRequestMessage  Request  = null;
            HttpResponseMessage Response = null;

            try
            {
                // The client will automatically follow redirects, unless we specifically disable it in the handler
                Request = new HttpRequestMessage(webRequest.Method, webRequest.GetPath());

                // If the request is a PUT, POST, or PATCH and there was supplied content, add it
                // to the request
                if (!String.IsNullOrEmpty(webRequest.Content) && (new HttpMethod[] { HttpMethod.Post, HttpMethod.Put, new HttpMethod("PATCH") }).Contains(webRequest.Method))
                {
                    Request.Content = webRequest.GetContent();
                }

                SW.Start();
                Response = await Client.SendAsync(Request);

                SW.Stop();

                bool RedirectSuccess = true;

                // If we're not auto following redirects, and a redirect response code was returned
                // check the headers (if any were provided) and then follow the redirect
                if (webRequest.PreventAutoRedirect && ((int)Response.StatusCode >= 300 && (int)Response.StatusCode <= 399))
                {
                    foreach (KeyValuePair <string, string> Item in webRequest.RedirectHeadersToValidate)
                    {
                        if (Response.Headers.TryGetValues(Item.Key, out IEnumerable <string> Values))
                        {
                            if (Values.Any())
                            {
                                if (!Values.Contains(Item.Value))
                                {
                                    Message         = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed because the {Item.Key} header did not contain the value {Item.Value}, it contained {String.Join(",", Values)}.";
                                    RedirectSuccess = false;
                                    break;
                                }
                            }
                            else
                            {
                                Message         = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed because the {Item.Key} header did not contain any values.";
                                RedirectSuccess = false;
                                break;
                            }
                        }
                        else
                        {
                            Message         = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed because the {Item.Key} header was not present in the redirect response. The response contained these headers:\r\n{JsonConvert.SerializeObject(Response.Headers)}";
                            RedirectSuccess = false;
                            break;
                        }
                    }

                    if (RedirectSuccess)
                    {
                        // Use a client now that doesn't prevent redirects
                        if (IgnoreSslErrors)
                        {
                            Client = _IgnoreSslErrorClient;
                        }
                        else
                        {
                            Client = _NormalClient;
                        }

                        // Now follow the redirect to see if the page is up
                        HttpRequestMessage NewRequest = new HttpRequestMessage(HttpMethod.Get, Response.Headers.Location);

                        SW.Start();
                        Response = await Client.SendAsync(NewRequest);

                        SW.Stop();
                    }
                }

                //If the response didn't match the expected response, send an SNS notification
                if (Response.StatusCode != webRequest.ExpectedResponse)
                {
                    // If the autofollowredirects was off and we successfully validated the redirect headers
                    // then this will be true and an error message won't have been set
                    if (RedirectSuccess)
                    {
                        Message = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} did not match the expected response of {(int)webRequest.ExpectedResponse} {webRequest.ExpectedResponse}: received {(int)Response.StatusCode} {Response.StatusCode}";
                    }
                }
                else
                {
                    if (webRequest.CookiesToValidate != null && webRequest.CookiesToValidate.Any())
                    {
                        // All the cookies to validate, except those in the cookie container. If the output is 0 (aka ! Any()), then all of the cookies to
                        // validate were in the container
                        IEnumerable <string> MissingCookies = webRequest.CookiesToValidate.Except(_Cookies.GetCookies(webRequest.GetPath()).Cast <Cookie>().Select(x => x.Name));

                        if (MissingCookies.Any())
                        {
                            Message = $"[ERROR] :  {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed because the response was missing required cookies {String.Join(",", MissingCookies)}.";
                        }
                        else
                        {
                            Success = true;
                            Message = $"[INFO] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} is up! ({SW.ElapsedMilliseconds.ToString()}ms latency)";
                        }
                    }
                    else
                    {
                        Success = true;
                        Message = $"[INFO] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} is up! ({SW.ElapsedMilliseconds.ToString()}ms latency)";
                    }
                }
            }
            catch (HttpRequestException e)
            {
                if (e.InnerException is WebException)
                {
                    Message = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed with an error: {((WebException)e.InnerException).Status} - {((WebException)e.InnerException).Message}";
                }
                else
                {
                    string ExContent = String.Empty;
                    try
                    {
                        ExContent = JsonConvert.SerializeObject(e);
                    }
                    catch (Exception ex)
                    {
                        StringBuilder Buffer = new StringBuilder();

                        Buffer.Append("{")
                        .Append("\"ClassName\":\"")
                        .Append(e.GetType().Name)
                        .Append("\",")
                        .Append("\"Message\":\"")
                        .Append(e.Message)
                        .Append("\",")
                        .Append("\"InnerException\":\"")
                        .Append(e.InnerException)
                        .Append("\",")
                        .Append("\"StackTraceString\":\"")
                        .Append(e.StackTrace)
                        .Append("\"")
                        .Append("}");

                        ExContent = Buffer.ToString();
                    }

                    Message = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed with an error:\r\n{SerializeException(e)}";
                }
            }
            catch (Exception e)
            {
                Message = $"[ERROR] : {webRequest.GetPath().ToString()} via HTTP {webRequest.Method.Method} failed with an unexpected error:\r\n{SerializeException(e)}";
            }
            finally
            {
                if (Response != null)
                {
                    Response.Dispose();
                }

                if (Request != null)
                {
                    Request.Dispose();
                }
            }

            // Don't send a data point if the check didn't succeed
            long Time = Success ? SW.ElapsedMilliseconds : -1;

            await this.ProcessResult(webRequest, Success, Message, Time);
        }
Exemplo n.º 18
0
 public bool AnyWithIngredients() => Values.Any(v => v.Count > 0);
 /// <summary>
 /// Compares two lists to see if they contain at least one value that is the same.
 /// </summary>
 /// <param name="values">Values for a profile</param>
 /// <param name="value">The value being sought</param>
 /// <returns></returns>
 private static bool Contains(Values values, string value)
 {
     return(values == null || value == null ? false : values.Any(i => value.Equals(i.Name)));
 }
Exemplo n.º 20
0
 public bool Contains(string name)
 {
     return(Values.Any(colParam => colParam.Name == name));
 }
Exemplo n.º 21
0
 public bool Exist <TExist>() where TExist : TMode
 {
     return(Values.Any(m => m is TExist));
 }
Exemplo n.º 22
0
        public override IEnumerable <HealthCheckStatus> GetStatus()
        {
            var successMessage = string.Format(CheckSuccessMessage, FileName, XPath, Values);

            var configValue = _configurationService.GetConfigurationValue();

            if (configValue.Success == false)
            {
                if (ValidIfConfigMissing)
                {
                    return(new[] { new HealthCheckStatus(successMessage)
                                   {
                                       ResultType = StatusResultType.Success
                                   } });
                }

                var errorMessage = configValue.Result;
                return(new[] { new HealthCheckStatus(errorMessage)
                               {
                                   ResultType = StatusResultType.Error
                               } });
            }

            CurrentValue = configValue.Result;

            // need to update the successMessage with the CurrentValue
            successMessage = string.Format(CheckSuccessMessage, FileName, XPath, Values, CurrentValue);

            var valueFound = Values.Any(value => string.Equals(CurrentValue, value.Value, StringComparison.InvariantCultureIgnoreCase));

            if (ValueComparisonType == ValueComparisonType.ShouldEqual && valueFound || ValueComparisonType == ValueComparisonType.ShouldNotEqual && valueFound == false)
            {
                return(new[] { new HealthCheckStatus(successMessage)
                               {
                                   ResultType = StatusResultType.Success
                               } });
            }

            // Declare the action for rectifying the config value
            var rectifyAction = new HealthCheckAction("rectify", Id)
            {
                Name          = TextService.Localize("healthcheck/rectifyButton"),
                ValueRequired = CanRectifyWithValue,
            };

            if (rectifyAction.ValueRequired)
            {
                rectifyAction.ProvidedValueValidation      = ProvidedValueValidation.ToString().ToLower();
                rectifyAction.ProvidedValueValidationRegex = ProvidedValueValidationRegex;
            }

            var resultMessage = string.Format(CheckErrorMessage, FileName, XPath, Values, CurrentValue);

            return(new[]
            {
                new HealthCheckStatus(resultMessage)
                {
                    ResultType = StatusResultType.Error,
                    Actions = CanRectify || CanRectifyWithValue ? new[] { rectifyAction } : new HealthCheckAction[0]
                }
            });
        }
Exemplo n.º 23
0
 public override string BuildComponentName() =>
 Values?.Any() ?? false
         ? BuildComponentNameWithArgument(string.Join("/", Values))
         : throw new InvalidOperationException($"Component name cannot be resolved automatically for {GetType().Name}. Term value(s) should be specified explicitly.");
Exemplo n.º 24
0
        /// <summary>
        /// Prepares the WHERE clause of the SQL query from the <see cref="Filter"/> argument: WHERE ABC
        /// </summary>
        private string PrepareWhereSql(QxCompilationContext ctx)
        {
            var ps = ctx.Parameters;

            // WHERE is cached
            if (_cachedWhere == null)
            {
                string whereFilter       = null;
                string whereInIds        = null;
                string whereInParentIds  = null;
                string whereInPropValues = null;

                if (Filter != null)
                {
                    whereFilter = Filter.Expression.CompileToBoolean(ctx);
                }

                if (Ids != null && Ids.Any())
                {
                    if (Ids.Count() == 1)
                    {
                        string paramName = ps.AddParameter(Ids.Single());
                        whereInIds = $"[P].[Id] = @{paramName}";
                    }
                    else
                    {
                        var isIntKey    = KeyType == KeyType.Int; // (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int);
                        var isStringKey = KeyType == KeyType.String;

                        // Prepare the ids table
                        DataTable idsTable = isIntKey ? RepositoryUtilities.DataTable(Ids.Select(id => new IdListItem {
                            Id = (int)id
                        }))
                            : isStringKey?RepositoryUtilities.DataTable(Ids.Select(id => new StringListItem {
                            Id = id.ToString()
                        }))
                                                 : throw new InvalidOperationException("Only string and Integer Ids are supported");

                        //
                        var idsTvp = new SqlParameter("@Ids", idsTable)
                        {
                            TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer Ids are supported"),
                                             SqlDbType = SqlDbType.Structured
                        };

                        ps.AddParameter(idsTvp);
                        whereInIds = $"[P].[Id] IN (SELECT Id FROM @Ids)";
                    }
                }

                if (ParentIds != null)
                {
                    if (!ParentIds.Any())
                    {
                        if (IncludeRoots)
                        {
                            whereInParentIds = $"[P].[ParentId] IS NULL";
                        }
                    }
                    else if (ParentIds.Count() == 1)
                    {
                        string paramName = ps.AddParameter(ParentIds.Single());
                        whereInParentIds = $"[P].[ParentId] = @{paramName}";
                        if (IncludeRoots)
                        {
                            whereInParentIds += " OR [P].[ParentId] IS NULL";
                        }
                    }
                    else
                    {
                        var isIntKey    = KeyType == KeyType.Int; // (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int);
                        var isStringKey = KeyType == KeyType.String;

                        // Prepare the data table
                        var    parentIdsTable = new DataTable();
                        string idName         = "Id";
                        var    idType         = KeyType switch
                        {
                            KeyType.String => typeof(string),
                            KeyType.Int => typeof(int),
                            _ => throw new InvalidOperationException("Bug: Only string and Integer ParentIds are supported"),
                        };

                        var column = new DataColumn(idName, idType);
                        if (isStringKey)
                        {
                            column.MaxLength = 450; // Just for performance
                        }
                        parentIdsTable.Columns.Add(column);
                        foreach (var id in ParentIds.Where(e => e != null))
                        {
                            DataRow row = parentIdsTable.NewRow();
                            row[idName] = id;
                            parentIdsTable.Rows.Add(row);
                        }

                        // Prepare the TVP
                        var parentIdsTvp = new SqlParameter("@ParentIds", parentIdsTable)
                        {
                            TypeName = KeyType == KeyType.Int ? "[dbo].[IdList]" : KeyType == KeyType.String ? "[dbo].[StringList]" : throw new InvalidOperationException("Bug: Only string and Integer ParentIds are supported"),
                                             SqlDbType = SqlDbType.Structured
                        };

                        ps.AddParameter(parentIdsTvp);
                        whereInParentIds = $"[P].[ParentId] IN (SELECT Id FROM @ParentIds)";
                        if (IncludeRoots)
                        {
                            whereInParentIds += " OR [P].[ParentId] IS NULL";
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(PropName) && Values != null && Values.Any())
                {
                    var propDesc = ResultDescriptor.Property(PropName);
                    var propType = propDesc.Type;

                    var isIntKey    = propType == typeof(int?) || propType == typeof(int);
                    var isStringKey = propType == typeof(string);

                    // Prepare the ids table
                    DataTable valuesTable =
                        isStringKey ? RepositoryUtilities.DataTable(Values.Select(id => new StringListItem {
                        Id = id.ToString()
                    })) :
                        isIntKey?RepositoryUtilities.DataTable(Values.Select(id => new IdListItem {
                        Id = (int)id
                    })) :
                        throw new InvalidOperationException("Only string and Integer Ids are supported");

                    var valuesTvp = new SqlParameter("@Values", valuesTable)
                    {
                        TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer values are supported"),
                                         SqlDbType = SqlDbType.Structured
                    };

                    ps.AddParameter(valuesTvp);
                    whereInPropValues = $"[P].[{propDesc.Name}] IN (SELECT Id FROM @Values)";
                }

                // The final WHERE clause (if any)
                string whereSql = "";

                var clauses = new List <string> {
                    whereFilter, whereInIds, whereInParentIds, whereInPropValues
                }.Where(e => !string.IsNullOrWhiteSpace(e));
                if (clauses.Any())
                {
                    whereSql = clauses.Aggregate((c1, c2) => $"{c1}) AND ({c2}");
                    whereSql = $"WHERE ({whereSql})";
                }

                _cachedWhere = whereSql;
            }

            return(_cachedWhere);
        }
Exemplo n.º 25
0
 public bool Contains(string UID)
 => Values.Any(x => x == UID);
Exemplo n.º 26
0
 public bool IsConnected(string UID)
 => Values.Any(x => x == UID);
Exemplo n.º 27
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Indicates whether the given string occurs (as a substring) in any available
 /// alternative (using StringComparison.InvariantCultureIgnoreCase).
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public bool OccursInAnyAlternative(string s)
 {
     return(string.IsNullOrEmpty(s) ? Count > 0 :
            Values.Any(str => str.Length > 0 && str.Text.IndexOf(s, StringComparison.InvariantCultureIgnoreCase) >= 0));
 }
Exemplo n.º 28
0
        public override string ToString()
        {
            string raw = null;

            if (Engine != null)
            {
                var e = this.Contains("convert_string").FirstOrDefault();
                if (e != null)
                {
                    var scopes = new ValueContainer(Engine);

                    scopes.Push(Engine.Globals);
                    scopes.NewStackBoundary();

                    dynamic ss = new Value();
                    ss.@this = this;

                    scopes.Push(ss);

                    dynamic scopeValue
                        = new Value(scopes, Engine.GlobalContainer.FindValue("Scopes"));

                    var expression = ((FunctionAbstract)e.RawValue).Lambda;

                    var c = new FunctionCallExpression(expression, new List <Value>()
                    {
                        (Value)scopeValue
                    });

                    dynamic res = Engine.RunExpressionCustomScope(c, scopes);

                    return((string)res);
                }
            }

            if (IsNumber)
            {
                raw = RawValue.ToString();
            }

            if (RawValue is string)
            {
                raw = $"\"{RawValue}\"";
            }

            if (RawValue is Expression)
            {
                raw = ((Expression)RawValue).ToString();
            }

            if (IsBool)
            {
                raw = $"{RawValue}";
            }

            if (RawValue is FunctionAbstract)
            {
                raw = ((FunctionAbstract)RawValue).ToString();
                return(raw);
            }

            if (RawValue is Delegate)
            {
                raw = ((Delegate)RawValue).ToString();
            }

            if (IsArray)
            {
                var v = (List <Value>)RawValue;
                raw = "[" + string.Join(",", v.Select(x => x.ToString())) + "]";
            }

            var left  = raw;
            var right = (Values?.Any() ?? false) ? $"({string.Join(",", Values.Keys)})" : null;

            if (left != null && right != null)
            {
                return($"{left}: {right}");
            }

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

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

            if (RawValue.ToString() != RawValue.GetType().ToString())
            {
                return(RawValue.ToString());
            }

            return("null");
        }
Exemplo n.º 29
0
 public bool Contains(float value) => Values.Any(v => v.Value.Equals(value));
Exemplo n.º 30
0
 public override string ToString()
 {
     return(TableName + ":" + (Values.Any() ? string.Join(",", Values) : Empty) + ":" + LogSequenceNumberMax);
 }
Exemplo n.º 31
0
 /// <summary>
 /// リディール可能か?
 /// </summary>
 /// <returns></returns>
 public bool CanRedeal()
 {
     // 山札が一枚もなくWastePileに一枚以上あればOK
     return(!Values.Any(e => e is Stock) && Values.Any(e => e is WastePile));
 }