コード例 #1
0
        public JsonResult GetTracesPaged(int offset, int limit, string search, string sort, string order)
        {
            // get logs newer than 7 days
            var nowUtc = _now.UtcNow;

            var traces =
                _context.AsQueryable <LogEntry>().Include(x => x.Steps)
                .Where(x => DbFunctions.AddHours(x.Timestamp, LogLimit) > nowUtc)
                .AsQueryable();

            IOrderedQueryable <LogEntry> pagedTraces;

            switch (order)
            {
            case LogsSortAscendingKey:
                pagedTraces = traces.OrderAscending(sort);
                break;

            case LogsSortDescendingKey:
                pagedTraces = traces.OrderDescending(sort);
                break;

            default:
                pagedTraces = traces.OrderDescending(sort);
                break;
            }

            List <LogEntry> pagedTracesList;

            if (string.IsNullOrEmpty(search))
            {
                pagedTracesList = pagedTraces
                                  .Skip((offset / limit) * limit)
                                  .Take(limit).ToList();
            }
            else
            {
                string searchLikeExpression = string.Format("%{0}%", search);
                Expression <Func <LogEntry, bool> > searchExpression =
                    entry => SqlFunctions.PatIndex(searchLikeExpression, entry.RequestUri) > 0 ||
                    entry.Steps.Any(x => SqlFunctions.PatIndex(searchLikeExpression, x.Frame) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Message) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Name) > 0 ||
                                    SqlFunctions.PatIndex(searchLikeExpression, x.Metadata) > 0);

                pagedTracesList = pagedTraces.AsExpandable().Where(searchExpression).Skip((offset / limit) * limit).Take(limit).ToList();
            }

            var tracesVms = new List <TraceViewModel>();

            foreach (var trace in pagedTracesList)
            {
                var traceSteps = trace.Steps.OrderBy(x => x.Index).ToList();

                var builder = new StringBuilder();
                builder.Append("<p style=\"white-space: nowrap;\">Start request </p>");

                foreach (var tracestep in traceSteps)
                {
                    builder.Append(string.Format("<p style=\"white-space: nowrap;\">{0}</p>", string.Format("From {0} method located in frame {1} {2} {3} \r\n", tracestep.Source,
                                                                                                            string.Format("<pre class=\"prettyprint lang-cs\">{0}</pre>", tracestep.Frame),
                                                                                                            (!string.IsNullOrEmpty(tracestep.Name) ? string.Format(" (which processes {0}) ", tracestep.Name) : ""),
                                                                                                            (!string.IsNullOrEmpty(tracestep.Message) ? string.Format(" (with message {0}) ", tracestep.Message) : ""))));

                    if (string.IsNullOrEmpty(tracestep.Metadata))
                    {
                        continue;
                    }

                    builder.Append("<p style=\"white-space: nowrap;\">With metadata: </p>");

                    string beautified;
                    if (XmlUtils.IsValidXml(tracestep.Metadata))
                    {
                        // xml
                        // operation metadata is xml in our case
                        beautified = XmlPrettifyHelper.Prettify(tracestep.Metadata.Replace(XmlHeader8, "").Replace(XmlHeader16, ""));
                    }
                    else if (JsonUtils.IsValidJson(tracestep.Metadata))
                    {
                        beautified = string.Format("<pre class=\"prettyprint lang-json\">{0}</pre>",
                                                   JsonPrettifier.BeautifyJson(tracestep.Metadata));
                    }
                    else
                    {
                        beautified = tracestep.Metadata;
                    }

                    builder.Append(beautified);
                }

                builder.Append("<p style=\"white-space: nowrap;\">End request </p>");

                var traceString = HttpUtility.HtmlEncode(builder.ToString());

                var captureDuration = trace.ResponseTimestamp.HasValue && trace.RequestTimestamp.HasValue;

                var item = new TraceViewModel
                {
                    Duration = captureDuration ? string.Format("{0} seconds",
                                                               (trace.ResponseTimestamp.Value - trace.RequestTimestamp.Value).TotalSeconds.ToString("#.##")) : "Duration not captured",
                    Timestamp = trace.Timestamp.ToString(CultureInfo.InvariantCulture),
                    Uri       = trace.RequestUri,
                    Workflow  = new HtmlString(HttpUtility.HtmlDecode(traceString)).ToHtmlString()
                };

                tracesVms.Add(item);
            }

            var model = new
            {
                total = traces.Count(),
                rows  = tracesVms
            };

            return(Json(model, JsonRequestBehavior.AllowGet));
        }
コード例 #2
0
 void ViewJsonObjects()
 {
     JsonObjectsView?.ShowJsonString(JsonUtils.Format(ObjectResult));
 }
コード例 #3
0
        public void UpdateYouTubePlaylistVideo(string playlistId)
        {
            // Make sure we have a TEMP directory
            string dir = IOHelper.MapPath("~/App_Data/TEMP/YouTube/");

            Directory.CreateDirectory(dir);

            // Make an initial request to get information about the playlist
            var response1 = Api.YouTube.Playlists.GetPlaylists(new YouTubeGetPlaylistListOptions
            {
                Ids = new[] { playlistId }
            });

            // Get a reference to the playlist (using "Single" as there should be exactly one playlist)
            var playlist = response1.Body.Items.Single();

            // Save the playlist to the disk
            JsonUtils.SaveJsonObject(dir + "Playlist_" + playlist.Id + ".json", playlist);

            // List of all video IDs
            List <string> ids = new List <string>();

            // Initialize the options for getting the playlist items
            var playlistItemsOptions = new YouTubeGetPlaylistItemListOptions(playlistId)
            {
                // Maximum allowed value is 50
                MaxResults = 50
            };

            int page = 0;

            while (page < 10)
            {
                // Get the playlist items
                var response2 = Api.YouTube.PlaylistItems.GetPlaylistItems(playlistItemsOptions);

                // Append each video ID to the list
                foreach (var item in response2.Body.Items)
                {
                    ids.Add(item.VideoId);
                }

                // Break the loop if there are no additional pages
                if (String.IsNullOrWhiteSpace(response2.Body.NextPageToken))
                {
                    break;
                }

                // Update the options with the page token
                playlistItemsOptions.PageToken = response2.Body.NextPageToken;

                page++;
            }

            // Iterate through groups of IDs (maximum 50 items per group)
            foreach (var group in ids.Where(x => !ExistsOnDiskAndIsUpToDate(x)).InGroupsOf(50))
            {
                // Initialize the video options
                var videosOptions = new YouTubeGetVideoListOptions
                {
                    Ids  = group.ToArray(),
                    Part = YouTubeVideoParts.Snippet + YouTubeVideoParts.ContentDetails + YouTubeVideoParts.Statistics
                };

                // Make a request to the APi to get video information
                var res3 = Api.YouTube.Videos.GetVideos(videosOptions);

                // Iterate through the videos
                foreach (var video in res3.Body.Items)
                {
                    // Save the video to the disk
                    string path = dir + "Video_" + video.Id + ".json";
                    JsonUtils.SaveJsonObject(path, video);
                }
            }

            // Load the videos from the individual files, and save them to a common file
            JsonUtils.SaveJsonArray(dir + "Playlist_" + playlistId + "_Videos.json", ids.Select(LoadYouTubeVideo).WhereNotNull());
        }
コード例 #4
0
 public void Put(string key, object value)
 {
     ValidateObject(value);
     _session.SetString(key, JsonUtils.ToJson(value));
 }
コード例 #5
0
ファイル: ServiceHelper.cs プロジェクト: abbottCheer/K3Cloud
        /// <summary>
        /// 从Redis获取同步数据
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="dataType"></param>
        /// <param name="redis"></param>
        /// <param name="redisKeys"></param>
        /// <returns></returns>
        private static List <AbsSynchroDataInfo> GetSynchroObjects(Context ctx, SynchroDataType dataType, IRedisClient redis, IEnumerable <string> redisKeys, SynchroDirection direction = SynchroDirection.ToK3)
        {
            List <AbsSynchroDataInfo> datas = null;
            List <string>             jsons = null;

            Dictionary <string, string> dict = null;

            if (redis != null)
            {
                if (redisKeys != null && redisKeys.Count() > 0)
                {
                    dict  = new Dictionary <string, string>();
                    jsons = new List <string>();

                    foreach (var item in redisKeys)
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            string json = redis.Get <string>(item.ToString());

                            if (!string.IsNullOrWhiteSpace(json))
                            {
                                BackupJson.WriteJsonToLocal(ctx, dataType, json);
                                jsons.Add(json);
                                dict.Add(item.ToString(), JsonUtils.ReplaceDoubleQuotes(json));
                            }
                        }
                    }

                    BackupDataToRedis(ctx, dict, redisKeys, dataType, direction);
                }
            }

            if (jsons != null && jsons.Count > 0)
            {
                datas = new List <AbsSynchroDataInfo>();

                foreach (var json in jsons)
                {
                    if (json.IsNullOrEmptyOrWhiteSpace() || json.EqualsIgnoreCase("None"))
                    {
                        continue;
                    }
                    try
                    {
                        AbsSynchroDataInfo data = SynchroDataHelper.BuildSynchroData(ctx, dataType, json);

                        if (data != null)
                        {
                            datas.Add(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtils.WriteSynchroLog(ctx, dataType,
                                                 "下载" + dataType + "出现异常" +
                                                 ex.Message + System.Environment.NewLine + ex.StackTrace);
                    }
                }
            }

            return(datas);
        }
コード例 #6
0
 private static string ToJson(object value)
 {
     return(JsonUtils.ToJson(value));
 }
コード例 #7
0
        public async Task <List <MetaDataResponseDTO> > UploadSomeBaseMetaData(int nuberDto)
        {
            string                     url                  = ApiPaths.ALGO_STORE_METADATA;
            List <MetaDataDTO>         metadataList         = new List <MetaDataDTO>();
            List <MetaDataResponseDTO> responceMetadataList = new List <MetaDataResponseDTO>();

            for (int i = 0; i < nuberDto; i++)
            {
                MetaDataDTO metadata = new MetaDataDTO()
                {
                    Name        = Helpers.RandomString(13),
                    Description = Helpers.RandomString(13)
                };
                metadataList.Add(metadata);
            }

            foreach (var metadata in metadataList)
            {
                var response = await this.Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(metadata), Method.POST);

                MetaDataResponseDTO responceMetaData = JsonUtils.DeserializeJson <MetaDataResponseDTO>(response.ResponseJson);
                responceMetadataList.Add(responceMetaData);
            }

            return(responceMetadataList);
        }
