예제 #1
1
 public static byte[] ResetPass( string email )
 {
     object obj = new {
         email = email
     };
     return obj.JData();
 }
        private async Task<string> GetAccessToken()
        {

            string accessToken = string.Empty;
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(this.domain);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var payLoad = new
                {
                    client_id = this.clientID,
                    client_secret = this.clientSecret,
                    grant_type = "client_credentials"
                };

                HttpResponseMessage response = await client.PostAsJsonAsync("oauth/token", payLoad);

                if (response.IsSuccessStatusCode)
                {
                    var JsonObject = JObject.Parse(response.Content.ReadAsStringAsync().Result);

                    accessToken = JsonObject["access_token"].ToString();

                    return accessToken;

                }

                return string.Empty;
            }
        }
예제 #3
0
 public static byte[] GetDownloadLink( string[] ids )
 {
     object oids = new {
         ids = ids
     };
     return oids.JData();
 }
예제 #4
0
 public static byte[] ShareDownloadLink( string id, string[] links )
 {
     object s = new {
         id = id,
         links = links
     };
     return s.JData();
 }
예제 #5
0
 public static byte[] Contact( string name, string email )
 {
     //Create contact object
     object c = new {
         email = email,
         name = name
     };
     //return token
     return c.JData();
 }
예제 #6
0
 public static byte[] RenameMetadata( string idMetadata, string name )
 {
     //Create contact object
     object m = new {
         id = idMetadata,
         name = name
     };
     //return token
     return m.JData();
 }
예제 #7
0
 public static byte[] MakeDir( string idMetadata, string dirName )
 {
     //Create upload object
     //object will ref chunked upload
     object d = new {
         target = idMetadata,
         name = dirName,
     };
     //return token
     return d.JData();
 }
예제 #8
0
 public static byte[] Upload( string idMetadata, string fileName )
 {
     //Create upload object
     //object will ref chunked upload
     object u = new {
         parent = idMetadata,
         name = fileName,
         upload_type = "chunked"
     };
     //return token
     return u.JData();
 }
예제 #9
0
    static void Main(string[] args)
    {
      var points = new[] { new Point(3, 4), new Point(-1, 0), new Point(5, -2), new Point(7, 6) };
      WriteLine(Point.ToString(points));

      var json = new JArray(from p in points select p.ToJson()).ToString();
      WriteLine(json);

      var pointsAgain =
        from j in JArray.Parse(json)
        select Point.FromJson(j as JObject);
      WriteLine(Point.ToString(pointsAgain));

      ReadKey();
    }
예제 #10
0
        public static void Y2015_Day12_Solve_Returns_Correct_Solution()
        {
            // Act
            var puzzle = PuzzleTestHelpers.SolvePuzzle<Day12>();

            // Assert
            Assert.Equal(191164, puzzle.Sum);

            // Arrange
            string[] args = new[] { "red" };

            // Act
            puzzle = PuzzleTestHelpers.SolvePuzzle<Day12>(args);

            // Assert
            Assert.Equal(87842, puzzle.Sum);
        }
예제 #11
0
        public void TestUnknownReferer()
        {
            var set = new[] 
            {
                  new 
                  { 
                      Name = "Unknown referer #1",
                      Url = "http://www.behance.net/gallery/psychicbazaarcom/2243272",
                      Source = string.Empty,
                  },
                  new 
                  {
                      Name = "Unknown referer #2",
                      Url = "http://www.wishwall.me/home",
                      Source = string.Empty,
                  },
                  new 
                  {
                      Name = "Unknown referer #3",
                      Url = "http://www.spyfu.com/domain.aspx?d=3897225171967988459",
                      Source = string.Empty,
                  },
                  new
                  {
                     Name = "Unknown referer #4",
                     Url = "http://seaqueen.wordpress.com/",
                     Source = string.Empty,
                  },
                  new 
                  {
                    Name = "Non-search Yahoo! site",
                    Url = "http://finance.yahoo.com",
                    Source = "Yahoo!",
                  },
            };

            foreach (var sample in set)
            {
                var result = Parser.Parse(new Uri(sample.Url), "www.snowplowanalytics.com");
                Assert.NotNull(result);
                Assert.Equal(sample.Source, result.Source ?? string.Empty);
            }
        }
