Ejemplo n.º 1
0
 public bool Configuration(string key, object value)
 {
     if (key == "MaxUploadFilesize")
     {
         long val;
         try
         {
             val = Convert.ToInt64(value);
             if (val > 0)
             {
                 this._MaxFileSize = val;
             }
             else
             {
                 this._MaxFileSize = TwitterPhoto.MaxfilesizeDefault;
             }
         }
         catch (Exception)
         {
             this._MaxFileSize = TwitterPhoto.MaxfilesizeDefault;
             return(false);   // error
         }
         return(true);        // 正常に設定終了
     }
     return(true);            // 設定項目がない場合はとりあえずエラー扱いにしない
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Initilze Rendering
        /// </summary>
        /// <param name="rendering">Rendering to Initialze
        /// </param>
        public void Initialize(Rendering rendering)
        {
            if (string.IsNullOrEmpty(rendering.DataSource))
            {
                return;
            }

            var datasource = Context.Database.GetItem(rendering.DataSource);

            BackgroundImageUrl = datasource.ImageUrl(FieldConstants.Banner.BackgroundImage.ToString());

            TitleColor    = datasource[FieldConstants.Banner.TitleColor];
            SubTitleColor = datasource[FieldConstants.Banner.SubtitleColor];
            LinkColor     = datasource[FieldConstants.Banner.LinkColor];
            var y = double.Parse(datasource[FieldConstants.Banner.LogoTop]);

            LogoTop = Convert.ToInt32(30 * y);
            var x = double.Parse(datasource[FieldConstants.Banner.LogoLeft]);

            LogoLeft = Convert.ToInt32(8 * x);
            var bannerHeightValue = datasource[FieldConstants.Banner.BannerHeight];

            if (bannerHeightValue == null)
            {
                return;
            }

            var z = double.Parse(bannerHeightValue);

            BannerHeight = Convert.ToInt32(z * 100);
        }
        internal Color GetPercentageColor(double pct, double max = 100, double min = 0)
        {
            pct = pct / 100;
            max = max / 100;
            min = min / 100;

            double red   = 0;
            double green = 0;
            double blue  = 0;

            if (pct > max)
            {
                return(Color.FromRgb(Convert.ToByte(0), Convert.ToByte(255), Convert.ToByte(0)));
            }
            if (pct < min)
            {
                return(Color.FromRgb(Convert.ToByte(255), Convert.ToByte(0), Convert.ToByte(0)));
            }

            double median   = min + ((max - min) / 2);
            double modifier = (pct - min) / (max - min);

            if (pct >= median)
            {
                red   = (1 - modifier) * 2 * 255;
                green = 255;
            }
            else
            {
                red   = 255;
                green = modifier * 2 * 255;
            }

            return(Color.FromRgb(Convert.ToByte(red), Convert.ToByte(green), Convert.ToByte(blue)));
        }
Ejemplo n.º 4
0
        public override string EncodeIntAsCharEscape(int v)
        {
            if (v < char.MinValue || v > char.MaxValue)
            {
                throw new ArgumentException(string.Format("Cannot encode the specified value: {0}", v));
            }

            if (v >= 0 && v < targetCharValueEscape.Length && targetCharValueEscape[v] != null)
            {
                return(targetCharValueEscape[v]);
            }

            if (v >= 0x20 && v < 127 && (!char.IsDigit((char)v) || v == '8' || v == '9'))
            {
                return(((char)v).ToString());
            }

            if (v >= 0 && v <= 127)
            {
                string oct = Convert.ToString(v, 8);
                return("\\" + oct);
            }

            string hex = v.ToString("x4");

            return("\\u" + hex);
        }
Ejemplo n.º 5
0
        protected override void CustomSort(int ColumnIndex)
        {
            if (OldColumnIndex != ColumnIndex)
            {
                SortDirection = SortDirection.Asc;
            }
            if (SortDirection == SortDirection.Desc)
            {
                SortDirection = SortDirection.Asc;
            }
            else
            {
                SortDirection = SortDirection.Desc;
            }

            OldColumnIndex = ColumnIndex;
            var resultList = new List <NextPerformance>();
            var list       = radGridView1.Rows.Select(i => i).ToList();

            list.Sort(new GridViewDataRowInfoComparer(ColumnIndex, Convert.ToInt32(SortDirection)));

            resultList.AddRange(list.Select(i => i.Tag as NextPerformance));

            SetItemsArray(resultList.ToArray());
        }
Ejemplo n.º 6
0
        protected override void CustomSort(int ColumnIndex)
        {
            if (OldColumnIndex != ColumnIndex)
            {
                SortDirection = SortDirection.Asc;
            }
            if (SortDirection == SortDirection.Desc)
            {
                SortDirection = SortDirection.Asc;
            }
            else
            {
                SortDirection = SortDirection.Desc;
            }

            var resultList = new List <Directive>();
            var list       = radGridView1.Rows.Select(i => i).ToList();

            list.Sort(new DirectiveGridViewDataRowInfoComparer(ColumnIndex, Convert.ToInt32(SortDirection)));

            foreach (var item in list)
            {
                resultList.Add(item.Tag as Directive);
            }

            SetItemsArray(resultList.ToArray());
            OldColumnIndex = ColumnIndex;
        }
 private void LoadVariables()
 {
     cupboardnorefill = Convert.ToBoolean(GetConfig("Cupboard inventory access", "Block access", "false"));
     if (!ConfigChanged)
     {
         return;
     }
     SaveConfig();
     ConfigChanged = false;
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Converts the specified input to the given output.
 /// </summary>
 /// <typeparam name="TInput">The type of the input.</typeparam>
 /// <typeparam name="TOutput">The type of the output.</typeparam>
 /// <param name="input">The input object of TInput.</param>
 /// <returns>A resulting TOutput.</returns>
 public TOutput Convert <TInput, TOutput>(TInput input)
 {
     //throw new FormatException(
     //	string.Format(
     //		"Cannot convert '{0}' from {1} to {2}.",
     //		input,
     //		typeof (TInput),
     //		typeof (TOutput)));
     return((TOutput)SystemConvert.ChangeType(input, typeof(TOutput)));
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates the arm.
        /// </summary>
        /// <returns>The arm.</returns>
        /// <param name="side">Side.</param>
        public static IList <IJoint> CreateArm(Side side)
        {
            int handY           = -50;
            int wristX          = 50;
            int wristY          = 0;
            int elbowX          = 75;
            int elbowY          = 218;
            int shoulderX       = 160;
            var handOrientation = new Vector4(0, 0, 0, 0);

            var arm = new List <IJoint>();

            var shoulder = new OrientedJoint();
            var elbow    = new OrientedJoint();
            var wrist    = new OrientedJoint();
            var hand     = new HandJoint();

            if (side == Side.LEFT)
            {
                shoulder.JointType = JointType.SHOULDER_LEFT;
                elbow.JointType    = JointType.ELBOW_LEFT;
                wrist.JointType    = JointType.WRIST_LEFT;
                hand.JointType     = JointType.HAND_LEFT;
            }
            else
            {
                shoulder.JointType = JointType.SHOULDER_RIGHT;
                elbow.JointType    = JointType.ELBOW_RIGHT;
                wrist.JointType    = JointType.WRIST_RIGHT;
                hand.JointType     = JointType.HAND_RIGHT;
            }

            int s = Convert.ToInt32(side);

            // shoulders relative to neck
            shoulder.Point = new Vector3(s * shoulderX, 400, 0);
            shoulder.Valid = true;
            arm.Add(shoulder);

            // elbows relative to shoulders
            elbow.Point = new Vector3(s * (elbowX + shoulderX), elbowY, 0);
            elbow.Valid = true;
            arm.Add(elbow);

            wrist.Point = new Vector3(s * (wristX + shoulderX), wristY, 0);
            wrist.Valid = true;
            arm.Add(wrist);

            hand.Orientation = handOrientation * -s;
            hand.Point       = new Vector3(s * (wristX + shoulderX), handY, 0);
            hand.Valid       = true;
            arm.Add(hand);

            return(arm);
        }
        private void LoadVariables()
        {
            limit = Convert.ToInt32(GetConfig("Limit Settings", "Max Cupboard by player", "1"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
Ejemplo n.º 11
0
        void SerializeString(string aString, StringBuilder builder)
        {
            builder.Append("\"");

            char[] charArray = aString.ToCharArray();
            for (int i = 0; i < charArray.Length; i++)
            {
                char c = charArray[i];
                if (c == '"')
                {
                    builder.Append("\\\"");
                }
                else if (c == '\\')
                {
                    builder.Append("\\\\");
                }
                else if (c == '\b')
                {
                    builder.Append("\\b");
                }
                else if (c == '\f')
                {
                    builder.Append("\\f");
                }
                else if (c == '\n')
                {
                    builder.Append("\\n");
                }
                else if (c == '\r')
                {
                    builder.Append("\\r");
                }
                else if (c == '\t')
                {
                    builder.Append("\\t");
                }
                else
                {
                    int codepoint = Convert.ToInt32(c);
                    if ((codepoint >= 32) && (codepoint <= 126))
                    {
                        builder.Append(c);
                    }
                    else
                    {
                        builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
                    }
                }
            }

            builder.Append("\"");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates the leg.
        /// </summary>
        /// <returns>The leg.</returns>
        /// <param name="side">Side.</param>
        public static IList <IJoint> CreateLeg(Side side)
        {
            int footLength = 255;
            int ankleY     = -830;
            int kneeY      = -427;
            int hipX       = 50;
            int hipY       = -100;

            var leg = new List <IJoint>();

            var footOrientation = new Vector4(0, 0, 0, 0);

            var foot  = new OrientedJoint();
            var ankle = new OrientedJoint();
            var knee  = new OrientedJoint();
            var hip   = new OrientedJoint();

            if (side == Side.LEFT)
            {
                foot.JointType  = JointType.FOOT_LEFT;
                ankle.JointType = JointType.ANKLE_LEFT;
                knee.JointType  = JointType.KNEE_LEFT;
                hip.JointType   = JointType.HIP_LEFT;
            }
            else
            {
                foot.JointType  = JointType.FOOT_RIGHT;
                ankle.JointType = JointType.ANKLE_RIGHT;
                knee.JointType  = JointType.KNEE_RIGHT;
                hip.JointType   = JointType.HIP_RIGHT;
            }

            int s = Convert.ToInt32(side);

            hip.Point = new Vector3(s * hipX, hipY, 0);
            hip.Valid = true;
            leg.Add(hip);

            knee.Point = new Vector3(s * hipX, kneeY, 0);
            knee.Valid = true;
            leg.Add(knee);

            ankle.Point = new Vector3(s * hipX, ankleY, 0);
            ankle.Valid = true;
            leg.Add(ankle);

            foot.Orientation = footOrientation;
            foot.Point       = new Vector3(s * hipX, ankleY, -footLength);
            foot.Valid       = true;

            return(leg);
        }
Ejemplo n.º 13
0
        private void LoadVariables()
        {
            Prefix      = Convert.ToString(GetConfig("Chat Settings", "Prefix", "[My MiniCopter] :"));             // CHAT PLUGIN PREFIX
            SteamIDIcon = Convert.ToUInt64(GetConfig("Chat Settings", "SteamIDIcon", "76561198059533272"));        // SteamID FOR PLUGIN ICON - STEAM PROFILE CREATED FOR THIS PLUGIN / NONE YET /
            cooldownmin = Convert.ToSingle(GetConfig("Cooldown (on permission)", "Value in minutes", "60"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
Ejemplo n.º 14
0
        public ActionResult Column()
        {
            var renderingParameters = RenderingContext.Current.Rendering.Parameters;
            var colNumberString     = renderingParameters["Col Number"];
            var size  = renderingParameters["size"];
            var model = new ColumnModel
            {
                ColumnNumber = Convert.ToInt32(colNumberString),
                Size         = size
            };


            return(View("~/Views/DynamicComponents/Layout/Column.cshtml", model));
        }
Ejemplo n.º 15
0
        public void ConvertXmlToJson()
        {
            var manufacturers = _xmlConverter.GetXml()
                                .Element("Manufacturers")
                                ?.Elements("Manufacturer")
                                .Select(m => new Manufacturer
            {
                City = m.Attribute("City")?.Value,
                Name = m.Attribute("Name")?.Value,
                Year = Convert.ToInt32(m.Attribute("Year")?.Value)
            });

            new CustomJsonConverter(manufacturers).ConvertToJson();
        }
        private void LoadVariables()
        {
            maxdistanceother  = Convert.ToSingle(GetConfig("Healing Others", "Max Distance (2 by default)", "2"));
            healdurationother = Convert.ToSingle(GetConfig("Healing Others", "Heal duration (4 by default)", "4"));
            canuseonother     = Convert.ToBoolean(GetConfig("Healing Others", "Can heal others (true by default)", "true"));
            healdurationself  = Convert.ToSingle(GetConfig("Healing Self", "Heal duration (4 by default)", "4"));
            canrevive         = Convert.ToBoolean(GetConfig("Revive", "Can be used to revive (false by default)", "false"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// OAuthで使用する共通情報を取得する
        /// </summary>
        /// <param name="token">アクセストークン、もしくはリクエストトークン。未取得なら空文字列</param>
        /// <returns>OAuth情報のディクショナリ</returns>
        protected Dictionary <string, string> GetOAuthParameter(string token)
        {
            Dictionary <string, string> parameter = new Dictionary <string, string>();

            parameter.Add("oauth_consumer_key", this.consumerKey);
            parameter.Add("oauth_signature_method", "HMAC-SHA1");
            parameter.Add("oauth_timestamp", Convert.ToInt64((DateTime.UtcNow - HttpConnectionOAuth.UnixEpoch).TotalSeconds).ToString());                   // epoch秒
            parameter.Add("oauth_nonce", HttpConnectionOAuth.NonceRandom.Next(123400, 9999999).ToString());
            parameter.Add("oauth_version", "1.0");
            if (!string.IsNullOrEmpty(token))
            {
                parameter.Add("oauth_token", token);                   // トークンがあれば追加
            }
            return(parameter);
        }
Ejemplo n.º 18
0
        private void LoadVariables()
        {
            Prefix        = Convert.ToString(GetConfig("Chat Settings", "Prefix", "[My CH47] "));                // CHAT PLUGIN PREFIX
            PrefixColor   = Convert.ToString(GetConfig("Chat Settings", "PrefixColor", "#149800"));              // CHAT PLUGIN PREFIX COLOR
            ChatColor     = Convert.ToString(GetConfig("Chat Settings", "ChatColor", "#bbffb1"));                // CHAT MESSAGE COLOR
            SteamIDIcon   = Convert.ToUInt64(GetConfig("Chat Settings", "SteamIDIcon", "76561198332562475"));    // SteamID FOR PLUGIN ICON - STEAM PROFILE CREATED FOR THIS PLUGIN / NONE YET /
            withoutdebris = Convert.ToBoolean(GetConfig("Debris Settings", "Remove debris", "false"));
            cooldownmin   = Convert.ToSingle(GetConfig("Cooldown (on permission)", "Value in minutes", "60"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
        private void LoadVariables()
        {
            Prefix       = Convert.ToString(GetConfig("Chat Settings", "Prefix", "[PSS] :"));                 // CHAT PLUGIN PREFIX
            PrefixColor  = Convert.ToString(GetConfig("Chat Settings", "PrefixColor", "#42d7f4"));            // CHAT PLUGIN PREFIX COLOR
            ChatColor    = Convert.ToString(GetConfig("Chat Settings", "ChatColor", "#b7f5ff"));              // CHAT  COLOR
            SteamIDIcon  = Convert.ToUInt64(GetConfig("Chat Settings", "SteamIDIcon", 76561198859649789));
            bonusratemin = Convert.ToSingle(GetConfig("Bonus Playtime", "Value in minutes", "60"));
            spawnbonus   = Convert.ToBoolean(GetConfig("Bonus on Spawn", "Give a SupplySignal on first arrival", "true"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
Ejemplo n.º 20
0
 private void KillMyMinicopterConsoleCommand(ConsoleSystem.Arg arg)
 {
     if (arg.Args.Length == 1)
     {
         ulong cherche = Convert.ToUInt64(arg.Args[0]);
         if (cherche == null)
         {
             return;
         }
         if (cherche.IsSteamId() == false)
         {
             return;
         }
         BasePlayer player = BasePlayer.FindByID(cherche);
         KillMyMinicopterPlease(player);
     }
 }
        public ActionResult Rendering()
        {
            var cart        = GetCart();
            var basketModel = new BasketRenderingViewModel();

            var currency = new Currency()
            {
                ISOCode = cart.CurrencyCode
            };

            foreach (var cartLine in cart.Lines)
            {
                var orderLineViewModel = new BasketRenderingViewModel.OrderlineViewModel();

                orderLineViewModel.Quantity    = (int)cartLine.Quantity;
                orderLineViewModel.ProductName = cartLine.Product.ProductName;
                orderLineViewModel.Sku         = cartLine.Product.ProductId;
                if (cartLine.GetPropertyValue("VariantSku") != null)
                {
                    orderLineViewModel.VariantSku = cartLine.GetPropertyValue("VariantSku").ToString();
                }
                orderLineViewModel.Total    = new Money(cartLine.Total.Amount, currency.ISOCode).ToString();
                orderLineViewModel.Discount = new Money(cartLine.Adjustments.Sum(x => x.Amount), currency.ISOCode).Value;
                if (cartLine.Total.TaxTotal != null)
                {
                    orderLineViewModel.Tax = new Money(cartLine.Total.TaxTotal.Amount, currency.ISOCode).ToString();
                }
                orderLineViewModel.Price      = new Money(cartLine.Product.Price.Amount, currency.ISOCode).ToString();
                orderLineViewModel.ProductUrl = _urlService.GetUrl(_catalogContext.CurrentCatalog,
                                                                   _catalogLibrary.GetProduct(cartLine.Product.ProductId));
                orderLineViewModel.PriceWithDiscount = new Money((cartLine.Product.Price.Amount - cartLine.Adjustments.Sum(x => x.Amount)), currency.ISOCode).ToString();
                orderLineViewModel.OrderLineId       = Convert.ToInt32(cartLine.ExternalCartLineId);

                basketModel.OrderLines.Add(orderLineViewModel);
            }

            basketModel.OrderTotal    = new Money(cart.Total.Amount, currency.ISOCode).ToString();
            basketModel.DiscountTotal = new Money(cart.Adjustments.Sum(x => x.Amount), currency.ISOCode).ToString();
            if (cart.Total.TaxTotal != null)
            {
                basketModel.TaxTotal = new Money(cart.Total.TaxTotal.Amount, currency.ISOCode).ToString();
            }
            basketModel.SubTotal = new Money((cart.Total.Amount - cart.Total.TaxTotal.Amount), currency.ISOCode).ToString();

            return(View(basketModel));
        }
Ejemplo n.º 22
0
 bool SerializeValue(object value, StringBuilder builder)
 {
     if (value == null)
     {
         builder.Append("null");
     }
     else if (value.GetType().IsArray)
     {
         SerializeArray(new ArrayList((ICollection)value), builder);
     }
     else if (value is string)
     {
         SerializeString((string)value, builder);
     }
     else if (value is Char)
     {
         SerializeString(Convert.ToString((char)value), builder);
     }
     else if (value is Hashtable)
     {
         SerializeObject((Hashtable)value, builder);
     }
     else if (value is ArrayList)
     {
         SerializeArray((ArrayList)value, builder);
     }
     else if ((value is bool) && ((bool)value == true))
     {
         builder.Append("true");
     }
     else if ((value is bool) && ((bool)value == false))
     {
         builder.Append("false");
     }
     else if (value.GetType().IsPrimitive)
     {
         SerializeNumber(Convert.ToDouble(value), builder);
     }
     else
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 23
0
        private void LoadVariables()
        {
            /*Prefix = Convert.ToString(GetConfig("Chat Settings", "Prefix", "[My CH47] "));                       // CHAT PLUGIN PREFIX
             * PrefixColor = Convert.ToString(GetConfig("Chat Settings", "PrefixColor", "#149800"));                // CHAT PLUGIN PREFIX COLOR
             * ChatColor = Convert.ToString(GetConfig("Chat Settings", "ChatColor", "#bbffb1"));                    // CHAT MESSAGE COLOR
             * SteamIDIcon = Convert.ToUInt64(GetConfig("Chat Settings", "SteamIDIcon", "76561198332562475"));*/
            sound         = Convert.ToBoolean(GetConfig("Sound Settings", "play soundfx", "false"));
            bannerdisplay = Convert.ToBoolean(GetConfig("Banner Settings", "display banner", "false"));
            HUDfontsize   = Convert.ToInt32(GetConfig("HUD Settings", "font size", "10"));
            HUDcolor      = Convert.ToString(GetConfig("HUD Settings", "color on 3 firsts numbers - opacity on last number", "0.5 0.5 0.5 0.30"));
            bannercolor   = Convert.ToString(GetConfig("Banner Settings", "color on 3 firsts numbers - opacity on last number", "0.5 0.5 0.5 0.30"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
Ejemplo n.º 24
0
        protected override void OnGUIValue()
        {
            char _value    = (char)CachedValue;
            var  str       = EditorGUILayout.TextField(_value.ToString(), GUILayout.ExpandWidth(true));
            var  intValue  = Convert.ToInt32(_value);
            var  intValue2 = EditorGUILayout.IntField(intValue, GUILayout.ExpandWidth(true));

            if (intValue2 != intValue)
            {
                SetValue((char)intValue2);
            }
            else if (str.Length > 0)
            {
                char val = str[0];
                if (val != _value)
                {
                    SetValue(val);
                }
            }
        }
Ejemplo n.º 25
0
        private void LoadVariables()
        {
            /*Prefix = Convert.ToString(GetConfig("Chat Settings", "Prefix", "[NightPVP] "));                       // CHAT PLUGIN PREFIX
             * PrefixColor = Convert.ToString(GetConfig("Chat Settings", "PrefixColor", "#bf0000"));                // CHAT PLUGIN PREFIX COLOR
             * ChatColor = Convert.ToString(GetConfig("Chat Settings", "ChatColor", "#dd8e8e"));                    // CHAT MESSAGE COLOR
             * SteamIDIcon = Convert.ToUInt64(GetConfig("Chat Settings", "SteamIDIcon", "76561198079320022")); */// SteamID FOR PLUGIN ICON - STEAM PROFILE CREATED FOR THIS PLUGIN / NONE YET /
            pvpcolor        = Convert.ToString(GetConfig("HUD COLOR", "for PVP", "0.6 0.2 0.2"));
            pvecolor        = Convert.ToString(GetConfig("HUD COLOR", "for PVE", "0.5 1.0 0.0"));
            pvpcoloropacity = Convert.ToString(GetConfig("HUD OPACITY", "for PVP", "0.5"));
            pvecoloropacity = Convert.ToString(GetConfig("HUD OPACITY", "for PVE", "0.4"));
            textsize        = Convert.ToInt32(GetConfig("HUD TEXT", "size", "12"));
            pvptextcolor    = Convert.ToString(GetConfig("HUD TEXT", "color for PVP", "1.0 1.0 1.0"));
            pvetextcolor    = Convert.ToString(GetConfig("HUD TEXT", "color for PVE", "1.0 1.0 1.0"));
            HUDleft         = Convert.ToDouble(GetConfig("HUD POSITION", "left", "0.65"));
            HUDbottom       = Convert.ToDouble(GetConfig("HUD COLOR", "bottom", "0.04"));

            if (!ConfigChanged)
            {
                return;
            }
            SaveConfig();
            ConfigChanged = false;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// OAuth認証ヘッダの署名作成
        /// </summary>
        /// <param name="tokenSecret">アクセストークン秘密鍵</param>
        /// <param name="method">HTTPメソッド文字列</param>
        /// <param name="uri">アクセス先Uri</param>
        /// <param name="parameter">クエリ、もしくはPOSTデータ</param>
        /// <returns>署名文字列</returns>
        protected virtual string CreateSignature(string tokenSecret, string method, Uri uri, Dictionary <string, string> parameter)
        {
            // パラメタをソート済みディクショナリに詰替(OAuthの仕様)
            SortedDictionary <string, string> sorted = new SortedDictionary <string, string>(parameter);
            // URLエンコード済みのクエリ形式文字列に変換
            string paramString = this.CreateQueryString(sorted);
            // アクセス先URLの整形
            string url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath);
            // 署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする
            string signatureBase = string.Format("{0}&{1}&{2}", method, this.UrlEncode(url), this.UrlEncode(paramString));
            // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと)
            string key = this.UrlEncode(this.consumerSecret) + "&";

            if (!string.IsNullOrEmpty(tokenSecret))
            {
                key += this.UrlEncode(tokenSecret);
            }
            // 鍵生成&署名生成
            using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key)))
            {
                byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
                return(Convert.ToBase64String(hash));
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 转换 NCM 文件为 Flac/MP3 文件
        /// </summary>
        /// <param name="filePath">NCM 文件路径</param>
        /// <returns>转换状态</returns>
        public NCMConverterEnum ProcessFile(string filePath)
        {
            using (var fs = File.Open(filePath, FileMode.Open))
            {
                // 校验是否是网易云加密的 NCM 文件
                if (NCMExtenstion.ReadInt32(fs) != 0x4e455443)
                {
                    return(NCMConverterEnum.Invalid);
                }

                if (NCMExtenstion.ReadInt32(fs) != 0x4d414446)
                {
                    return(NCMConverterEnum.Invalid);
                }

                // 读取密钥
                NCMExtenstion.Seek(fs, 2);
                var keyBytes = NCMExtenstion.ReadBytes(fs, NCMExtenstion.ReadInt32(fs));

                for (int i = 0; i < keyBytes.Length; i++)
                {
                    keyBytes[i] ^= 0x64;
                }

                // 减去 "neteasecloudmusic" 字符串之后的数据即为密钥数据
                var deKeyDataBytes = NCMExtenstion.GetBytesByOffset(NCMExtenstion.DecryptAes128Ecb(Encoding.UTF8.GetBytes(NCMConveterConsts.AesCoreKeyString), keyBytes), 17);

                var modifyDataBytes = NCMExtenstion.ReadBytes(fs, NCMExtenstion.ReadInt32(fs));
                for (int i = 0; i < modifyDataBytes.Length; i++)
                {
                    modifyDataBytes[i] ^= 0x63;
                }

                var decryptBase64          = SystemConvert.FromBase64String(Encoding.UTF8.GetString(NCMExtenstion.GetBytesByOffset(modifyDataBytes, 22)));
                var decryptModifyDataBytes = NCMExtenstion.DecryptAes128Ecb(Encoding.UTF8.GetBytes(NCMConveterConsts.AesModifyKeyBytes), decryptBase64);

                // 获取 NCM 文件的歌曲文件信息 Json
                var musicJson     = JObject.Parse(Encoding.UTF8.GetString(NCMExtenstion.GetBytesByOffset(decryptModifyDataBytes, 6)));
                var fileExtension = musicJson.SelectToken("$.format").Value <string>();

                // 跳过 CRC 校验
                NCMExtenstion.Seek(fs, 9);

                // 跳过专辑图像数据
                var imageBytes = new byte[NCMExtenstion.ReadInt32(fs)];
                if (imageBytes.Length != 0)
                {
                    fs.Read(imageBytes, 0, imageBytes.Length);
                }

                var box = NCMExtenstion.BuildKeyBox(deKeyDataBytes);

                var n = 0x8000;
                using (var outputFile = File.Create(Path.Combine(Path.GetDirectoryName(filePath), $"{Path.GetFileNameWithoutExtension(filePath)}.{fileExtension}")))
                {
                    while (true)
                    {
                        var tb     = new byte[n];
                        var result = fs.Read(tb, 0, n);
                        if (result <= 0)
                        {
                            break;
                        }

                        for (int i = 0; i < n; i++)
                        {
                            var j = (byte)((i + 1) & 0xff);
                            tb[i] ^= box[box[j] + box[(box[j] + j) & 0xff] & 0xff];
                        }

                        outputFile.Write(tb, 0, n);
                    }

                    outputFile.Flush();
                }

                fs.Close();
                return(NCMConverterEnum.Success);
            }
        }
Ejemplo n.º 28
0
 void SerializeNumber(double number, StringBuilder builder)
 {
     builder.Append(Convert.ToString(number)); // , CultureInfo.InvariantCulture));
 }
Ejemplo n.º 29
0
        private static int Str_Format(ILuaState lua)
        {
            int           top    = lua.GetTop();
            StringBuilder sb     = new StringBuilder();
            int           arg    = 1;
            string        format = lua.L_CheckString(arg);
            int           s      = 0;
            int           e      = format.Length;

            while (s < e)
            {
                if (format[s] != L_ESC)
                {
                    sb.Append(format[s++]);
                    continue;
                }

                if (format[++s] == L_ESC)
                {
                    sb.Append(format[s++]);
                    continue;
                }

                // else format item
                if (++arg > top)
                {
                    lua.L_ArgError(arg, "no value");
                }

                string form;
                s = ScanFormat(lua, format, s, out form);
                switch (format[s++])                  // TODO: properly handle form
                {
                case 'c':
                {
                    sb.Append((char)lua.L_CheckInteger(arg));
                    break;
                }

                case 'd':
                case 'i':
                {
                    int n = lua.L_CheckInteger(arg);
                    sb.Append(n.ToString());
                    break;
                }

                case 'u':
                {
                    int n = lua.L_CheckInteger(arg);
                    lua.L_ArgCheck(n >= 0, arg,
                                   "not a non-negative number is proper range");
                    sb.Append(n.ToString());
                    break;
                }

                case 'o':
                {
                    int n = lua.L_CheckInteger(arg);
                    lua.L_ArgCheck(n >= 0, arg,
                                   "not a non-negative number is proper range");
                    sb.Append(Convert.ToString(n, 8));
                    break;
                }

                case 'x':
                {
                    int n = lua.L_CheckInteger(arg);
                    lua.L_ArgCheck(n >= 0, arg,
                                   "not a non-negative number is proper range");
                    // sb.Append( string.Format("{0:x}", n) );
                    sb.AppendFormat("{0:x}", n);
                    break;
                }

                case 'X':
                {
                    int n = lua.L_CheckInteger(arg);
                    lua.L_ArgCheck(n >= 0, arg,
                                   "not a non-negative number is proper range");
                    // sb.Append( string.Format("{0:X}", n) );
                    sb.AppendFormat("{0:X}", n);
                    break;
                }

                case 'e':
                case 'E':
                {
                    sb.AppendFormat("{0:E}", lua.L_CheckNumber(arg));
                    break;
                }

                case 'f':
                {
                    sb.AppendFormat("{0:F}", lua.L_CheckNumber(arg));
                    break;
                }

#if LUA_USE_AFORMAT
                case 'a':
                case 'A':
#endif
                case 'g':
                case 'G':
                {
                    sb.AppendFormat("{0:G}", lua.L_CheckNumber(arg));
                    break;
                }

                case 'q':
                {
                    AddQuoted(lua, sb, arg);
                    break;
                }

                case 's':
                {
                    sb.Append(lua.L_CheckString(arg));
                    break;
                }

                default:                         // also treat cases `pnLlh'
                {
                    return(lua.L_Error("invalid option '{0}' to 'format'",
                                       format[s - 1]));
                }
                }
            }
            lua.PushString(sb.ToString());
            return(1);
        }
Ejemplo n.º 30
0
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     TestClient.StartRecieveThread(Convert.ToInt32(portRecieve.Text));
     _readyTowork = true;
 }