コード例 #8
0
        public static bool TryParseDecimal(ReadOnlySpan <char> value, bool allowThousands, out decimal result)
        {
            result = 0;

            if (value.Length == 0)
            {
                return(false);
            }

            ulong preResult     = 0;
            bool  isLargeNumber = false;
            int   i             = 0;
            int   end           = value.Length;
            var   state         = ParseState.LeadingWhite;
            bool  negative      = false;
            bool  noIntegerPart = false;
            sbyte scale         = 0;

            while (i < end)
            {
                var c = value[i++];

                switch (state)
                {
                case ParseState.LeadingWhite:
                    if (JsonUtils.IsWhiteSpace(c))
                    {
                        break;
                    }

                    if (c == '-')
                    {
                        negative = true;
                        state    = ParseState.Sign;
                    }
                    else if (c == '.')
                    {
                        noIntegerPart = true;
                        state         = ParseState.FractionNumber;

                        if (i == end)
                        {
                            return(false);
                        }
                    }
                    else if (c == '0')
                    {
                        state = ParseState.DecimalPoint;
                    }
                    else if (c > '0' && c <= '9')
                    {
                        preResult = (ulong)(c - '0');
                        state     = ParseState.Number;
                    }
                    else
                    {
                        return(false);
                    }

                    break;

                case ParseState.Sign:
                    if (c == '.')
                    {
                        noIntegerPart = true;
                        state         = ParseState.FractionNumber;

                        if (i == end)
                        {
                            return(false);
                        }
                    }
                    else if (c == '0')
                    {
                        state = ParseState.DecimalPoint;
                    }
                    else if (c > '0' && c <= '9')
                    {
                        preResult = (ulong)(c - '0');
                        state     = ParseState.Number;
                    }
                    else
                    {
                        return(false);
                    }

                    break;

                case ParseState.Number:
                    if (c == '.')
                    {
                        state = ParseState.FractionNumber;
                    }
                    else if (c >= '0' && c <= '9')
                    {
                        if (isLargeNumber)
                        {
                            checked
                            {
                                result = 10 * result + (c - '0');
                            }
                        }
                        else
                        {
                            preResult = 10 * preResult + (ulong)(c - '0');
                            if (preResult > ulong.MaxValue / 10 - 10)
                            {
                                isLargeNumber = true;
                                result        = preResult;
                            }
                        }
                    }
                    else if (JsonUtils.IsWhiteSpace(c))
                    {
                        state = ParseState.TrailingWhite;
                    }
                    else if (allowThousands && c == ',')
                    {
                    }
                    else
                    {
                        return(false);
                    }

                    break;

                case ParseState.DecimalPoint:
                    if (c == '.')
                    {
                        state = ParseState.FractionNumber;
                    }
                    else
                    {
                        return(false);
                    }

                    break;

                case ParseState.FractionNumber:
                    if (JsonUtils.IsWhiteSpace(c))
                    {
                        if (noIntegerPart)
                        {
                            return(false);
                        }
                        state = ParseState.TrailingWhite;
                    }
                    else if (c == 'e' || c == 'E')
                    {
                        if (noIntegerPart && scale == 0)
                        {
                            return(false);
                        }
                        state = ParseState.Exponent;
                    }
                    else if (c >= '0' && c <= '9')
                    {
                        if (isLargeNumber)
                        {
                            checked
                            {
                                result = 10 * result + (c - '0');
                            }
                        }
                        else
                        {
                            preResult = 10 * preResult + (ulong)(c - '0');
                            if (preResult > ulong.MaxValue / 10 - 10)
                            {
                                isLargeNumber = true;
                                result        = preResult;
                            }
                        }

                        scale++;
                    }
                    else
                    {
                        return(false);
                    }

                    break;

                case ParseState.Exponent:
                    bool expNegative = false;
                    if (c == '-')
                    {
                        if (i == end)
                        {
                            return(false);
                        }

                        expNegative = true;
                        c           = value[i++];
                    }
                    else if (c == '+')
                    {
                        if (i == end)
                        {
                            return(false);
                        }
                        c = value[i++];
                    }

                    //skip leading zeroes
                    while (c == '0' && i < end)
                    {
                        c = value[i++];
                    }

                    if (c > '0' && c <= '9')
                    {
                        var exp = SignedInteger <long> .ParseInt64(value.Slice(i - 1, end - i + 1));

                        if (exp < sbyte.MinValue || exp > sbyte.MaxValue)
                        {
                            return(false);
                        }

                        if (!expNegative)
                        {
                            exp = (sbyte)-exp;
                        }

                        if (exp >= 0 || scale > -exp)
                        {
                            scale += (sbyte)exp;
                        }
                        else
                        {
                            for (int j = 0; j < -exp - scale; j++)
                            {
                                if (isLargeNumber)
                                {
                                    checked
                                    {
                                        result = 10 * result;
                                    }
                                }
                                else
                                {
                                    preResult = 10 * preResult;
                                    if (preResult > ulong.MaxValue / 10)
                                    {
                                        isLargeNumber = true;
                                        result        = preResult;
                                    }
                                }
                            }

                            scale = 0;
                        }

                        //set i to end of string, because ParseInt16 eats number and all trailing whites
                        i = end;
                    }
                    else
                    {
                        return(false);
                    }

                    break;

                case ParseState.TrailingWhite:
                    if (!JsonUtils.IsWhiteSpace(c))
                    {
                        return(false);
                    }
                    break;
                }
            }

            if (!isLargeNumber)
            {
                var mid = (int)(preResult >> 32);
                var lo  = (int)(preResult & 0xffffffff);
                result = new decimal(lo, mid, 0, negative, (byte)scale);
            }
            else
            {
                var bits = decimal.GetBits(result);
                result = new decimal(bits[0], bits[1], bits[2], negative, (byte)scale);
            }

            return(true);
        }
コード例 #9
0
        public static long ParseInt64(ReadOnlySpan <char> value)
        {
            if (value.IsEmpty)
            {
                throw new FormatException(MemoryProvider.BadFormat);
            }

            long result   = 0;
            int  i        = 0;
            int  end      = value.Length;
            var  state    = ParseState.LeadingWhite;
            bool negative = false;

            //skip leading whitespaces
            while (i < end && JsonUtils.IsWhiteSpace(value[i]))
            {
                i++;
            }

            if (i == end)
            {
                throw new FormatException(MemoryProvider.BadFormat);
            }

            //skip leading zeros
            while (i < end && value[i] == '0')
            {
                state = ParseState.Number;
                i++;
            }

            while (i < end)
            {
                var c = value[i++];

                switch (state)
                {
                case ParseState.LeadingWhite:
                    if (c == '-')
                    {
                        negative = true;
                        state    = ParseState.Sign;
                    }
                    else if (c == '0')
                    {
                        state = ParseState.TrailingWhite;
                    }
                    else if (c > '0' && c <= '9')
                    {
                        result = -(c - '0');
                        state  = ParseState.Number;
                    }
                    else
                    {
                        throw new FormatException(MemoryProvider.BadFormat);
                    }

                    break;

                case ParseState.Sign:
                    if (c == '0')
                    {
                        state = ParseState.TrailingWhite;
                    }
                    else if (c > '0' && c <= '9')
                    {
                        result = -(c - '0');
                        state  = ParseState.Number;
                    }
                    else
                    {
                        throw new FormatException(MemoryProvider.BadFormat);
                    }

                    break;

                case ParseState.Number:
                    if (c >= '0' && c <= '9')
                    {
                        checked
                        {
                            result = 10 * result - (c - '0');
                        }

                        if (result < minValue
                            ) //check only minvalue, because in absolute value it's greater than maxvalue
                        {
                            throw DefaultMemory.CreateOverflowException(maxValue);
                        }
                    }
                    else if (JsonUtils.IsWhiteSpace(c))
                    {
                        state = ParseState.TrailingWhite;
                    }
                    else
                    {
                        throw new FormatException(MemoryProvider.BadFormat);
                    }

                    break;

                case ParseState.TrailingWhite:
                    if (JsonUtils.IsWhiteSpace(c))
                    {
                        state = ParseState.TrailingWhite;
                    }
                    else
                    {
                        throw new FormatException(MemoryProvider.BadFormat);
                    }

                    break;
                }
            }

            if (state != ParseState.Number && state != ParseState.TrailingWhite)
            {
                throw new FormatException(MemoryProvider.BadFormat);
            }

            if (negative)
            {
                return(result);
            }

            checked
            {
                result = -result;
            }

            if (result > maxValue)
            {
                throw DefaultMemory.CreateOverflowException(maxValue);
            }

            return(result);
        }
コード例 #10
0
 /// <summary>
 /// 将对象序列化成string
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public static string ToJson(object value)
 {
     return(JsonUtils.SerializeCustom(value));
 }
        /// <summary>
        /// Remove keys with null values
        /// </summary>
        /// <param name="jObject"></param>
        /// <returns></returns>
        private JObject HandleNullValues(JObject jObject)
        {
            JObject noNullConfigSection = JsonUtils.RemoveKeysWithNullValue(jObject);

            return(noNullConfigSection);
        }
コード例 #12
0
 /// <summary>
 /// 解析Json成对象
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="jsonStr"></param>
 /// <returns></returns>
 public static T ParseJson <T>(string jsonStr)
 {
     return(JsonUtils.DeserializeCustom <T>(jsonStr));
 }