예제 #12
0
        private static List<object> ParseExceptionMessages(string jsonException, List<object> jsonObjects)
        {
            var json = JObject.Parse(jsonException);
            var messageDefinition = new { Message = "", ExceptionType = "", ExceptionMessage = "", ExceptionSource = "" };
            var exceptionObject = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(jsonException, messageDefinition);
            if (jsonObjects == null)
            {
                jsonObjects = new List<object>();
            }
            jsonObjects.Add(exceptionObject);

            JToken innerExceptionValue;
            if (json.TryGetValue("InnerException", out innerExceptionValue))
            {
                var innerException = innerExceptionValue.ToString();
                return ParseExceptionMessages(innerException, jsonObjects);
            }
            return jsonObjects;
        }
예제 #13
0
파일: R.cs 프로젝트: Inmeta/aspc2016
        internal async Task<string> InvokeRequestResponseService(double latitude, double longitude, int year)
        {
            using (var client = new HttpClient())
            {
                var scoreRequest = new
                {

                    Inputs = new Dictionary<string, StringTable>() {
                    {
                        "input1",
                        new StringTable()
                        {
                            ColumnNames = new string[] {"lat", "long", "N", "Y"},
                            Values = new string[,] {  { latitude.ToString(), longitude.ToString(), "0", year.ToString() }  }
                        }
                    },
                },
                    GlobalParameters = new Dictionary<string, string>()
                    {
                    }
                };
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                client.BaseAddress = new Uri(ServiceUri);
                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    return result;
                }
                else
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    return responseContent;
                }
            }
        }
예제 #14
0
        public string GetToken(string email, string secret)
        {
            //done V2ing
            var request = new
            {
                email,
                password = secret,
                hospitalId = HospitalId,
                userTypeId = 1
            };

            var response = Post("v2/account/token", request);

            var dataEnumerator = response.ToObject<ApiResponseV2<SerializableToken>>();
            if (dataEnumerator.Data != null)
            {
                foreach (var entry in dataEnumerator.Data)
                {
                    return entry.access_token;
                }
            }

            return null;
        }
예제 #15
0
        public void TestFalsePositivies()
        {
            var set = new[] 
            {
                  new 
                  {
                      Name = "Unknown Google service",
                      Url = "http://xxx.google.com",
                      Medium = RefererMedium.Search,
                      Source = "Google",
                      Term = string.Empty
                  },
                  new
                  {
                      Name = "Unknown Yahoo! service",
                      Url = "http://yyy.yahoo.com",
                      Medium = RefererMedium.Search,
                      Source = "Yahoo!",
                      Term = string.Empty
                  },
                  new 
                  {
                      Name = "Non-search Google Drive link",
                      Url = "http://www.google.com/url?q=http://www.whatismyreferer.com/&sa=D&usg=ALhdy2_qs3arPmg7E_e2aBkj6K0gHLa5rQ",
                      Medium = RefererMedium.Search,
                      Source = "Google",
                      Term = "http://www.whatismyreferer.com/",
                  },
            };

            foreach (var sample in set)
            {
                var result = Parser.Parse(new Uri(sample.Url), "www.snowplowanalytics.com");
                Assert.NotNull(result);
                Assert.Equal(sample.Source, result.Source ?? string.Empty);
            }
        }
예제 #16
0
 public void EditPage(string page, string content, string previous = null, string reason = null)
 {
     var request = WebAgent.CreatePost(string.Format(WikiPageEditUrl, Subreddit.Name));
     dynamic param = new 
     {
         content = content,
         page = page,
         uh = Reddit.User.Modhash
     };
     List<string> addParams = new List<string>();
     if (previous != null) 
     {
         addParams.Add("previous");
         addParams.Add(previous);
     }
     if (reason != null) 
     {
         addParams.Add("reason");
         addParams.Add(reason);
     }
     WebAgent.WritePostBody(request.GetRequestStream(), param,addParams.ToArray());
     var response = request.GetResponse();
 }