コード例 #13
0
    private void WriteMessageCore(HubMessage message, IBufferWriter <byte> stream)
    {
        var textWriter = Utf8BufferTextWriter.Get(stream);

        try
        {
            using (var writer = JsonUtils.CreateJsonTextWriter(textWriter))
            {
                writer.WriteStartObject();
                switch (message)
                {
                case InvocationMessage m:
                    WriteMessageType(writer, HubProtocolConstants.InvocationMessageType);
                    WriteHeaders(writer, m);
                    WriteInvocationMessage(m, writer);
                    break;

                case StreamInvocationMessage m:
                    WriteMessageType(writer, HubProtocolConstants.StreamInvocationMessageType);
                    WriteHeaders(writer, m);
                    WriteStreamInvocationMessage(m, writer);
                    break;

                case StreamItemMessage m:
                    WriteMessageType(writer, HubProtocolConstants.StreamItemMessageType);
                    WriteHeaders(writer, m);
                    WriteStreamItemMessage(m, writer);
                    break;

                case CompletionMessage m:
                    WriteMessageType(writer, HubProtocolConstants.CompletionMessageType);
                    WriteHeaders(writer, m);
                    WriteCompletionMessage(m, writer);
                    break;

                case CancelInvocationMessage m:
                    WriteMessageType(writer, HubProtocolConstants.CancelInvocationMessageType);
                    WriteHeaders(writer, m);
                    WriteCancelInvocationMessage(m, writer);
                    break;

                case PingMessage _:
                    WriteMessageType(writer, HubProtocolConstants.PingMessageType);
                    break;

                case CloseMessage m:
                    WriteMessageType(writer, HubProtocolConstants.CloseMessageType);
                    WriteCloseMessage(m, writer);
                    break;

                default:
                    throw new InvalidOperationException($"Unsupported message type: {message.GetType().FullName}");
                }
                writer.WriteEndObject();
                writer.Flush();
            }
        }
        finally
        {
            Utf8BufferTextWriter.Return(textWriter);
        }
    }
コード例 #14
0
    private HubMessage?ParseMessage(Utf8BufferTextReader textReader, IInvocationBinder binder)
    {
        try
        {
            // We parse using the JsonTextReader directly but this has a problem. Some of our properties are dependent on other properties
            // and since reading the json might be unordered, we need to store the parsed content as JToken to re-parse when true types are known.
            // if we're lucky and the state we need to directly parse is available, then we'll use it.

            int?       type         = null;
            string?    invocationId = null;
            string?    target       = null;
            string?    error        = null;
            var        hasItem      = false;
            object?    item         = null;
            JToken?    itemToken    = null;
            var        hasResult    = false;
            object?    result       = null;
            JToken?    resultToken  = null;
            var        hasArguments = false;
            object?[]? arguments    = null;
            string[]? streamIds = null;
            JArray?argumentsToken = null;
            ExceptionDispatchInfo?      argumentBindingException = null;
            Dictionary <string, string>?headers = null;
            var completed      = false;
            var allowReconnect = false;

            using (var reader = JsonUtils.CreateJsonTextReader(textReader))
            {
                reader.DateParseHandling = DateParseHandling.None;

                JsonUtils.CheckRead(reader);

                // We're always parsing a JSON object
                JsonUtils.EnsureObjectStart(reader);

                do
                {
                    switch (reader.TokenType)
                    {
                    case JsonToken.PropertyName:
                        var memberName = reader.Value?.ToString();

                        switch (memberName)
                        {
                        case TypePropertyName:
                            var messageType = JsonUtils.ReadAsInt32(reader, TypePropertyName);

                            if (messageType == null)
                            {
                                throw new InvalidDataException($"Missing required property '{TypePropertyName}'.");
                            }

                            type = messageType.Value;
                            break;

                        case InvocationIdPropertyName:
                            invocationId = JsonUtils.ReadAsString(reader, InvocationIdPropertyName);
                            break;

                        case StreamIdsPropertyName:
                            JsonUtils.CheckRead(reader);

                            if (reader.TokenType != JsonToken.StartArray)
                            {
                                throw new InvalidDataException($"Expected '{StreamIdsPropertyName}' to be of type {JTokenType.Array}.");
                            }

                            var newStreamIds = new List <string>();
                            reader.Read();
                            while (reader.TokenType != JsonToken.EndArray)
                            {
                                newStreamIds.Add(reader.Value?.ToString() ?? throw new InvalidDataException($"Null value for '{StreamIdsPropertyName}' is not valid."));
                                reader.Read();
                            }

                            streamIds = newStreamIds.ToArray();
                            break;

                        case TargetPropertyName:
                            target = JsonUtils.ReadAsString(reader, TargetPropertyName);
                            break;

                        case ErrorPropertyName:
                            error = JsonUtils.ReadAsString(reader, ErrorPropertyName);
                            break;

                        case AllowReconnectPropertyName:
                            allowReconnect = JsonUtils.ReadAsBoolean(reader, AllowReconnectPropertyName);
                            break;

                        case ResultPropertyName:
                            hasResult = true;

                            if (string.IsNullOrEmpty(invocationId))
                            {
                                JsonUtils.CheckRead(reader);

                                // If we don't have an invocation id then we need to store it as a JToken so we can parse it later
                                resultToken = JToken.Load(reader);
                            }
                            else
                            {
                                // If we have an invocation id already we can parse the end result
                                var returnType = binder.GetReturnType(invocationId);

                                if (!JsonUtils.ReadForType(reader, returnType))
                                {
                                    throw new JsonReaderException("Unexpected end when reading JSON");
                                }

                                result = PayloadSerializer.Deserialize(reader, returnType);
                            }
                            break;

                        case ItemPropertyName:
                            JsonUtils.CheckRead(reader);

                            hasItem = true;

                            string?id = null;
                            if (!string.IsNullOrEmpty(invocationId))
                            {
                                id = invocationId;
                            }
                            else
                            {
                                // If we don't have an id yet then we need to store it as a JToken to parse later
                                itemToken = JToken.Load(reader);
                                break;
                            }

                            try
                            {
                                var itemType = binder.GetStreamItemType(id);
                                item = PayloadSerializer.Deserialize(reader, itemType);
                            }
                            catch (Exception ex)
                            {
                                return(new StreamBindingFailureMessage(id, ExceptionDispatchInfo.Capture(ex)));
                            }
                            break;

                        case ArgumentsPropertyName:
                            JsonUtils.CheckRead(reader);

                            int initialDepth = reader.Depth;
                            if (reader.TokenType != JsonToken.StartArray)
                            {
                                throw new InvalidDataException($"Expected '{ArgumentsPropertyName}' to be of type {JTokenType.Array}.");
                            }

                            hasArguments = true;

                            if (string.IsNullOrEmpty(target))
                            {
                                // We don't know the method name yet so just parse an array of generic JArray
                                argumentsToken = JArray.Load(reader);
                            }
                            else
                            {
                                try
                                {
                                    var paramTypes = binder.GetParameterTypes(target);
                                    arguments = BindArguments(reader, paramTypes);
                                }
                                catch (Exception ex)
                                {
                                    argumentBindingException = ExceptionDispatchInfo.Capture(ex);

                                    // Could be at any point in argument array JSON when an error is thrown
                                    // Read until the end of the argument JSON array
                                    while (reader.Depth == initialDepth && reader.TokenType == JsonToken.StartArray ||
                                           reader.Depth > initialDepth)
                                    {
                                        JsonUtils.CheckRead(reader);
                                    }
                                }
                            }
                            break;

                        case HeadersPropertyName:
                            JsonUtils.CheckRead(reader);
                            headers = ReadHeaders(reader);
                            break;

                        default:
                            // Skip read the property name
                            JsonUtils.CheckRead(reader);
                            // Skip the value for this property
                            reader.Skip();
                            break;
                        }
                        break;

                    case JsonToken.EndObject:
                        completed = true;
                        break;
                    }
                }while (!completed && JsonUtils.CheckRead(reader));
            }

            HubMessage message;

            switch (type)
            {
            case HubProtocolConstants.InvocationMessageType:
            {
                if (target is null)
                {
                    throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
                }

                if (argumentsToken != null)
                {
                    // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
                    try
                    {
                        var paramTypes = binder.GetParameterTypes(target);
                        arguments = BindArguments(argumentsToken, paramTypes);
                    }
                    catch (Exception ex)
                    {
                        argumentBindingException = ExceptionDispatchInfo.Capture(ex);
                    }
                }

                message = argumentBindingException != null
                            ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
                            : BindInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder);
            }
            break;

            case HubProtocolConstants.StreamInvocationMessageType:
            {
                if (target is null)
                {
                    throw new InvalidDataException($"Missing required property '{TargetPropertyName}'.");
                }

                if (argumentsToken != null)
                {
                    // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
                    try
                    {
                        var paramTypes = binder.GetParameterTypes(target);
                        arguments = BindArguments(argumentsToken, paramTypes);
                    }
                    catch (Exception ex)
                    {
                        argumentBindingException = ExceptionDispatchInfo.Capture(ex);
                    }
                }

                message = argumentBindingException != null
                            ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
                            : BindStreamInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder);
            }
            break;

            case HubProtocolConstants.StreamItemMessageType:
                if (invocationId is null)
                {
                    throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
                }

                if (itemToken != null)
                {
                    try
                    {
                        var itemType = binder.GetStreamItemType(invocationId);
                        item = itemToken.ToObject(itemType, PayloadSerializer);
                    }
                    catch (Exception ex)
                    {
                        message = new StreamBindingFailureMessage(invocationId, ExceptionDispatchInfo.Capture(ex));
                        break;
                    };
                }

                message = BindStreamItemMessage(invocationId, item, hasItem, binder);
                break;

            case HubProtocolConstants.CompletionMessageType:
                if (invocationId is null)
                {
                    throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'.");
                }

                if (resultToken != null)
                {
                    var returnType = binder.GetReturnType(invocationId);
                    result = resultToken.ToObject(returnType, PayloadSerializer);
                }

                message = BindCompletionMessage(invocationId, error, result, hasResult, binder);
                break;

            case HubProtocolConstants.CancelInvocationMessageType:
                message = BindCancelInvocationMessage(invocationId);
                break;

            case HubProtocolConstants.PingMessageType:
                return(PingMessage.Instance);

            case HubProtocolConstants.CloseMessageType:
                return(BindCloseMessage(error, allowReconnect));

            case null:
                throw new InvalidDataException($"Missing required property '{TypePropertyName}'.");

            default:
                // Future protocol changes can add message types, old clients can ignore them
                return(null);
            }

            return(ApplyHeaders(message, headers));
        }
        catch (JsonReaderException jrex)
        {
            throw new InvalidDataException("Error reading JSON.", jrex);
        }
    }