예제 #17
0
 public static async Task<object> GetRuneSetups(string realm, double summonerId)
 {
     RiotAccount[] all = JsApiService.AccountBag.GetAll();
     RiotAccount riotAccount = JsApiService.AccountBag.Get(realm);
     SpellBookDTO spellBookDTO = await riotAccount.InvokeCachedAsync<SpellBookDTO>("spellBookService", "getSpellBook", summonerId);
     SpellBookDTO spellBookDTO1 = spellBookDTO;
     List<SpellBookPageDTO> bookPages = spellBookDTO1.BookPages;
     SpellBookPageDTO spellBookPageDTO = bookPages.FirstOrDefault<SpellBookPageDTO>((SpellBookPageDTO x) => x.Current);
     if (spellBookPageDTO == null)
     {
         spellBookPageDTO = new SpellBookPageDTO();
     }
     SpellBookPageDTO spellBookPageDTO1 = spellBookPageDTO;
     bool flag = all.Any<RiotAccount>((RiotAccount x) =>
     {
         if (!string.Equals(x.RealmId, realm, StringComparison.OrdinalIgnoreCase))
         {
             return false;
         }
         return (double)x.SummonerId == summonerId;
     });
     double pageId = spellBookPageDTO1.PageId;
     List<SpellBookPageDTO> spellBookPageDTOs = spellBookDTO1.BookPages;
     IOrderedEnumerable<SpellBookPageDTO> pageId1 =
         from page in spellBookPageDTOs
         orderby page.PageId
         select page;
     object variable = new
     {
         Local = flag,
         ActiveId = pageId,
         Setups =
             from page in pageId1
             select new
             {
                 Id = page.PageId,
                 Name = page.Name,
                 Runes =
                     from entry in page.SlotEntries
                     group entry by entry.RuneId into entries
                     select new { Id = entries.Key, Count = entries.Count<SlotEntry>() }
             }
     };
     return variable;
 }
        public void ShowDevOptionsDialog()
        {
            if (_devOptionsDialog != null || !IsEnabled)
            {
                return;
            }

            DispatcherHelpers.RunOnDispatcher(() =>
            {
                var options = new[]
                {
                    new DevOptionHandler(
                        "Reload JavaScript",
                        HandleReloadJavaScript),
                    new DevOptionHandler(
                        IsRemoteDebuggingEnabled
                            ? "Stop JS Remote Debugging"
                            : "Start JS Remote Debugging",
                        () =>
                        {
                            IsRemoteDebuggingEnabled = !IsRemoteDebuggingEnabled;
                            HandleReloadJavaScript();
                        }),
                    new DevOptionHandler(
                        _devSettings.IsHotModuleReplacementEnabled
                            ? "Disable Hot Reloading"
                            : "Enable Hot Reloading",
                        () =>
                        {
                            _devSettings.IsHotModuleReplacementEnabled = !_devSettings.IsHotModuleReplacementEnabled;
                            HandleReloadJavaScript();
                        }),
                    new DevOptionHandler(
                        _devSettings.IsReloadOnJavaScriptChangeEnabled
                            ? "Disable Live Reload"
                            : "Enable Live Reload",
                        () =>
                            _devSettings.IsReloadOnJavaScriptChangeEnabled =
                                !_devSettings.IsReloadOnJavaScriptChangeEnabled),
                    new DevOptionHandler(
                        _devSettings.IsElementInspectorEnabled
                            ? "Hide Inspector"
                            : "Show Inspector",
                        () =>
                        {
                            _devSettings.IsElementInspectorEnabled = !_devSettings.IsElementInspectorEnabled;
                            _reactInstanceCommandsHandler.ToggleElementInspector();
                        }),
                };

                _devOptionsDialogOpen = true;
                _devOptionsDialog = new DevOptionDialog();
                _devOptionsDialog.Closed += (_, __) =>
                {
                    _devOptionsDialogOpen = false;
                    _dismissDevOptionsDialog = null;
                    _devOptionsDialog = null;
                };

                foreach (var option in options)
                {
                    _devOptionsDialog.Add(option.Name, option.OnSelect);
                }

                if (_redBoxDialog != null)
                {
                    _dismissRedBoxDialog();
                }

#if WINDOWS_UWP
                var asyncInfo = _devOptionsDialog.ShowAsync();
                _dismissDevOptionsDialog = asyncInfo.Cancel;

                foreach (var option in options)
                {
                    option.HideDialog = _dismissDevOptionsDialog;
                }
#else
                var asyncInfo = _devOptionsDialog.ShowDialog();

                foreach (var option in options)
                {
                    option.HideDialog = _devOptionsDialog.Hide;
                }
#endif
            });
        }
        private async Task<JObject> SendRequestAsync(string action, params JProperty[] args)
        {
            var requestId = Guid.NewGuid().ToString();
            var requestInfo = new RequestInfo();
            lock (_requests)
            {
                _requests.Add(requestId, requestInfo);
            }

            var commonProperties = new[]
            {
                new JProperty("action", action),
                new JProperty("requestId", requestId)
            };

            var requestJson = new JObject(commonProperties.Concat(args).Cast<object>().ToArray());
            _webSocket.Send(requestJson.ToString());

            var resultTask = await Task.WhenAny(requestInfo.Task, Task.Delay(Timeout));
            if (resultTask != requestInfo.Task)
                throw new DeviceHiveException("Timeout while waiting for server response!");

            var result = requestInfo.Task.Result;
            var status = (string)result["status"];
            if (status == "error")
                throw new DeviceHiveException((string)result["error"]);

            return result;
        }
        public static StyleElement ParseJson(JToken contentJson)
        {
            contentJson = contentJson.ElementAtOrDefault(0);
            if (contentJson == null)
                return new StyleElement(StyleType.None, new List<ContentElement>());

            var styleStatus = new[] { false, false, false };
            var styleStack = new Stack<StyleType>();
            var blocksStack = new Stack<List<ContentElement>>();
            blocksStack.Push(new List<ContentElement>());
            foreach (var item in contentJson)
                switch ((int)item[0])
                {
                    case 0:
                    case 2:
                    case 3:
                    case 4:
                        //itemの書式を取得
                        var newStyleStatus = new[] { false, false, false };
                        if (item.Count() > 2 && item[2].Type == JTokenType.Array)
                            foreach (var styleItem in item[2].Select((token, idx) => new { Token = token, Index = idx }))
                                newStyleStatus[styleItem.Index] = styleItem.Token.Type != JTokenType.Null && (int)styleItem.Token == 1;
                        //書式解除があった場合は新旧比較し、解除書式全てを消すまで書式スタックを削る
                        //ここで開始地点がスライドしてる書式などの巻き添えになる書式も発生する。その
                        //書式は後続の書式追加で補填する
                        for (var currentStyleIdx = 0; currentStyleIdx < styleStatus.Length; currentStyleIdx++)
                        {
                            if (newStyleStatus[currentStyleIdx] == false && styleStatus[currentStyleIdx])
                                while (blocksStack.Count > 0)
                                {
                                    styleStatus[(int)styleStack.Peek()] = false;
                                    var newElement = new StyleElement(styleStack.Peek(), blocksStack.Pop());
                                    blocksStack.Peek().Add(newElement);
                                    if (styleStack.Pop() == (StyleType)currentStyleIdx)
                                        break;
                                }
                        }
                        //書式追加がある場合は書式スタックの追加とブロックスタックの最上にある
                        //要素リストを新規追加で新品リストにする
                        for (var currentStyleIdx = 0; currentStyleIdx < styleStatus.Length; currentStyleIdx++)
                        {
                            if (newStyleStatus[currentStyleIdx] && styleStatus[currentStyleIdx] == false)
                            {
                                styleStack.Push((StyleType)currentStyleIdx);
                                styleStatus[currentStyleIdx] = true;
                                blocksStack.Push(new List<ContentElement>());
                            }
                        }
                        switch ((int)item[0])
                        {
                            case 0:
                                blocksStack.Peek().Add(new TextElement((string)item[1]));
                                break;
                            case 2:
                            case 4:
                                blocksStack.Peek().Add(new HyperlinkElement(new Uri((string)item[3][0]), (string)item[1]));
                                break;
                            case 3:
                                blocksStack.Peek().Add(new MensionElement(new ProfileData((string)item[4][1], (string)item[1])));
                                break;
                        }
                        break;
                    case 1:
                        blocksStack.Peek().Add(new BreakElement());
                        break;
                }
            //ルート要素は書式設定無しのスタイル要素にする。しかし、配列に要素が
            //一つしか入っておらず、要素がスタイル要素だった場合には新しく生成せ
            //ずにそのスタイル要素を戻り値とする
            if (blocksStack.Peek().Count == 1 && blocksStack.Peek().First() is StyleElement)
                return (StyleElement)blocksStack.Peek().First();
            else
                return new StyleElement(StyleType.None, blocksStack.Pop());
        }
예제 #21
0
 private static JObject CreateDateInfoJson(DateTimeFormatInfo di)
 {
     var obj = new
     {
         firstDay = di.FirstDayOfWeek,
         days = new
         {
             names = di.DayNames,
             namesAbbr = di.AbbreviatedDayNames,
             namesShort = di.ShortestDayNames
         },
         months = new
         {
             names = di.MonthNames,
             namesAbbr = di.AbbreviatedMonthNames
         },
         AM = di.AMDesignator,
         PM = di.PMDesignator,
         eras = di.Calendar.Eras.Select(era => new { offset = 0, start = (string)null, name = di.GetEraName(era) }).ToArray(),
         twoDigitYearMax = di.Calendar.TwoDigitYearMax,
         patterns = new
         {
             d = di.ShortDatePattern,
             D = di.LongDatePattern,
             t = di.ShortTimePattern,
             T = di.LongTimePattern,
             f = di.LongDatePattern + " " + di.ShortTimePattern,
             F = di.LongDatePattern + " " + di.LongTimePattern,
             M = di.MonthDayPattern,
             Y = di.YearMonthPattern,
         }
     };
     var jobj = JObject.FromObject(obj);
     jobj["/"] = di.DateSeparator;
     jobj[":"] = di.TimeSeparator;
     if (!di.MonthNames.SequenceEqual(di.MonthGenitiveNames))
     {
         var monthsGenitive = jobj["monthsGenitive"] = new JObject();
         monthsGenitive["names"] = JArray.FromObject(di.MonthGenitiveNames);
         monthsGenitive["namesAbbr"] = JArray.FromObject(di.AbbreviatedMonthGenitiveNames);
     }
     return new JObject()
     {
         {"standard", jobj }
     };
 }