コード例 #15
0
        public void OnEvent(ReceiveData data, long sequence, bool endOfBatch)
        {
            var messageEvent = data;

            if (messageEvent != null)
            {
                if (messageEvent.Message is IControler || messageEvent.RawMsg == null)
                {
                    return; //neu msg chua dc hoan thien thi ko thuc hien giai ma
                }
                IMessage bizData = null;
                try
                {
                    string rawStr = EncodingUtils.GetString(messageEvent.RawMsg);
                    bizData = JsonUtils.DeserializeMessage(rawStr);
                    if (Endpoint.IsWriteLogInfo)
                    {
                        LogTo.Info(rawStr); //Ghi toan bo thong tin gia nhan duoc
                    }
                    if (Endpoint.IsWriteLog && bizData != null)
                    {
                        #region Xu ly luu thong tin log msg
                        try
                        {
                            var     msgNameBiz = bizData.GetType().ToString();
                            decimal sizeBiz    = (decimal)messageEvent.RawMsg.Length / (1024 * 1024);
                            if (!Endpoint.DicMessageCount.ContainsKey(msgNameBiz))
                            {
                                Endpoint.DicMessageCount[msgNameBiz] = 0;
                                Endpoint.DicMessageSize[msgNameBiz]  = 0;
                            }
                            Endpoint.DicMessageCount[msgNameBiz] += 1;
                            Endpoint.DicMessageSize[msgNameBiz]  += sizeBiz;

                            if (!Endpoint.DicMessageCountFull.ContainsKey(msgNameBiz))
                            {
                                Endpoint.DicMessageCountFull[msgNameBiz] = 0;
                                Endpoint.DicMessageSizeFull[msgNameBiz]  = 0;
                            }
                            Endpoint.DicMessageCountFull[msgNameBiz] += 1;
                            Endpoint.DicMessageSizeFull[msgNameBiz]  += sizeBiz;

                            // sau 5p se ghi log tong so message gui di
                            var timeCheck = (DateTime.Now - Endpoint.LastCheckCountMsg).TotalSeconds;
                            if (timeCheck > Endpoint.TimeWriteLogMsgReceived)
                            {
                                // sau 5 phut ghi log 1 lan
                                // sau 5 moi ghi log
                                decimal       countAll         = 0;
                                decimal       countSizeAll     = 0;
                                decimal       count5MinAll     = 0;
                                decimal       count5MinSizeAll = 0;
                                StringBuilder strDetail        = new StringBuilder();
                                var           dicSort          = Endpoint.DicMessageSizeFull.OrderBy(s => s.Key);
                                foreach (var keyValue in dicSort)
                                {
                                    string  msgName     = keyValue.Key;
                                    decimal sizeForMsg  = keyValue.Value;
                                    decimal countForMsg = Endpoint.DicMessageCountFull[msgName];
                                    decimal count5Min   = 0;
                                    if (Endpoint.DicMessageCount.ContainsKey(msgName))
                                    {
                                        count5Min = Endpoint.DicMessageCount[msgName];
                                    }

                                    decimal byte5Min = 0;
                                    if (Endpoint.DicMessageSize.ContainsKey(msgName))
                                    {
                                        byte5Min = Endpoint.DicMessageSize[msgName];
                                    }

                                    decimal avg5Min = count5Min / Endpoint.TimeWriteLogMsgReceived;
                                    countAll         += countForMsg;
                                    countSizeAll     += sizeForMsg;
                                    count5MinAll     += count5Min;
                                    count5MinSizeAll += byte5Min;

                                    strDetail.AppendLine(GetLog(msgName, countForMsg, sizeForMsg, count5Min, byte5Min, avg5Min));
                                }
                                decimal avgAll5Min  = count5MinAll / Endpoint.TimeWriteLogMsgReceived;
                                var     textLogFull = string.Format(
                                    "Total message = {0} with size = {1} MB; In 5min count = {2} and size = {3} MB; avg 5 min = {4} msg/s",
                                    countAll, countSizeAll.ToString("#,##0.0000"), count5MinAll, count5MinSizeAll.ToString("#,##0.0000"), avgAll5Min.ToString("#,##0.00"));
                                StringBuilder strBuild = new StringBuilder();
                                strBuild.AppendLine(string.Format("Thoi diem dang nhap {0}", Endpoint.StartTimeLogin));
                                strBuild.AppendLine(textLogFull);
                                strBuild.AppendLine("Thong tin chi tiet : ");
                                strBuild.AppendLine(strDetail.ToString());
                                LogTo.Info(strBuild.ToString());

                                Endpoint.DicMessageCount   = new Dictionary <string, decimal>();
                                Endpoint.DicMessageSize    = new Dictionary <string, decimal>();
                                Endpoint.LastCheckCountMsg = DateTime.Now;
                            }
                        }
                        catch (Exception ex1)
                        {
                            LogTo.Error(ex1.ToString());
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    LogTo.Error(ex.ToString());
                    _processor.Send(new JournalMessage()
                    {
                        Tag   = messageEvent.DeliveryTag,
                        IsAck = true,
                    }, messageEvent.QueueType);
                    data.SetMessage(messageEvent);
                    return;
                }

                if (_isWorker)
                {
                    switch (messageEvent.QueueType)
                    {
                    case (byte)QueueType.MainQueue:
                        //main queue se co trach nhiem xu ly msg, nen no can danh seq cho cac msg ma no xu ly
                        //tang seq truoc
                        if (_isBStarMode && !bizData.IsNotPersist)
                        {
                            //cap nhat seq vao msg goc de gui di sang replicator
                            var str = JsonUtils.SerializeMessage(bizData);
                            messageEvent.RawMsg = EncodingUtils.GetBytes(str);
                        }
                        break;
                    }
                }

                if (!messageEvent.IsObsolate && bizData is PartialMessage)
                {
                    try
                    {
                        //neu day la msg partial thi thuc hien tong hop lai
                        var pendingMsg = bizData as PartialMessage;
                        //raise event change
                        _processor.ProcessControlerMsg(new NewMessageCommingEvent {
                            Count = pendingMsg.Count, Index = pendingMsg.Index, MsgId = pendingMsg.MainRequestKey
                        }, messageEvent.QueueType);
                        PartialMessageStorage storage;
                        if (_listPending.ContainsKey(pendingMsg.MainRequestKey))
                        {
                            storage = _listPending[pendingMsg.MainRequestKey];
                        }
                        else
                        {
                            storage = new PartialMessageStorage(pendingMsg.Count);
                            _listPending[pendingMsg.MainRequestKey] = storage;
                        }
                        bool isFull = storage.Append(pendingMsg.RawMessage, pendingMsg.Index, pendingMsg.Count);
                        if (isFull)
                        {
                            var      fullRawStr = storage.GetFullMessge();
                            IMessage rawFullObj = JsonUtils.DeserializeMessage(fullRawStr);
                            if (Endpoint.IsWriteLog && rawFullObj != null)
                            {
                                #region Xu ly luu thong tin log msg
                                try
                                {
                                    var     msgNameBiz = rawFullObj.GetType().ToString();
                                    decimal sizeBiz    = (decimal)System.Text.ASCIIEncoding.UTF8.GetByteCount(fullRawStr) / (1024 * 1024);
                                    if (!Endpoint.DicMessageCount.ContainsKey(msgNameBiz))
                                    {
                                        Endpoint.DicMessageCount[msgNameBiz] = 0;
                                        Endpoint.DicMessageSize[msgNameBiz]  = 0;
                                    }
                                    Endpoint.DicMessageCount[msgNameBiz] += 1;
                                    Endpoint.DicMessageSize[msgNameBiz]  += sizeBiz;

                                    if (!Endpoint.DicMessageCountFull.ContainsKey(msgNameBiz))
                                    {
                                        Endpoint.DicMessageCountFull[msgNameBiz] = 0;
                                        Endpoint.DicMessageSizeFull[msgNameBiz]  = 0;
                                    }
                                    Endpoint.DicMessageCountFull[msgNameBiz] += 1;
                                    Endpoint.DicMessageSizeFull[msgNameBiz]  += sizeBiz;

                                    // sau 5p se ghi log tong so message gui di
                                    var timeCheck = (DateTime.Now - Endpoint.LastCheckCountMsg).TotalSeconds;
                                    if (timeCheck > Endpoint.TimeWriteLogMsgReceived)
                                    {
                                        // sau 5 phut ghi log 1 lan
                                        // sau 5 moi ghi log
                                        decimal       countAll         = 0;
                                        decimal       countSizeAll     = 0;
                                        decimal       count5MinAll     = 0;
                                        decimal       count5MinSizeAll = 0;
                                        StringBuilder strDetail        = new StringBuilder();
                                        var           dicSort          = Endpoint.DicMessageSizeFull.OrderBy(s => s.Key);
                                        foreach (var keyValue in dicSort)
                                        {
                                            string  msgName     = keyValue.Key;
                                            decimal sizeForMsg  = keyValue.Value;
                                            decimal countForMsg = Endpoint.DicMessageCountFull[msgName];
                                            decimal count5Min   = 0;
                                            if (Endpoint.DicMessageCount.ContainsKey(msgName))
                                            {
                                                count5Min = Endpoint.DicMessageCount[msgName];
                                            }

                                            decimal byte5Min = 0;
                                            if (Endpoint.DicMessageSize.ContainsKey(msgName))
                                            {
                                                byte5Min = Endpoint.DicMessageSize[msgName];
                                            }

                                            decimal avg5Min = count5Min / Endpoint.TimeWriteLogMsgReceived;
                                            countAll         += countForMsg;
                                            countSizeAll     += sizeForMsg;
                                            count5MinAll     += count5Min;
                                            count5MinSizeAll += byte5Min;

                                            strDetail.AppendLine(GetLog(msgName, countForMsg, sizeForMsg, count5Min, byte5Min, avg5Min));
                                        }
                                        decimal avgAll5Min  = count5MinAll / Endpoint.TimeWriteLogMsgReceived;
                                        var     textLogFull = string.Format(
                                            "Total message = {0} with size = {1} MB; In 5min count = {2} and size = {3} MB; avg 5 min = {4} msg/s",
                                            countAll, countSizeAll.ToString("#,##0.0000"), count5MinAll, count5MinSizeAll.ToString("#,##0.0000"), avgAll5Min.ToString("#,##0.00"));
                                        StringBuilder strBuild = new StringBuilder();
                                        strBuild.AppendLine(string.Format("Thoi diem dang nhap {0}", Endpoint.StartTimeLogin));
                                        strBuild.AppendLine(textLogFull);
                                        strBuild.AppendLine("Thong tin chi tiet : ");
                                        strBuild.AppendLine(strDetail.ToString());
                                        LogTo.Info(strBuild.ToString());

                                        Endpoint.DicMessageCount   = new Dictionary <string, decimal>();
                                        Endpoint.DicMessageSize    = new Dictionary <string, decimal>();
                                        Endpoint.LastCheckCountMsg = DateTime.Now;
                                    }
                                }
                                catch (Exception ex1)
                                {
                                    LogTo.Error(ex1.ToString());
                                }
                                #endregion
                            }
                            messageEvent.Message = rawFullObj;
                            storage.Dispose();
                            _listPending.Remove(pendingMsg.MainRequestKey);
                        }
                    }
                    catch (Exception ex)
                    {
                        //neu phat sinh ra loi thi ghi ra console va thuc hien close network de load lai du lieu.
                        LogTo.Error(ex.ToString());
                        //neu khong hop le thi canh bao
                        _processor.ProcessControlerMsg(new InvalidMessageSeqEvent(), messageEvent.QueueType);
                    }
                }
                else if (!messageEvent.IsObsolate)
                {
                    messageEvent.Message = bizData;
                }
            }
            data.SetMessage(messageEvent);
        }
コード例 #16
0
        public InformationEditViewModel()
        {
            this.closeCommand       = new DelegateCommand(new Action <object>(closeExecute), new Func <Object, bool>(closeCanExecute));
            this.getCityCommand     = new DelegateCommand(new Action <object>(getCityExecute));
            this.photoChooseCommand = new DelegateCommand(new Action <object>(photoChooseExecute));
            this.photoDeleteCommand = new DelegateCommand(new Action <object>(photoDeleteExecute));
            this.editCommand        = new DelegateCommand(new Action <object>(editExecute));
            #region 初始化INformation属性
            var database   = client.GetDatabase("hrms");
            var collection = database.GetCollection <BsonDocument>("informations");
            var filter     = Builders <BsonDocument> .Filter.Eq("Id", "5436");

            var projection = Builders <BsonDocument> .Projection.Exclude("_id");

            var    doc     = collection.Find(filter).Project(projection).First();
            string jsonStr = doc.ToJson();
            this.Information = JsonUtils.DeserializeJsonToObject <Information>(jsonStr);
            #endregion

            #region 初始化照片
            ServiceProxy.ServiceTestClient serviceTestClient = new ServiceProxy.ServiceTestClient("WSHttpBinding_IServiceTest");
            string imgStr = serviceTestClient.PicDownload(Information.Photo);
            Image  img    = Utils.ByteArrayToImg(imgStr);
            string path   = "C:/Users/victo/Desktop/Csharp/HRMS_MVVM/HRMS_MVVM/images/" + Information.Photo + ".jpg";
            img.Save(path);
            Photo = path;
            #endregion

            #region 初始化民族
            Nations = new ObservableCollection <string>();
            Nations.Add("请选择");
            Nations.Add("土家族");
            Nations.Add("汉族");
            Nations.Add("苗族");
            #endregion
            #region 性别
            Genders = new ObservableCollection <string>();
            Genders.Add("请选择");
            Genders.Add("男");
            Genders.Add("女");
            #endregion
            #region 婚姻
            Marriages = new ObservableCollection <string>();
            Marriages.Add("请选择");
            Marriages.Add("已婚");
            Marriages.Add("未婚");
            #endregion
            #region 学历
            Educations = new ObservableCollection <string>();
            Educations.Add("请选择");
            Educations.Add("初中及以下");
            Educations.Add("高中");
            Educations.Add("本科");
            Educations.Add("硕士");
            Educations.Add("博士");
            #endregion
            #region 政治面貌
            Politics = new ObservableCollection <string>();
            Politics.Add("请选择");
            Politics.Add("群众");
            Politics.Add("共青团员");
            Politics.Add("中共党员");
            Politics.Add("其他");
            #endregion
            #region 籍贯
            Provinces = new ObservableCollection <string>();
            Provinces.Add("请选择");
            Provinces.Add("湖北");
            Provinces.Add("四川");

            Cities = new ObservableCollection <string>();
            if (Information.Province == "湖北")
            {
                Cities.Add("武汉");
                Cities.Add("恩施");
                Cities.Add("宜昌");
                City = Information.City;
            }
            else if (Information.Province == "四川")
            {
                Cities.Add("成都");
                Cities.Add("德阳");
                Cities.Add("绵阳");
                City = Information.City;
            }
            #endregion
        }
コード例 #17
0
 protected internal string GetFileProviderDefinition()
 {
     return("new " + ClientFileProviderName + "(" + JsonUtils.SafeSerialize(StoreOptions) + ")");
 }
コード例 #18
0
        public async Task GetInfo([Remainder, Name("termi")] string query)
        {
            var normalized = StringUtils.NormalizeQuery(query);

            if (normalized == null)
            {
                await ReplyAsync($"Termi **{query}** nuk u gjet.");

                return;
            }

            var obj = JsonUtils.LookupObject(Data, normalized);

            if (obj != null)
            {
                await ReplyAsync(
                    $"Informatat për **{query}**",
                    embed : JsonUtils.EmbedObject(obj));

                return;
            }

            const int threshold = 8;
            const int count     = 3;

            // No match, try finding suggestions.
            var matches = JsonUtils.FindClosest(Data, normalized, threshold, count);

            if (matches.Length != 0)
            {
                var emojis = new[] { "\u0031\u20E3", "\u0032\u20E3", "\u0033\u20E3" };

                // Give suggestions and listen for reactions.
                var text = $"Termi **{query}** nuk u gjet.\n\n"
                           + "Mos keni menduar për ndonjërën nga:\n"
                           + matches.Select((match, i) => i + 1 + ") " + match["_label"]).Join("\n");

                var callback = new ReactionCallbackData(
                    text,
                    embed: null,
                    expiresAfterUse: true,
                    singleUsePerUser: true,
                    timeout: TimeSpan.FromSeconds(30d));

                for (var i = 0; i < matches.Length; i++)
                {
                    var term = matches[i]["_label"].ToString();
                    callback.WithCallback(
                        new Emoji(emojis[i]), async(c, r) =>
                    {
                        var newObj = TryLookup(term);
                        if (newObj != null)
                        {
                            await c.Channel.SendMessageAsync(
                                $"Informatat për **{term}**",
                                embed: JsonUtils.EmbedObject(newObj));
                        }
                        else
                        {
                            await c.Channel.SendMessageAsync("Fatkeqësisht ka ndodhur një gabim. Ju lutem provoni përsëri.");
                        }
                    });
                }

                await InlineReactionReplyAsync(callback, fromSourceUser : true);
            }
            else
            {
                // No suggestions.
                await ReplyAsync($"Termi **{query}** nuk u gjet.");
            }
        }
コード例 #19
0
ファイル: ClassReader.cs プロジェクト: Bluegent/MeRpgBot
        public ClassTemplate FromJson(JObject json)
        {
            ClassTemplate result = new ClassTemplate();

            result.LoadBase(json);

            AddBaseValueVector(GcConstants.Classes.BASE_VALUES, json, result, result.BasicValues);
            foreach (string baseV in result.BasicValues.Keys)
            {
                if (!Engine.GetPropertyManager().HasBaseValue(baseV))
                {
                    throw new MeException($"Class {result.Name} references unknown base value {baseV}.");
                }
            }

            foreach (BaseObject baseValue in Engine.GetPropertyManager().BaseValues.Values)
            {
                if (!result.BasicValues.ContainsKey(baseValue.Key))
                {
                    result.BasicValues.Add(baseValue.Key, 0);
                }
            }



            AddBaseValueVector(GcConstants.Classes.BASIC_ATTRIBUTES, json, result, result.Attributes);
            foreach (string baseV in result.Attributes.Keys)
            {
                if (!Engine.GetPropertyManager().HasAttribute(baseV))
                {
                    throw new MeException($"Class {result.Name} references unknown attribute {baseV}.");
                }
            }
            foreach (BaseObject attribute in Engine.GetPropertyManager().Attributes.Values)
            {
                if (!result.Attributes.ContainsKey(attribute.Key))
                {
                    result.Attributes.Add(attribute.Key, 0);
                }
            }

            JToken[] skills = JsonUtils.GetValueOrDefault <JToken[]>(json, GcConstants.Classes.SKILLS, null);
            if (skills != null)
            {
                foreach (JToken value in skills)
                {
                    SkillTemplate skill = SkillFromJson(value, result);
                    result.Skills.Add(skill.Key, skill);
                }
            }

            JToken        baseAttack = JsonUtils.ValidateJsonEntry(GcConstants.Classes.BASE_ATTACK, json, JTokenType.String, $"Class {result.Name} does not contain a {GcConstants.Classes.BASE_ATTACK} entry.");
            SkillTemplate baseSkill  = SkillFromJson(baseAttack, result);

            result.BaseAttack = baseSkill;

            JToken[] resources = JsonUtils.GetValueOrDefault <JToken[]>(json, GcConstants.Classes.RESOURCES, null);
            if (resources != null)
            {
                foreach (JToken value in resources)
                {
                    ResourceTemplate res = ResourceFromJson(value, result);
                    result.Resources.Add(res.Key, res);
                }
            }
            return(result);
        }
コード例 #20
0
ファイル: MapController.cs プロジェクト: dnvgithub/camn
        private async Task <List <Meta> > ProcessMetaAsync(List <object> data)
        {
            bool          codeValuesBlock = false;
            int           i         = 0;
            JArray        tempJA    = new JArray();
            List <Meta>   layerMeta = new List <Meta>();
            StringBuilder sb        = new StringBuilder();
            StringWriter  sw        = new StringWriter(sb);
            JsonWriter    writer    = new JsonTextWriter(sw);

            try
            {
                JObject jObj = JsonUtils.MergeJSON <object>(data);
                tempJA = (JArray)jObj["fields"];

                JsonReader reader = tempJA.CreateReader();
                await writer.WriteStartArrayAsync();

                while (reader.Read())
                {
                    if (codeValuesBlock == false)
                    {
                        if (reader.Value != null)
                        {
                            if (reader.TokenType == JsonToken.PropertyName)
                            {
                                if (reader.Value.ToString() == "domain")
                                {
                                    codeValuesBlock = true;

                                    if (jObj["fields"][i]["domain"].HasValues)
                                    {
                                        var something = "";
                                        try
                                        {
                                            something = jObj["fields"][i]["domain"]["codedValues"].ToString();
                                            await writer.WritePropertyNameAsync("domain");

                                            await writer.WriteRawValueAsync(something);

                                            await writer.WritePropertyNameAsync("range");
                                        }
                                        catch (NullReferenceException e)
                                        {
                                            await writer.WritePropertyNameAsync("range");

                                            something = jObj["fields"][i]["domain"]["range"].ToString();
                                            await writer.WriteRawValueAsync(something);

                                            await writer.WritePropertyNameAsync("domain");
                                        }

                                        await writer.WriteStartArrayAsync();

                                        await writer.WriteEndArrayAsync();

                                        await writer.WriteEndObjectAsync();
                                    }
                                    else
                                    {
                                        await writer.WritePropertyNameAsync("domain");

                                        await writer.WriteStartArrayAsync();

                                        await writer.WriteEndArrayAsync();

                                        await writer.WritePropertyNameAsync("range");

                                        await writer.WriteStartArrayAsync();

                                        await writer.WriteEndArrayAsync();

                                        await writer.WriteEndObjectAsync();

                                        codeValuesBlock = false;
                                    }
                                    i++;
                                }
                                else
                                {
                                    if (reader.Value.ToString() == "name")
                                    {
                                        await writer.WriteStartObjectAsync();
                                    }

                                    await writer.WritePropertyNameAsync(reader.Value.ToString());
                                }
                            }
                            else
                            {
                                await writer.WriteValueAsync(reader.Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        if (reader.Depth == 1)
                        {
                            codeValuesBlock = false;
                        }
                    }
                }
                await writer.WriteEndAsync();

                layerMeta = JsonConvert.DeserializeObject <List <Meta> >(sw.ToString());
                writer.Close();
            }
            catch (Exception e)
            {
                writer.Close();
            }
            //from appsettings.[env].json
            string[] excludesList = _config.GetSection("excludeFilters").Get <string[]>();
            layerMeta = layerMeta.Where(m => !excludesList.Any(e => e.ToLower() == m.name.ToLower())).ToList();
            return(layerMeta);
        }
コード例 #21
0
        public async Task <List <Response> > ClearAllCascadeDelete(List <MetaDataResponseDTO> listDtoToBeDeleted)
        {
            List <Response> responces = new List <Response>();
            string          url       = ApiPaths.ALGO_STORE_CASCADE_DELETE;

            foreach (var deleteMetadata in listDtoToBeDeleted)
            {
                CascadeDeleteDTO editMetaData = new CascadeDeleteDTO()
                {
                    Id   = deleteMetadata.Id,
                    Name = deleteMetadata.Name
                };
                var responceCascadeDelete = await this.Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(editMetaData), Method.POST);

                responces.Add(responceCascadeDelete);
            }

            return(responces);
        }
コード例 #22
0
        private async Task PrepareTestData()
        {
            var TestClient = await Consumer.RegisterNewUser();

            TestClientId = TestClient.Account.Id;
            var walletsFromDB    = this.WalletRepository.GetAllAsync(w => w.ClientId == TestClientId && w.State != "deleted");
            var operationsFromDB = this.OperationsRepository.GetAllAsync(o => o.PartitionKey == OperationsEntity.GeneratePartitionKey() && o.ClientId.ToString() == TestClientId);

            this.TestAssetId      = Constants.TestAssetId;
            this.AssetPrecission  = 2;
            this.AllWalletsFromDb = (await walletsFromDB).Cast <WalletEntity>().ToList();
            this.TestWallet       = await CreateTestWallet();

            //fill wallet with funds
            await MEConsumer.Client.UpdateBalanceAsync(Guid.NewGuid().ToString(), TestWallet.Id, Constants.TestAssetId, 50.0);

            this.TestWalletWithBalanceId = TestWallet.Id;


            this.TestWalletDelete = await CreateTestWallet();

            this.TestWalletAccount = await AccountRepository.TryGetAsync(TestWallet.Id) as AccountEntity;

            this.TestWalletOperations = await CreateTestWallet();

            this.TestWalletRegenerateKey = await CreateTestWallet(true);

            this.TestOperation = await CreateTestOperation();

            this.TestOperationCancel = await CreateTestOperation();

            this.TestOperationCreateDetails = await CreateTestOperation();

            this.TestOperationRegisterDetails = await CreateTestOperation();


            this.ClientInfoConsumer = new ApiConsumer(_apiV2Settings);
            await this.ClientInfoConsumer.RegisterNewUser();

            AddOneTimeCleanupAction(async() => await ClientAccounts.DeleteClientAccount(ClientInfoConsumer.ClientInfo.Account.Id));

            // set the id to the default one in case it has been changed by any test
            BaseAssetDTO body     = new BaseAssetDTO(this.TestAssetId);
            var          response = await Consumer.ExecuteRequest(ApiPaths.ASSETS_BASEASSET_PATH, Helpers.EmptyDictionary, JsonUtils.SerializeObject(body), Method.POST);
        }
コード例 #23
0
 public void WriteAuditPostDataPoint(ProcessedPostDataPoint dataPoint)
 {
     db.WriteAudit("post-data-point", dataPoint.Author, JsonUtils.ToJson(dataPoint));
 }
コード例 #24
0
        public override void Build(ImGui gui)
        {
            BuildHeader(gui, "Module customisation");
            if (recipe.modules == null)
            {
                if (gui.BuildButton("Enable custom modules"))
                {
                    recipe.RecordUndo().modules = new CustomModules(recipe);
                }
            }
            else
            {
                var effects = new ModuleEffects();
                if (recipe.entity?.moduleSlots > 0)
                {
                    gui.BuildText("Internal modules:", Font.subheader);
                    gui.BuildText("Leave zero amount to fill the remainings slots");
                    DrawRecipeModules(gui, null, ref effects);
                }
                else
                {
                    gui.BuildText("This building doesn't have module slots, but can be affected by beacons");
                }
                gui.BuildText("Beacon modules:", Font.subheader);
                if (recipe.modules.beacon == null)
                {
                    gui.BuildText("Use default parameters");
                    if (gui.BuildButton("Override beacons as well"))
                    {
                        SelectBeacon(gui);
                    }
                    var defaultFiller = recipe.GetModuleFiller();
                    if (defaultFiller != null && defaultFiller.beacon != null && defaultFiller.beaconModule != null)
                    {
                        effects.AddModules(defaultFiller.beaconModule.module, defaultFiller.beacon.beaconEfficiency * defaultFiller.beacon.moduleSlots * defaultFiller.beaconsPerBuilding);
                    }
                }
                else
                {
                    if (gui.BuildFactorioObjectButtonWithText(recipe.modules.beacon))
                    {
                        SelectBeacon(gui);
                    }
                    gui.BuildText("Input the amount of modules, not the amount of beacons. Single beacon can hold " + recipe.modules.beacon.moduleSlots + " modules.", wrap: true);
                    DrawRecipeModules(gui, recipe.modules.beacon, ref effects);
                }

                gui.BuildText("Current effects:", Font.subheader);
                gui.BuildText("Productivity bonus: " + DataUtils.FormatAmount(effects.productivity, UnitOfMeasure.Percent));
                gui.BuildText("Speed bonus: " + DataUtils.FormatAmount(effects.speedMod, UnitOfMeasure.Percent) + " (Crafting speed: " + DataUtils.FormatAmount((recipe.entity?.craftingSpeed ?? 1f) * (1f + effects.speedMod), UnitOfMeasure.None) + ")");
                var energyUsageLine = "Energy usage: " + DataUtils.FormatAmount(effects.energyUsageMod, UnitOfMeasure.Percent);
                if (!recipe.recipe.flags.HasFlagAny(RecipeFlags.UsesFluidTemperature | RecipeFlags.ScaleProductionWithPower) && recipe.entity != null)
                {
                    energyUsageLine += " (" + DataUtils.FormatAmount(effects.energyUsageMod * recipe.entity.power / recipe.entity.energy.effectivity, UnitOfMeasure.Megawatt) + " per building)";
                }
                gui.BuildText(energyUsageLine);
            }

            gui.AllocateSpacing(3f);
            using (gui.EnterRow(allocator: RectAllocator.RightRow))
            {
                if (gui.BuildButton("Done"))
                {
                    Close();
                }
                if (recipe.modules != null && gui.BuildButton("Copy settings", SchemeColor.Grey))
                {
                    if (copiedModuleSettings == null)
                    {
                        MessageBox.Show("Info", "Use ctrl+click on module slot to paste settings", "Ok");
                    }
                    copiedModuleSettings = JsonUtils.SaveToJson(recipe.modules);
                }
                gui.allocator = RectAllocator.LeftRow;
                if (recipe.modules != null && gui.BuildRedButton("Remove module customisation") == ImGuiUtils.Event.Click)
                {
                    recipe.RecordUndo().modules = null;
                    Close();
                }
            }
        }
コード例 #25
0
        public async Task PrepareGlobalTestData()
        {
            Task <List <ApiConsumer> > registerUsersTasks = RegisterNUsers(2);

            this.GlobalConsumer = new ApiConsumer(this._configBuilder);
            await this.GlobalConsumer.RegisterNewUser();

            var createLinkResponse = await this.GlobalConsumer.ExecuteRequest(ApiPaths.REFERRAL_LINKS_INVITATION_PATH, Helpers.EmptyDictionary, null, Method.POST);

            if (createLinkResponse.Status == HttpStatusCode.Created)
            {
                this.TestInvitationLink = JsonUtils.DeserializeJson <RequestInvitationLinkResponseDto>(createLinkResponse.ResponseJson);
            }

            List <ApiConsumer> registeredUsers = await registerUsersTasks;

            foreach (ApiConsumer consumer in registeredUsers)
            {
                var body = new InvitationLinkClaimDTO()
                {
                    //ReferalLinkId = this.TestInvitationLink.RefLinkId,
                    ReferalLinkUrl = this.TestInvitationLink.RefLinkUrl,
                    IsNewClient    = true
                };
                var response = await consumer.ExecuteRequest($"{ApiPaths.REFERRAL_LINKS_INVITATION_PATH}/{TestInvitationLink.RefLinkId}/claim", Helpers.EmptyDictionary, JsonUtils.SerializeObject(body), Method.PUT);
            }
        }
コード例 #26
0
        /// <summary>
        /// 至少两人到位了进行 开局,开局就会扣掉配置钱===============================================
        /// </summary>
        public void Start(int userid)
        {
            lock (objLock)
            {
                TCUser myu = GetUserByID(userid);
                if (myu == null)
                {
                    return;
                }
                if (myu.CheckisWatch())
                {
                    return;
                }
                if (!myu.CheckFirstDeal())
                {
                    return;
                }
                if (HaveSomeBodyUnDeal())
                {
                    return;
                }
                if (_numpertable < _num_min)
                {
                    return;
                }

                base.StartBase(60 * 10);
                //第一次随机庄
                _bankpos = new Random().Next(1, _numpertable + 1); //BankerPos = 1;

                Queue <int> _tcardLeft = new Queue <int>();
                Dictionary <int, List <int> > _pokerList = ThreeCard.DistributePoker(out _tcardLeft, _numpertable);   //分牌


                List <UserIDMSG>      imList  = new List <UserIDMSG>();
                List <CommonPosValSD> _uplist = new List <CommonPosValSD>();
                ForeashAllDo((i) =>
                {
                    _uplist.Add(new CommonPosValSD()
                    {
                        pos = i, val = _DicPos2User[i]._userid
                    });
                });
                // 同时把每位玩家的数据确认修改了 //发送消息到所有玩家
                ForeashAllDo((i) =>
                {
                    TCUser tempUser = _DicPos2User[i];

                    tempUser._isPlaying  = true;
                    tempUser._Pos        = i;
                    tempUser._shouPaiArr = _pokerList[i];

                    _DicPos2User[i] = tempUser;//必须要赋值回去 要求有3个返馈才处理

                    _tablRecord.MatchCode = _tableMathCode;
                    _tablRecord._guid     = _guid;
                    _tablRecord.StartTime = DateTime.Now;

                    //发送通知消息
                    sc_tablestart_tc_n _start = new sc_tablestart_tc_n()
                    {
                        result = 1, fn = "sc_tablestart_tc_n"
                    };
                    _start.tableid   = _tableid;
                    _start.pos       = i;
                    _start.BankerPos = _bankpos;
                    _start._user2pos = _uplist;//所有玩家及对应 的位置信息
                    imList.Add(new UserIDMSG(tempUser._userid, JsonUtils.Serialize(_start), tempUser._isRobot, tempUser._isDisconnet));
                });

                TCSendDataServer.instance.SendDataDelay(imList);
                _tableSendData.Add(imList);
                AutoBaseGamble();

                // ,只有庄的下一个位置有超时处理
                MoveNextToken();
                _DicPos2User[_userTokenPos].SetTimeOutAction(1, "sc_tablestart_tc_n");//下一位的处理 令牌功能           MoveTableToken();
            }
        }
コード例 #27
0
        public async Task ClaimInvitationLink()
        {
            await this.PrepareClainInvitationLink();

            var url = $"{ApiPaths.REFERRAL_LINKS_PATH}/{GlobalConstants.AutoTest}/claim";

            //send request without data
            var response = await this.Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, null, Method.PUT);

            Assert.True(response.Status == HttpStatusCode.NotFound);

            var body = new InvitationLinkClaimDTO()
            {
                ReferalLinkUrl = GlobalConstants.AutoTest,
                IsNewClient    = false
            };

            //send request with wrong data
            response = await this.Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(body), Method.PUT);

            Assert.True(response.Status == HttpStatusCode.NotFound);



            //Create link to be claimed
            var         createLinkUrl      = ApiPaths.REFERRAL_LINKS_INVITATION_PATH;
            ApiConsumer createLinkConsumer = this.InvitationLinkClaimersConsumers[0];

            this.InvitationLinkClaimersConsumers.RemoveAt(0);

            var createLinkResponse = await createLinkConsumer.ExecuteRequest(createLinkUrl, Helpers.EmptyDictionary, null, Method.POST);

            Assert.True(createLinkResponse.Status == HttpStatusCode.Created);
            var createdLink = JsonUtils.DeserializeJson <RequestInvitationLinkResponseDto>(createLinkResponse.ResponseJson);

            body = new InvitationLinkClaimDTO()
            {
                ReferalLinkUrl = createdLink.RefLinkUrl,
                IsNewClient    = true
            };
            string claimParam = JsonUtils.SerializeObject(body);

            url = $"{ApiPaths.REFERRAL_LINKS_INVITATION_PATH}/{createdLink.RefLinkId}/claim";

            for (int i = 0; i < this.InvitationLinkClaimersConsumers.Count; i++)
            {
                ApiConsumer claimConsumer = this.InvitationLinkClaimersConsumers[i];
                var         claimResponse = await claimConsumer.ExecuteRequest(url, Helpers.EmptyDictionary, claimParam, Method.PUT);

                InvitationLinkClaimResponseDTO parsedClaimResponse = JsonUtils.DeserializeJson <InvitationLinkClaimResponseDTO>(claimResponse.ResponseJson);

                ClientBalanceResponseModel senderBalance   = null;
                ClientBalanceResponseModel recieverBalance = null;

                if (Constants.TREE_COIN_INVIRATION_AWARD != 0.0)
                {
                    List <ClientBalanceResponseModel> senderBalances = (await this.BalancesClient.GetClientBalances(createLinkConsumer.ClientInfo.Account.Id)).ToList();
                    senderBalance = senderBalances.Where(b => b.AssetId == Constants.TREE_COIN_ID).FirstOrDefault();

                    List <ClientBalanceResponseModel> recieverBalances = (await this.BalancesClient.GetClientBalances(claimConsumer.ClientInfo.Account.Id)).ToList();
                    recieverBalance = recieverBalances.Where(b => b.AssetId == Constants.TREE_COIN_ID).FirstOrDefault();
                }

                var statisticsResponse = await createLinkConsumer.ExecuteRequest($"{ApiPaths.REFERRAL_LINKS_PATH}/statistics", Helpers.EmptyDictionary, null, Method.GET);

                RefLinksStatisticsDTO linkStatistics = JsonUtils.DeserializeJson <RefLinksStatisticsDTO>(statisticsResponse.ResponseJson);

                //assert first five claimers should claim successfully and recieve reward
                if (i < 6)
                {
                    //Assert.True(Guid.TryParse(parsedClaimResponse.TransactionRewardSender, out Guid temp1));
                    //Assert.True(Guid.TryParse(parsedClaimResponse.TransactionRewardRecipient, out Guid temp2));
                    if (Constants.TREE_COIN_INVIRATION_AWARD != 0.0)
                    {
                        Assert.True(senderBalance.Balance == (i + 1) * Constants.TREE_COIN_INVIRATION_AWARD);
                        Assert.True(recieverBalance.Balance == Constants.TREE_COIN_INVIRATION_AWARD);
                    }
                }
                else
                {
                    //Assert.Null(parsedClaimResponse.TransactionRewardSender);
                    //Assert.Null(parsedClaimResponse.TransactionRewardRecipient);
                    if (Constants.TREE_COIN_INVIRATION_AWARD != 0.0)
                    {
                        Assert.True(senderBalance.Balance == 5 * Constants.TREE_COIN_INVIRATION_AWARD);
                        Assert.Null(recieverBalance);
                    }
                }

                Assert.True(linkStatistics.NumberOfInvitationLinksAccepted == i + 1);

                //attempt to claim again with single user should result in error
                if (i == 0)
                {
                    var secondClaimResponse = await claimConsumer.ExecuteRequest(url, Helpers.EmptyDictionary, claimParam, Method.POST);

                    Assert.True(secondClaimResponse.Status != HttpStatusCode.OK);
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// 此桌结束了,所有人  比完了, ===============喜钱,,,两种喜钱==============================
        /// </summary>
        private void DoExecuteAllEnd(bool _forceOver)
        {
            lock (objLock)
            {
                bool isEnd = false;//必须提前处理
                if (GetGiveUp() >= _numpertable - 1)
                {
                    isEnd = true;                                 //一桌结束,
                }
                if (!isEnd)
                {
                    return;
                }
                List <int>            _wincard   = new List <int>();
                List <CommonPosValSD> _moneylist = new List <CommonPosValSD>();//缺的清单信息
                ForeashAllDo((i) =>
                {
                    _moneylist.Add(new CommonPosValSD()
                    {
                        pos = i, val = _DicPos2User[i]._tempMoney
                    });
                    if (!_DicPos2User[i]._isgiveup)
                    {
                        _wincard = _DicPos2User[i]._shouPaiArr;
                    }
                });
                //只有最后一家才有收喜钱,,,还有一种规则是直接看牌的不给喜钱,
                ForeashAllDo((i) =>
                {
                });

                //向X家返回结果 通知 结束
                List <UserIDMSG> imList = new List <UserIDMSG>();
                ForeashAllDo((i) =>
                {
                    TCUser tempUser = _DicPos2User[i];

                    sc_end_tc_n _end_n = new sc_end_tc_n()
                    {
                        fn = "sc_end_tc_n", result = 1
                    };                                                                        // 显示结束面板就行
                    _end_n.allmoney     = _allMoney;
                    _end_n.winCard      = _wincard;
                    _end_n.endMoneylist = _moneylist;
                    _end_n.EasterEgg    = 0;
                    imList.Add(new UserIDMSG(tempUser._userid, JsonUtils.Serialize(_end_n), tempUser._isRobot, tempUser._isDisconnet));
                });

                TCSendDataServer.instance.SendDataDelay(imList);
                _tableSendData.Add(imList);
                ForeashAllDo((i) => { _DicPos2User[i].SetTimeOutAction(1, "sc_end_tc_n"); });//下把的自动开始功能        ReStart();

                //写入此桌的录相 记录
                _tablRecord.ActionList = "";
                _tablRecord.EndTime    = DateTime.Now;
                try
                {
                    tb_tablerecord tr = new tb_tablerecord()
                    {
                        MatchCode = _tablRecord.MatchCode,
                        StartTime = _tablRecord.StartTime,
                        EndTime   = _tablRecord.EndTime,
                        //PostoIPArr = _tablRecord.PostoIPArr,
                        //posarr = _tablRecord.posarr,
                        ActionList = _tablRecord.ActionList,
                        //ActionCount = _tablRecord.ActionCount,
                        LookCount = _tablRecord.LookCount
                    };
                    //// LogWriteToDB(0, tr);
                }
                catch (Exception ex)
                {
                    ErrorRecord.Record(ex, " 201207231051TC");
                }
                //重置此桌信息
                ///// Reset(CheckResetTable());
            }
        }
コード例 #29
0
        public async Task <IHttpActionResult> GetCollection(string q)
        {
            if (String.IsNullOrWhiteSpace(q))
            {
                return(BadRequest("Empty query."));
            }
            var collectionName = GeneralUtils.SanitizeSpaceSeparatedWords(q);

            // Try to find the picture collection for the query in the internal Table storage.
            var    table     = AzureStorageUtils.GetCloudTable(AzureStorageUtils.TableNames.GamePicapick);
            var    operation = TableOperation.Retrieve <GamePickapicEntity>(collectionName, String.Empty);
            var    entity    = (await table.ExecuteAsync(operation)).Result as GamePickapicEntity;
            string json      = entity != null ? entity.Json : null;

            // If the data not found in our internal Table, query the YouTube API.
            if (json == null)
            {
                // We do not use the Google API Client library to materialize result as a POCO. Anyway the API itself is RESTful, and JSON can be parsed easily. Avoid overhead, overkill, bloatware etc.
                // +https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.search.list

                var youtubeParams = HttpUtility.ParseQueryString(String.Empty); // returns System.Web.HttpValueCollection: System.Collections.Specialized.NameValueCollection
                youtubeParams["key"]        = ConfigurationManager.AppSettings["YoutubeApiKey"];
                youtubeParams["part"]       = "snippet";
                youtubeParams["type"]       = "video";
                youtubeParams["maxResults"] = "50";
                youtubeParams["q"]          = collectionName;
                youtubeParams["fields"]     = "items(id,snippet(thumbnails(high)))";
                var youtubeQueryString = youtubeParams.ToString();

                var url = "https://www.googleapis.com/youtube/v3/search?" + youtubeQueryString;

                var handler = new HttpClientHandler();
                if (handler.SupportsAutomaticDecompression)
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                }

                string response = null;
                using (var client = new HttpClient(handler))
                {
                    // If User-Agent is not sent, the server ignores "Accept-Encoding: gzip, deflate" and does not compress the response. The observed compression is 10kB -> 1kB.
                    client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "google-api-dotnet-client/1.8.1.31685 (gzip)");

                    response = await client.GetStringAsync(url);
                }

                var urls = JObject.Parse(response)
                           .GetValue("items")
                           .Children()
                           .Select(i => i["snippet"]["thumbnails"]["high"]["url"].Value <string>())
                           .OrderBy(i => Guid.NewGuid()) // Shuffle
                           .ToArray();

                var controlNumber = Math.Abs(String.Join(String.Empty, urls).GetHashCode()) % 100;
                json   = JsonUtils.SerializeAsJson(new { CollectionName = collectionName, ControlNumber = controlNumber, Urls = urls, });
                entity = new GamePickapicEntity(collectionName, json);
                await AzureStorageUtils.InsertEntityAsync(AzureStorageUtils.TableNames.GamePicapick, entity);
            }

            return(new RawStringResult(this, json, RawStringResult.TextMediaType.Json));
        }
コード例 #30
0
        protected void ExtendModel(JObject model, bool onlyData, bool onlyMainData, string id = null)
        {
            if (_module.CanvasUnavailable)
            {
                onlyData = true;
            }

            if (_templateFiles != null)
            {
                // include additional data in the Model
                if (_templateFiles.AdditionalDataInTemplate && _manifest.AdditionalDataDefined())
                {
                    model["AdditionalData"] = GetAdditionalData(onlyData);
                }
                // include collections
                if (_templateFiles.Model != null)
                {
                    var additionalCollections = _templateFiles.Model.Where(c => c.Key != _collection);
                    if (additionalCollections.Any())
                    {
                        var collections  = model["Collections"] = new JObject();
                        var dsColContext = OpenContentUtils.CreateDataContext(_module);
                        foreach (var item in additionalCollections)
                        {
                            var colManifest = item.Value;
                            dsColContext.Collection = item.Key;
                            Select select = null;
                            if (item.Value.Query != null)
                            {
                                var                 indexConfig  = OpenContentUtils.GetIndexConfig(_module.Settings.TemplateDir, item.Key);
                                QueryBuilder        queryBuilder = new QueryBuilder(indexConfig);
                                var                 u            = PortalSettings.Current.UserInfo;
                                NameValueCollection queryString  = null;
                                if (item.Value.Query["RelatedField"] != null)
                                {
                                    queryString = new NameValueCollection();
                                    queryString.Add(item.Value.Query["RelatedField"].ToString(), id);
                                }
                                queryBuilder.Build(item.Value.Query, true, u.UserID, DnnLanguageUtils.GetCurrentCultureCode(), u.Social.Roles.FromDnnRoles(), queryString);
                                select = queryBuilder.Select;
                            }
                            IDataItems dataItems   = _ds.GetAll(dsColContext, select);
                            var        colDataJson = new JArray();
                            foreach (var dataItem in dataItems.Items)
                            {
                                var json = dataItem.Data;
                                if (json != null)
                                {
                                    JsonUtils.SimplifyJson(json, GetCurrentCultureCode());
                                }
                                if (json is JObject)
                                {
                                    JObject context = new JObject();
                                    json["Context"] = context;
                                    context["Id"]   = dataItem.Id;
                                    EnhanceSelect2(json as JObject, onlyData);
                                    JsonUtils.SimplifyJson(json, GetCurrentCultureCode());
                                }
                                colDataJson.Add(json);
                            }
                            collections[item.Key]          = new JObject();
                            collections[item.Key]["Items"] = colDataJson;
                        }
                    }
                }
            }
            // include settings in the Model
            if (!onlyMainData && _templateManifest != null && _templateManifest.SettingsNeeded() && !string.IsNullOrEmpty(_settingsJson))
            {
                try
                {
                    var jsonSettings = JToken.Parse(_settingsJson);
                    //if (DnnLanguageUtils.GetPortalLocales(_portalId).Count > 1)
                    //{
                    //    JsonUtils.SimplifyJson(jsonSettings, GetCurrentCultureCode());
                    //}
                    JsonUtils.SimplifyJson(jsonSettings, GetCurrentCultureCode());
                    model["Settings"] = jsonSettings;
                }
                catch (Exception ex)
                {
                    throw new Exception("Error parsing Json of Settings", ex);
                }
            }

            // include static localization in the Model
            if (!onlyMainData)
            {
                var localizationJson = LocalizationUtils.LoadLocalizationJson(_module.Settings.TemplateDir, GetCurrentCultureCode());
                if (localizationJson != null)
                {
                    model["Localization"] = localizationJson;
                }
            }
            if (!onlyData)
            {
                // include CONTEXT in the Model
                JObject context = new JObject();
                model["Context"]        = context;
                context["TabId"]        = _module.ViewModule.TabId;
                context["ModuleId"]     = _module.ViewModule.ModuleId;
                context["GoogleApiKey"] = App.Services.CreateGlobalSettingsRepository(_portalId).GetGoogleApiKey();
                context["ModuleTitle"]  = _module.ViewModule.ModuleTitle;
                var editIsAllowed = !_manifest.DisableEdit && !_templateManifest.DisableEdit && IsEditAllowed(-1);
                context["IsEditable"]    = editIsAllowed; //allowed to edit the item or list (meaning allow Add)
                context["IsEditMode"]    = IsEditMode;
                context["PortalId"]      = _portalId;
                context["MainUrl"]       = _module.GetUrl(_detailTabId, GetCurrentCultureCode());
                context["HomeDirectory"] = _module.HomeDirectory;
                context["HTTPAlias"]     = _module.HostName;
                context["PortalName"]    = _module.PortalName;
                context["TemplatePath"]  = _module.Settings.TemplateDir.UrlFolder;
                context["TemplateName"]  = (String.IsNullOrEmpty(_manifest.Title) ? Path.GetFileName(_templateManifest.MainTemplateUri().FolderPath) : _manifest.Title) + " - " + (string.IsNullOrEmpty(_templateManifest.Title) ? _templateManifest.Key.ShortKey : _templateManifest.Title);
                //context["TemplateName"] = _templateManifest.MainTemplateUri().UrlFilePath ;
            }
        }