예제 #22
0
		private dynamic GetBrackets()
		{
			var suffix = (options.data.Next == null) ? "" : ",";
			dynamic v = new { top = "{", bottom = "}" + suffix };
			if (options.data is JArray)
				v = new { top = "[", bottom = "]" + suffix };

			return v;
		}
예제 #23
0
        private static JObject CreateNumberInfoJson(NumberFormatInfo ni)
        {
            var numberFormat = new
            {
                pattern = new[] { numberPatternStrings[ni.NumberNegativePattern] },
                decimals = ni.NumberDecimalDigits,
                groupSizes = ni.NumberGroupSizes,
                NaN = ni.NaNSymbol,
                negativeInfinity = ni.NegativeInfinitySymbol,
                positiveInfinity = ni.PositiveInfinitySymbol,
                percent = new
                {
                    pattern = new[] {
                            percentNegativePatternStrings[ni.PercentNegativePattern],
                            percentPositivePatternStrings[ni.PercentPositivePattern]
                        },
                    decimals = ni.PercentDecimalDigits,
                    groupSizes = ni.PercentGroupSizes,
                    symbol = ni.PercentSymbol
                },
                currency = new
                {
                    pattern = new[]
                        {
                            currencyNegativePatternStrings[ni.CurrencyNegativePattern],
                            currencyPositivePatternStrings[ni.CurrencyPositivePattern]
                        },
                    decimals = ni.CurrencyDecimalDigits,
                    groupSizes = ni.CurrencyGroupSizes,
                    symbol = ni.CurrencySymbol
                }
            };
            var jobj = JObject.FromObject(numberFormat);
            jobj[","] = ni.NumberGroupSeparator;
            jobj["."] = ni.NumberDecimalSeparator;
            jobj["percent"][","] = ni.PercentGroupSeparator;
            jobj["percent"]["."] = ni.PercentDecimalSeparator;

            jobj["currency"][","] = ni.CurrencyGroupSeparator;
            jobj["currency"]["."] = ni.CurrencyGroupSeparator;
            return jobj;
        }
예제 #24
0
        /// <summary>
        /// Creates a new <see cref="ShopifyProduct"/> on the store.
        /// </summary>
        /// <param name="product">A new <see cref="ShopifyProduct"/>. Id should be set to null.</param>
        /// <param name="options">Options for creating the product.</param>
        /// <returns>The new <see cref="ShopifyProduct"/>.</returns>
        public async Task<ShopifyProduct> CreateAsync(ShopifyProduct product, ShopifyProductCreateOptions options = null)
        {
            IRestRequest req = RequestEngine.CreateRequest("products.json", Method.POST, "product");

            //Build the request body as a dictionary. Necessary because the create options must be added to the 
            //'product' property.
            var productBody = product.ToDictionary();

            if(options != null)
            {
                foreach(var kvp in options.ToDictionary())
                {
                    productBody.Add(kvp);
                }
            }

            var requestBody = new { product = productBody };

            req.AddJsonBody(requestBody);

            return await RequestEngine.ExecuteRequestAsync<ShopifyProduct>(_RestClient, req);
        }
예제 #25
0
        public static JObject BuildCultureInfoJson(CultureInfo ci)
        {
            var cultureInfoClientObj = new
            {
                name = ci.Name,
                nativeName = ci.NativeName,
                englishName = ci.EnglishName,
                isRTL = ci.TextInfo.IsRightToLeft,
                language = ci.IetfLanguageTag
            };
            var jobj = JObject.FromObject(cultureInfoClientObj);

            jobj["numberFormat"] = CreateNumberInfoJson(ci.NumberFormat);
            jobj["calendars"] = CreateDateInfoJson(ci.DateTimeFormat);
            return JsonUtils.Diff(defaultJson, jobj);
        }
        public static StyleElement ParseHtml(string contentHtml, IPlatformClient client)
        {
            if (string.IsNullOrEmpty(contentHtml))
                return null;

            //"<"はhtml上では&lt;と書くため、これの出現は確実にタグの開始となる。よって、
            //内容を読み取ることができる。以下のwhile文はhtmlをリンク、メンション、テキスト
            //に分割する処理を記述している
            int nextReadIdx = 0, idx, startIdx, endIdx, tmpInt;
            string tmpStr;
            var currentEleStack = new Stack<char>();
            var blocks = new Stack<List<ContentElement>>();
            blocks.Push(new List<ContentElement>());
            while ((idx = contentHtml.IndexOf('<', nextReadIdx)) >= 0)
            {
                //タグが開始される前に出現したテキストをblocksに入れる
                tmpStr = contentHtml.Substring(nextReadIdx, idx - nextReadIdx);
                if (tmpStr.Length > 0)
                    blocks.Peek().Add(new TextElement(Primitive.ApiAccessorUtility.DecodeHtmlText(tmpStr)));

                //メンション、リンク用
                if (contentHtml[idx + 1] == 'a' || contentHtml.IndexOf("span", idx + 1) == idx + 1)
                {
                    //開始されたタグがspanタグである場合は12/03/08時点ではメンション
                    //用の要素である
                    var isMension = contentHtml[idx + 1] == 's';

                    //IndexOf("<a href=\"", idx)のidx引数の部分は効率を考えた場合はidx + 1
                    //するとメンションの読み取りはより良い。しかしリンクの場合には現状の検索
                    //文字ではidxの添字に存在する"<"が存在しないと"<a"を検出出来ない。現状で
                    //は"<a href"の"<"を省かず、検索開始位置をidx + 1にしない事で動かしてる
                    var innerCloseEleIdx = contentHtml.IndexOf("</span>", idx + 5);
                    var outerCloseEleIdx = isMension ? contentHtml.IndexOf("</span>", innerCloseEleIdx + 7) : contentHtml.IndexOf("</a>", idx);
                    startIdx = Math.Min(
                        (tmpInt = contentHtml.IndexOf("href=\"", idx, outerCloseEleIdx - idx)) < 0 ? int.MaxValue : tmpInt,
                        (tmpInt = contentHtml.IndexOf("href='", idx, outerCloseEleIdx - idx)) < 0 ? int.MaxValue : tmpInt) + 6;
                    string mensionTargetProfileUrl = null, mensionTargetName = null;
                    if (startIdx >= 0)
                    {
                        endIdx = Math.Min(
                            (tmpInt = contentHtml.IndexOf("\"", startIdx, outerCloseEleIdx - startIdx)) < 0 ? int.MaxValue : tmpInt,
                            (tmpInt = contentHtml.IndexOf("'", startIdx, outerCloseEleIdx - startIdx)) < 0 ? int.MaxValue : tmpInt);
                        mensionTargetProfileUrl = contentHtml.Substring(startIdx, endIdx - startIdx);
                        idx = endIdx + 1;
                    }
                    else
                        idx = innerCloseEleIdx;

                    startIdx = contentHtml.IndexOf(">", idx) + 1;
                    endIdx = contentHtml.IndexOf("</", startIdx);
                    mensionTargetName = Primitive.ApiAccessorUtility.DecodeHtmlText(
                        contentHtml.Substring(startIdx, endIdx - startIdx));

                    //最端の閉じタグの最後の">"部分の直後の番地を次の文字処理位置とする
                    //たまに閉じタグが探し出せない(IndexOfのバグ?)事があり、無限ループする。これをMath.Maxで対策
                    nextReadIdx = Math.Max(nextReadIdx + 1, contentHtml.IndexOf('>', outerCloseEleIdx) + 1);

                    if (isMension)
                    {
                        if (mensionTargetProfileUrl != null)
                            blocks.Peek().Add(new MensionElement(new ProfileData(
                                mensionTargetProfileUrl.Substring(mensionTargetProfileUrl.LastIndexOf('/') + 1),
                                mensionTargetName, loadedApiTypes: ProfileUpdateApiFlag.Base)));
                        else
                            blocks.Peek().Add(new TextElement("+" + mensionTargetName));
                    }
                    else
                    {
                        Uri tmpUrl;
                        if (!Uri.TryCreate(client.PlusBaseUrl, mensionTargetProfileUrl, out tmpUrl)
                            && !Uri.TryCreate("about:blank", UriKind.Absolute, out tmpUrl)) { }
                        blocks.Peek().Add(new HyperlinkElement(tmpUrl, mensionTargetName));
                    }
                }
                else if (contentHtml.IndexOf("br", idx + 1) == idx + 1)
                {
                    blocks.Peek().Add(new BreakElement());
                    //たまに閉じタグが探し出せない(IndexOfのバグ?)事があり、無限ループする。これをMath.Maxで対策
                    nextReadIdx = Math.Max(nextReadIdx + 1, contentHtml.IndexOf(">", idx + 3) + 1);
                }
                //文字装飾タグ用
                else
                    switch (contentHtml[idx + 1])
                    {
                        case '/':
                            var currentEleChildren = blocks.Pop().ToArray();
                            switch (currentEleStack.Pop())
                            {
                                case 'b':
                                    blocks.Peek().Add(new StyleElement(StyleType.Bold, currentEleChildren));
                                    break;
                                case 'i':
                                    blocks.Peek().Add(new StyleElement(StyleType.Italic, currentEleChildren));
                                    break;
                                case 's':
                                case 'd':
                                    blocks.Peek().Add(new StyleElement(StyleType.Middle, currentEleChildren));
                                    break;
                                default:
                                    blocks.Peek().Add(new StyleElement(StyleType.Unknown, currentEleChildren));
                                    break;
                            }
                            nextReadIdx = Math.Max(nextReadIdx + 1, contentHtml.IndexOf('>', idx + 2) + 1);
                            break;
                        default:
                            startIdx = contentHtml.IndexOf('>', idx + 1) + 1;
                            var closeEleIdx = contentHtml.IndexOf("</", startIdx);
                            var otherStartEleIdx = contentHtml.IndexOf("<", startIdx);
                            if (closeEleIdx == otherStartEleIdx)
                            {
                                var elements = new[] { new TextElement(
                                    Primitive.ApiAccessorUtility.DecodeHtmlText(
                                    contentHtml.Substring(startIdx, closeEleIdx - startIdx))) };
                                switch (contentHtml[idx + 1])
                                {
                                    case 'b':
                                        blocks.Peek().Add(new StyleElement(StyleType.Bold, elements));
                                        break;
                                    case 'i':
                                        blocks.Peek().Add(new StyleElement(StyleType.Italic, elements));
                                        break;
                                    case 's':
                                    case 'd':
                                        blocks.Peek().Add(new StyleElement(StyleType.Middle, elements));
                                        break;
                                    default:
                                        blocks.Peek().Add(new StyleElement(StyleType.Unknown, elements));
                                        break;
                                }
                                nextReadIdx = contentHtml.IndexOf('>', closeEleIdx + 1) + 1;
                            }
                            else
                            {
                                var elements = new List<ContentElement>();
                                tmpStr = Primitive.ApiAccessorUtility.DecodeHtmlText(
                                    contentHtml.Substring(startIdx, otherStartEleIdx - startIdx));
                                if (tmpStr.Length > 0)
                                    elements.Add(new TextElement(tmpStr));
                                blocks.Push(elements);

                                currentEleStack.Push(contentHtml[idx + 1]);
                                nextReadIdx = otherStartEleIdx;
                            }
                            break;
                    }
            }
            //タグが無くなったら残りの文字列をblocksに入れる
            tmpStr = contentHtml.Substring(nextReadIdx, contentHtml.Length - nextReadIdx);
            if (tmpStr.Length > 0)
                blocks.Peek().Add(new TextElement(Primitive.ApiAccessorUtility.DecodeHtmlText(tmpStr)));

            //ルート要素は書式設定無しのスタイル要素にする。しかし、配列に要素が
            //一つしか入っておらず、要素がスタイル要素だった場合には新しく生成せ
            //ずにそのスタイル要素を戻り値とする
            if (blocks.Peek().Count == 1 && blocks.Peek().First() is StyleElement)
                return (StyleElement)blocks.Peek().First();
            else
                return new StyleElement(StyleType.None, blocks.Pop().ToArray());
        }
예제 #27
0
 private string GenerateAuthorizationHeaderValue(IEnumerable<KeyValuePair<string, string>> parameters, string signature)
 {
     IEnumerable<KeyValuePair<string, string>> test = new[] { new KeyValuePair<string, string>("oauth_signature", signature) };
     return new StringBuilder("OAuth ")
         .Append(parameters.Concat(test)
                     .Where(x => x.Key.StartsWith("oauth_"))
                     .Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value.EncodeRFC3986()))
                     .Join(","))
         .ToString();
 }
예제 #28
0
 public static string BuildErrorJson(string type_name, string err_msg, NameValueCollection col)
 {
     var item = new
     {
         api_name = type_name,
         err_msg = err_msg,
         query = col.ToDictionary().ToJson(),
     };
     return item.ToJson();
 }